tests.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from django.core import management
  2. from django.core.management import CommandError
  3. from django.test import TestCase
  4. from .models import Article
  5. class SampleTestCase(TestCase):
  6. fixtures = ["model_package_fixture1.json", "model_package_fixture2.json"]
  7. def test_class_fixtures(self):
  8. "Test cases can load fixture objects into models defined in packages"
  9. self.assertQuerySetEqual(
  10. Article.objects.all(),
  11. [
  12. "Django conquers world!",
  13. "Copyright is fine the way it is",
  14. "Poker has no place on ESPN",
  15. ],
  16. lambda a: a.headline,
  17. )
  18. class FixtureTestCase(TestCase):
  19. def test_loaddata(self):
  20. "Fixtures can load data into models defined in packages"
  21. # Load fixture 1. Single JSON file, with two objects
  22. management.call_command("loaddata", "model_package_fixture1.json", verbosity=0)
  23. self.assertQuerySetEqual(
  24. Article.objects.all(),
  25. [
  26. "Time to reform copyright",
  27. "Poker has no place on ESPN",
  28. ],
  29. lambda a: a.headline,
  30. )
  31. # Load fixture 2. JSON file imported by default. Overwrites some
  32. # existing objects
  33. management.call_command("loaddata", "model_package_fixture2.json", verbosity=0)
  34. self.assertQuerySetEqual(
  35. Article.objects.all(),
  36. [
  37. "Django conquers world!",
  38. "Copyright is fine the way it is",
  39. "Poker has no place on ESPN",
  40. ],
  41. lambda a: a.headline,
  42. )
  43. # Load a fixture that doesn't exist
  44. with self.assertRaisesMessage(
  45. CommandError, "No fixture named 'unknown' found."
  46. ):
  47. management.call_command("loaddata", "unknown.json", verbosity=0)
  48. self.assertQuerySetEqual(
  49. Article.objects.all(),
  50. [
  51. "Django conquers world!",
  52. "Copyright is fine the way it is",
  53. "Poker has no place on ESPN",
  54. ],
  55. lambda a: a.headline,
  56. )