def naturalKeySerializerTest(format, self): # Create all the objects defined in the test data objects = [] instance_count = {} for (func, pk, klass, datum) in natural_key_test_data: with connection.constraint_checks_disabled(): objects.extend(func[0](pk, klass, datum)) # Get a count of the number of objects created for each class for klass in instance_count: instance_count[klass] = klass.objects.count() # Serialize the test database serialized_data = serializers.serialize(format, objects, indent=2, use_natural_keys=True) for obj in serializers.deserialize(format, serialized_data): obj.save() # Assert that the deserialized data is the same # as the original source for (func, pk, klass, datum) in natural_key_test_data: func[1](self, pk, klass, datum) # Assert that the number of objects deserialized is the # same as the number that was serialized. for klass, count in instance_count.items(): self.assertEqual(count, klass.objects.count())
def test_check_constraints(self): """ Constraint checks should raise an IntegrityError when bad data is in the DB. """ with transaction.commit_manually(): # Create an Article. models.Article.objects.create( headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r ) # Retrive it from the DB a = models.Article.objects.get(headline="Test article") a.reporter_id = 30 try: with connection.constraint_checks_disabled(): a.save() with self.assertRaises(IntegrityError): connection.check_constraints() finally: transaction.rollback()
def test_disable_constraint_checks_context_manager(self): """ When constraint checks are disabled (using context manager), should be able to write bad data without IntegrityErrors. """ with transaction.commit_manually(): # Create an Article. models.Article.objects.create( headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r ) # Retrive it from the DB a = models.Article.objects.get(headline="Test article") a.reporter_id = 30 try: with connection.constraint_checks_disabled(): a.save() except IntegrityError: self.fail("IntegrityError should not have occurred.") finally: transaction.rollback()
def test_forward_refs(self): """ Tests that objects ids can be referenced before they are defined in the serialization data. """ # The deserialization process needs to be contained # within a transaction in order to test forward reference # handling. transaction.enter_transaction_management() transaction.managed(True) objs = serializers.deserialize(self.serializer_name, self.fwd_ref_str) with connection.constraint_checks_disabled(): for obj in objs: obj.save() transaction.commit() transaction.leave_transaction_management() for model_cls in (Category, Author, Article): self.assertEqual(model_cls.objects.all().count(), 1) art_obj = Article.objects.all()[0] self.assertEqual(art_obj.categories.all().count(), 1) self.assertEqual(art_obj.author.name, "Agnes")