could you please help me to understand what is the difference between these 2 syntaxes in Django tests (Python 3.7):
def test_updateItem_deletion(self): # some logic in here with self.assertRaises(OrderItem.DoesNotExist): OrderItem.objects.get(id=self.product_1.id)
And:
# all the same, but self.assertRaises not wrapped in 'with' self.assertRaises(OrderItem.DoesNotExist, OrderItem.objects.get(id=self.product_1.id))
The first one worked and test passed. But the second one raised:
models.OrderItem.DoesNotExist: OrderItem matching query does not exist.
Does it somehow replicate the behaviour of try/catch block? Thank you a lot!
The first one will catch the exception raised if executed as context manager. On the second one, nothing is catching the exception.
This is known as ContextManager. When using the with statement, an __exit__ method is called at the end of the with block, containing any exception raised during execution of the block.
This __exit__ method is not called when directly calling assertRaises, so the exception is not captured.
Here you will find more info about this: