Skip to content

Commit

Permalink
document Throwing in reference (#139)
Browse files Browse the repository at this point in the history
  • Loading branch information
haarcuba authored May 22, 2024
1 parent dbc0b74 commit 7a31c66
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
22 changes: 22 additions & 0 deletions docs/reference/advanced_argument_expectations.rst
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,28 @@ The ``test_this_will_fail()`` test would have passed, because ``joe`` is equal t
E expected: mylist.append(|IS <classroom.Person object at 0x7f5162c2c5e0>|)
E actual : mylist.append(<classroom.Person object at 0x7f5162c2c250>)
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
-------------------
Expand Down
7 changes: 7 additions & 0 deletions docs/reference/argument_expectations/particle_classifier.py
Original file line number Diff line number Diff line change
@@ -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
14 changes: 14 additions & 0 deletions docs/reference/argument_expectations/test_particle_classifier.py
Original file line number Diff line number Diff line change
@@ -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')

0 comments on commit 7a31c66

Please sign in to comment.