pytest.fail.Exception

Here are the examples of the python api pytest.fail.Exception taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

17 Examples 7

Example 1

Project: pytest Source File: metafunc.py
    def test_addcall_funcargs(self):
        def func(x): pass
        metafunc = self.Metafunc(func)
        class obj: pass
        metafunc.addcall(funcargs={"x": 2})
        metafunc.addcall(funcargs={"x": 3})
        pytest.raises(pytest.fail.Exception, "metafunc.addcall({'xyz': 0})")
        assert len(metafunc._calls) == 2
        assert metafunc._calls[0].funcargs == {'x': 2}
        assert metafunc._calls[1].funcargs == {'x': 3}
        assert not hasattr(metafunc._calls[1], 'param')

Example 2

Project: pytest Source File: test_skipping.py
    def test_marked_skip_with_not_string(self, testdir):
        item = testdir.getitem("""
            import pytest
            @pytest.mark.skipif(False)
            def test_func():
                pass
        """)
        ev = MarkEvaluator(item, 'skipif')
        exc = pytest.raises(pytest.fail.Exception, ev.istrue)
        assert """Failed: you need to specify reason=STRING when using booleans as conditions.""" in exc.value.msg

Example 3

Project: qutebrowser Source File: quteprocess.py
Function: compare_session
    def compare_session(self, expected):
        """Compare the current sessions against the given template.

        partial_compare is used, which means only the keys/values listed will
        be compared.
        """
        __tracebackhide__ = lambda e: e.errisinstance(pytest.fail.Exception)
        # Translate ... to ellipsis in YAML.
        loader = yaml.SafeLoader(expected)
        loader.add_constructor('!ellipsis', lambda loader, node: ...)
        loader.add_implicit_resolver('!ellipsis', re.compile(r'\.\.\.'), None)

        data = self.get_session()
        expected = loader.get_data()
        outcome = testutils.partial_compare(data, expected)
        if not outcome:
            msg = "Session comparison failed: {}".format(outcome.error)
            msg += '\nsee stdout for details'
            pytest.fail(msg)

Example 4

Project: pytest-catchlog Source File: test_reporting.py
def test_nothing_logged(testdir):
    testdir.makepyfile('''
        import sys

        def test_foo():
            sys.stdout.write('text going to stdout')
            sys.stderr.write('text going to stderr')
            assert False
        ''')
    result = testdir.runpytest()
    assert result.ret == 1
    result.stdout.fnmatch_lines(['*- Captured stdout call -*',
                                 'text going to stdout'])
    result.stdout.fnmatch_lines(['*- Captured stderr call -*',
                                 'text going to stderr'])
    with pytest.raises(pytest.fail.Exception):
        result.stdout.fnmatch_lines(['*- Captured *log call -*'])

Example 5

Project: pyp2rpm Source File: test_pytester.py
def test_hookrecorder_basic():
    rec = HookRecorder(PluginManager())
    class ApiClass:
        def pytest_xyz(self, arg):
            "x"
    rec.start_recording(ApiClass)
    rec.hook.pytest_xyz(arg=123)
    call = rec.popcall("pytest_xyz")
    assert call.arg == 123
    assert call._name == "pytest_xyz"
    pytest.raises(pytest.fail.Exception, "rec.popcall('abc')")

Example 6

Project: pyp2rpm Source File: python.py
Function: repr_failure_py
    def _repr_failure_py(self, excinfo, style="long"):
        if excinfo.errisinstance(FuncargRequest.LookupError):
            fspath, lineno, msg = self.reportinfo()
            lines, _ = inspect.getsourcelines(self.obj)
            for i, line in enumerate(lines):
                if line.strip().startswith('def'):
                    return FuncargLookupErrorRepr(fspath, lineno,
            lines[:i+1], str(excinfo.value))
        if excinfo.errisinstance(pytest.fail.Exception):
            if not excinfo.value.pytrace:
                return str(excinfo.value)
        return super(FunctionMixin, self)._repr_failure_py(excinfo,
            style=style)

Example 7

Project: pytest Source File: test_recwarn.py
    def test_deprecated_call_as_context_manager_no_warning(self):
        with pytest.raises(pytest.fail.Exception) as ex:
            with pytest.deprecated_call():
                self.dep(1)
        assert str(ex.value) == "DID NOT WARN"

Example 8

Project: pytest-django Source File: test_database.py
def test_noaccess():
    with pytest.raises(pytest.fail.Exception):
        Item.objects.create(name='spam')
    with pytest.raises(pytest.fail.Exception):
        Item.objects.count()

Example 9

Project: pytest-django Source File: test_environment.py
def test_database_noaccess():
    with pytest.raises(pytest.fail.Exception):
        Item.objects.count()

Example 10

Project: qutebrowser Source File: quteprocess.py
Function: after_test
    def after_test(self):
        """Handle unexpected/skip logging and clean up after each test."""
        __tracebackhide__ = lambda e: e.errisinstance(pytest.fail.Exception)
        bad_msgs = [msg for msg in self._data
                    if self._is_error_logline(msg) and not msg.expected]

        try:
            call = self.request.node.rep_call
        except AttributeError:
            pass
        else:
            if call.failed or hasattr(call, 'wasxfail'):
                super().after_test()
                return

        try:
            if bad_msgs:
                text = 'Logged unexpected errors:\n\n' + '\n'.join(
                    str(e) for e in bad_msgs)
                # We'd like to use pytrace=False here but don't as a WORKAROUND
                # for https://github.com/pytest-dev/pytest/issues/1316
                pytest.fail(text)
            else:
                self._maybe_skip()
        finally:
            super().after_test()

Example 11

Project: qutebrowser Source File: test_logfail.py
Function: test_log_warning
def test_log_warning():
    with pytest.raises(pytest.fail.Exception):
        logging.warning('foo')

Example 12

Project: qutebrowser Source File: test_logfail.py
def test_log_expected_wrong_level(caplog):
    with pytest.raises(pytest.fail.Exception):
        with caplog.at_level(logging.ERROR):
            logging.critical('foo')

Example 13

Project: qutebrowser Source File: test_logfail.py
def test_log_expected_logger_wrong_level(caplog):
    logger = 'logfail_test_logger'
    with pytest.raises(pytest.fail.Exception):
        with caplog.at_level(logging.ERROR, logger):
            logging.getLogger(logger).critical('foo')

Example 14

Project: qutebrowser Source File: test_logfail.py
def test_log_expected_wrong_logger(caplog):
    logger = 'logfail_test_logger'
    with pytest.raises(pytest.fail.Exception):
        with caplog.at_level(logging.ERROR, logger):
            logging.error('foo')

Example 15

Project: pytest-catchlog Source File: test_compat.py
def test_camel_case_aliases(testdir):
    testdir.makepyfile('''
        import logging

        logger = logging.getLogger(__name__)

        def test_foo(caplog):
            caplog.setLevel(logging.INFO)
            logger.debug('boo!')

            with caplog.atLevel(logging.WARNING):
                logger.info('catch me if you can')
        ''')
    result = testdir.runpytest()
    assert result.ret == 0

    with pytest.raises(pytest.fail.Exception):
        result.stdout.fnmatch_lines(['*- Captured *log call -*'])

    result = testdir.runpytest('-rw')
    assert result.ret == 0
    result.stdout.fnmatch_lines('''
        =*warning summary*=
        *WL1*test_camel_case_aliases*caplog.setLevel()*deprecated*
        *WL1*test_camel_case_aliases*caplog.atLevel()*deprecated*
    ''')

Example 16

Project: pytest-catchlog Source File: test_reporting.py
def test_disable_log_capturing(testdir):
    testdir.makepyfile('''
        import sys
        import logging

        logger = logging.getLogger(__name__)

        def test_foo():
            sys.stdout.write('text going to stdout')
            logger.warning('catch me if you can!')
            sys.stderr.write('text going to stderr')
            assert False
        ''')
    result = testdir.runpytest('--no-print-logs')
    print(result.stdout)
    assert result.ret == 1
    result.stdout.fnmatch_lines(['*- Captured stdout call -*',
                                 'text going to stdout'])
    result.stdout.fnmatch_lines(['*- Captured stderr call -*',
                                 'text going to stderr'])
    with pytest.raises(pytest.fail.Exception):
        result.stdout.fnmatch_lines(['*- Captured *log call -*'])

Example 17

Project: pytest-catchlog Source File: test_reporting.py
def test_disable_log_capturing_ini(testdir):
    testdir.makeini(
        '''
        [pytest]
        log_print=False
        '''
    )
    testdir.makepyfile('''
        import sys
        import logging

        logger = logging.getLogger(__name__)

        def test_foo():
            sys.stdout.write('text going to stdout')
            logger.warning('catch me if you can!')
            sys.stderr.write('text going to stderr')
            assert False
        ''')
    result = testdir.runpytest()
    print(result.stdout)
    assert result.ret == 1
    result.stdout.fnmatch_lines(['*- Captured stdout call -*',
                                 'text going to stdout'])
    result.stdout.fnmatch_lines(['*- Captured stderr call -*',
                                 'text going to stderr'])
    with pytest.raises(pytest.fail.Exception):
        result.stdout.fnmatch_lines(['*- Captured *log call -*'])