python类Module()的实例源码

plugin.py 文件源码 项目:pytest-cython 作者: lgpage 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def _importtestmodule(self):
        # we assume we are only called once per module
        importmode = self.config.getoption("--import-mode", default=True)
        try:
            # XXX patch pyimport in pytest._pytest.pythod.Module
            mod = _patch_pyimport(self.fspath, ensuresyspath=importmode)
        except SyntaxError:
            raise self.CollectError(
                _pytest._code.ExceptionInfo().getrepr(style="short"))
        except self.fspath.ImportMismatchError:
            e = sys.exc_info()[1]
            raise self.CollectError(
                "import file mismatch:\n"
                "imported module %r has this __file__ attribute:\n"
                "  %s\n"
                "which is not the same as the test file we want to collect:\n"
                "  %s\n"
                "HINT: remove __pycache__ / .pyc files and/or use a "
                "unique basename for your test file modules"
                % e.args
            )
        # print "imported test module", mod
        self.config.pluginmanager.consider_module(mod)
        return mod
unittest.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def collect(self):
        from unittest import TestLoader
        cls = self.obj
        if not getattr(cls, "__test__", True):
            return
        self.session._fixturemanager.parsefactories(self, unittest=True)
        loader = TestLoader()
        module = self.getparent(pytest.Module).obj
        foundsomething = False
        for name in loader.getTestCaseNames(self.obj):
            x = getattr(self.obj, name)
            if not getattr(x, '__test__', True):
                continue
            funcobj = getattr(x, 'im_func', x)
            transfer_markers(funcobj, cls, module)
            yield TestCaseFunction(name, parent=self)
            foundsomething = True

        if not foundsomething:
            runtest = getattr(self.obj, 'runTest', None)
            if runtest is not None:
                ut = sys.modules.get("twisted.trial.unittest", None)
                if ut is None or runtest != ut.TestCase.runTest:
                    yield TestCaseFunction('runTest', parent=self)
unittest.py 文件源码 项目:sslstrip-hsts-openwrt 作者: adde88 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def collect(self):
        from unittest import TestLoader
        cls = self.obj
        if not getattr(cls, "__test__", True):
            return
        self.session._fixturemanager.parsefactories(self, unittest=True)
        loader = TestLoader()
        module = self.getparent(pytest.Module).obj
        foundsomething = False
        for name in loader.getTestCaseNames(self.obj):
            x = getattr(self.obj, name)
            if not getattr(x, '__test__', True):
                continue
            funcobj = getattr(x, 'im_func', x)
            transfer_markers(funcobj, cls, module)
            yield TestCaseFunction(name, parent=self)
            foundsomething = True

        if not foundsomething:
            runtest = getattr(self.obj, 'runTest', None)
            if runtest is not None:
                ut = sys.modules.get("twisted.trial.unittest", None)
                if ut is None or runtest != ut.TestCase.runTest:
                    yield TestCaseFunction('runTest', parent=self)
unittest.py 文件源码 项目:godot-python 作者: touilleMan 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def collect(self):
        from unittest import TestLoader
        cls = self.obj
        if not getattr(cls, "__test__", True):
            return
        self.session._fixturemanager.parsefactories(self, unittest=True)
        loader = TestLoader()
        module = self.getparent(pytest.Module).obj
        foundsomething = False
        for name in loader.getTestCaseNames(self.obj):
            x = getattr(self.obj, name)
            if not getattr(x, '__test__', True):
                continue
            funcobj = getattr(x, 'im_func', x)
            transfer_markers(funcobj, cls, module)
            yield TestCaseFunction(name, parent=self)
            foundsomething = True

        if not foundsomething:
            runtest = getattr(self.obj, 'runTest', None)
            if runtest is not None:
                ut = sys.modules.get("twisted.trial.unittest", None)
                if ut is None or runtest != ut.TestCase.runTest:
                    yield TestCaseFunction('runTest', parent=self)
unittest.py 文件源码 项目:godot-python 作者: touilleMan 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def collect(self):
        from unittest import TestLoader
        cls = self.obj
        if not getattr(cls, "__test__", True):
            return
        self.session._fixturemanager.parsefactories(self, unittest=True)
        loader = TestLoader()
        module = self.getparent(pytest.Module).obj
        foundsomething = False
        for name in loader.getTestCaseNames(self.obj):
            x = getattr(self.obj, name)
            if not getattr(x, '__test__', True):
                continue
            funcobj = getattr(x, 'im_func', x)
            transfer_markers(funcobj, cls, module)
            yield TestCaseFunction(name, parent=self)
            foundsomething = True

        if not foundsomething:
            runtest = getattr(self.obj, 'runTest', None)
            if runtest is not None:
                ut = sys.modules.get("twisted.trial.unittest", None)
                if ut is None or runtest != ut.TestCase.runTest:
                    yield TestCaseFunction('runTest', parent=self)
collect.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def test_pytest_pycollect_module(self, testdir):
        testdir.makeconftest("""
            import pytest
            class MyModule(pytest.Module):
                pass
            def pytest_pycollect_makemodule(path, parent):
                if path.basename == "test_xyz.py":
                    return MyModule(path, parent)
        """)
        testdir.makepyfile("def test_some(): pass")
        testdir.makepyfile(test_xyz="def test_func(): pass")
        result = testdir.runpytest("--collect-only")
        result.stdout.fnmatch_lines([
            "*<Module*test_pytest*",
            "*<MyModule*xyz*",
        ])
collect.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def test_collector_attributes(testdir):
    testdir.makeconftest("""
        import pytest
        def pytest_pycollect_makeitem(collector):
            assert collector.Function == pytest.Function
            assert collector.Class == pytest.Class
            assert collector.Instance == pytest.Instance
            assert collector.Module == pytest.Module
    """)
    testdir.makepyfile("""
         def test_hello():
            pass
    """)
    result = testdir.runpytest()
    result.stdout.fnmatch_lines([
        "*1 passed*",
    ])
fixture.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def test_request_addfinalizer(self, testdir):
        item = testdir.getitem("""
            teardownlist = []
            def pytest_funcarg__something(request):
                request.addfinalizer(lambda: teardownlist.append(1))
            def test_func(something): pass
        """)
        item.session._setupstate.prepare(item)
        pytest._fillfuncargs(item)
        # successively check finalization calls
        teardownlist = item.getparent(pytest.Module).obj.teardownlist
        ss = item.session._setupstate
        assert not teardownlist
        ss.teardown_exact(item, None)
        print(ss.stack)
        assert teardownlist == [1]
test_collection.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def test_getparent(self, testdir):
        modcol = testdir.getmodulecol("""
            class TestClass:
                 def test_foo():
                     pass
        """)
        cls = testdir.collect_by_name(modcol, "TestClass")
        fn = testdir.collect_by_name(
            testdir.collect_by_name(cls, "()"), "test_foo")

        parent = fn.getparent(pytest.Module)
        assert parent is modcol

        parent = fn.getparent(pytest.Function)
        assert parent is fn

        parent = fn.getparent(pytest.Class)
        assert parent is cls
test_collection.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def test_pytest_fs_collect_hooks_are_seen(self, testdir):
        testdir.makeconftest("""
            import pytest
            class MyModule(pytest.Module):
                pass
            def pytest_collect_file(path, parent):
                if path.ext == ".py":
                    return MyModule(path, parent)
        """)
        testdir.mkdir("sub")
        testdir.makepyfile("def test_x(): pass")
        result = testdir.runpytest("--collect-only")
        result.stdout.fnmatch_lines([
            "*MyModule*",
            "*test_x*"
        ])
python.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def getmodpath(self, stopatmodule=True, includemodule=False):
        """ return python path relative to the containing module. """
        chain = self.listchain()
        chain.reverse()
        parts = []
        for node in chain:
            if isinstance(node, Instance):
                continue
            name = node.name
            if isinstance(node, Module):
                assert name.endswith(".py")
                name = name[:-3]
                if stopatmodule:
                    if includemodule:
                        parts.append(name)
                    break
            parts.append(name)
        parts.reverse()
        s = ".".join(parts)
        return s.replace(".[", "[")
unittest.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def collect(self):
        from unittest import TestLoader
        cls = self.obj
        if not getattr(cls, "__test__", True):
            return
        self.session._fixturemanager.parsefactories(self, unittest=True)
        loader = TestLoader()
        module = self.getparent(pytest.Module).obj
        foundsomething = False
        for name in loader.getTestCaseNames(self.obj):
            x = getattr(self.obj, name)
            funcobj = getattr(x, 'im_func', x)
            transfer_markers(funcobj, cls, module)
            yield TestCaseFunction(name, parent=self)
            foundsomething = True

        if not foundsomething:
            runtest = getattr(self.obj, 'runTest', None)
            if runtest is not None:
                ut = sys.modules.get("twisted.trial.unittest", None)
                if ut is None or runtest != ut.TestCase.runTest:
                    yield TestCaseFunction('runTest', parent=self)
fixtures.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def pytest_namespace():
    scopename2class.update({
        'class': pytest.Class,
        'module': pytest.Module,
        'function': pytest.Item,
    })
    return {
        'fixture': fixture,
        'yield_fixture': yield_fixture,
        'collect': {'_fillfuncargs': fillfixtures}
    }
fixtures.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def module(self):
        """ python module object where the test function was collected. """
        return self._pyfuncitem.getparent(pytest.Module).obj
fixtures.py 文件源码 项目:sslstrip-hsts-openwrt 作者: adde88 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def pytest_namespace():
    scopename2class.update({
        'class': pytest.Class,
        'module': pytest.Module,
        'function': pytest.Item,
    })
    return {
        'fixture': fixture,
        'yield_fixture': yield_fixture,
        'collect': {'_fillfuncargs': fillfixtures}
    }
fixtures.py 文件源码 项目:sslstrip-hsts-openwrt 作者: adde88 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def module(self):
        """ python module object where the test function was collected. """
        return self._pyfuncitem.getparent(pytest.Module).obj
fixtures.py 文件源码 项目:godot-python 作者: touilleMan 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def pytest_namespace():
    scopename2class.update({
        'class': pytest.Class,
        'module': pytest.Module,
        'function': pytest.Item,
    })
    return {
        'fixture': fixture,
        'yield_fixture': yield_fixture,
        'collect': {'_fillfuncargs': fillfixtures}
    }
fixtures.py 文件源码 项目:godot-python 作者: touilleMan 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def module(self):
        """ python module object where the test function was collected. """
        return self._pyfuncitem.getparent(pytest.Module).obj
fixtures.py 文件源码 项目:godot-python 作者: touilleMan 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def module(self):
        """ python module object where the test function was collected. """
        return self._pyfuncitem.getparent(pytest.Module).obj
test_01_marker.py 文件源码 项目:pytest-dependency 作者: RKrahl 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def test_marker(ctestdir):
    ctestdir.makepyfile("""
        import pytest
        from pytest_dependency import DependencyManager

        @pytest.mark.dependency()
        def test_marker(request):
            node = request.node.getparent(pytest.Module)
            assert hasattr(node, 'dependencyManager')
            assert isinstance(node.dependencyManager, DependencyManager)
            assert 'test_marker' in node.dependencyManager.results
    """)
    result = ctestdir.runpytest("--verbose")
    result.assert_outcomes(passed=1)
collect.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def test_getmodulecollector(self, testdir):
        item = testdir.getitem("def test_func(): pass")
        modcol = item.getparent(pytest.Module)
        assert isinstance(modcol, pytest.Module)
        assert hasattr(modcol.obj, 'test_func')
collect.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def test_makeitem_non_underscore(self, testdir, monkeypatch):
        modcol = testdir.getmodulecol("def _hello(): pass")
        l = []
        monkeypatch.setattr(pytest.Module, 'makeitem',
            lambda self, name, obj: l.append(name))
        l = modcol.collect()
        assert '_hello' not in l
test_collection.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def test_pytest_collect_file_from_sister_dir(self, testdir):
        sub1 = testdir.mkpydir("sub1")
        sub2 = testdir.mkpydir("sub2")
        conf1 = testdir.makeconftest("""
            import pytest
            class MyModule1(pytest.Module):
                pass
            def pytest_collect_file(path, parent):
                if path.ext == ".py":
                    return MyModule1(path, parent)
        """)
        conf1.move(sub1.join(conf1.basename))
        conf2 = testdir.makeconftest("""
            import pytest
            class MyModule2(pytest.Module):
                pass
            def pytest_collect_file(path, parent):
                if path.ext == ".py":
                    return MyModule2(path, parent)
        """)
        conf2.move(sub2.join(conf2.basename))
        p = testdir.makepyfile("def test_x(): pass")
        p.copy(sub1.join(p.basename))
        p.copy(sub2.join(p.basename))
        result = testdir.runpytest("--collect-only")
        result.stdout.fnmatch_lines([
            "*MyModule1*",
            "*MyModule2*",
            "*test_x*"
        ])
test_collection.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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)
        py.std.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)"),
            #("pytest_collectreport",
            #    "report.fspath == %r" % str(rcol.fspath)),
        ])
test_collection.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def test_global_file(self, testdir, tmpdir):
        x = tmpdir.ensure("x.py")
        config = testdir.parseconfigure(x)
        col = testdir.getnode(config, x)
        assert isinstance(col, pytest.Module)
        assert col.name == 'x.py'
        assert col.parent.name == testdir.tmpdir.basename
        assert col.parent.parent is None
        for col in col.listchain():
            assert col.config is config
conftest.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def pytest_runtest_setup(item):
    if isinstance(item, pytest.Function):
        if not item.fspath.relto(mydir):
            return
        mod = item.getparent(pytest.Module).obj
        if hasattr(mod, 'hello'):
            print ("mod.hello %r" % (mod.hello,))
python.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def pytest_namespace():
    raises.Exception = pytest.fail.Exception
    return {
        'fixture': fixture,
        'yield_fixture': yield_fixture,
        'raises' : raises,
        'collect': {
        'Module': Module, 'Class': Class, 'Instance': Instance,
        'Function': Function, 'Generator': Generator,
        '_fillfuncargs': fillfixtures}
    }
python.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def pytest_pycollect_makemodule(path, parent):
    return Module(path, parent)
python.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def _genfunctions(self, name, funcobj):
        module = self.getparent(Module).obj
        clscol = self.getparent(Class)
        cls = clscol and clscol.obj or None
        transfer_markers(funcobj, cls, module)
        fm = self.session._fixturemanager
        fixtureinfo = fm.getfixtureinfo(self, funcobj, cls)
        metafunc = Metafunc(funcobj, fixtureinfo, self.config,
                            cls=cls, module=module)
        methods = []
        if hasattr(module, "pytest_generate_tests"):
            methods.append(module.pytest_generate_tests)
        if hasattr(cls, "pytest_generate_tests"):
            methods.append(cls().pytest_generate_tests)
        if methods:
            self.ihook.pytest_generate_tests.call_extra(methods,
                                                        dict(metafunc=metafunc))
        else:
            self.ihook.pytest_generate_tests(metafunc=metafunc)

        Function = self._getcustomclass("Function")
        if not metafunc._calls:
            yield Function(name, parent=self, fixtureinfo=fixtureinfo)
        else:
            # add funcargs() as fixturedefs to fixtureinfo.arg2fixturedefs
            add_funcarg_pseudo_fixture_def(self, metafunc, fm)

            for callspec in metafunc._calls:
                subname = "%s[%s]" %(name, callspec.id)
                yield Function(name=subname, parent=self,
                               callspec=callspec, callobj=funcobj,
                               fixtureinfo=fixtureinfo,
                               keywords={callspec.id:True})
python.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def collect(self):
        self.session._fixturemanager.parsefactories(self)
        return super(Module, self).collect()


问题


面经


文章

微信
公众号

扫码关注公众号