当前位置: 首页>>代码示例>>Python>>正文


Python pytest.PytestWarning方法代码示例

本文整理汇总了Python中pytest.PytestWarning方法的典型用法代码示例。如果您正苦于以下问题:Python pytest.PytestWarning方法的具体用法?Python pytest.PytestWarning怎么用?Python pytest.PytestWarning使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pytest的用法示例。


在下文中一共展示了pytest.PytestWarning方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: pytest_runtest_protocol

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import PytestWarning [as 别名]
def pytest_runtest_protocol(self, item):
        lines1 = self.get_open_files()
        yield
        if hasattr(sys, "pypy_version_info"):
            gc.collect()
        lines2 = self.get_open_files()

        new_fds = {t[0] for t in lines2} - {t[0] for t in lines1}
        leaked_files = [t for t in lines2 if t[0] in new_fds]
        if leaked_files:
            error = []
            error.append("***** %s FD leakage detected" % len(leaked_files))
            error.extend([str(f) for f in leaked_files])
            error.append("*** Before:")
            error.extend([str(f) for f in lines1])
            error.append("*** After:")
            error.extend([str(f) for f in lines2])
            error.append(error[0])
            error.append("*** function %s:%s: %s " % item.location)
            error.append("See issue #2366")
            item.warn(pytest.PytestWarning("\n".join(error)))


# used at least by pytest-xdist plugin 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:26,代码来源:pytester.py

示例2: setenv

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import PytestWarning [as 别名]
def setenv(self, name, value, prepend=None):
        """ Set environment variable ``name`` to ``value``.  If ``prepend``
        is a character, read the current environment variable value
        and prepend the ``value`` adjoined with the ``prepend`` character."""
        if not isinstance(value, str):
            warnings.warn(
                pytest.PytestWarning(
                    "Value of environment variable {name} type should be str, but got "
                    "{value!r} (type: {type}); converted to str implicitly".format(
                        name=name, value=value, type=type(value).__name__
                    )
                ),
                stacklevel=2,
            )
            value = str(value)
        if prepend and name in os.environ:
            value = value + prepend + os.environ[name]
        self.setitem(os.environ, name, value) 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:20,代码来源:monkeypatch.py

示例3: pytest_runtest_protocol

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import PytestWarning [as 别名]
def pytest_runtest_protocol(self, item: Item) -> Generator[None, None, None]:
        lines1 = self.get_open_files()
        yield
        if hasattr(sys, "pypy_version_info"):
            gc.collect()
        lines2 = self.get_open_files()

        new_fds = {t[0] for t in lines2} - {t[0] for t in lines1}
        leaked_files = [t for t in lines2 if t[0] in new_fds]
        if leaked_files:
            error = [
                "***** %s FD leakage detected" % len(leaked_files),
                *(str(f) for f in leaked_files),
                "*** Before:",
                *(str(f) for f in lines1),
                "*** After:",
                *(str(f) for f in lines2),
                "***** %s FD leakage detected" % len(leaked_files),
                "*** function %s:%s: %s " % item.location,
                "See issue #2366",
            ]
            item.warn(pytest.PytestWarning("\n".join(error)))


# used at least by pytest-xdist plugin 
开发者ID:pytest-dev,项目名称:pytest,代码行数:27,代码来源:pytester.py

示例4: setenv

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import PytestWarning [as 别名]
def setenv(self, name: str, value: str, prepend: Optional[str] = None) -> None:
        """ Set environment variable ``name`` to ``value``.  If ``prepend``
        is a character, read the current environment variable value
        and prepend the ``value`` adjoined with the ``prepend`` character."""
        if not isinstance(value, str):
            warnings.warn(
                pytest.PytestWarning(
                    "Value of environment variable {name} type should be str, but got "
                    "{value!r} (type: {type}); converted to str implicitly".format(
                        name=name, value=value, type=type(value).__name__
                    )
                ),
                stacklevel=2,
            )
            value = str(value)
        if prepend and name in os.environ:
            value = value + prepend + os.environ[name]
        self.setitem(os.environ, name, value) 
开发者ID:pytest-dev,项目名称:pytest,代码行数:20,代码来源:monkeypatch.py

示例5: test_on_rm_rf_error

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import PytestWarning [as 别名]
def test_on_rm_rf_error(self, tmp_path: Path) -> None:
        adir = tmp_path / "dir"
        adir.mkdir()

        fn = adir / "foo.txt"
        fn.touch()
        self.chmod_r(fn)

        # unknown exception
        with pytest.warns(pytest.PytestWarning):
            exc_info1 = (None, RuntimeError(), None)
            on_rm_rf_error(os.unlink, str(fn), exc_info1, start_path=tmp_path)
            assert fn.is_file()

        # we ignore FileNotFoundError
        exc_info2 = (None, FileNotFoundError(), None)
        assert not on_rm_rf_error(None, str(fn), exc_info2, start_path=tmp_path)

        # unknown function
        with pytest.warns(
            pytest.PytestWarning,
            match=r"^\(rm_rf\) unknown function None when removing .*foo.txt:\nNone: ",
        ):
            exc_info3 = (None, PermissionError(), None)
            on_rm_rf_error(None, str(fn), exc_info3, start_path=tmp_path)
            assert fn.is_file()

        # ignored function
        with pytest.warns(None) as warninfo:
            exc_info4 = (None, PermissionError(), None)
            on_rm_rf_error(os.open, str(fn), exc_info4, start_path=tmp_path)
            assert fn.is_file()
        assert not [x.message for x in warninfo]

        exc_info5 = (None, PermissionError(), None)
        on_rm_rf_error(os.unlink, str(fn), exc_info5, start_path=tmp_path)
        assert not fn.is_file() 
开发者ID:pytest-dev,项目名称:pytest,代码行数:39,代码来源:test_tmpdir.py

示例6: test_pytest_warnings_repr_integration_test

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import PytestWarning [as 别名]
def test_pytest_warnings_repr_integration_test(testdir):
    """Small integration test to ensure our small hack of setting the __module__ attribute
    of our warnings actually works (#5452).
    """
    testdir.makepyfile(
        """
        import pytest
        import warnings

        def test():
            warnings.warn(pytest.PytestWarning("some warning"))
    """
    )
    result = testdir.runpytest()
    result.stdout.fnmatch_lines(["E       pytest.PytestWarning: some warning"]) 
开发者ID:pytest-dev,项目名称:pytest,代码行数:17,代码来源:test_warning_types.py

示例7: test_hide_pytest_internal_warnings

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import PytestWarning [as 别名]
def test_hide_pytest_internal_warnings(testdir, ignore_pytest_warnings):
    """Make sure we can ignore internal pytest warnings using a warnings filter."""
    testdir.makepyfile(
        """
        import pytest
        import warnings

        warnings.warn(pytest.PytestWarning("some internal warning"))

        def test_bar():
            pass
    """
    )
    if ignore_pytest_warnings == "ini":
        testdir.makeini(
            """
            [pytest]
            filterwarnings = ignore::pytest.PytestWarning
        """
        )
    args = (
        ["-W", "ignore::pytest.PytestWarning"]
        if ignore_pytest_warnings == "cmdline"
        else []
    )
    result = testdir.runpytest(*args)
    if ignore_pytest_warnings != "no":
        assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()
    else:
        result.stdout.fnmatch_lines(
            [
                "*== %s ==*" % WARNINGS_SUMMARY_HEADER,
                "*test_hide_pytest_internal_warnings.py:4: PytestWarning: some internal warning",
                "* 1 passed, 1 warning *",
            ]
        ) 
开发者ID:pytest-dev,项目名称:pytest,代码行数:38,代码来源:test_warnings.py

示例8: pytest_ignore_collect

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import PytestWarning [as 别名]
def pytest_ignore_collect(path, config):
    if config.pluginmanager.hasplugin("pytest-benchmark"):
        return False
    else:
        global warn
        if warn:
            warnings.warn(pytest.PytestWarning("Skipping benchmarks because pytest-benchmark plugin was not found."))
            warn = False

        return True 
开发者ID:Ultimaker,项目名称:Uranium,代码行数:12,代码来源:conftest.py

示例9: pytest_runtestloop

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import PytestWarning [as 别名]
def pytest_runtestloop(self, session):
        yield

        if self._disabled:
            return

        compat_session = compat.SessionWrapper(session)

        self.failed = bool(compat_session.testsfailed)
        if self.cov_controller is not None:
            self.cov_controller.finish()

        if not self._is_worker(session) and self._should_report():

            # import coverage lazily here to avoid importing
            # it for unit tests that don't need it
            from coverage.misc import CoverageException

            try:
                self.cov_total = self.cov_controller.summary(self.cov_report)
            except CoverageException as exc:
                message = 'Failed to generate report: %s\n' % exc
                session.config.pluginmanager.getplugin("terminalreporter").write(
                    'WARNING: %s\n' % message, red=True, bold=True)
                warnings.warn(pytest.PytestWarning(message))
                self.cov_total = 0
            assert self.cov_total is not None, 'Test coverage should never be `None`'
            if self._failed_cov_total():
                # make sure we get the EXIT_TESTSFAILED exit code
                compat_session.testsfailed += 1 
开发者ID:pytest-dev,项目名称:pytest-cov,代码行数:32,代码来源:plugin.py

示例10: pytest_terminal_summary

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import PytestWarning [as 别名]
def pytest_terminal_summary(self, terminalreporter):
        if self._disabled:
            if self.options.no_cov_should_warn:
                message = 'Coverage disabled via --no-cov switch!'
                terminalreporter.write('WARNING: %s\n' % message, red=True, bold=True)
                warnings.warn(pytest.PytestWarning(message))
            return
        if self.cov_controller is None:
            return

        if self.cov_total is None:
            # we shouldn't report, or report generation failed (error raised above)
            return

        terminalreporter.write('\n' + self.cov_report.getvalue() + '\n')

        if self.options.cov_fail_under is not None and self.options.cov_fail_under > 0:
            failed = self.cov_total < self.options.cov_fail_under
            markup = {'red': True, 'bold': True} if failed else {'green': True}
            message = (
                '{fail}Required test coverage of {required}% {reached}. '
                'Total coverage: {actual:.2f}%\n'
                .format(
                    required=self.options.cov_fail_under,
                    actual=self.cov_total,
                    fail="FAIL " if failed else "",
                    reached="not reached" if failed else "reached"
                )
            )
            terminalreporter.write(message, **markup) 
开发者ID:pytest-dev,项目名称:pytest-cov,代码行数:32,代码来源:plugin.py


注:本文中的pytest.PytestWarning方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。