Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / html / tests_html_structure.lucb

#==============================================================================================
#
#   tests_html_structure - region r26 against the reference build: source sets, tables, lists
#
#   DESCRIPTION:
#       Runs the cases of tests_html_structure_cases (a local oracle's output: the reference
#       Ladybird build on the same inputs) through the port and compares:
#
#           srcset     parse_a_srcset_attribute: each source's URL and descriptor
#           select     the first img's select_an_image_source (sizes, picture sources, media
#                      and type) and its dimension attribute source
#           cors       cors_setting_attribute_from_keyword and the credentials mode
#           keyhash    ListOfAvailableImages::Key::hash
#           tablerows  a table's rows collection, sections, rowIndex/sectionRowIndex, cells,
#                      cellIndex, colSpan/rowSpan and col span
#           tableop    insertRow/deleteRow, caption/tHead/tFoot/tBody creation and deletion,
#                      insertCell/deleteCell, section rows, the setters' exceptions
#           ol         an ol's start, starting value and its li values
#           details    details exclusivity of a name group (waits for the CSP inline check)
#           title      the document's title and the title element's text
#           meta       http-equiv states
#           referrer   <meta name=referrer>'s policy (waits for region r28: the document's
#                      policy container)
#
#       The documents are tests_html_elements' (web_test_create_document's heap documents of
#       type HTML, parsed with scripting disabled, without a browsing context).
#
#==============================================================================================

# mark: Output helpers ==========================================================================

## Appends a string view.
func test_html_structure_put(builder: ak.StringBuilder*, text: ak.StringView):
    ak.string_builder_append_string_view(builder, text)

## A density as the oracle prints it: rounded millionths.
func test_html_structure_millionths(value: f64) -> i64:
    return i64(math.round(value * 1000000.0))

## The id attribute of an element.
func test_html_structure_id(element: DomElement*) -> ak.String:
    return dom_element_get_attribute_value(element, html_attribute_names_id)

## "exception <name>" of a pending DOMException.
func test_html_structure_put_exception(builder: ak.StringBuilder*):
    let name = test_html_take_dom_exception_name()
    ak.string_builder_append(builder, "exception ")
    test_html_structure_put(builder, ak.fly_string_bytes_as_string_view(&name))
    ak.string_builder_append(builder, "\n")

## Parses `op` ("name" or "name:index").
func test_html_structure_op(op: str) -> (ak.StringView, i32):
    let view = ak.sv(op)
    if let colon = ak.string_view_find_u8(&view, ':'):
        let index_view = ak.string_view_substring_view(&view, colon + 1)
        return (ak.string_view_substring_view_usize(&view, 0, colon), ak.string_view_to_number_i32(&index_view) else trap("an index"))
    return (view, 0)

# mark: Running a case ===========================================================================

## The port's output for one case, in the oracle's format.
func test_html_structure_run(realm: Realm*, test_case: const TestHtmlStructureCase*) -> ak.String:
    var out = ak.string_builder_new()
    let mode = test_case.mode
    if mode == "srcset":
        let set = html_parse_a_srcset_attribute(ak.sv(test_case.arguments[0]))
        for source in ak.vector_span_const(&set.m_sources):
            html_parser_append_string(&out, source.url)
            ak.string_builder_append(&out, "|")
            match source.descriptor:
                .empty: ak.string_builder_append(&out, "-")
                .html_image_source_pixel_density_descriptor_value(value):
                    ak.string_builder_append(&out, "x ")
                    test_html_elements_put_number(&out, test_html_structure_millionths(value.value))
                .html_image_source_width_descriptor_value(value):
                    ak.string_builder_append(&out, "w ")
                    test_html_elements_put_number(&out, (i64)value.value.m_value)
            ak.string_builder_append(&out, "\n")
    elif mode == "select":
        let document = test_html_elements_parse(realm, test_case.arguments[0])
        let img = as_html_image_element(test_html_elements_first(document, "img"))
        if let result = html_image_element_select_an_image_source(img):
            html_parser_append_string(&out, result.source.url)
            ak.string_builder_append(&out, " ")
            test_html_elements_put_number(&out, test_html_structure_millionths(result.pixel_density))
            ak.string_builder_append(&out, "\n")
        else:
            ak.string_builder_append(&out, "none\n")
        ak.string_builder_append(&out, "dimension source ")
        html_parser_append_fly_string(&out, dom_element_local_name(html_image_element_dimension_attribute_source(img)))
        ak.string_builder_append(&out, "\n")
    elif mode == "cors":
        var keyword: ak.String? = none
        if test_case.arguments[0] != "-":
            keyword = ak.string_from_str(test_case.arguments[0])
        let state = html_cors_setting_attribute_from_keyword(keyword)
        test_html_elements_put_number(&out, (i64)(i32)state)
        ak.string_builder_append(&out, " ")
        test_html_elements_put_number(&out, (i64)(i32)html_cors_settings_attribute_credentials_mode(state))
        ak.string_builder_append(&out, "\n")
    elif mode == "keyhash":
        let mode_view = ak.sv(test_case.arguments[1])
        let mode_number = ak.string_view_to_number_i32(&mode_view) else trap("a mode")
        var key = HtmlListOfAvailableImagesKey(url = ak.string_from_str(test_case.arguments[0]), mode = (HtmlCorsSettingAttribute)mode_number, origin = none, cached_hash = none)
        if test_case.arguments[2] != "-":
            let url = web_url.parser_basic_parse(ak.sv(test_case.arguments[2])) else trap("an origin URL")
            key.origin = web_url.url_origin(&url)
        test_html_elements_put_number(&out, (i64)html_list_of_available_images_key_hash(&key))
        ak.string_builder_append(&out, "\n")
    elif mode == "tablerows":
        let document = test_html_elements_parse(realm, test_case.arguments[0])
        let table = as_html_table_element(test_html_elements_first(document, "table"))
        ak.string_builder_append(&out, "caption 1" if html_table_element_caption(table) != none else "caption 0")
        ak.string_builder_append(&out, " thead 1" if html_table_element_t_head(table) != none else " thead 0")
        ak.string_builder_append(&out, " tfoot 1" if html_table_element_t_foot(table) != none else " tfoot 0")
        ak.string_builder_append(&out, " tbodies ")
        test_html_elements_put_number(&out, (i64)dom_html_collection_length(html_table_element_t_bodies(table)))
        ak.string_builder_append(&out, "\nrows")
        let rows = html_table_element_rows(table)
        for i in 0..<dom_html_collection_length(rows):
            ak.string_builder_append(&out, " ")
            html_parser_append_string(&out, test_html_structure_id(dom_html_collection_item(rows, i) else trap("a row")))
        ak.string_builder_append(&out, "\n")
        for node in dom_node_subtree(document.dom_node()):
            let row = as_if_html_table_row_element(node) else continue
            ak.string_builder_append(&out, "tr ")
            html_parser_append_string(&out, test_html_structure_id(row.dom_element()))
            ak.string_builder_append(&out, " ")
            test_html_elements_put_number(&out, (i64)html_table_row_element_row_index(row))
            ak.string_builder_append(&out, " ")
            test_html_elements_put_number(&out, (i64)html_table_row_element_section_row_index(row))
            ak.string_builder_append(&out, " cells ")
            test_html_elements_put_number(&out, (i64)dom_html_collection_length(html_table_row_element_cells(row)))
            ak.string_builder_append(&out, "\n")
        for node in dom_node_subtree(document.dom_node()):
            let cell = as_if_html_table_cell_element(node) else continue
            ak.string_builder_append(&out, "cell ")
            html_parser_append_string(&out, test_html_structure_id(cell.dom_element()))
            ak.string_builder_append(&out, " ")
            test_html_elements_put_number(&out, (i64)html_table_cell_element_cell_index(cell))
            ak.string_builder_append(&out, " ")
            test_html_elements_put_number(&out, (i64)html_table_cell_element_col_span(cell))
            ak.string_builder_append(&out, " ")
            test_html_elements_put_number(&out, (i64)html_table_cell_element_row_span(cell))
            ak.string_builder_append(&out, "\n")
        for node in dom_node_subtree(document.dom_node()):
            let col = as_if_html_table_col_element(node) else continue
            ak.string_builder_append(&out, "col ")
            test_html_elements_put_number(&out, (i64)html_table_col_element_span(col))
            ak.string_builder_append(&out, "\n")
        for node in dom_node_subtree(document.dom_node()):
            let section = as_if_html_table_section_element(node) else continue
            ak.string_builder_append(&out, "section ")
            html_parser_append_fly_string(&out, dom_element_local_name(section.dom_element()))
            ak.string_builder_append(&out, " rows ")
            test_html_elements_put_number(&out, (i64)dom_html_collection_length(html_table_section_element_rows(section)))
            ak.string_builder_append(&out, "\n")
    elif mode == "tableop":
        let document = test_html_elements_parse(realm, test_case.arguments[1])
        let table = as_html_table_element(test_html_elements_first(document, "table"))
        let (name, index) = test_html_structure_op(test_case.arguments[0])
        if not test_html_structure_table_op(document, table, name, index, &out):
            test_html_structure_put_exception(&out)
        test_html_elements_dump_node(&out, table.dom_node(), 0)
    elif mode == "ol":
        let document = test_html_elements_parse(realm, test_case.arguments[0])
        let ol = as_html_htmlo_list_element(test_html_elements_first(document, "ol"))
        ak.string_builder_append(&out, "start ")
        test_html_elements_put_number(&out, (i64)html_htmlo_list_element_start(ol))
        ak.string_builder_append(&out, " starting ")
        let starting = html_htmlo_list_element_starting_value(ol)
        test_html_elements_put_number(&out, (i64)ak.checked_value(&starting))
        ak.string_builder_append(&out, "\n")
        for node in dom_node_subtree(document.dom_node()):
            let li = as_if_html_htmlli_element(node) else continue
            ak.string_builder_append(&out, "li ")
            test_html_elements_put_number(&out, (i64)html_htmlli_element_value(li))
            ak.string_builder_append(&out, "\n")
    elif mode == "details":
        let document = test_html_elements_parse(realm, test_case.arguments[0])
        for node in dom_node_subtree(document.dom_node()):
            let details = as_if_html_details_element(node) else continue
            html_parser_append_string(&out, test_html_structure_id(details.dom_element()))
            ak.string_builder_append(&out, " open\n" if dom_element_has_attribute(details.dom_element(), html_attribute_names_open) else " closed\n")
    elif mode == "title":
        let document = test_html_elements_parse(realm, test_case.arguments[0])
        let title = dom_document_title(document)
        ak.string_builder_append(&out, "title [")
        html_parser_append_string(&out, ak.utf16_string_base_to_utf8(&title.utf16_string_base))
        ak.string_builder_append(&out, "]\ntext [")
        let text = html_title_element_text(as_html_title_element(test_html_elements_first(document, "title")))
        html_parser_append_string(&out, ak.utf16_string_base_to_utf8(&text.utf16_string_base))
        ak.string_builder_append(&out, "]\n")
    elif mode == "meta":
        let document = test_html_elements_parse(realm, test_case.arguments[0])
        for node in dom_node_subtree(document.dom_node()):
            let meta = as_if_html_meta_element(node) else continue
            ak.string_builder_append(&out, "http-equiv ")
            if let state = html_meta_element_http_equiv_state(meta):
                test_html_elements_put_number(&out, (i64)(i32)state)
            else:
                ak.string_builder_append(&out, "none")
            ak.string_builder_append(&out, "\n")
    elif mode == "referrer":
        let document = test_html_elements_parse(realm, test_case.arguments[0])
        ak.string_builder_append(&out, "referrer policy ")
        test_html_elements_put_number(&out, (i64)(i32)dom_document_policy_container(document).referrer_policy)
        ak.string_builder_append(&out, "\n")
    else:
        trap("unknown mode")
    return ak.string_builder_to_string_without_validation(&out)

## Runs one tableop operation; false when it threw (the DOMException is pending).
func test_html_structure_table_op(document: DomDocument*, table: HtmlTableElement*, name: ak.StringView, index: i32, out: ak.StringBuilder*) -> bool:
    if ak.string_view_equals(&name, "insertRow"):
        let row: HtmlTableRowElement*? = html_table_element_insert_row(table, index) catch: recover none
        return row != none
    if ak.string_view_equals(&name, "deleteRow"):
        var ok = true
        html_table_element_delete_row(table, index) catch:
            ok = false
        return ok
    if ak.string_view_equals(&name, "createCaption"):
        _ = html_table_element_create_caption(table)
    elif ak.string_view_equals(&name, "deleteCaption"):
        html_table_element_delete_caption(table)
    elif ak.string_view_equals(&name, "createTHead"):
        _ = html_table_element_create_t_head(table)
    elif ak.string_view_equals(&name, "deleteTHead"):
        html_table_element_delete_t_head(table)
    elif ak.string_view_equals(&name, "createTFoot"):
        _ = html_table_element_create_t_foot(table)
    elif ak.string_view_equals(&name, "deleteTFoot"):
        html_table_element_delete_t_foot(table)
    elif ak.string_view_equals(&name, "createTBody"):
        _ = html_table_element_create_t_body(table)
    elif ak.string_view_equals(&name, "insertCell"):
        let row = as_html_table_row_element(test_html_elements_first(document, "tr"))
        let cell: HtmlTableCellElement*? = html_table_row_element_insert_cell(row, index) catch: recover none
        return cell != none
    elif ak.string_view_equals(&name, "deleteCell"):
        let row = as_html_table_row_element(test_html_elements_first(document, "tr"))
        var ok = true
        html_table_row_element_delete_cell(row, index) catch:
            ok = false
        return ok
    elif ak.string_view_equals(&name, "sectionInsertRow"):
        let section = as_html_table_section_element(test_html_elements_first(document, "tbody"))
        let row: HtmlTableRowElement*? = html_table_section_element_insert_row(section, index) catch: recover none
        return row != none
    elif ak.string_view_equals(&name, "sectionDeleteRow"):
        let section = as_html_table_section_element(test_html_elements_first(document, "tbody"))
        var ok = true
        html_table_section_element_delete_row(section, index) catch:
            ok = false
        return ok
    elif ak.string_view_equals(&name, "setTHeadTFoot"):
        let tfoot = as_html_table_section_element(test_html_elements_first(document, "tfoot"))
        var ok = true
        html_table_element_set_t_head(table, tfoot) catch:
            ok = false
        return ok
    elif ak.string_view_equals(&name, "setCaptionNull"):
        var ok = true
        html_table_element_set_caption(table, none) catch:
            ok = false
        return ok
    elif ak.string_view_equals(&name, "setColSpan"):
        let cell = as_html_table_cell_element(test_html_elements_first(document, "td"))
        html_table_cell_element_set_col_span(cell, (u32)index)
        ak.string_builder_append(out, "colspan ")
        test_html_elements_put_number(out, (i64)html_table_cell_element_col_span(cell))
        ak.string_builder_append(out, "\n")
    else:
        ak.string_builder_append(out, "unknown op\n")
    return true

## Runs every case of `mode`, printing each mismatch, and fails if any.
func test_html_structure_run_mode(mode: str):
    web_initialize_strings()
    let (vm, realm) = web_test_create_vm_and_settings_realm()
    defer web_test_destroy_vm(vm)
    var failures = 0
    var count = 0
    # The documents and their trees live in the VM's heap (the test's own allocator is a small
    # fixed buffer).
    let allocator: memory.Allocator = vm_heap(vm)
    with allocator:
        for test_case in &test_html_structure_cases:
            if test_case.mode != mode:
                continue
            count += 1
            let actual = test_html_structure_run(realm, test_case)
            if ak.string_eq_string_view(&actual, ak.sv(test_case.expected)):
                continue
            failures += 1
            let view = ak.string_bytes_as_string_view(&actual)
            print(f"{mode} {test_case.arguments[0]} {test_case.arguments[1]} {test_case.arguments[2]}\nexpected:\n{test_case.expected}actual:\n{(str)ak.string_view_bytes(&view)}")
    assert(count > 0, "no cases of the mode")
    assert(failures == 0, "cases differ from the reference build")

# mark: Oracle tests =============================================================================

test "parse a srcset attribute: URLs, descriptors and parse errors as the reference build":
    test_html_structure_run_mode("srcset")

test "select an image source: srcset, sizes, picture sources (media, type, dimensions) and src":
    test_html_structure_run_mode("select")

test "CORS settings attribute: keyword states and their credentials modes":
    test_html_structure_run_mode("cors")

test "ListOfAvailableImages keys hash as the reference build (URL, mode, origin)":
    test_html_structure_run_mode("keyhash")

test "tables: rows collection order, sections, row and cell indices, colSpan/rowSpan and col span":
    test_html_structure_run_mode("tablerows")

test "table operations: rows, cells, caption/tHead/tFoot/tBody and their DOMExceptions":
    test_html_structure_run_mode("tableop")

test "ordered lists: start, the starting value and li values":
    test_html_structure_run_mode("ol")

test "title: the document's title and the title element's text":
    test_html_structure_run_mode("title")

test "meta: http-equiv states":
    test_html_structure_run_mode("meta")