1. import json
    
  2. 
    
  3. from django.contrib.contenttypes.fields import GenericForeignKey
    
  4. from django.db import models
    
  5. from django.test import TestCase
    
  6. from django.test.utils import isolate_apps
    
  7. 
    
  8. from .models import Answer, Post, Question
    
  9. 
    
  10. 
    
  11. @isolate_apps("contenttypes_tests")
    
  12. class GenericForeignKeyTests(TestCase):
    
  13.     def test_str(self):
    
  14.         class Model(models.Model):
    
  15.             field = GenericForeignKey()
    
  16. 
    
  17.         self.assertEqual(str(Model.field), "contenttypes_tests.Model.field")
    
  18. 
    
  19.     def test_get_content_type_no_arguments(self):
    
  20.         with self.assertRaisesMessage(
    
  21.             Exception, "Impossible arguments to GFK.get_content_type!"
    
  22.         ):
    
  23.             Answer.question.get_content_type()
    
  24. 
    
  25.     def test_incorrect_get_prefetch_queryset_arguments(self):
    
  26.         with self.assertRaisesMessage(
    
  27.             ValueError, "Custom queryset can't be used for this lookup."
    
  28.         ):
    
  29.             Answer.question.get_prefetch_queryset(
    
  30.                 Answer.objects.all(), Answer.objects.all()
    
  31.             )
    
  32. 
    
  33.     def test_get_object_cache_respects_deleted_objects(self):
    
  34.         question = Question.objects.create(text="Who?")
    
  35.         post = Post.objects.create(title="Answer", parent=question)
    
  36. 
    
  37.         question_pk = question.pk
    
  38.         Question.objects.all().delete()
    
  39. 
    
  40.         post = Post.objects.get(pk=post.pk)
    
  41.         with self.assertNumQueries(1):
    
  42.             self.assertEqual(post.object_id, question_pk)
    
  43.             self.assertIsNone(post.parent)
    
  44.             self.assertIsNone(post.parent)
    
  45. 
    
  46. 
    
  47. class GenericRelationTests(TestCase):
    
  48.     def test_value_to_string(self):
    
  49.         question = Question.objects.create(text="test")
    
  50.         answer1 = Answer.objects.create(question=question)
    
  51.         answer2 = Answer.objects.create(question=question)
    
  52.         result = json.loads(Question.answer_set.field.value_to_string(question))
    
  53.         self.assertCountEqual(result, [answer1.pk, answer2.pk])