當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。