|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Test suite for the method to sort annotated text with css selector pairs""" |
| 3 | +from ..html_tools import html_to_annotated_text, sort_annotated_text_by_selectors |
| 4 | + |
| 5 | +def test_sort_annotated_text(): |
| 6 | + # Minimal HTML: two 'outer' divs, each containing 'inner' spans |
| 7 | + # that have a 'name' child. The ordering is B,A and D,C so we |
| 8 | + # expect it to become A,B and C,D after sorting by name text. |
| 9 | + test_html = """ |
| 10 | + <html> |
| 11 | + <body> |
| 12 | + <div class="outer"> |
| 13 | + <span class="inner">Y-Item <span class="name">B</span></span> |
| 14 | + <span class="inner">Z-Item <span class="name">A</span></span> |
| 15 | + </div> |
| 16 | + <div class="outer"> |
| 17 | + <span class="inner">W-Item <span class="name">D</span></span> |
| 18 | + <span class="inner">X-Item <span class="name">C</span></span> |
| 19 | + </div> |
| 20 | + </body> |
| 21 | + </html> |
| 22 | + """ |
| 23 | + |
| 24 | + # Annotation rules: outer, inner, name |
| 25 | + test_annotation_rules = \ |
| 26 | + { |
| 27 | + "div[class*='outer']": ["outer"], |
| 28 | + "span[class*='inner']": ["inner"], |
| 29 | + "span[class*='name']": ["name"] |
| 30 | + } |
| 31 | + |
| 32 | + # Convert HTML to annotated text |
| 33 | + annotated_xml = html_to_annotated_text( |
| 34 | + test_html, |
| 35 | + test_annotation_rules |
| 36 | + ) |
| 37 | + |
| 38 | + # We'll test the same sorting logic with three different selector approaches: |
| 39 | + # 1) CSS |
| 40 | + # 2) XPath (note the second part is .// to stay within context) |
| 41 | + # 3) xpath1 |
| 42 | + selector_groups = [ |
| 43 | + [("outer", ""), ("outer > inner", "name")], # CSS direct child |
| 44 | + [("//outer", ""), ("//inner", "xpath:.//name")], # XPath |
| 45 | + [("xpath1://outer", ""), ("xpath1://outer/inner", "xpath1:.//name")] # xpath1 |
| 46 | + ] |
| 47 | + |
| 48 | + # The expected order after sorting each 'outer' group by its 'name' text: |
| 49 | + # First <div.outer>: (A, B) instead of (B, A) |
| 50 | + # Second <div.outer>: (C, D) instead of (D, C) |
| 51 | + expected_annotated_xml = ( |
| 52 | + '<text><outer><inner>Z-Item<name>A</name></inner>\n' |
| 53 | + '<inner>Y-Item<name>B</name></inner></outer><outer><inner>X-Item<name>C</name></inner>\n' |
| 54 | + '<inner>W-Item<name>D</name></inner></outer></text>' |
| 55 | + ) |
| 56 | + |
| 57 | + # Check sorting with each selector approach: |
| 58 | + for selectors in selector_groups: |
| 59 | + sorted_annotated_xml = sort_annotated_text_by_selectors(annotated_xml, selectors) |
| 60 | + |
| 61 | + assert sorted_annotated_xml == expected_annotated_xml, ( |
| 62 | + f"Sorting failed for selectors: {selectors}\n" |
| 63 | + f"Got:\n{sorted_annotated_xml}\n" |
| 64 | + f"Expected:\n{expected_annotated_xml}" |
| 65 | + ) |
0 commit comments