Python pytest.__version__() Examples

The following are 30 code examples for showing how to use pytest.__version__(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module pytest , or try the search function .

Example 1
Project: python-netsurv   Author: sofia-netsurv   File: helpconfig.py    License: MIT License 6 votes vote down vote up
def pytest_report_header(config):
    lines = []
    if config.option.debug or config.option.traceconfig:
        lines.append(
            "using: pytest-{} pylib-{}".format(pytest.__version__, py.__version__)
        )

        verinfo = getpluginversioninfo(config)
        if verinfo:
            lines.extend(verinfo)

    if config.option.traceconfig:
        lines.append("active plugins:")
        items = config.pluginmanager.list_name_plugin()
        for name, plugin in items:
            if hasattr(plugin, "__file__"):
                r = plugin.__file__
            else:
                r = repr(plugin)
            lines.append("    {:<20}: {}".format(name, r))
    return lines 
Example 2
Project: python-netsurv   Author: sofia-netsurv   File: terminal.py    License: MIT License 6 votes vote down vote up
def pytest_sessionstart(self, session):
        self._session = session
        self._sessionstarttime = time.time()
        if not self.showheader:
            return
        self.write_sep("=", "test session starts", bold=True)
        verinfo = platform.python_version()
        msg = "platform {} -- Python {}".format(sys.platform, verinfo)
        if hasattr(sys, "pypy_version_info"):
            verinfo = ".".join(map(str, sys.pypy_version_info[:3]))
            msg += "[pypy-{}-{}]".format(verinfo, sys.pypy_version_info[3])
        msg += ", pytest-{}, py-{}, pluggy-{}".format(
            pytest.__version__, py.__version__, pluggy.__version__
        )
        if (
            self.verbosity > 0
            or self.config.option.debug
            or getattr(self.config.option, "pastebin", None)
        ):
            msg += " -- " + str(sys.executable)
        self.write_line(msg)
        lines = self.config.hook.pytest_report_header(
            config=self.config, startdir=self.startdir
        )
        self._write_report_lines_from_hooks(lines) 
Example 3
Project: python-netsurv   Author: sofia-netsurv   File: helpconfig.py    License: MIT License 6 votes vote down vote up
def pytest_report_header(config):
    lines = []
    if config.option.debug or config.option.traceconfig:
        lines.append(
            "using: pytest-{} pylib-{}".format(pytest.__version__, py.__version__)
        )

        verinfo = getpluginversioninfo(config)
        if verinfo:
            lines.extend(verinfo)

    if config.option.traceconfig:
        lines.append("active plugins:")
        items = config.pluginmanager.list_name_plugin()
        for name, plugin in items:
            if hasattr(plugin, "__file__"):
                r = plugin.__file__
            else:
                r = repr(plugin)
            lines.append("    {:<20}: {}".format(name, r))
    return lines 
Example 4
Project: python-netsurv   Author: sofia-netsurv   File: terminal.py    License: MIT License 6 votes vote down vote up
def pytest_sessionstart(self, session):
        self._session = session
        self._sessionstarttime = time.time()
        if not self.showheader:
            return
        self.write_sep("=", "test session starts", bold=True)
        verinfo = platform.python_version()
        msg = "platform {} -- Python {}".format(sys.platform, verinfo)
        if hasattr(sys, "pypy_version_info"):
            verinfo = ".".join(map(str, sys.pypy_version_info[:3]))
            msg += "[pypy-{}-{}]".format(verinfo, sys.pypy_version_info[3])
        msg += ", pytest-{}, py-{}, pluggy-{}".format(
            pytest.__version__, py.__version__, pluggy.__version__
        )
        if (
            self.verbosity > 0
            or self.config.option.debug
            or getattr(self.config.option, "pastebin", None)
        ):
            msg += " -- " + str(sys.executable)
        self.write_line(msg)
        lines = self.config.hook.pytest_report_header(
            config=self.config, startdir=self.startdir
        )
        self._write_report_lines_from_hooks(lines) 
Example 5
Project: python-pytest-cases   Author: smarie   File: plugin.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def to_list(self):
        """
        Converts self to a list to get all fixture names, and caches the result.
        :return:
        """
        if self._as_list is None:
            # crawl the tree to get the list of unique fixture names
            fixturenames_closure = self._to_list()

            if LooseVersion(pytest.__version__) >= LooseVersion('3.5.0'):
                # sort by scope
                def sort_by_scope(arg_name):
                    try:
                        fixturedefs = self.get_all_fixture_defs()[arg_name]
                    except KeyError:
                        return get_pytest_function_scopenum()
                    else:
                        return fixturedefs[-1].scopenum
                fixturenames_closure.sort(key=sort_by_scope)

            self._as_list = fixturenames_closure

        return self._as_list 
Example 6
Project: pytest   Author: pytest-dev   File: helpconfig.py    License: MIT License 6 votes vote down vote up
def pytest_report_header(config: Config) -> List[str]:
    lines = []
    if config.option.debug or config.option.traceconfig:
        lines.append(
            "using: pytest-{} pylib-{}".format(pytest.__version__, py.__version__)
        )

        verinfo = getpluginversioninfo(config)
        if verinfo:
            lines.extend(verinfo)

    if config.option.traceconfig:
        lines.append("active plugins:")
        items = config.pluginmanager.list_name_plugin()
        for name, plugin in items:
            if hasattr(plugin, "__file__"):
                r = plugin.__file__
            else:
                r = repr(plugin)
            lines.append("    {:<20}: {}".format(name, r))
    return lines 
Example 7
Project: pytest   Author: pytest-dev   File: __init__.py    License: MIT License 6 votes vote down vote up
def _checkversion(self) -> None:
        import pytest

        minver = self.inicfg.get("minversion", None)
        if minver:
            # Imported lazily to improve start-up time.
            from packaging.version import Version

            if not isinstance(minver, str):
                raise pytest.UsageError(
                    "%s: 'minversion' must be a single value" % self.inifile
                )

            if Version(minver) > Version(pytest.__version__):
                raise pytest.UsageError(
                    "%s: 'minversion' requires pytest-%s, actual pytest-%s'"
                    % (self.inifile, minver, pytest.__version__,)
                ) 
Example 8
Project: pytest   Author: pytest-dev   File: test_terminal.py    License: MIT License 6 votes vote down vote up
def test_no_header_trailer_info(self, testdir, request):
        testdir.monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD")
        testdir.makepyfile(
            """
            def test_passes():
                pass
        """
        )
        result = testdir.runpytest("--no-header")
        verinfo = ".".join(map(str, sys.version_info[:3]))
        result.stdout.no_fnmatch_line(
            "platform %s -- Python %s*pytest-%s*py-%s*pluggy-%s"
            % (
                sys.platform,
                verinfo,
                pytest.__version__,
                py.__version__,
                pluggy.__version__,
            )
        )
        if request.config.pluginmanager.list_plugin_distinfo():
            result.stdout.no_fnmatch_line("plugins: *") 
Example 9
Project: pytest   Author: pytest-dev   File: test_assertrewrite.py    License: MIT License 6 votes vote down vote up
def test_cached_pyc_includes_pytest_version(self, testdir, monkeypatch):
        """Avoid stale caches (#1671)"""
        monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", raising=False)
        testdir.makepyfile(
            test_foo="""
            def test_foo():
                assert True
            """
        )
        result = testdir.runpytest_subprocess()
        assert result.ret == 0
        found_names = glob.glob(
            "__pycache__/*-pytest-{}.pyc".format(pytest.__version__)
        )
        assert found_names, "pyc with expected tag not found in names: {}".format(
            glob.glob("__pycache__/*.pyc")
        ) 
Example 10
Project: python3_ios   Author: holzschu   File: setupext.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check(self):
        super().check()

        msgs = []
        msg_template = ('{package} is required to run the Matplotlib test '
                        'suite. Please install it with pip or your preferred '
                        'tool to run the test suite')

        bad_pytest = msg_template.format(
            package='pytest %s or later' % self.pytest_min_version
        )
        try:
            import pytest
            if is_min_version(pytest.__version__, self.pytest_min_version):
                msgs += ['using pytest version %s' % pytest.__version__]
            else:
                msgs += [bad_pytest]
        except ImportError:
            msgs += [bad_pytest]

        return ' / '.join(msgs) 
Example 11
Project: spyder-unittest   Author: spyder-ide   File: pytestrunner.py    License: MIT License 6 votes vote down vote up
def get_versions(self):
        """Return versions of framework and its plugins."""
        import pytest
        versions = ['pytest {}'.format(pytest.__version__)]

        class GetPluginVersionsPlugin():
            def pytest_cmdline_main(self, config):
                nonlocal versions
                plugininfo = config.pluginmanager.list_plugin_distinfo()
                if plugininfo:
                    for plugin, dist in plugininfo:
                        versions.append("   {} {}".format(dist.project_name,
                                                          dist.version))

        # --capture=sys needed on Windows to avoid
        # ValueError: saved filedescriptor not valid anymore
        pytest.main(['-V', '--capture=sys'],
                    plugins=[GetPluginVersionsPlugin()])
        return versions 
Example 12
Project: cgpm   Author: probcomp   File: hacks.py    License: Apache License 2.0 5 votes vote down vote up
def skip(reason):
    if pytest.__version__ >= '3':
        raise pytest.skip.Exception(reason, allow_module_level=True)
    else:
        pytest.skip(reason) 
Example 13
Project: ara-archive   Author: dmsimard   File: test_cli.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_generate_empty_html(self):
        """ Ensures the application is still rendered gracefully """
        self.app.config['ARA_IGNORE_EMPTY_GENERATION'] = False
        dir = self.generate_dir
        shell = ara.shell.AraCli()
        shell.prepare_to_run_command(ara.cli.generate.GenerateHtml)
        cmd = ara.cli.generate.GenerateHtml(shell, None)
        parser = cmd.get_parser('test')
        args = parser.parse_args([dir])

        with pytest.warns(MissingURLGeneratorWarning) as warnings:
            cmd.take_action(args)

        # pytest 3.0 through 3.1 are backwards incompatible here
        if LooseVersion(pytest.__version__) >= LooseVersion('3.1.0'):
            cat = [item._category_name for item in warnings]
            self.assertTrue(any('MissingURLGeneratorWarning' in c
                                for c in cat))
        else:
            self.assertTrue(any(MissingURLGeneratorWarning == w.category
                                for w in warnings))

        paths = [
            os.path.join(dir, 'index.html'),
            os.path.join(dir, 'static'),
        ]

        for path in paths:
            self.assertTrue(os.path.exists(path)) 
Example 14
Project: python-netsurv   Author: sofia-netsurv   File: helpconfig.py    License: MIT License 5 votes vote down vote up
def pytest_cmdline_parse():
    outcome = yield
    config = outcome.get_result()
    if config.option.debug:
        path = os.path.abspath("pytestdebug.log")
        debugfile = open(path, "w")
        debugfile.write(
            "versions pytest-%s, py-%s, "
            "python-%s\ncwd=%s\nargs=%s\n\n"
            % (
                pytest.__version__,
                py.__version__,
                ".".join(map(str, sys.version_info)),
                os.getcwd(),
                config._origargs,
            )
        )
        config.trace.root.setwriter(debugfile.write)
        undo_tracing = config.pluginmanager.enable_tracing()
        sys.stderr.write("writing pytestdebug information to %s\n" % path)

        def unset_tracing():
            debugfile.close()
            sys.stderr.write("wrote pytestdebug information to %s\n" % debugfile.name)
            config.trace.root.setwriter(None)
            undo_tracing()

        config.add_cleanup(unset_tracing) 
Example 15
Project: python-netsurv   Author: sofia-netsurv   File: helpconfig.py    License: MIT License 5 votes vote down vote up
def showversion(config):
    p = py.path.local(pytest.__file__)
    sys.stderr.write(
        "This is pytest version {}, imported from {}\n".format(pytest.__version__, p)
    )
    plugininfo = getpluginversioninfo(config)
    if plugininfo:
        for line in plugininfo:
            sys.stderr.write(line + "\n") 
Example 16
Project: python-netsurv   Author: sofia-netsurv   File: __init__.py    License: MIT License 5 votes vote down vote up
def _checkversion(self):
        import pytest

        minver = self.inicfg.get("minversion", None)
        if minver:
            if Version(minver) > Version(pytest.__version__):
                raise pytest.UsageError(
                    "%s:%d: requires pytest-%s, actual pytest-%s'"
                    % (
                        self.inicfg.config.path,
                        self.inicfg.lineof("minversion"),
                        minver,
                        pytest.__version__,
                    )
                ) 
Example 17
Project: python-netsurv   Author: sofia-netsurv   File: helpconfig.py    License: MIT License 5 votes vote down vote up
def showversion(config):
    p = py.path.local(pytest.__file__)
    sys.stderr.write(
        "This is pytest version {}, imported from {}\n".format(pytest.__version__, p)
    )
    plugininfo = getpluginversioninfo(config)
    if plugininfo:
        for line in plugininfo:
            sys.stderr.write(line + "\n") 
Example 18
Project: python-netsurv   Author: sofia-netsurv   File: __init__.py    License: MIT License 5 votes vote down vote up
def _checkversion(self):
        import pytest

        minver = self.inicfg.get("minversion", None)
        if minver:
            if Version(minver) > Version(pytest.__version__):
                raise pytest.UsageError(
                    "%s:%d: requires pytest-%s, actual pytest-%s'"
                    % (
                        self.inicfg.config.path,
                        self.inicfg.lineof("minversion"),
                        minver,
                        pytest.__version__,
                    )
                ) 
Example 19
def test_synthesis(module_results_dct):
    if LooseVersion(pytest.__version__) < LooseVersion('3.0.0'):
        # the way to make ids uniques in case of duplicates was different in old pytest
        assert list(module_results_dct) == ['test_foo[0u_is_a]', 'test_foo[1u_is_a]']
    else:
        assert list(module_results_dct) == ['test_foo[u_is_a0]', 'test_foo[u_is_a1]'] 
Example 20
def get_parametrization_markers(fnode):
    """
    Returns the parametrization marks on a pytest Function node.
    :param fnode:
    :return:
    """
    if LooseVersion(pytest.__version__) >= LooseVersion('3.4.0'):
        return list(fnode.iter_markers(name="parametrize"))
    else:
        return list(fnode.parametrize) 
Example 21
def transform_marks_into_decorators(marks):
    """
    Transforms the provided marks (MarkInfo) obtained from marked cases, into MarkDecorator so that they can
    be re-applied to generated pytest parameters in the global @pytest.mark.parametrize.

    :param marks:
    :return:
    """
    marks_mod = []
    try:
        # suppress the warning message that pytest generates when calling pytest.mark.MarkDecorator() directly
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            for m in marks:
                md = pytest.mark.MarkDecorator()

                if LooseVersion(pytest.__version__) >= LooseVersion('3.0.0'):
                    if isinstance(m, type(md)):
                        # already a decorator, we can use it
                        marks_mod.append(m)
                    else:
                        md.mark = m
                        marks_mod.append(md)
                else:
                    # always recreate one, type comparison does not work (all generic stuff)
                    md.name = m.name
                    # md.markname = m.name
                    md.args = m.args
                    md.kwargs = m.kwargs

                    # markinfodecorator = getattr(pytest.mark, markinfo.name)
                    # markinfodecorator(*markinfo.args)

                    marks_mod.append(md)

    except Exception as e:
        warn("Caught exception while trying to mark case: [%s] %s" % (type(e), e))
    return marks_mod 
Example 22
Project: vnpy_crypto   Author: birforce   File: __init__.py    License: MIT License 5 votes vote down vote up
def __call__(self, extra_args=None):
        try:
            import pytest
            if not LooseVersion(pytest.__version__) >= LooseVersion('3.0'):
                raise ImportError
            extra_args = ['--tb=short','--disable-pytest-warnings'] if extra_args is None else extra_args
            cmd = [self.package_path] + extra_args
            print('Running pytest ' + ' '.join(cmd))
            pytest.main(cmd)
        except ImportError:
            raise ImportError('pytest>=3 required to run the test') 
Example 23
Project: pytest-responses   Author: getsentry   File: pytest_responses.py    License: Apache License 2.0 5 votes vote down vote up
def get_withoutresponses_marker(item):
    if LooseVersion(pytest.__version__) >= LooseVersion('4.0.0'):
        return item.get_closest_marker('withoutresponses')
    else:
        return item.get_marker('withoutresponses')


# pytest plugin support 
Example 24
Project: pytest   Author: pytest-dev   File: helpconfig.py    License: MIT License 5 votes vote down vote up
def pytest_cmdline_parse():
    outcome = yield
    config = outcome.get_result()  # type: Config
    if config.option.debug:
        path = os.path.abspath("pytestdebug.log")
        debugfile = open(path, "w")
        debugfile.write(
            "versions pytest-%s, py-%s, "
            "python-%s\ncwd=%s\nargs=%s\n\n"
            % (
                pytest.__version__,
                py.__version__,
                ".".join(map(str, sys.version_info)),
                os.getcwd(),
                config.invocation_params.args,
            )
        )
        config.trace.root.setwriter(debugfile.write)
        undo_tracing = config.pluginmanager.enable_tracing()
        sys.stderr.write("writing pytestdebug information to %s\n" % path)

        def unset_tracing() -> None:
            debugfile.close()
            sys.stderr.write("wrote pytestdebug information to %s\n" % debugfile.name)
            config.trace.root.setwriter(None)
            undo_tracing()

        config.add_cleanup(unset_tracing) 
Example 25
Project: pytest   Author: pytest-dev   File: helpconfig.py    License: MIT License 5 votes vote down vote up
def showversion(config: Config) -> None:
    if config.option.version > 1:
        sys.stderr.write(
            "This is pytest version {}, imported from {}\n".format(
                pytest.__version__, pytest.__file__
            )
        )
        plugininfo = getpluginversioninfo(config)
        if plugininfo:
            for line in plugininfo:
                sys.stderr.write(line + "\n")
    else:
        sys.stderr.write("pytest {}\n".format(pytest.__version__)) 
Example 26
Project: pytest   Author: pytest-dev   File: terminal.py    License: MIT License 5 votes vote down vote up
def pytest_sessionstart(self, session: "Session") -> None:
        self._session = session
        self._sessionstarttime = timing.time()
        if not self.showheader:
            return
        self.write_sep("=", "test session starts", bold=True)
        verinfo = platform.python_version()
        if not self.no_header:
            msg = "platform {} -- Python {}".format(sys.platform, verinfo)
            pypy_version_info = getattr(sys, "pypy_version_info", None)
            if pypy_version_info:
                verinfo = ".".join(map(str, pypy_version_info[:3]))
                msg += "[pypy-{}-{}]".format(verinfo, pypy_version_info[3])
            msg += ", pytest-{}, py-{}, pluggy-{}".format(
                pytest.__version__, py.__version__, pluggy.__version__
            )
            if (
                self.verbosity > 0
                or self.config.option.debug
                or getattr(self.config.option, "pastebin", None)
            ):
                msg += " -- " + str(sys.executable)
            self.write_line(msg)
            lines = self.config.hook.pytest_report_header(
                config=self.config, startdir=self.startdir
            )
            self._write_report_lines_from_hooks(lines) 
Example 27
Project: pytest   Author: pytest-dev   File: test_helpconfig.py    License: MIT License 5 votes vote down vote up
def test_version_verbose(testdir, pytestconfig):
    testdir.monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD")
    result = testdir.runpytest("--version", "--version")
    assert result.ret == 0
    result.stderr.fnmatch_lines(
        ["*pytest*{}*imported from*".format(pytest.__version__)]
    )
    if pytestconfig.pluginmanager.list_plugin_distinfo():
        result.stderr.fnmatch_lines(["*setuptools registered plugins:", "*at*"]) 
Example 28
Project: pytest   Author: pytest-dev   File: test_helpconfig.py    License: MIT License 5 votes vote down vote up
def test_version_less_verbose(testdir, pytestconfig):
    testdir.monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD")
    result = testdir.runpytest("--version")
    assert result.ret == 0
    # p = py.path.local(py.__file__).dirpath()
    result.stderr.fnmatch_lines(["pytest {}".format(pytest.__version__)]) 
Example 29
Project: python3_ios   Author: holzschu   File: setupext.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check(self):
        min_version = extract_versions()['__version__numpy__']
        try:
            import numpy
        except ImportError:
            return 'not found. pip may install it below.'

        if not is_min_version(numpy.__version__, min_version):
            raise SystemExit(
                "Requires numpy %s or later to build.  (Found %s)" %
                (min_version, numpy.__version__))

        return 'version %s' % numpy.__version__ 
Example 30
Project: pytest-timeout   Author: pytest-dev   File: pytest_timeout.py    License: MIT License 5 votes vote down vote up
def timeout_timer(item, timeout):
    """Dump stack of threads and call os._exit().

    This disables the capturemanager and dumps stdout and stderr.
    Then the stacks are dumped and os._exit(1) is called.
    """
    if is_debugging():
        return
    try:
        capman = item.config.pluginmanager.getplugin("capturemanager")
        if capman:
            pytest_version = StrictVersion(pytest.__version__)
            if pytest_version >= StrictVersion("3.7.3"):
                capman.suspend_global_capture(item)
                stdout, stderr = capman.read_global_capture()
            else:
                stdout, stderr = capman.suspend_global_capture(item)
        else:
            stdout, stderr = None, None
        write_title("Timeout", sep="+")
        caplog = item.config.pluginmanager.getplugin("_capturelog")
        if caplog and hasattr(item, "capturelog_handler"):
            log = item.capturelog_handler.stream.getvalue()
            if log:
                write_title("Captured log")
                write(log)
        if stdout:
            write_title("Captured stdout")
            write(stdout)
        if stderr:
            write_title("Captured stderr")
            write(stderr)
        dump_stacks()
        write_title("Timeout", sep="+")
    except Exception:
        traceback.print_exc()
    finally:
        sys.stdout.flush()
        sys.stderr.flush()
        os._exit(1)