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