Python pytest.File() Examples

The following are 17 code examples of pytest.File(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pytest , or try the search function .
Example #1
Source File: test_collection.py    From pytest with MIT License 6 votes vote down vote up
def test_getcustomfile_roundtrip(self, testdir):
        hello = testdir.makefile(".xxx", hello="world")
        testdir.makepyfile(
            conftest="""
            import pytest
            class CustomFile(pytest.File):
                pass
            def pytest_collect_file(path, parent):
                if path.ext == ".xxx":
                    return CustomFile.from_parent(fspath=path, parent=parent)
        """
        )
        node = testdir.getpathnode(hello)
        assert isinstance(node, pytest.File)
        assert node.name == "hello.xxx"
        nodes = node.session.perform_collect([node.nodeid], genitems=False)
        assert len(nodes) == 1
        assert isinstance(nodes[0], pytest.File) 
Example #2
Source File: test_collection.py    From pytest with MIT License 6 votes vote down vote up
def test_custom_repr_failure(self, testdir):
        p = testdir.makepyfile(
            """
            import not_exists
        """
        )
        testdir.makeconftest(
            """
            import pytest
            def pytest_collect_file(path, parent):
                return MyFile(path, parent)
            class MyError(Exception):
                pass
            class MyFile(pytest.File):
                def collect(self):
                    raise MyError()
                def repr_failure(self, excinfo):
                    if excinfo.errisinstance(MyError):
                        return "hello world"
                    return pytest.File.repr_failure(self, excinfo)
        """
        )

        result = testdir.runpytest(p)
        result.stdout.fnmatch_lines(["*ERROR collecting*", "*hello world*"]) 
Example #3
Source File: test_collection.py    From pytest with MIT License 6 votes vote down vote up
def test_fscollector_from_parent(tmpdir, request):
    """Ensure File.from_parent can forward custom arguments to the constructor.

    Context: https://github.com/pytest-dev/pytest-cpp/pull/47
    """

    class MyCollector(pytest.File):
        def __init__(self, fspath, parent, x):
            super().__init__(fspath, parent)
            self.x = x

        @classmethod
        def from_parent(cls, parent, *, fspath, x):
            return super().from_parent(parent=parent, fspath=fspath, x=x)

    collector = MyCollector.from_parent(
        parent=request.session, fspath=tmpdir / "foo", x=10
    )
    assert collector.x == 10 
Example #4
Source File: conftest.py    From pytest with MIT License 6 votes vote down vote up
def dummy_yaml_custom_test(testdir):
    """Writes a conftest file that collects and executes a dummy yaml test.

    Taken from the docs, but stripped down to the bare minimum, useful for
    tests which needs custom items collected.
    """
    testdir.makeconftest(
        """
        import pytest

        def pytest_collect_file(parent, path):
            if path.ext == ".yaml" and path.basename.startswith("test"):
                return YamlFile(path, parent)

        class YamlFile(pytest.File):
            def collect(self):
                yield YamlItem(self.fspath.basename, self)

        class YamlItem(pytest.Item):
            def runtest(self):
                pass
    """
    )
    testdir.makefile(".yaml", test1="") 
Example #5
Source File: test_resultlog.py    From pytest with MIT License 6 votes vote down vote up
def test_failure_issue380(testdir):
    testdir.makeconftest(
        """
        import pytest
        class MyCollector(pytest.File):
            def collect(self):
                raise ValueError()
            def repr_failure(self, excinfo):
                return "somestring"
        def pytest_collect_file(path, parent):
            return MyCollector(parent=parent, fspath=path)
    """
    )
    testdir.makepyfile(
        """
        def test_func():
            pass
    """
    )
    result = testdir.runpytest("--resultlog=log")
    assert result.ret == 2 
Example #6
Source File: acceptance_test.py    From pytest with MIT License 6 votes vote down vote up
def test_early_hook_error_issue38_1(self, testdir):
        testdir.makeconftest(
            """
            def pytest_sessionstart():
                0 / 0
        """
        )
        result = testdir.runpytest(testdir.tmpdir)
        assert result.ret != 0
        # tracestyle is native by default for hook failures
        result.stdout.fnmatch_lines(
            ["*INTERNALERROR*File*conftest.py*line 2*", "*0 / 0*"]
        )
        result = testdir.runpytest(testdir.tmpdir, "--fulltrace")
        assert result.ret != 0
        # tracestyle is native by default for hook failures
        result.stdout.fnmatch_lines(
            ["*INTERNALERROR*def pytest_sessionstart():*", "*INTERNALERROR*0 / 0*"]
        ) 
Example #7
Source File: acceptance_test.py    From pytest with MIT License 6 votes vote down vote up
def test_multiple_items_per_collector_byid(self, testdir):
        c = testdir.makeconftest(
            """
            import pytest
            class MyItem(pytest.Item):
                def runtest(self):
                    pass
            class MyCollector(pytest.File):
                def collect(self):
                    return [MyItem(name="xyz", parent=self)]
            def pytest_collect_file(path, parent):
                if path.basename.startswith("conftest"):
                    return MyCollector(path, parent)
        """
        )
        result = testdir.runpytest(c.basename + "::" + "xyz")
        assert result.ret == 0
        result.stdout.fnmatch_lines(["*1 pass*"]) 
Example #8
Source File: capture.py    From python-netsurv with MIT License 5 votes vote down vote up
def pytest_make_collect_report(self, collector):
        if isinstance(collector, pytest.File):
            self.resume_global_capture()
            outcome = yield
            self.suspend_global_capture()
            out, err = self.read_global_capture()
            rep = outcome.get_result()
            if out:
                rep.sections.append(("Captured stdout", out))
            if err:
                rep.sections.append(("Captured stderr", err))
        else:
            yield 
Example #9
Source File: capture.py    From pytest with MIT License 5 votes vote down vote up
def pytest_make_collect_report(self, collector: Collector):
        if isinstance(collector, pytest.File):
            self.resume_global_capture()
            outcome = yield
            self.suspend_global_capture()
            out, err = self.read_global_capture()
            rep = outcome.get_result()
            if out:
                rep.sections.append(("Captured stdout", out))
            if err:
                rep.sections.append(("Captured stderr", err))
        else:
            yield 
Example #10
Source File: test_collection.py    From pytest with MIT License 5 votes vote down vote up
def test_collect_custom_nodes_multi_id(self, testdir):
        p = testdir.makepyfile("def test_func(): pass")
        testdir.makeconftest(
            """
            import pytest
            class SpecialItem(pytest.Item):
                def runtest(self):
                    return # ok
            class SpecialFile(pytest.File):
                def collect(self):
                    return [SpecialItem(name="check", parent=self)]
            def pytest_collect_file(path, parent):
                if path.basename == %r:
                    return SpecialFile(fspath=path, parent=parent)
        """
            % p.basename
        )
        id = p.basename

        items, hookrec = testdir.inline_genitems(id)
        pprint.pprint(hookrec.calls)
        assert len(items) == 2
        hookrec.assert_contains(
            [
                ("pytest_collectstart", "collector.fspath == collector.session.fspath"),
                (
                    "pytest_collectstart",
                    "collector.__class__.__name__ == 'SpecialFile'",
                ),
                ("pytest_collectstart", "collector.__class__.__name__ == 'Module'"),
                ("pytest_pycollect_makeitem", "name == 'test_func'"),
                ("pytest_collectreport", "report.nodeid.startswith(p.basename)"),
            ]
        )
        assert len(self.get_reported_items(hookrec)) == 2 
Example #11
Source File: test_collection.py    From pytest with MIT License 5 votes vote down vote up
def test_matchnodes_two_collections_same_file(testdir):
    testdir.makeconftest(
        """
        import pytest
        def pytest_configure(config):
            config.pluginmanager.register(Plugin2())

        class Plugin2(object):
            def pytest_collect_file(self, path, parent):
                if path.ext == ".abc":
                    return MyFile2(path, parent)

        def pytest_collect_file(path, parent):
            if path.ext == ".abc":
                return MyFile1(path, parent)

        class MyFile1(pytest.Item, pytest.File):
            def runtest(self):
                pass
        class MyFile2(pytest.File):
            def collect(self):
                return [Item2("hello", parent=self)]

        class Item2(pytest.Item):
            def runtest(self):
                pass
    """
    )
    p = testdir.makefile(".abc", "")
    result = testdir.runpytest()
    assert result.ret == 0
    result.stdout.fnmatch_lines(["*2 passed*"])
    res = testdir.runpytest("%s::hello" % p.basename)
    res.stdout.fnmatch_lines(["*1 passed*"]) 
Example #12
Source File: capture.py    From python-netsurv with MIT License 5 votes vote down vote up
def pytest_make_collect_report(self, collector):
        if isinstance(collector, pytest.File):
            self.resume_global_capture()
            outcome = yield
            self.suspend_global_capture()
            out, err = self.read_global_capture()
            rep = outcome.get_result()
            if out:
                rep.sections.append(("Captured stdout", out))
            if err:
                rep.sections.append(("Captured stderr", err))
        else:
            yield 
Example #13
Source File: acceptance_test.py    From pytest with MIT License 5 votes vote down vote up
def test_import_star_pytest(self, testdir):
        p = testdir.makepyfile(
            """
            from pytest import *
            #Item
            #File
            main
            skip
            xfail
        """
        )
        result = testdir.runpython(p)
        assert result.ret == 0 
Example #14
Source File: test_mongo_sql_types.py    From pymongo-schema with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test00_get_type_string():
    assert get_type_string([]) == 'ARRAY'
    assert get_type_string({}) == 'OBJECT'
    assert get_type_string({'a': []}) == 'OBJECT'
    assert get_type_string(None) == 'null'
    assert get_type_string(1.5) == 'float'
    assert get_type_string(set()) == 'unknown'
    assert get_type_string(pytest.File) == 'unknown' 
Example #15
Source File: plugin.py    From pytest-pylint with MIT License 5 votes vote down vote up
def collect(self):
        """Create a PyLintItem for the File."""
        yield PyLintItem.from_parent(
            parent=self,
            name='{}::PYLINT'.format(self.fspath)
        ) 
Example #16
Source File: conftest.py    From rst2pdf with MIT License 4 votes vote down vote up
def _build(self):
        input_ref = self.name + '.txt'
        output_pdf = os.path.join(OUTPUT_DIR, self.name + '.pdf')
        output_log = os.path.join(OUTPUT_DIR, self.name + '.log')

        for path in (output_log, output_pdf):
            if os.path.exists(path):
                if os.path.isdir(path):
                    shutil.rmtree(path)
                else:
                    os.remove(path)

        cmd = ['rst2pdf', '--date-invariant', '-v', input_ref]

        cli_file = os.path.join(INPUT_DIR, self.name + '.cli')
        if os.path.exists(cli_file):
            with open(cli_file) as fh:
                cmd += shlex.split(fh.read())

        style_file = os.path.join(INPUT_DIR, self.name + '.style')
        if os.path.exists(style_file):
            cmd += ['-s', os.path.basename(style_file)]

        cmd += ['-o', output_pdf]

        try:
            output = subprocess.check_output(
                cmd, cwd=INPUT_DIR, stderr=subprocess.STDOUT,
            )
            retcode = 0
        except subprocess.CalledProcessError as exc:
            output = exc.output
            retcode = exc.returncode

        with open(output_log, 'wb') as fh:
            fh.write(output)

        output_file = os.path.join(OUTPUT_DIR, self.name + '.pdf')
        no_pdf = os.path.exists(os.path.join(INPUT_DIR, self.name + '.nopdf'))
        if not os.path.exists(output_file) and not no_pdf:
            self._fail(
                'File %r was not generated' % (os.path.relpath(output_file, ROOT_DIR),),
                output,
            )
        elif os.path.exists(output_file) and no_pdf:
            self._fail(
                'File %r was erroneously generated'
                % (os.path.relpath(output_file, ROOT_DIR),),
                output,
            )

        return retcode, output 
Example #17
Source File: test_junitxml.py    From pytest with MIT License 4 votes vote down vote up
def test_fancy_items_regression(testdir, run_and_parse):
    # issue 1259
    testdir.makeconftest(
        """
        import pytest
        class FunItem(pytest.Item):
            def runtest(self):
                pass
        class NoFunItem(pytest.Item):
            def runtest(self):
                pass

        class FunCollector(pytest.File):
            def collect(self):
                return [
                    FunItem('a', self),
                    NoFunItem('a', self),
                    NoFunItem('b', self),
                ]

        def pytest_collect_file(path, parent):
            if path.check(ext='.py'):
                return FunCollector(path, parent)
    """
    )

    testdir.makepyfile(
        """
        def test_pass():
            pass
    """
    )

    result, dom = run_and_parse()

    result.stdout.no_fnmatch_line("*INTERNALERROR*")

    items = sorted("%(classname)s %(name)s" % x for x in dom.find_by_tag("testcase"))
    import pprint

    pprint.pprint(items)
    assert items == [
        "conftest a",
        "conftest a",
        "conftest b",
        "test_fancy_items_regression a",
        "test_fancy_items_regression a",
        "test_fancy_items_regression b",
        "test_fancy_items_regression test_pass",
    ]