Python pytest.__version__() Examples

The following are 30 code examples of pytest.__version__(). 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: plugin.py    From python-pytest-cases with 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 #2
Source File: __init__.py    From pytest with 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 #3
Source File: test_terminal.py    From pytest with 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 #4
Source File: helpconfig.py    From pytest with 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 #5
Source File: test_assertrewrite.py    From pytest with 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 #6
Source File: setupext.py    From python3_ios with 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 #7
Source File: pytestrunner.py    From spyder-unittest with 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 #8
Source File: terminal.py    From python-netsurv with 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 #9
Source File: helpconfig.py    From python-netsurv with 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 #10
Source File: terminal.py    From python-netsurv with 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 #11
Source File: helpconfig.py    From python-netsurv with 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 #12
Source File: test_metadata.py    From scout_apm_python with MIT License 5 votes vote down vote up
def test_report_app_metadata(send):
    report_app_metadata()

    assert send.call_count == 1
    (command,), kwargs = send.call_args
    assert kwargs == {}

    message = command.message()
    assert message["ApplicationEvent"]["event_type"] == "scout.metadata"
    data = message["ApplicationEvent"]["event_value"]
    assert data["language"] == "python"
    # pytest is installed, since it's running tests right now.
    assert ("pytest", pytest.__version__) in data["libraries"] 
Example #13
Source File: test_pytest_cov.py    From pytest-cov with MIT License 5 votes vote down vote up
def test_dist_missing_data(testdir):
    """Test failure when using a worker without pytest-cov installed."""
    venv_path = os.path.join(str(testdir.tmpdir), 'venv')
    virtualenv.cli_run([venv_path])
    if sys.platform == 'win32':
        if platform.python_implementation() == "PyPy":
            exe = os.path.join(venv_path, 'bin', 'python.exe')
        else:
            exe = os.path.join(venv_path, 'Scripts', 'python.exe')
    else:
        exe = os.path.join(venv_path, 'bin', 'python')
    subprocess.check_call([
        exe,
        '-mpip',
        'install',
        'py==%s' % py.__version__,
        'pytest==%s' % pytest.__version__,
        'pytest_xdist==%s' % xdist.__version__

    ])
    script = testdir.makepyfile(SCRIPT)

    result = testdir.runpytest('-v',
                               '--assert=plain',
                               '--cov=%s' % script.dirpath(),
                               '--cov-report=term-missing',
                               '--dist=load',
                               '--tx=popen//python=%s' % exe,
                               max_worker_restart_0,
                               script)
    result.stdout.fnmatch_lines([
        'The following workers failed to return coverage data, ensure that pytest-cov is installed on these workers.'
    ]) 
Example #14
Source File: hpe_test_utils.py    From oneview-ansible with Apache License 2.0 5 votes vote down vote up
def setUp(self, mock_ansible_module, mock_ov_client, request, testing_module):
        class_name = type(self).__name__
        if StrictVersion(pytest.__version__) < StrictVersion("3.6"):
            marker = request.node.get_marker('resource')
        else:
            marker = request.node.get_closest_marker('resource')
        self.resource = getattr(mock_ov_client, "%s" % (marker.kwargs[class_name]))
        self.resource.get_by_name.return_value = self.resource
        self.mock_ov_client = mock_ov_client
        self.mock_ansible_module = mock_ansible_module 
Example #15
Source File: pytest_timeout.py    From pytest-timeout with 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) 
Example #16
Source File: pytest_checklogs.py    From s3ql with GNU General Public License v3.0 5 votes vote down vote up
def pytest_configure(config):
    # pytest-catchlog was integrated in pytest 3.3.0
    if (LooseVersion(pytest.__version__) < "3.3.0" and
        not config.pluginmanager.hasplugin('pytest_catchlog')):
        raise ImportError('pytest catchlog plugin not found')

# Fail tests if they result in log messages of severity WARNING or more. 
Example #17
Source File: setupext.py    From python3_ios with 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 #18
Source File: test_helpconfig.py    From pytest with 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 #19
Source File: test_helpconfig.py    From pytest with 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 #20
Source File: requirements.py    From suds with GNU Lesser General Public License v3.0 5 votes vote down vote up
def check_Python24_pytest_requirements():
    """
    Check pytest requirements in the current Python 2.4.x environment.

    Installing pytest into a Python 2.4.x environment requires specific py &
    pytest package versions. This function checks whether the environment has
    such compatible Python environments installed.

    Returns a 2-tuple (have_pytest, have_py) indicating whether valid pytest &
    py library packages have been detected in the current Python 2.4.x
    environment. If the pytest package has not been detected, the py library
    package will not be checked and the have_py value will be set to None.

    See the module docstring for more detailed information.

    """
    assert sys.version_info[:2] == (2, 4)
    try:
        from pytest import __version__ as pytest_version
    except ImportError:
        return False, None  # no pytest
    pv_from = parse_version(_first_supported_pytest_version)
    pv_to = parse_version(_first_unsupported_pytest_version_on_Python_24)
    if not (pv_from <= parse_version(pytest_version) < pv_to):
        return False, None  # incompatible pytest version
    try:
        from py import __version__ as py_version
    except ImportError:
        return True, False  # no py library package
    pv_unsupported = parse_version(_first_unsupported_py_version_on_Python_24)
    if parse_version(py_version) >= pv_unsupported:
        return True, False  # incompatible py library package version
    return True, True 
Example #21
Source File: conftest.py    From aiomysql with MIT License 5 votes vote down vote up
def ensure_mysql_verison(request, mysql_tag):
    if StrictVersion(pytest.__version__) >= StrictVersion('4.0.0'):
        mysql_version = request.node.get_closest_marker('mysql_verison')
    else:
        mysql_version = request.node.get_marker('mysql_verison')

    if mysql_version and mysql_version.args[0] != mysql_tag:
        pytest.skip('Not applicable for MySQL version: {0}'.format(mysql_tag)) 
Example #22
Source File: hacks.py    From cgpm with 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 #23
Source File: terminal.py    From pytest with 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 #24
Source File: helpconfig.py    From pytest with 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 #25
Source File: helpconfig.py    From pytest with 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 #26
Source File: pytest_responses.py    From pytest-responses with 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 #27
Source File: __init__.py    From vnpy_crypto with 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 #28
Source File: common_pytest.py    From python-pytest-cases with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #29
Source File: common_pytest.py    From python-pytest-cases with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #30
Source File: test_issue_fixture_union1.py    From python-pytest-cases with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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]']