Quellcodebibliothek Statistik Leitseite products/Sources/formale Sprachen/C/Firefox/testing/web-platform/tests/resources/test/   (Browser von der Mozilla Stiftung Version 136.0.1©)  Datei vom 10.2.2025 mit Größe 9 kB image not shown  

Quelle  conftest.py   Sprache: Python

 
import copy
import json
import os
import ssl
import sys
import subprocess
import urllib

import html5lib
import py
import pytest

from wptserver import WPTServer

HERE = os.path.dirname(os.path.abspath(__file__))
WPT_ROOT = os.path.normpath(os.path.join(HERE, '..''..'))
HARNESS = os.path.join(HERE, 'harness.html')
TEST_TYPES = ('functional''unit')

sys.path.insert(0, os.path.normpath(os.path.join(WPT_ROOT, "tools")))
import localpaths

sys.path.insert(0, os.path.normpath(os.path.join(WPT_ROOT, "tools""webdriver")))
import webdriver


def pytest_addoption(parser):
    parser.addoption("--binary", action="store", default=None, help="path to browser binary")
    parser.addoption("--headless", action="store_true", default=False, help="run browser in headless mode")


def pytest_collect_file(file_path, path, parent):
    if file_path.suffix.lower() != '.html':
        return

    # Tests are organized in directories by type
    test_type = os.path.relpath(str(file_path), HERE)
    if os.path.sep not in test_type or ".." in test_type:
        # HTML files in this directory are not tests
        return
    test_type = test_type.split(os.path.sep)[1]

    return HTMLFile.from_parent(parent, path=file_path, test_type=test_type)


def pytest_configure(config):
    config.proc = subprocess.Popen(["geckodriver"])
    config.add_cleanup(config.proc.kill)

    capabilities = {"alwaysMatch": {"acceptInsecureCerts"True"moz:firefoxOptions": {}}}
    if config.getoption("--binary"):
        capabilities["alwaysMatch"]["moz:firefoxOptions"]["binary"] = config.getoption("--binary")
    if config.getoption("--headless"):
        capabilities["alwaysMatch"]["moz:firefoxOptions"]["args"] = ["--headless"]

    config.driver = webdriver.Session("localhost", 4444,
                                      capabilities=capabilities)
    config.add_cleanup(config.driver.end)

    # Although the name of the `_create_unverified_context` method suggests
    # that it is not intended for external consumption, the standard library's
    # documentation explicitly endorses its use:
    #
    # > To revert to the previous, unverified, behavior
    # > ssl._create_unverified_context() can be passed to the context
    # > parameter.
    #
    https://docs.python.org/2/library/httplib.html#httplib.HTTPSConnection
    config.ssl_context = ssl._create_unverified_context()

    config.server = WPTServer(WPT_ROOT)
    config.server.start(config.ssl_context)
    config.add_cleanup(config.server.stop)


def resolve_uri(context, uri):
    if uri.startswith('/'):
        base = WPT_ROOT
        path = uri[1:]
    else:
        base = os.path.dirname(context)
        path = uri

    return os.path.exists(os.path.join(base, path))


def _summarize(actual):
    def _scrub_stack(test_obj):
        copy = dict(test_obj)
        del copy['stack']
        return copy

    def _expand_status(status_obj):
        for key, value in [item for item in status_obj.items()]:
            # In "status" and "test" objects, the "status" value enum
            # definitions are interspersed with properties for unrelated
            # metadata. The following condition is a best-effort attempt to
            # ignore non-enum properties.
            if key != key.upper() or not isinstance(value, int):
                continue

            del status_obj[key]

            if status_obj['status'] == value:
                status_obj[u'status_string'] = key

        del status_obj['status']

        return status_obj

    def _summarize_test(test_obj):
        del test_obj['index']

        assert 'phase' in test_obj
        assert 'phases' in test_obj
        assert 'COMPLETE' in test_obj['phases']
        assert test_obj['phase'] == test_obj['phases']['COMPLETE']
        del test_obj['phases']
        del test_obj['phase']

        return _expand_status(_scrub_stack(test_obj))

    def _summarize_status(status_obj):
        return _expand_status(_scrub_stack(status_obj))


    summarized = {}

    summarized[u'summarized_status'] = _summarize_status(actual['status'])
    summarized[u'summarized_tests'] = [
        _summarize_test(test) for test in actual['tests']]
    summarized[u'summarized_tests'].sort(key=lambda test_obj: test_obj.get('name'))
    summarized[u'summarized_asserts'] = [
        {"assert_name": assert_item["assert_name"],
        "test": assert_item["test"]["name"if assert_item["test"else None,
        "args": assert_item["args"],
        "status": assert_item["status"]} for assert_item in actual["asserts"]]
    summarized[u'type'] = actual['type']

    return summarized


class HTMLFile(pytest.File):
    def __init__(self, test_type=None, **kwargs):
        super().__init__(**kwargs)
        self.test_type = test_type

    def collect(self):
        url = self.session.config.server.url(self.path)
        # Some tests are reliant on the WPT servers substitution functionality,
        # so tests must be retrieved from the server rather than read from the
        # file system directly.
        handle = urllib.request.urlopen(url,
                                        context=self.parent.session.config.ssl_context)
        try:
            markup = handle.read()
        finally:
            handle.close()

        if self.test_type not in TEST_TYPES:
            raise ValueError('Unrecognized test type: "%s"' % self.test_type)

        parsed = html5lib.parse(markup, namespaceHTMLElements=False)
        name = None
        expected = None

        for element in parsed.iter():
            if not name and element.tag == 'title':
                name = element.text
                continue
            if element.tag == 'script':
                if element.attrib.get('id') == 'expected':
                    try:
                        expected = json.loads(element.text)
                    except ValueError:
                        print("Failed parsing JSON in %s" % filename)
                        raise

        if not name:
            raise ValueError('No name found in %s add a element'</span> % filename)<br>         <span style='color:red'>elif</span> self.test_type == <span style='color:blue'>'functional'</span>:<br>             <span style='color:red'>if</span> <span style='color:red'>not</span> expected:<br>                 <span style='color:red'>raise</span> ValueError(<span style='color:blue'>'Functional tests must specify expected report data'</span>)<br>         <span style='color:red'>elif</span> self.test_type == <span style='color:blue'>'unit'</span> <span style='color:red'>and</span> expected:<br>             <span style='color:red'>raise</span> ValueError(<span style='color:blue'>'Unit tests must not specify expected report data'</span>)<br> <br>         <span style='color:red'>yield</span> HTMLItem.from_parent(self, name=name, url=url, expected=expected)<br> <br> <br> <span style='color:red'>class</span> HTMLItem(pytest.Item):<br>     <span style='color:red'>def</span> __init__(self, name, parent=<span style='color:red'>None</span>, config=<span style='color:red'>None</span>, session=<span style='color:red'>None</span>, nodeid=<span style='color:red'>None</span>, test_type<wbr>=<span style='color:red'>None</span>, url=<span style='color:red'>None</span>, expected=<span style='color:red'>None</span>, **kwargs):<br>         super().__init__(name, parent, config, session, nodeid, **kwargs)<br> <br>         self.test_type = self.parent.test_type<br>         self.url = url<br>         self.expected = expected<br> <br>     <span style='color:red'>def</span> reportinfo(self):<br>         <span style='color:red'>return</span> self.fspath, <span style='color:red'>None</span>, self.url<br> <br>     <span style='color:red'>def</span> runtest(self):<br>         <span style='color:red'>if</span> self.test_type == <span style='color:blue'>'unit'</span>:<br>             self._run_unit_test()<br>         <span style='color:red'>elif</span> self.test_type == <span style='color:blue'>'functional'</span>:<br>             self._run_functional_test()<br>         <span style='color:red'>else</span>:<br>             <span style='color:red'>raise</span> NotImplementedError<br> <br>     <span style='color:red'>def</span> _run_unit_test(self):<br>         driver = self.session.config.driver<br>         server = self.session.config.server<br> <br>         driver.url = server.url(HARNESS)<br> <br>         actual = driver.execute_async_script(<br>             <span style='color:blue'>'runTest("%s", "foo", arguments[0])'</span> % self.url<br>         )<br> <br>         summarized = _summarize(copy.deepcopy(actual))<br> <br>         print(json.dumps(summarized, indent=2))<br> <br>         <span style='color:red'>assert</span> summarized[u<span style='color:blue'>'summarized_status'</span>][u<span style='color:blue'>'status_string'</span>] == u<span style='color:blue'>'OK'</span>, summarized[u<span style='color:blue'>'sum<wbr>marized_status'</span>][u<span style='color:blue'>'message'</span>]<br>         <span style='color:red'>for</span> test <span style='color:red'>in</span> summarized[u<span style='color:blue'>'summarized_tests'</span>]:<br>             msg = <span style='color:blue'>"%s\n%s"</span> % (test[u<span style='color:blue'>'name'</span>], test[u<span style='color:blue'>'message'</span>])<br>             <span style='color:red'>assert</span> test[u<span style='color:blue'>'status_string'</span>] == u<span style='color:blue'>'PASS'</span>, msg<br> <br>     <span style='color:red'>def</span> _run_functional_test(self):<br>         driver = self.session.config.driver<br>         server = self.session.config.server<br> <br>         driver.url = server.url(HARNESS)<br> <br>         test_url = self.url<br>         actual = driver.execute_async_script(<span style='color:blue'>'runTest("%s", "foo", arguments[0])'</span> % test_url<wbr>)<br> <br>         print(json.dumps(actual, indent=2))<br> <br>         summarized = _summarize(copy.deepcopy(actual))<br> <br>         print(json.dumps(summarized, indent=2))<br> <br>         <span style='color:green'># Test object ordering is not guaranteed. This weak assertion verifies</span><br>         <span style='color:green'># that the indices are unique and sequential</span><br>         indices = [test_obj.get(<span style='color:blue'>'index'</span>) <span style='color:red'>for</span> test_obj <span style='color:red'>in</span> actual[<span style='color:blue'>'tests'</span>]]<br>         self._assert_sequence(indices)<br> <br>         self.expected[u<span style='color:blue'>'summarized_tests'</span>].sort(key=<span style='color:red'>lambda</span> test_obj: test_obj.get(<span style='color:blue'>'name'</span>))<br> <br>         <span style='color:green'># Make asserts opt-in for now</span><br>         <span style='color:red'>if</span> <span style='color:blue'>"summarized_asserts"</span> <span style='color:red'>not</span> <span style='color:red'>in</span> self.expected:<br>             <span style='color:red'>del</span> summarized[<span style='color:blue'>"summarized_asserts"</span>]<br>         <span style='color:red'>else</span>:<br>             <span style='color:green'># We can't be sure of the order of asserts even within the same test</span><br>             <span style='color:green'># although we could also check for the failing assert being the final</span><br>             <span style='color:green'># one</span><br>             <span style='color:red'>for</span> obj <span style='color:red'>in</span> [summarized, self.expected]:<br>                 obj[<span style='color:blue'>"summarized_asserts"</span>].sort(<br>                     key=<span style='color:red'>lambda</span> x: (x[<span style='color:blue'>"test"</span>] <span style='color:red'>or</span> <span style='color:blue'>""</span>, x[<span style='color:blue'>"status"</span>], x[<span style='color:blue'>"assert_name"</span>], tuple(x[<span style='color:blue'>"args"</span>])))<br> <br>         <span style='color:red'>assert</span> summarized == self.expected<br> <br>     @staticmethod<br>     <span style='color:red'>def</span> _assert_sequence(nums):<br>         <span style='color:red'>if</span> nums <span style='color:red'>and</span> len(nums) > 0:<br>             <span style='color:red'>assert</span> nums == list(range(1, nums[-1] + 1))<br> </div><div align=center><br><table border=1 style='border: 1px solid black; border-collapse: collapse;'><tr><th colspan=3>Messung V0.5</th></tr><tr><td> <svg height='38' width='38' > <circle cx='19' cy='19' r='16' stroke='grey' fill='purple' fill-opacity='30%' stroke-linecap='round' stroke-width='3' stroke-dasharray='360' stroke-dashoffset='43' /> <text x='12' y='22' fill='red' font-size=6>C=94</text> </svg> </td><td> <svg height='38' width='38' > <circle cx='19' cy='19' r='16' stroke='grey' fill='purple' fill-opacity='30%' stroke-linecap='round' stroke-width='3' stroke-dasharray='360' stroke-dashoffset='14' /> <text x='12' y='22' fill='red' font-size=6>H=98</text> </svg> </td><td> <svg height='56' width='56' > <circle cx='28' cy='28' r='24' stroke='green' fill='purple' fill-opacity='30%' stroke-linecap='round' stroke-width='4' stroke-dasharray='360' stroke-dashoffset='36' /> <text x='18' y='32' fill='red' font-size=8>G=95</text> </svg> </td></tr></table></div></span><br> <h3><b>¤</b> Dauer der Verarbeitung: 0.4 Sekunden  <b>¤</b></h3> <p height="2" colspan="2" align="center"><span style="font-size: 3px;">*© Formatika GbR, Deutschland</span></p> </div> </td> <td valign="top" align="center" class="greenscreensmall"> <br><br><br> <br> <table width="20%"> <tr><td align="center"> <a href="mobile.jsp?content=directory"> <br>Wurzel<br> <img border="0" src="/Images/penguin.jpg" height=36 alt="" title="Wurzel"> </a> </td> </tr> <tr><td align="center"> <a href="mobile.jsp?content=search" title="Suchen"> <br>Suchen<br> <img src="/Images/find.png" height="48" alt="" border="0"> </a> </td> </tr> <tr><td align="left"><a href="mobile.jsp?content=directory&detail=products/Sources/formale%20Sprachen/PVS/" title="Projekt "><br>Beweissystem der NASA</a></td></tr> <tr><td align="left"><a href="mobile.jsp?content=directory&detail=products/Sources/formale%20Sprachen/Isabelle/" title="Projekt "><br>Beweissystem Isabelle</a></td></tr> <tr><td align="left"><a href="mobile.jsp?content=directory&detail=products/Sources/formale%20Sprachen/Cobol/Test-Suite/" title="Projekt "><br>NIST Cobol Testsuite</a></td></tr> <tr><td align="left"><a href="mobile.jsp?content=directory&detail=products/Sources/formale%20Sprachen/Fortran/f90gl-1.2.15/" title="Projekt "><br>Cephes Mathematical Library</a></td></tr> <tr><td align="left"><a href="mobile.jsp?content=directory&detail=products/Sources/formale%20Sprachen/VDM/" title="Projekt "><br>Wiener Entwicklungsmethode</a></td></tr> <tr><td align="center"> <br> <h2>Haftungshinweis</h2> <div align="justify" class="featuresmall">Die Informationen auf dieser Webseite wurden nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit, noch Qualität der bereit gestellten Informationen zugesichert.</div> <br> <h2>Bemerkung:</h2> <div align="justify" class="featuresmall"> Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.</div> <br> </td> </tr> </table> <br><br> <div> <br> <script src="https://formatika.de/base/formcheck.js"></script> <script> function checkform(form) { var res = true; res = res && isnotempty(form.file); res = res && isurl(form.file); return res; } </script> </div><br> <br> </td> </tr> </table> </div> <div class="printelement"> <script> warningpreview(); </script> </div> <p align=right class=hidden>2026-04-02</p> </td></tr> </table> </body> </html>