Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / loader / tests_loader_1.lucb

#==============================================================================================
#
#   tests_loader_1 - region p2d's functions against the reference build's results
#
#   DESCRIPTION:
#       The donor has no unit tests for Loader/, PotentialCORSRequest or PreloadEntry. This
#       runs the cases of tests_loader_cases (a local oracle over the reference build):
#       AsciiStringMatcher and ContentFilter, ProxyMappings, create_potential_CORS_request,
#       translate_a_preload_destination, Traits<PreloadKey>::hash, the MIME type of a file
#       name, network error strings, the user agent (on macOS arm64, the oracle's target), the
#       Last-Modified header of a file and the generated error page over the repository's
#       templates (data/res).
#
#==============================================================================================

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

## A URL the case table names.
func loader_test_url(text: str) -> web_url.Url:
    return web_url.parser_basic_parse(ak.sv(text)) else trap("a case's URL parses")

## The patterns of a case: `text` split at '|' (none when empty).
func loader_test_patterns(text: str) -> ak.Vector[ak.String]:
    var patterns: ak.Vector[ak.String]
    if text.length == 0:
        return patterns
    var start: usize = 0
    for index in 0..<text.length + 1:
        if index == text.length or text.bytes[index] == '|':
            ak.vector_append_t(&patterns, ak.string_from_utf8(ak.string_view_from_bytes(text.bytes[start..<index])) else trap("a pattern"))
            start = index + 1
    return patterns

## A decimal argument of the case table.
func loader_test_number(text: str) -> i64:
    var negative = false
    var value: i64 = 0
    for byte in text.bytes:
        if byte == '-':
            negative = true
        else:
            value = value * 10 + (i64)(byte - '0')
    return -value if negative else value

## Appends a decimal number.
func loader_test_append_number(builder: ak.StringBuilder*, value: i64):
    let text = ak.string_number_i64(value)
    ak.string_builder_append_string_view(builder, ak.string_bytes_as_string_view(&text))

## Runs one case and answers its result as the oracle prints it.
func loader_test_run(vm: Vm*, test_case: const LoaderCase*) -> ak.String:
    var builder = ak.string_builder_new()
    let op = test_case.op
    if op == "contains":
        let patterns = loader_test_patterns(test_case.a)
        var matcher = AsciiStringMatcher()
        ascii_string_matcher_construct(&matcher, ak.vector_span_const(&patterns))
        ak.string_builder_append(&builder, "true" if ascii_string_matcher_contains(&matcher, ak.sv(test_case.b)) else "false")
    elif op == "filtered":
        let filter = content_filter_the()
        let patterns = loader_test_patterns("ads.|tracker")
        content_filter_set_patterns(filter, ak.vector_span_const(&patterns)) else trap("set_patterns")
        content_filter_set_filtering_enabled(filter, test_case.a == "enabled")
        ak.string_builder_append(&builder, "true" if content_filter_is_filtered(filter, loader_test_url(test_case.b)) else "false")
    elif op == "proxy":
        let proxy = proxy_mappings_proxy_for_url(proxy_mappings_the(), loader_test_url(test_case.a))
        loader_test_append_number(&builder, (i64)proxy.type_)
        ak.string_builder_append(&builder, " ")
        let host = ak.i_pv4_address_to_byte_string(&proxy.host_ipv4)
        ak.string_builder_append_string_view(&builder, ak.byte_string_view(&host))
        ak.string_builder_append(&builder, " ")
        loader_test_append_number(&builder, (i64)proxy.port)
    elif op == "cors":
        var destination: FetchRequestDestination? = none
        if test_case.a != "none":
            destination = (FetchRequestDestination)loader_test_number(test_case.a)
        let request = html_create_potential_cors_request(vm, loader_test_url("https://example.com/a.png"), destination,
                                                         (HtmlCorsSettingAttribute)loader_test_number(test_case.b), (HtmlSameOriginFallbackFlag)loader_test_number(test_case.c))
        loader_test_append_number(&builder, (i64)fetch_request_mode(request))
        ak.string_builder_append(&builder, " ")
        loader_test_append_number(&builder, (i64)fetch_request_credentials_mode(request))
        ak.string_builder_append(&builder, " true " if fetch_request_use_url_credentials(request) else " false ")
        if let request_destination = fetch_request_destination(request):
            loader_test_append_number(&builder, (i64)request_destination)
        else:
            ak.string_builder_append(&builder, "-1")
        ak.string_builder_append(&builder, " ")
        let url = fetch_request_url(request)
        let serialized = web_url.url_serialize(&url)
        ak.string_builder_append_string_view(&builder, ak.string_bytes_as_string_view(&serialized))
    elif op == "translate":
        var argument: ak.String? = none
        if test_case.a != "(null)":
            argument = ak.string_from_str(test_case.a)
        match html_translate_a_preload_destination(argument):
            .empty:
                ak.string_builder_append(&builder, "empty")
            .destination(value):
                if let translated = value:
                    loader_test_append_number(&builder, (i64)translated)
                else:
                    ak.string_builder_append(&builder, "none")
    elif op == "preload_hash":
        var destination: FetchRequestDestination? = none
        let destination_value = loader_test_number(test_case.b)
        if destination_value >= 0:
            destination = (FetchRequestDestination)destination_value
        let mode_and_credentials = test_case.c
        let key = HtmlPreloadKey(url = loader_test_url(test_case.a), destination = destination, mode = (FetchRequestMode)(mode_and_credentials.bytes[0] - '0'),
                                 credentials_mode = (FetchRequestCredentialsMode)(mode_and_credentials.bytes[2] - '0'))
        loader_test_append_number(&builder, (i64)html_preload_key_traits_hash(&key))
    elif op == "mime":
        ak.string_builder_append_string_view(&builder, core_guess_mime_type_based_on_filename(ak.sv(test_case.a)))
    elif op == "network_error":
        ak.string_builder_append_string_view(&builder, requests_network_error_to_string((RequestsNetworkError)loader_test_number(test_case.a)))
    elif op == "user_agent":
        ak.string_builder_append(&builder, default_user_agent)
    elif op == "platform":
        ak.string_builder_append(&builder, default_platform)
    elif op == "last_modified":
        let headers = response_headers_for_file(ak.sv("/tmp/x.txt"), loader_test_number(test_case.a))
        let value = http_header_list_get(headers, ak.sv("Last-Modified")) else trap("a Last-Modified header")
        ak.string_builder_append_string_view(&builder, ak.byte_string_view(&value))
    elif op == "error_page":
        let page = load_error_page(loader_test_url(test_case.a), ak.sv(test_case.b)) else trap("load_error_page")
        ak.string_builder_append_string_view(&builder, ak.string_bytes_as_string_view(&page))
    else:
        trap("an unknown case operation")
    return ak.string_builder_to_string(&builder) else trap("a case's result")

## Whether a case runs on this target: the user agent and the platform are macOS arm64's.
func loader_test_runs_here(test_case: const LoaderCase*) -> bool:
    if test_case.op == "user_agent" or test_case.op == "platform":
        return os.macos and os.arm64
    return true

## The proxy mappings of the oracle's ProxyMappings case.
func loader_test_install_proxy_mappings():
    var proxies: ak.Vector[ak.ByteString]
    let urls: str[4] = ["socks5://127.0.0.1:1080", "http://10.0.0.1:3128", "socks5://localhost:9050", "socks5://10.1.2.3"]
    for url in urls:
        ak.vector_append_t(&proxies, ak.byte_string_from_str(url))
    var mappings: ak.OrderedHashMap[ak.ByteString, u64, ByteStringTraits]
    _ = ak.ordered_hash_map_set(&mappings, ak.byte_string_from_str("*://*.onion/*"), 2)
    _ = ak.ordered_hash_map_set(&mappings, ak.byte_string_from_str("*example.com*"), 0)
    _ = ak.ordered_hash_map_set(&mappings, ak.byte_string_from_str("*://insecure.test/*"), 1)
    _ = ak.ordered_hash_map_set(&mappings, ak.byte_string_from_str("*://noport.test/*"), 3)
    _ = ak.ordered_hash_map_set(&mappings, ak.byte_string_from_str("*"), 0)
    proxy_mappings_set_mappings(proxy_mappings_the(), proxies, mappings)

## The process-wide loader state the cases change, back to its default: no patterns, filtering on, no proxies.
func loader_test_reset_globals():
    let empty = ak.Vector[ak.String]()
    content_filter_set_patterns(content_filter_the(), ak.vector_span_const(&empty)) else trap("set_patterns")
    content_filter_set_filtering_enabled(content_filter_the(), true)
    proxy_mappings_set_mappings(proxy_mappings_the(), ak.Vector[ak.ByteString](), ak.OrderedHashMap[ak.ByteString, u64, ByteStringTraits]())

## The repository's resources (data/res) as resource://, as the tests' embedder installs them.
func loader_test_install_resources():
    core_resource_implementation_install(core_resource_implementation_file_create(ak.sv("data/res")))

# mark: The cases ===============================================================================

test "loader: the reference build's matcher, filter, proxies, CORS requests, preload keys, MIME types, errors and error page":
    let vm = web_test_create_vm()
    defer web_test_destroy_vm(vm)
    loader_test_install_resources()
    loader_test_install_proxy_mappings()
    defer loader_test_reset_globals()
    var failures: usize = 0
    var checked: usize = 0
    for index in 0..<loader_cases.length:
        let test_case = &loader_cases[index]
        if not loader_test_runs_here(test_case):
            continue
        checked += 1
        let result = loader_test_run(vm, test_case)
        let result_view = ak.string_bytes_as_string_view(&result)
        if not ak.string_view_equals(&result_view, test_case.expected):
            failures += 1
            print(f"loader case {index} ({test_case.op} {test_case.a} {test_case.b} {test_case.c}):\n  expected {test_case.expected}\n  got      {ak.string_view_text(result_view)}")
    print(f"loader cases: {checked - failures} passed, {failures} failed")
    assert(failures == 0)