Package: pytest-raises
pytest-raisesApytestplugin implementation of pytest.raises as a pytest.mark fixture.ContentsFeaturesRequirementsInstallationUsageAvailable MarkersLimitations on MarkersAvailable Parameters@pytest.mark.raisesExamples@pytest.mark.setup_raisesExamplesLicenseIssuesFeaturesAdds functionality for marking tests with apytest.mark.raisesfixture, which
functions similarly to usingwith pytest.raisesRequirementspython 2.7 or abovepytest 2.8.1 or aboveInstallationYou can install "pytest-raises" viapipfromPyPI$ pip install pytest-raisesUsageMarking a test with the@pytest.mark.raises()or@pytest.mark.setup_raisesdecorator will mark that the code the test
executes isexpectedto raise an error.  This is different from@pytest.mark.xfail()as it does not mean the test itself might fail, but
instead that the "pass" for the test is that the code raises an error.It will allow tests which raise errors to pass.  The main usage is to assert
that an error of a specific type is raise.If a test is marked with@pytest.mark.raisesor@pytest.mark.setup_raisesand it doesnotraisein the appropriate
testing phase, the test will be failed.Available MarkersThis extension provides two markers for different phases ofpytest:@pytest.mark.raises: for marking a function that shouldraiseduring
thepytest_runtest_callphase.This decorator can be used in place of thewith pytest.raises(...)context manager.@pytest.mark.setup_raises: for marking a function that shouldraiseduring thepytest_runtest_setupphase.Limitations on MarkersAny test function decorated with@pytest.mark.setup_raisesis assumed
to have an empty function body@pytest.mark.setup_raises()deftest_something():passThis is becausepytest_runtest_callmay still be executed depending on
what raised when.  So any code in the test function body may cause
erroneous errors (particularly if you are using fixtures, since the
fixture setup may be incomplete).See the@pytest.mark.setup_raisesExamplesfor more information.Since the function body of anything decorated with@pytest.mark.setup_raisesis assumed to be empty, test functions that
are decorated with both@pytest.mark.raisesand@pytest.mark.setup_raisesisnotsupported.The implementation details of this limitation are further documented in
the_pytest_raises_validationfunction.Available ParametersBoth markers accept the following optional parameters:exception=<Some Exception Class>: the exact exceptionclassthat is
expected to be raised.message='some string': a verbatim message that is expected to be in the
raised exception message.  Note that whenmessageis supplied, the check
performed is essentiallymessage in exception_message.  So any substring
can be used, but if the message is "too simple" you may get false
positives.match=r'some regular expression': a regular expression to be matched for
in the raised exception message.  Note thatre.matchis used
(rather thanre.search).  This behavior is identical to thewith pytest.raisescontext manager.match_flags=<regular expression flags>: any regular expressionflagsdesired to be used with thematchargument.  For example,match_flags=(re.IGNORECASE | re.DOTALL).  No validity checks are
performed on the specified flags, but you will receive an error when the
match is performed and invalid flags are provided (since theremodule
will not understand the flags).Note:themessageandmatcharguments maynotbe supplied at the
same time.  Only one or the other may be provided.@pytest.mark.raisesExamplesA very simple example is:importpytestclassSomeException(Exception):passclassAnotherException(Exception):pass@pytest.mark.raises(exception=SomeException)deftest_mark_raises_named():raiseSomeException('the message')@pytest.mark.raises()deftest_mark_raises_general():raiseAnotherException('the message')A more useful example using test parametrization is:importpytestclassSomeException(Exception):passclassAnotherException(Exception):pass@pytest.mark.parametrize('error',[None,pytest.param(SomeException('the message'),marks=pytest.mark.raises(exception=SomeException)),pytest.param(AnotherException('the message'),marks=pytest.mark.raises(exception=AnotherException)),pytest.param(Exception('the message'),marks=pytest.mark.raises())])deftest_mark_raises_demo(error):iferror:raiseerrorAll of these tests pass.  These examples are actualtests for this plugin(exact test case is intest_pytest_raises_parametrize_demotest).@pytest.mark.setup_raisesExamplesUsage of the@pytest.mark.setup_raisesdecorator is likely to be uncommon,
but when it is needed there is no known alternative.  Consider the following
contrived example, where in aconftest.pywe have the following check for
some custom marker we are concerned about:# in conftest.pydefpytest_runtest_setup(item):custom_marker=item.get_closest_marker('custom_marker')ifcustom_marker:valid=custom_marker.kwargs.get('valid',True)ifnotvalid:raiseValueError('custom_marker.valid was False')and two tests using this markerimportpytest@pytest.mark.custom_marker(valid=False)@pytest.mark.setup_raises(exception=ValueError,match=r'.*was False$')deftest_mark_setup_raises_demo():pass@pytest.mark.custom_marker(valid=True)deftest_all_good():passThis example is in thetests for this pluginin thetest_pytest_mark_setup_raises_demotest case.  This example is awkward, but
the idea is you can use@pytest.mark.setup_raisesto catch expected errors
during thepytest_runtest_setupphase.  So when we usedcustom_markerwithvalid=False, thepytest_runtest_setupwillraiseas expected, but
not whenvalid=True.In the real world, the utility of@pytest.mark.setup_raisescomes in when
you have potentially less control over the execution of fixtures or perhaps
want to stress-test custom markers or fixtures.  Consider writing a decorator
that auto-uses a fixture for a given test function, but deliberately provides
invalid arguments to the fixture.In short: the chances are good that you willnotneed@pytest.mark.setup_raisesin the average testing framework.  However, if
you need to verify failures during thepytest_runtest_setupphase, it is
an invaluable tool.Reminder: notice that when@pytest.mark.setup_raisesis used,the
function body should be exactlypass.  Thepytest_runtest_setupphase
has raised, meaning the setup for the test is incomplete.  Anything other
than an empty test function body ofpassisnotsupported by this
extension.LicenseDistributed under the terms of theMITlicense, "pytest-raises" is free and
open source software.IssuesIf you encounter any problems, pleasefile an issuealong with a detailed
description.