tests.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from __future__ import unicode_literals
  2. from django.db import transaction, IntegrityError, DatabaseError
  3. from django.test import TestCase
  4. from .models import (Counter, WithCustomPK, InheritedCounter, ProxyCounter,
  5. SubCounter)
  6. class ForceTests(TestCase):
  7. def test_force_update(self):
  8. c = Counter.objects.create(name="one", value=1)
  9. # The normal case
  10. c.value = 2
  11. c.save()
  12. # Same thing, via an update
  13. c.value = 3
  14. c.save(force_update=True)
  15. # Won't work because force_update and force_insert are mutually
  16. # exclusive
  17. c.value = 4
  18. with self.assertRaises(ValueError):
  19. c.save(force_insert=True, force_update=True)
  20. # Try to update something that doesn't have a primary key in the first
  21. # place.
  22. c1 = Counter(name="two", value=2)
  23. with self.assertRaises(ValueError):
  24. with transaction.atomic():
  25. c1.save(force_update=True)
  26. c1.save(force_insert=True)
  27. # Won't work because we can't insert a pk of the same value.
  28. c.value = 5
  29. with self.assertRaises(IntegrityError):
  30. with transaction.atomic():
  31. c.save(force_insert=True)
  32. # Trying to update should still fail, even with manual primary keys, if
  33. # the data isn't in the database already.
  34. obj = WithCustomPK(name=1, value=1)
  35. with self.assertRaises(DatabaseError):
  36. with transaction.atomic():
  37. obj.save(force_update=True)
  38. class InheritanceTests(TestCase):
  39. def test_force_update_on_inherited_model(self):
  40. a = InheritedCounter(name="count", value=1, tag="spam")
  41. a.save()
  42. a.save(force_update=True)
  43. def test_force_update_on_proxy_model(self):
  44. a = ProxyCounter(name="count", value=1)
  45. a.save()
  46. a.save(force_update=True)
  47. def test_force_update_on_inherited_model_without_fields(self):
  48. '''
  49. Issue 13864: force_update fails on subclassed models, if they don't
  50. specify custom fields.
  51. '''
  52. a = SubCounter(name="count", value=1)
  53. a.save()
  54. a.value = 2
  55. a.save(force_update=True)