python - How does pytest.raises(Error) work? -


new-ish python i'm trying understand slice of code:

with pytest.raises(valueerror):     group_adjust(vals, [grps_1, grps_2], weights) 

after reading this tutorial on with, understand pytest.raises() returns context manager sets , cleans things before , after group_adjust() called. understand group_adjust() should raise valueerror if goes wrong.

how pytest "react" when valueerror raised? afaik, there's setting , cleaning i'm not sure how catches exception. end goal understand benefits of having pytest context manager.

__exit__ magic function accepts exception_type, exception_value , traceback parameters:

in [5]: class raisescontext:    ...:     def __enter__(self):    ...:         return self    ...:     def __exit__(self, exception_type, exception_value, traceback):    ...:         print('exception type:', exception_type)    ...:         print('exception value:', exception_value)    ...:         print('traceback:', traceback)    ...:         return true    ...:       in [6]: raisescontext():    ...:     raise valueerror('something went wrong')    ...:  exception type: <class 'valueerror'> exception value: went wrong traceback: <traceback object @ 0x7fd92f4a2c48> 

they none, if with block ends normally:

in [7]: raisescontext():    ...:     pass    ...:  exception type: none exception value: none traceback: none 

Comments