tests.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536
  1. from django.test import TestCase
  2. from regressiontests.reverse_single_related.models import *
  3. class ReverseSingleRelatedTests(TestCase):
  4. """
  5. Regression tests for an object that cannot access a single related
  6. object due to a restrictive default manager.
  7. """
  8. def test_reverse_single_related(self):
  9. public_source = Source.objects.create(is_public=True)
  10. public_item = Item.objects.create(source=public_source)
  11. private_source = Source.objects.create(is_public=False)
  12. private_item = Item.objects.create(source=private_source)
  13. # Only one source is available via all() due to the custom default manager.
  14. self.assertQuerysetEqual(
  15. Source.objects.all(),
  16. ["<Source: Source object>"]
  17. )
  18. self.assertEqual(public_item.source, public_source)
  19. # Make sure that an item can still access its related source even if the default
  20. # manager doesn't normally allow it.
  21. self.assertEqual(private_item.source, private_source)
  22. # If the manager is marked "use_for_related_fields", it'll get used instead
  23. # of the "bare" queryset. Usually you'd define this as a property on the class,
  24. # but this approximates that in a way that's easier in tests.
  25. Source.objects.use_for_related_fields = True
  26. private_item = Item.objects.get(pk=private_item.pk)
  27. self.assertRaises(Source.DoesNotExist, lambda: private_item.source)