def test_decorator_saves_changes(self): def arbitrary_view_func(*args, **kwargs): return HttpResponse() request = mock.MagicMock(user=self.user) # This time, it's important it's an actual user instance view = mana_change(arbitrary_view_func, increment_func=lambda req: 10, increment=8) self.assertFalse(request.user.manatransaction_set.exists()) response = view(request) # First, we check that there's actually a record self.assertTrue(request.user.manatransaction_set.exists()) mana_transaction = request.user.manatransaction_set.latest() # Then, that the record has the correct value both for change and for event self.assertEqual(mana_transaction.change, 18) self.assertEqual(mana_transaction.operation, 'arbitrary_view_func') # We should also allow a name to be set for specific circumstances view = mana_change(arbitrary_view_func, increment_func=lambda req: 10, increment=8, operation="Random stuff") response = view(request) mana_transaction = request.user.manatransaction_set.latest() self.assertEqual(mana_transaction.operation, 'Random stuff')
def test_decorator_accepts_lambdas_with_request(self): request = mock.MagicMock() view_func = mock.MagicMock(return_value=HttpResponse(), __name__="irrelevant") view = mana_change(view_func, increment_func=lambda req: 10) request.user = self.user request.user.mana = 0 response = view(request) self.assertEqual(request.user.mana, 10) # A decorator with both the value and the func should accept both and apply both view = mana_change(view_func, increment=5, increment_func=lambda req: 10) request.user.mana = 0 response = view(request) self.assertEqual(request.user.mana, 15) # Increment_func must be applied only when the user is authenticated, of course request.user.mana = 0 request.user.is_authenticated = lambda: False response = view(request) self.assertEqual(request.user.mana, 0)
def test_decorator_can_be_applied(self): # The basic assumption is that most mana-related operations will be on views. request = mock.MagicMock() # mock does not support __name__ at the moment, so... view_func = mock.MagicMock(return_value=HttpResponse(), __name__="irrelevant") view = mana_change(view_func) # the basic requirement is that the view gets called, of course response = view(request) self.assertTrue(view_func.called) self.assertEqual(response.status_code, 200)
def test_decorator_updates_user_mana(self): request = mock.MagicMock() view_func = mock.MagicMock(return_value=HttpResponse(), __name__="irrelevant") view = mana_change(view_func, 10) request.user = self.user request.user.mana = 0 response = view(request) self.assertEqual(request.user.mana, 10) # Unauthenticated users should have no mana change request.user.is_authenticated = lambda: False response = view(request) self.assertEqual(request.user.mana, 10)