"""One test (or more) for every bug fixed on 11 Nov 2026. Run with  python3 -m pytest -q  from ato-generator/."""
import copy, json, re, sys, datetime as dt
from fractions import Fraction
from pathlib import Path
import pytest

HERE = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(HERE))
import generator, rating, rules  # noqa: E402

TODAY = dt.date(2026, 11, 9)
PAID = json.loads((HERE / "data/ato/example-flight-academy.json").read_text())
UNPAID = json.loads((HERE / "data/ato/example-air-school.json").read_text())


def render(tmp_path, ato, **kw):
    d = tmp_path / "data"; d.mkdir(exist_ok=True)
    (d / "a.json").write_text(json.dumps(ato))
    generator.build(d, tmp_path / "out", "amethyst", kw.pop("today", TODAY), **kw)
    return (tmp_path / "out" / ato["slug"] / "index.html").read_text()


def card(html):
    return html.split('<div class="ob-ratebanner">', 1)[1].split('<div class="ob-list-r">', 1)[0]


# ---- Bug 1: bars and counts come from the rating summary, not from the reviews printed on the page ----
def test_bars_and_counts_come_from_the_summary_not_from_the_top_reviews(tmp_path):
    h = card(render(tmp_path, copy.deepcopy(PAID)))                # the page prints 3 reviews; the school has 9 ratings
    assert re.findall(r'<div class="ob-bar"><span>(\d)</span>.*?<b>(\d+)</b></div>', h) == [("5", "4"), ("4", "4"), ("3", "1"), ("2", "0"), ("1", "0")]
    assert re.findall(r'<span class="ob-ratechip"><b>([^<]+)</b> ([^<]+)</span>', h) == [("8", "Written reviews"), ("8", "Rated 4.0+")]
    assert "scaleX(0.4444" in h                                     # 4 of 9, not 1 of 3
    html = render(tmp_path, copy.deepcopy(PAID))
    assert '<p class="ob-from">from 9 reviews</p>' in html           # review count once, in the hero, not as a chip
    assert '<p class="ob-facts">2 certificates · 2 bases</p>' in html  # certificates counted once, in the hero


def test_a_summary_that_does_not_add_up_stops_the_build():
    a = copy.deepcopy(PAID); a["rating"]["bars"][0]["count"] = 7
    with pytest.raises(ValueError, match="bars must add up"):
        generator.check(a)
    b = copy.deepcopy(PAID); b["rating"] = {"count": 28, "avg_overall": 4.3}      # the old shape: an average with a count
    with pytest.raises(ValueError, match="must be the server summary"):
        generator.check(b)
    c = copy.deepcopy(PAID); c["rating"]["written"] = 10
    with pytest.raises(ValueError, match="more written reviews than reviews"):
        generator.check(c)


# ---- Bug 2: one stated rounding rule ----
@pytest.mark.parametrize("overall,bar", [("9/2", 5), ("7/2", 4), ("5/2", 3), ("3/2", 2), ("349/100", 3), ("13/3", 4), ("1", 1), ("5", 5)])
def test_bar_is_the_overall_rounded_half_up(overall, bar):
    assert rating.bar_of(Fraction(overall)) == bar                  # round() would give 4.5 -> 4 and 2.5 -> 2


def test_display_rounding_is_half_up_and_exact():
    assert [rating.display1(17, 4), rating.display1(13, 3), rating.display1(79, 20), rating.display1(789, 200)] == ["4.3", "4.3", "4.0", "3.9"]


def test_summary_mirror_matches_the_server_rules():
    old = "2026-01-01"
    rows = [{"stars": {"org": 4}, "text": "x", "account_created": old} for _ in range(24)] + [{"stars": {"org": 3}, "text": "", "account_created": old}]
    s = rating.summarise(rows, TODAY, certificates=2)
    assert (s["score"], s["gold"], s["count"], s["written"], s["rated_hi"]) == ("4.0", False, 25, 24, 24)   # raw 3.96: not gold (NEW-01)
    assert [b["count"] for b in s["bars"]] == [0, 24, 1, 0, 0]
    assert generator.check({**copy.deepcopy(PAID), "rating": s}) is not None      # the mirror's output is a valid summary
    mixed = [{"stars": {"org": 5, "flt": 5, "gnd": 5, "ins": 5, "saf": 5, "val": 5, "avl": 5}, "text": "a", "account_created": old},
             {"stars": {"org": 1}, "text": "b", "account_created": old},
             {"stars": {"org": 5, "flt": 5, "gnd": 5, "ins": 5, "saf": 5, "val": 5, "avl": 5}, "status": "deleted", "text": "c", "account_created": old},
             {"stars": {"org": 1}, "status": "spam_held", "text": "d", "account_created": old}]
    assert rating.summarise(mixed, TODAY)["score"] == "3.7"                         # decision D1: average of review overalls
    assert rating.summarise(mixed, TODAY, mode="every_star")["score"] == "4.7"      # ... or of every star
    assert rating.summarise(mixed, TODAY)["written"] == 2                           # the deleted one counts, but is not "written"
    cats = {c["key"]: c for c in rating.summarise(mixed, TODAY)["categories"]}
    assert cats["org"]["score"] == "3.7" and cats["flt"]["score"] is None           # Fleet has only 2 ratings (REV-011)


# ---- Bug 3: no frozen default date ----
def test_today_defaults_to_today_in_south_africa(tmp_path, monkeypatch):
    monkeypatch.setattr(generator, "today_sast", lambda: dt.date(2030, 1, 2))
    generator.main(["--data", str(HERE / "data/ato"), "--out", str(tmp_path / "o")])
    assert json.loads((tmp_path / "o" / "manifest.json").read_text())["today"] == "2030-01-02"
    h = (tmp_path / "o" / "example-flight-academy" / "index.html").read_text()
    assert ">Current<" not in h and h.count(">Expired<") == 2      # both example certificates have ended by 2030
    assert 'data-until="2027-06-30"' in h                          # the pill carries its date for the page script


def test_sast_date_does_not_lag_behind_utc():
    assert generator.SAST.utcoffset(None) == dt.timedelta(hours=2)
    assert generator.day_ms(dt.date(2026, 11, 9)) == int(dt.datetime(2026, 11, 8, 22, 0, tzinfo=dt.timezone.utc).timestamp() * 1000)


# ---- Bug 4: "shown" is the server's decision (3 ratings from 3 aged reviewers) ----
def test_rating_stays_hidden_when_the_server_says_so_even_with_enough_reviews(tmp_path):
    a = copy.deepcopy(PAID); a["rating"] = {"shown": False, "count": 5, "written": 5}     # e.g. two of the accounts are 3 days old
    h = render(tmp_path, a)
    assert 'data-rating-kind="empty"' in h and 'data-v=""' in h and ">–</span>" in h
    assert '<p class="ob-from">from' not in h                        # no scored "from N reviews"
    assert '<p class="ob-from is-wait">5 of 3 reviews needed for a rating</p>' in h
    assert "ob-ratechip" not in h and "Rated 4.0+" not in h          # no 4.0+ number while hidden
    assert "Stars and the 5-to-1 breakdown appear at 3 reviews." in h
    assert "application/ld+json" not in h
    assert rating.summarise([{"stars": {"org": 5}, "text": "x", "account_created": d} for d in ("2026-01-01", "2026-01-01", "2026-11-06")], TODAY)["shown"] is False


def test_a_rating_can_never_show_under_three():
    a = copy.deepcopy(UNPAID); a["rating"] = {"shown": True, "count": 2, "written": 1, "score": "4.5", "gold": True, "rated_hi": 2, "bars": []}
    with pytest.raises(ValueError, match="cannot show under 3"):
        generator.check(a)


# ---- Bug 5: the sign-in gate promises only cards that exist ----
def test_gate_counts_written_reviews_only(tmp_path):
    h = render(tmp_path, copy.deepcopy(PAID))                       # 9 ratings, 8 written, 3 shown
    assert "5 more reviews, and voting after you sign in" in h
    a = copy.deepcopy(PAID); a["rating"]["written"] = 3; a["visible_reviews"] = 3
    assert "Sign in to see the rest" not in render(tmp_path, a)     # nothing more to open: no gate


# ---- Bug 6 and 8: slugs ----
def test_two_files_with_one_slug_stop_the_build(tmp_path):
    d = tmp_path / "d"; d.mkdir()
    for n in ("a", "b"):
        (d / f"{n}.json").write_text(json.dumps({**copy.deepcopy(UNPAID), "id": f"EXAMPLE_{n}"}))
    with pytest.raises(ValueError, match="is used by both a.json and b.json"):
        generator.build(d, tmp_path / "out", "amethyst", TODAY)


@pytest.mark.parametrize("slug", ["../../etc", "a/b", "Upper", "two--hyphens", "-lead", "trail-", "", "static", "fonts", "x" * 81, None, 7])
def test_unsafe_or_reserved_slug_stops_the_build(slug):
    with pytest.raises(ValueError, match="slug"):
        generator.check({**copy.deepcopy(UNPAID), "slug": slug})


# ---- Bug 9: contact details ----
def test_bad_contact_values_are_left_out_and_never_become_links(tmp_path):
    a = copy.deepcopy(UNPAID)
    a["contact"] = {"phone": "call now!", "email": 'x@y.z" onclick="alert(1)', "web": "javascript:alert(1)"}
    warn = generator.check(a)
    assert a["contact"] == {"phone": None, "email": None, "web": None}
    assert sum("left out" in w for w in warn) == 3
    h = render(tmp_path, a)
    assert 'href="#"' not in h and "javascript:" not in h and "onclick" not in h
    assert h.count('<span class="ob-clink is-off" aria-disabled="true">') == 3  # about row: same pill, not a dead link
    assert h.count('<span class="ob-hc" aria-disabled="true">') == 3            # hero row: same buttons, not a dead link
    assert '<a class="ob-clink"' not in h and '<a class="ob-hc"' not in h


def test_good_contact_values_are_links(tmp_path):
    a = copy.deepcopy(UNPAID); a["contact"] = {"phone": "+27 11 555 0100", "email": "info@school.example", "web": "https://www.school.example/"}
    h = render(tmp_path, a)
    assert 'href="tel:+27115550100"' in h and 'href="mailto:info@school.example"' in h and 'href="https://www.school.example"' in h
    assert "aria-disabled" not in h


# ---- Bug 10: counted upvotes ----
def test_server_count_wins_and_builds_are_repeatable():
    old = 1767225600000
    assert generator.counted_upvotes({"up": 3, "vote_records": [{"value": 1, "accountCreated": old}] * 50}) == 3
    assert generator.counted_upvotes({"upvotes": 99}) == 0                         # a raw "upvotes" number is never trusted
    with pytest.raises(ValueError, match="needs the build date"):
        generator.counted_upvotes({"vote_records": [{"value": 1, "accountCreated": old}]})
    a, b = copy.deepcopy(PAID), copy.deepcopy(PAID)
    generator.check(a); generator.check(b)
    assert [r["id"] for r in generator.page_model(a, TODAY)["top"]] == [r["id"] for r in generator.page_model(b, TODAY)["top"]] == ["r2", "r1", "r3"]


def test_top_three_uses_the_server_count_when_given(tmp_path):
    a = copy.deepcopy(PAID)
    for r, up in zip(a["top_reviews"], (1, 2, 30, 0)):
        r.pop("vote_records", None); r["up"] = up
    ids = re.findall(r'<article class="ob-review[^"]*" data-id="([^"]+)"', render(tmp_path, a))
    assert ids == ["r3", "r2", "r1"]


# ---- Bug 11: the word "pilot" in course names is a switch (decision D4) ----
def test_pilot_in_course_names_follows_the_switch(tmp_path):
    assert "Private Licence (A)" in render(tmp_path, copy.deepcopy(PAID))                         # default: as before
    assert "Private Pilot Licence (A)" in render(tmp_path, copy.deepcopy(PAID), scrub_courses=False)


def test_courses_are_grouped_on_the_original_name(tmp_path):
    """PPL/CPL stay licences after 'pilot' is stripped; Night / Instrument / Instructor / Multi-engine are ratings."""
    paid = {g["name"]: g["items"] for g in generator.course_groups(copy.deepcopy(PAID))}
    assert paid["Licences"] == ["Private Licence (A)", "Commercial Licence (A)"]
    assert paid["Ratings"] == ["Instructor rating, Grade III", "Night rating", "Instrument rating", "Multi-engine class rating"]
    assert "Other" not in paid
    unpaid = {g["name"]: g["items"] for g in generator.course_groups(copy.deepcopy(UNPAID))}
    assert unpaid["Licences"] == ["Private Licence (A)"]
    assert unpaid["Ratings"] == ["Night rating"]
    assert "Other" not in unpaid
    kept = {g["name"]: g["items"] for g in generator.course_groups(copy.deepcopy(PAID), scrub_courses=False)}
    assert kept["Licences"] == ["Private Pilot Licence (A)", "Commercial Pilot Licence (A)"]
    h = render(tmp_path, copy.deepcopy(PAID))
    lic = re.search(r'<h3 class="ob-cr-gh">Licences <span class="ob-cr-n">2</span></h3>.*?</ul>', h, re.S).group(0)
    rat = re.search(r'<h3 class="ob-cr-gh">Ratings <span class="ob-cr-n">4</span></h3>.*?</ul>', h, re.S).group(0)
    assert "Private Licence (A)" in lic and "Commercial Licence (A)" in lic
    assert "Night rating" in rat and "Instrument rating" in rat
    assert "Other" not in re.search(r'<section class="ob-sec ob-crs"[^>]*>.*?</section>', h, re.S).group(0)


# ---- Bug 13: page head, sign-in return, API by school ----
def test_head_is_noindex_by_default_and_complete_when_indexed(tmp_path):
    h = render(tmp_path, copy.deepcopy(PAID))
    assert '<meta name="robots" content="noindex,nofollow">' in h and 'rel="canonical"' not in h
    assert '<meta name="description" content="Example Flight Academy: flight training at FACT, FAGG.' in h
    h = render(tmp_path, copy.deepcopy(PAID), site="https://example.co.za", index=True)
    assert '<meta name="robots" content="index,follow">' in h
    assert '<link rel="canonical" href="https://example.co.za/ato/example-flight-academy">' in h
    ld = json.loads(re.search(r'<script type="application/ld\+json">(.*?)</script>', h, re.S).group(1))
    assert ld["aggregateRating"] == {"@type": "AggregateRating", "ratingValue": "4.3", "bestRating": "5", "worstRating": "1", "ratingCount": 9}


def test_rating_markup_cannot_be_broken_out_of(tmp_path):
    a = copy.deepcopy(PAID); a["name"] = 'Evil</script><script>alert(1)</script> & Co'
    h = render(tmp_path, a)
    assert "<script>alert(1)" not in h
    ld = json.loads(re.search(r'<script type="application/ld\+json">(.*?)</script>', h, re.S).group(1))
    assert ld["name"] == a["name"]


def test_sign_in_returns_to_the_school_and_the_api_is_by_school(tmp_path):
    h = render(tmp_path, copy.deepcopy(PAID))
    assert 'href="/signup/?next=%2Fato%2Fexample-flight-academy"' in h           # sign-in lives on /signup/
    assert 'data-api="/api/ato/example-flight-academy/view"' in h                  # the school, never a certificate number
    assert "EXAMPLE_9991_ATO/view" not in h


# ---- More: allow-list, anonymous dates, category rows ----
def test_an_unknown_field_stops_the_build():
    for path in (["member_email"], ["top_reviews", 0, "author_email"], ["top_reviews", 0, "author", "plan"], ["bases", 0, "owner"]):
        a = copy.deepcopy(PAID); o = a
        for k in path[:-1]:
            o = o[k]
        o[path[-1]] = "x"
        with pytest.raises(ValueError, match="not allowed|private field"):
            generator.check(a)


def test_sample_reviews_cannot_ride_into_real_data():
    a = copy.deepcopy(PAID); a["id"] = "SACAA/1132/ATO"; a["top_reviews"][0]["id"] = "ex11"
    with pytest.raises(ValueError, match="REV-022"):
        generator.check(a)


def test_anonymous_review_shows_the_month_only(tmp_path):
    h = render(tmp_path, copy.deepcopy(PAID))
    anon = re.search(r'<article class="ob-review is-anon".*?</article>', h, re.S).group(0)
    assert "<time>Aug 2026</time>" in anon and "30 Aug" not in h and "1 Aug 2026" not in h       # REV-038: no day, real or made up
    assert "<time>2 Oct 2026</time>" in h                                                        # named reviews keep the day


def test_category_rows_only_with_the_switch(tmp_path):
    assert "ob-catavgs" not in render(tmp_path, copy.deepcopy(PAID))
    h = render(tmp_path, copy.deepcopy(PAID), show_categories=True)
    rows = re.findall(r'<div class="ob-cat( is-hi)?" data-cat="(\w+)"><span class="ob-cat-l"><span>([^<]+)</span></span>.*?<b class="ob-score-num[^"]*">([^<]+)</b></div>', h, re.S)
    assert [(r[2], r[3]) for r in rows] == [("Organisation", "4.2"), ("Fleet", "4.3"), ("Ground school", "4.0"), ("Instructors", "4.6"),
                                            ("Safety culture", "4.6"), ("Value", "3.8"), ("Availability", "4.2")]
    assert [bool(r[0]) for r in rows] == [True, True, True, True, True, False, True]             # 3.8 is not gold
    a = copy.deepcopy(PAID); a["rating"]["categories"][1].update(score=None, gold=False, count=2)
    assert re.search(r'data-cat="flt">.*?<b class="ob-score-num">–</b>', render(tmp_path, a, show_categories=True), re.S)   # a dash under 3 ratings


def test_licences_list_ppl_first():
    ato = {
        "courses": [
            "Airline Transport Pilot Licence (A)",
            "ATPL (Modular - A)",
            "Commercial Pilot Licence (A)",
            "CPL - (Modular - A)",
            "Flight Instructor (A)",
            "Night Rating (A)",
            "Instrument Rating (A)",
            "PPL (A)",
            "Beechcraft Super King Air 350",
        ]
    }
    groups = {g["name"]: g["items"] for g in generator.course_groups(ato)}
    assert groups["Licences"][0].startswith("PPL")
    assert groups["Licences"][:3] == ["PPL (A)", "Commercial Licence (A)", "CPL - (Modular - A)"]
    assert groups["Licences"][3:] == ["Airline Transport Licence (A)", "ATPL (Modular - A)"]
    assert groups["Ratings"][0].startswith("Flight Instructor")
    assert groups["Other"] == ["Beechcraft Super King Air 350"]


def test_stats_row_puts_licences_with_courses_and_reviews(tmp_path):
    """Option A: no stats row. Licences sit inside Courses; Reviews is its own section."""
    h = render(tmp_path, copy.deepcopy(PAID))
    courses = re.search(r'<section class="ob-sec ob-crs"[^>]*>.*?</section>', h, re.S).group(0)
    assert '<h2 class="ob-h">Courses</h2>' in courses
    assert '<h3 class="ob-cr-gh">Licences <span class="ob-cr-n">2</span></h3>' in courses
    assert '<h3 class="ob-cr-gh">Ratings <span class="ob-cr-n">4</span></h3>' in courses
    assert "Reviews" not in courses
    assert "ob-statsrow" not in h
    assert re.search(r'<section class="ob-sec ob-revs"[^>]*id="reviews">', h)
    assert '<h2 class="ob-h">Reviews</h2>' in h
    assert h.find('id="courses"') < h.find('id="reviews"')


# ---- MT t329u / t330u (13 Nov): hero contact row and long names ----
def test_unclaimed_school_with_no_contact_has_no_dead_hero_row(tmp_path):
    a = copy.deepcopy(UNPAID); a["status"] = "unclaimed"; a["contact"] = {"phone": None, "email": None, "web": None}
    h = render(tmp_path, a)
    assert 'class="ob-claim-step"' in h
    assert "ob-hcontact" not in h                                   # the claim step already explains it
    assert h.count('<span class="ob-clink is-off" aria-disabled="true">') == 3  # About keeps the muted row


def test_claimed_school_keeps_hero_contact_row(tmp_path):
    h = render(tmp_path, copy.deepcopy(UNPAID))
    assert 'class="ob-hcontact' in h


def test_long_school_name_steps_down(tmp_path):
    a = copy.deepcopy(UNPAID); a["name"] = "Western Cape Advanced Multi-Engine and Instrument Training Organisation"
    assert "is-longname" in render(tmp_path, a)
    (tmp_path / "short").mkdir()
    assert "is-longname" not in render(tmp_path / "short", copy.deepcopy(UNPAID))


# ---- MT t333u (13 Nov): a stars-only rating is private to its author, never in the feed, never voted on ----
MEMBER = {"kind": "member", "plan": "pro", "name": "pilot.five", "anonymous_on": False}


def feed(html):
    return html.split('<div class="ob-list-r">', 1)[1]


def test_stars_only_rating_is_never_a_public_card_for_guests_or_members(tmp_path):
    a = copy.deepcopy(UNPAID)                                       # s2 is stars only
    (tmp_path / "g").mkdir(); (tmp_path / "m").mkdir()
    for h in (render(tmp_path / "g", copy.deepcopy(a)), render(tmp_path / "m", copy.deepcopy(a), viewer=dict(MEMBER))):
        assert 'data-id="s2"' not in h
        assert "Stars only, no written review." not in h
        assert 'data-id="s1"' in h


def test_member_votes_only_on_written_reviews(tmp_path):
    h = feed(render(tmp_path, copy.deepcopy(UNPAID), viewer=dict(MEMBER)))
    assert h.count('class="ap-vote ob-vote"') == h.count('<article class="ob-review') == 1


def test_author_sees_own_stars_only_slot_with_no_votes(tmp_path):
    v = dict(MEMBER, own_rating={"ratings": {"org": 4, "flt": 5, "ins": 5}, "published_at": "2026-11-09"})
    h = render(tmp_path, copy.deepcopy(PAID), viewer=v)
    slot = h.split('class="ob-review is-own is-rateonly', 1)[1].split("</article>", 1)[0]
    assert "Only visible to you" in slot and 'href="#write-review"' in slot
    assert "ob-vote" not in slot and "ap-up" not in slot and "ap-dn" not in slot
    assert "<h3>Add your written review</h3>" in h                 # the form adds text to the same rating
    assert 'class="ob-prow is-hi is-lock" data-cat="org"' in h     # stars stay locked
    assert "uses <b>no review</b> from your quota" in h


def test_no_own_slot_for_guests_or_other_members(tmp_path):
    (tmp_path / "g").mkdir(); (tmp_path / "m").mkdir()
    assert "is-rateonly" not in render(tmp_path / "g", copy.deepcopy(PAID), viewer={"kind": "guest", "own_rating": {"ratings": {"org": 4}}})
    h = render(tmp_path / "m", copy.deepcopy(PAID), viewer=dict(MEMBER))
    assert "is-rateonly" not in h and "<h3>Write a review</h3>" in h
    assert "Stars-only ratings stay private to you" in h


def test_overall_number_sits_in_its_star_block(tmp_path):
    h = render(tmp_path, copy.deepcopy(PAID), viewer=dict(MEMBER, form_ratings={"org": 4, "flt": 5}))
    live = h.split('<div class="ob-live', 1)[1].split('<div class="ob-prow', 1)[0]
    assert re.search(r'<div class="ob-live-sc">.*pyr-line.*<b class="ob-live-num[^"]*">4\.5</b></div>', live, re.S)

def test_category_rows_show_the_chosen_star_number(tmp_path):
    h = render(tmp_path, copy.deepcopy(PAID), viewer=dict(MEMBER, form_ratings={"org": 4, "flt": 5}))
    form = h.split('id="write-review"', 1)[1]
    assert re.search(r'data-cat="org"[^>]*>.*?<b class="ob-cat-num is-sweep" aria-live="polite">4\.0</b>', form, re.S)
    assert re.search(r'data-cat="flt"[^>]*>.*?<b class="ob-cat-num is-sweep" aria-live="polite">5\.0</b>', form, re.S)
    assert re.search(r'data-cat="saf"[^>]*>.*?<b class="ob-cat-num" aria-live="polite">–</b>', form, re.S)
    # Safety culture is unrated; Organisation and Fleet carry the number to the right of the stars
    org = form.split('data-cat="org"', 1)[1].split('data-cat="flt"', 1)[0]
    assert org.index('class="ob-pick"') < org.index('class="ob-cat-num')


def test_own_rating_prefills_category_numbers_and_locks_them(tmp_path):
    v = dict(MEMBER, own_rating={"ratings": {"org": 4, "flt": 5, "ins": 3}, "published_at": "2026-11-09"})
    h = render(tmp_path, copy.deepcopy(PAID), viewer=v)
    form = h.split('id="write-review"', 1)[1]
    assert re.search(r'class="ob-prow is-hi is-lock" data-cat="org".*?<b class="ob-cat-num is-sweep" aria-live="polite">4\.0</b>', form, re.S)
    assert re.search(r'class="ob-prow is-lo is-lock" data-cat="ins".*?<b class="ob-cat-num is-lo" aria-live="polite">3\.0</b>', form, re.S)
    assert re.search(r'data-cat="saf"[^>]*>.*?<b class="ob-cat-num" aria-live="polite">–</b>', form, re.S)
