def test_with_app_models(self): call_command('create_session', 'simple', '2') from .simple.models import Player with use_cache(): players = Player.objects.all() self.assertEqual(len(players), 2) group = players[0].group group.save = Mock() group.round_number += 1 # Query session object to test that it's loaded.. group.session participants = group.session.participant_set.all() all_instances = { players[0], players[1], group, group.session, participants[0], participants[1] } self.assertEqual(set(_get_save_objects_model_instances()), all_instances) # No queries are executed. The group model shall be saved, but we # mocked out the save method. All other models should be left # untouched. with self.assertNumQueries(0): save_objects() self.assertTrue(group.save.called)
def test_nested_changes(self): call_command('create_session', 'simple', '1') # Reset cache. with use_cache(): # Query participant via session. session = Session.objects.get() participant = session.participant_set.get() participant.is_on_wait_page = not participant.is_on_wait_page # Save participant. with self.assertNumQueries(1): save_objects()
def test_save_only_changed_fields(self): call_command('create_session', 'simple', '1') with use_cache(): participant = Participant.objects.get() with mock.patch.object(django.db.models.Model, 'save') as patched_save: save_objects() # in save-the-change 2017 version, save is not called at all patched_save.assert_called_once_with(update_fields=[]) participant.code = 'hello' save_objects() # but is this necessarily the only argument? no patched_save.assert_called_with(update_fields=['code'])
def test_dont_save_if_no_change(self): call_command('create_session', 'simple', '1') with use_cache(): participant = Participant.objects.get() # We keep track of the participant. instances = _get_save_objects_model_instances() self.assertEqual(instances, [participant]) # But we won't save the participant since we didn't change it. with self.assertNumQueries(0): save_objects()
def test_with_app_models(self): call_command('create_session', 'simple', '2') from .simple.models import Player with use_cache(): players = Player.objects.all() self.assertEqual(len(players), 2) group = players[0].group group.save = Mock() group.round_number += 1 # Query session object to test that it's loaded.. group.session participants = group.session.participant_set.all() all_instances = { players[0], players[1], group, group.session, participants[0], participants[1] } self.assertEqual( set(_get_save_objects_model_instances()), all_instances) # No queries are executed. The group model shall be saved, but we # mocked out the save method. All other models should be left # untouched. with self.assertNumQueries(0): save_objects() self.assertTrue(group.save.called)