summaryrefslogtreecommitdiffstats
path: root/testing/mochitest/tests/python/conftest.py
blob: e418dfb8164ff525ad7adfae29ea6d23668ddf33 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import json
import os
from argparse import Namespace

import mozinfo
import pytest
import six
from manifestparser import TestManifest, expression
from moztest.selftest.fixtures import binary_fixture, setup_test_harness  # noqa

here = os.path.abspath(os.path.dirname(__file__))
setup_args = [os.path.join(here, "files"), "mochitest", "testing/mochitest"]


@pytest.fixture
def create_manifest(tmpdir, build_obj):
    def inner(string, name="manifest.ini"):
        manifest = tmpdir.join(name)
        manifest.write(string, ensure=True)
        # pylint --py3k: W1612
        path = six.text_type(manifest)
        return TestManifest(manifests=(path,), strict=False, rootdir=tmpdir.strpath)

    return inner


@pytest.fixture(scope="function")
def parser(request):
    parser = pytest.importorskip("mochitest_options")

    app = getattr(request.module, "APP", "generic")
    return parser.MochitestArgumentParser(app=app)


@pytest.fixture(scope="function")
def runtests(setup_test_harness, binary, parser, request):
    """Creates an easy to use entry point into the mochitest harness.

    :returns: A function with the signature `*tests, **opts`. Each test is a file name
              (relative to the `files` dir). At least one is required. The opts are
              used to override the default mochitest options, they are optional.
    """
    flavor = "plain"
    if "flavor" in request.fixturenames:
        flavor = request.getfixturevalue("flavor")

    runFailures = ""
    if "runFailures" in request.fixturenames:
        runFailures = request.getfixturevalue("runFailures")

    setup_test_harness(*setup_args, flavor=flavor)

    runtests = pytest.importorskip("runtests")

    mochitest_root = runtests.SCRIPT_DIR
    if flavor == "plain":
        test_root = os.path.join(mochitest_root, "tests", "selftests")
        manifest_name = "mochitest.ini"
    elif flavor == "browser-chrome":
        test_root = os.path.join(mochitest_root, "browser", "tests", "selftests")
        manifest_name = "browser.ini"
    else:
        raise Exception(f"Invalid flavor {flavor}!")

    # pylint --py3k: W1648
    buf = six.StringIO()
    options = vars(parser.parse_args([]))
    options.update(
        {
            "app": binary,
            "flavor": flavor,
            "runFailures": runFailures,
            "keep_open": False,
            "log_raw": [buf],
        }
    )

    if runFailures == "selftest":
        options["crashAsPass"] = True
        options["timeoutAsPass"] = True
        runtests.mozinfo.update({"selftest": True})

    if not os.path.isdir(runtests.build_obj.bindir):
        package_root = os.path.dirname(mochitest_root)
        options.update(
            {
                "certPath": os.path.join(package_root, "certs"),
                "utilityPath": os.path.join(package_root, "bin"),
            }
        )
        options["extraProfileFiles"].append(
            os.path.join(package_root, "bin", "plugins")
        )

    options.update(getattr(request.module, "OPTIONS", {}))

    def normalize(test):
        return {
            "name": test,
            "relpath": test,
            "path": os.path.join(test_root, test),
            # add a dummy manifest file because mochitest expects it
            "manifest": os.path.join(test_root, manifest_name),
            "manifest_relpath": manifest_name,
            "skip-if": runFailures,
        }

    def inner(*tests, **opts):
        assert len(tests) > 0

        # Inject a TestManifest in the runtests option if one
        # has not been already included by the caller.
        if not isinstance(options["manifestFile"], TestManifest):
            manifest = TestManifest()
            options["manifestFile"] = manifest
            # pylint --py3k: W1636
            manifest.tests.extend(list(map(normalize, tests)))
            options.update(opts)

        result = runtests.run_test_harness(parser, Namespace(**options))
        out = json.loads("[" + ",".join(buf.getvalue().splitlines()) + "]")
        buf.close()
        return result, out

    return inner


@pytest.fixture
def build_obj(setup_test_harness):
    setup_test_harness(*setup_args)
    mochitest_options = pytest.importorskip("mochitest_options")
    return mochitest_options.build_obj


@pytest.fixture(autouse=True)
def skip_using_mozinfo(request, setup_test_harness):
    """Gives tests the ability to skip based on values from mozinfo.

    Example:
        @pytest.mark.skip_mozinfo("!e10s || os == 'linux'")
        def test_foo():
            pass
    """

    setup_test_harness(*setup_args)
    runtests = pytest.importorskip("runtests")
    runtests.update_mozinfo()

    skip_mozinfo = request.node.get_closest_marker("skip_mozinfo")
    if skip_mozinfo:
        value = skip_mozinfo.args[0]
        if expression.parse(value, **mozinfo.info):
            pytest.skip("skipped due to mozinfo match: \n{}".format(value))