2
0

tests.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. from django.test import TestCase
  2. from django.core.exceptions import FieldError
  3. from regressiontests.null_queries.models import *
  4. class NullQueriesTests(TestCase):
  5. def test_none_as_null(self):
  6. """
  7. Regression test for the use of None as a query value.
  8. None is interpreted as an SQL NULL, but only in __exact queries.
  9. Set up some initial polls and choices
  10. """
  11. p1 = Poll(question='Why?')
  12. p1.save()
  13. c1 = Choice(poll=p1, choice='Because.')
  14. c1.save()
  15. c2 = Choice(poll=p1, choice='Why Not?')
  16. c2.save()
  17. # Exact query with value None returns nothing ("is NULL" in sql,
  18. # but every 'id' field has a value).
  19. self.assertQuerysetEqual(Choice.objects.filter(choice__exact=None), [])
  20. # Excluding the previous result returns everything.
  21. self.assertQuerysetEqual(
  22. Choice.objects.exclude(choice=None).order_by('id'),
  23. [
  24. '<Choice: Choice: Because. in poll Q: Why? >',
  25. '<Choice: Choice: Why Not? in poll Q: Why? >'
  26. ]
  27. )
  28. # Valid query, but fails because foo isn't a keyword
  29. self.assertRaises(FieldError, Choice.objects.filter, foo__exact=None)
  30. # Can't use None on anything other than __exact
  31. self.assertRaises(ValueError, Choice.objects.filter, id__gt=None)
  32. # Can't use None on anything other than __exact
  33. self.assertRaises(ValueError, Choice.objects.filter, foo__gt=None)
  34. # Related managers use __exact=None implicitly if the object hasn't been saved.
  35. p2 = Poll(question="How?")
  36. self.assertEqual(repr(p2.choice_set.all()), '[]')
  37. def test_reverse_relations(self):
  38. """
  39. Querying across reverse relations and then another relation should
  40. insert outer joins correctly so as not to exclude results.
  41. """
  42. obj = OuterA.objects.create()
  43. self.assertQuerysetEqual(
  44. OuterA.objects.filter(inner__second=None),
  45. ['<OuterA: OuterA object>']
  46. )
  47. self.assertQuerysetEqual(
  48. OuterA.objects.filter(inner__second__data=None),
  49. ['<OuterA: OuterA object>']
  50. )
  51. inner_obj = Inner.objects.create(first=obj)
  52. self.assertQuerysetEqual(
  53. Inner.objects.filter(first__inner__second=None),
  54. ['<Inner: Inner object>']
  55. )
  56. # Ticket #13815: check if <reverse>_isnull=False does not produce
  57. # faulty empty lists
  58. objB = OuterB.objects.create(data="reverse")
  59. self.assertQuerysetEqual(
  60. OuterB.objects.filter(inner__isnull=False),
  61. []
  62. )
  63. Inner.objects.create(first=obj)
  64. self.assertQuerysetEqual(
  65. OuterB.objects.exclude(inner__isnull=False),
  66. ['<OuterB: OuterB object>']
  67. )