diff --git a/docs/reference/advanced_argument_expectations.rst b/docs/reference/advanced_argument_expectations.rst index 3c0b6a8..38851c5 100644 --- a/docs/reference/advanced_argument_expectations.rst +++ b/docs/reference/advanced_argument_expectations.rst @@ -93,6 +93,28 @@ The ``test_this_will_fail()`` test would have passed, because ``joe`` is equal t E expected: mylist.append(|IS |) E actual : mylist.append() +Raising Exceptions +------------------ + +Sometimes you want to test that your code handles an exception correctly. Handling it "correctly" +may be allowing it to propagate, or catching it and doing something specific with it. + +Either way, you can make a ``Fake`` raise an exception using the ``Throwing`` modifier. Here is an example: + +.. literalinclude:: argument_expectations/test_particle_classifier.py + :linenos: + :emphasize-lines: 11 + +This test will enforce *both* that ``Fake('spin_verifier')`` is called, and that an exception is raised. + +NOTE: if you don't care about some details, e.g. the string inside ``Exception`` here, +you can just use ``Throwing(Exception)``. The ``Throwing`` modifier calls its argument, and raises the resulting object, +so in this case it will just raise a plain ``Exception()``. + +Here is the code that passes this test: + +.. literalinclude:: argument_expectations/particle_classifier.py + :linenos: Capturing Arguments ------------------- diff --git a/docs/reference/argument_expectations/particle_classifier.py b/docs/reference/argument_expectations/particle_classifier.py new file mode 100644 index 0000000..485b636 --- /dev/null +++ b/docs/reference/argument_expectations/particle_classifier.py @@ -0,0 +1,7 @@ +class ParticleClassifier: + def __init__(self, spin_verifier): + self._spin_verifier = spin_verifier + + def classify(self, mass, spin): + self._spin_verifier(spin) + # other logic here diff --git a/docs/reference/argument_expectations/test_particle_classifier.py b/docs/reference/argument_expectations/test_particle_classifier.py new file mode 100644 index 0000000..6a41922 --- /dev/null +++ b/docs/reference/argument_expectations/test_particle_classifier.py @@ -0,0 +1,14 @@ +from testix import * +import pytest + +import particle_classifier + +def my_exception_factory(): + return Exception('bad spin value') + +def test_allow_spin_verifier_to_raise_exceptions(): + with Scenario() as s: + s.spin_verifier('some spin value') >> Throwing(my_exception_factory) + tested = particle_classifier.ParticleClassifier(Fake('spin_verifier')) + with pytest.raises(Exception, match='bad spin value'): + tested.classify(mass='0.5MeV', spin='some spin value')