Ticket #13700: django-m2m-through-test-cleanup.2.diff

File django-m2m-through-test-cleanup.2.diff, 11.5 KB (added by Alex, 5 years ago)

2 years of using this trac and I still don't get it :/

  • tests/regressiontests/m2m_through_regress/models.py

    diff --git a/tests/regressiontests/m2m_through_regress/models.py b/tests/regressiontests/m2m_through_regress/models.py
    index 56aecd6..ec87985 100644
    a b  
    11from datetime import datetime
     2
    23from django.contrib.auth.models import User
    34from django.core import management
    45from django.db import models
    56
     7
    68# Forward declared intermediate model
    79class Membership(models.Model):
    810    person = models.ForeignKey('Person')
    class Through(ThroughBase): 
    5153class B(models.Model):
    5254    b_text = models.CharField(max_length=20)
    5355    a_list = models.ManyToManyField(A, through=Through)
    54 
    55 
    56 __test__ = {'API_TESTS':"""
    57 # Create some dummy data
    58 >>> bob = Person.objects.create(name='Bob')
    59 >>> jim = Person.objects.create(name='Jim')
    60 
    61 >>> rock = Group.objects.create(name='Rock')
    62 >>> roll = Group.objects.create(name='Roll')
    63 
    64 >>> frank = User.objects.create_user('frank','frank@example.com','password')
    65 >>> jane = User.objects.create_user('jane','jane@example.com','password')
    66 
    67 # Now test that the forward declared Membership works
    68 >>> Membership.objects.create(person=bob, group=rock)
    69 <Membership: Bob is a member of Rock>
    70 
    71 >>> Membership.objects.create(person=bob, group=roll)
    72 <Membership: Bob is a member of Roll>
    73 
    74 >>> Membership.objects.create(person=jim, group=rock)
    75 <Membership: Jim is a member of Rock>
    76 
    77 >>> bob.group_set.all()
    78 [<Group: Rock>, <Group: Roll>]
    79 
    80 >>> roll.members.all()
    81 [<Person: Bob>]
    82 
    83 # Error messages use the model name, not repr of the class name
    84 >>> bob.group_set = []
    85 Traceback (most recent call last):
    86 ...
    87 AttributeError: Cannot set values on a ManyToManyField which specifies an intermediary model.  Use m2m_through_regress.Membership's Manager instead.
    88 
    89 >>> roll.members = []
    90 Traceback (most recent call last):
    91 ...
    92 AttributeError: Cannot set values on a ManyToManyField which specifies an intermediary model.  Use m2m_through_regress.Membership's Manager instead.
    93 
    94 >>> rock.members.create(name='Anne')
    95 Traceback (most recent call last):
    96 ...
    97 AttributeError: Cannot use create() on a ManyToManyField which specifies an intermediary model.  Use m2m_through_regress.Membership's Manager instead.
    98 
    99 >>> bob.group_set.create(name='Funk')
    100 Traceback (most recent call last):
    101 ...
    102 AttributeError: Cannot use create() on a ManyToManyField which specifies an intermediary model.  Use m2m_through_regress.Membership's Manager instead.
    103 
    104 # Now test that the intermediate with a relationship outside
    105 # the current app (i.e., UserMembership) workds
    106 >>> UserMembership.objects.create(user=frank, group=rock)
    107 <UserMembership: frank is a user and member of Rock>
    108 
    109 >>> UserMembership.objects.create(user=frank, group=roll)
    110 <UserMembership: frank is a user and member of Roll>
    111 
    112 >>> UserMembership.objects.create(user=jane, group=rock)
    113 <UserMembership: jane is a user and member of Rock>
    114 
    115 >>> frank.group_set.all()
    116 [<Group: Rock>, <Group: Roll>]
    117 
    118 >>> roll.user_members.all()
    119 [<User: frank>]
    120 
    121 # Regression test for #8134 --
    122 # m2m-through models shouldn't be serialized as m2m fields on the model.
    123 
    124 # First, clean up a lot of objects we don't need.
    125 # The serialization test only requires three objects to work -
    126 # one for each end of the m2m, plus the through model.
    127 
    128 >>> User.objects.all().delete()
    129 >>> UserMembership.objects.all().delete()
    130 >>> frank.delete()
    131 >>> rock.delete()
    132 >>> jim.delete()
    133 
    134 # Dump the current contents of the database as a JSON fixture
    135 >>> management.call_command('dumpdata', 'm2m_through_regress', format='json', indent=2)
    136 [
    137   {
    138     "pk": 2,
    139     "model": "m2m_through_regress.membership",
    140     "fields": {
    141       "person": 1,
    142       "price": 100,
    143       "group": 2
    144     }
    145   },
    146   {
    147     "pk": 1,
    148     "model": "m2m_through_regress.person",
    149     "fields": {
    150       "name": "Bob"
    151     }
    152   },
    153   {
    154     "pk": 2,
    155     "model": "m2m_through_regress.group",
    156     "fields": {
    157       "name": "Roll"
    158     }
    159   }
    160 ]
    161 
    162 # Check the XML serializer too, since it doesn't use the common implementation
    163 >>> management.call_command('dumpdata', 'm2m_through_regress', format='xml', indent=2)
    164 <?xml version="1.0" encoding="utf-8"?>
    165 <django-objects version="1.0">
    166   <object pk="2" model="m2m_through_regress.membership">
    167     <field to="m2m_through_regress.person" name="person" rel="ManyToOneRel">1</field>
    168     <field to="m2m_through_regress.group" name="group" rel="ManyToOneRel">2</field>
    169     <field type="IntegerField" name="price">100</field>
    170   </object>
    171   <object pk="1" model="m2m_through_regress.person">
    172     <field type="CharField" name="name">Bob</field>
    173   </object>
    174   <object pk="2" model="m2m_through_regress.group">
    175     <field type="CharField" name="name">Roll</field>
    176   </object>
    177 </django-objects>
    178 
    179 ## Regression test for #8046:
    180 Check that we don't involve too many copies of the intermediate table when
    181 doing a join.
    182 
    183 >>> bob = Person.objects.create(name='Bob')
    184 >>> jim = Person.objects.create(name='Jim')
    185 >>> rock = Group.objects.create(name='Rock')
    186 >>> roll = Group.objects.create(name='Roll')
    187 >>> _ = Membership.objects.create(person=bob, group=rock)
    188 >>> _ = Membership.objects.create(person=jim, group=rock, price=50)
    189 >>> _ = Membership.objects.create(person=bob, group=roll, price=50)
    190 >>> rock.members.filter(membership__price=50)
    191 [<Person: Jim>]
    192 
    193 ## Regression test for #8254
    194 >>> bob.group_set.filter(membership__price=50)
    195 [<Group: Roll>]
    196 
    197 ## Regression test for #9804
    198 # Flush the database, just to make sure we can.
    199 >>> management.call_command('flush', verbosity=0, interactive=False)
    200 
    201 ## Regression test for #11107
    202 Ensure that sequences on m2m_through tables are being created for the through
    203 model, not for a phantom auto-generated m2m table.
    204 
    205 >>> management.call_command('loaddata', 'm2m_through', verbosity=0)
    206 >>> management.call_command('dumpdata', 'm2m_through_regress', format='json')
    207 [{"pk": 1, "model": "m2m_through_regress.usermembership", "fields": {"price": 100, "group": 1, "user": 1}}, {"pk": 1, "model": "m2m_through_regress.person", "fields": {"name": "Guido"}}, {"pk": 1, "model": "m2m_through_regress.group", "fields": {"name": "Python Core Group"}}]
    208 
    209 """}
  • new file tests/regressiontests/m2m_through_regress/tests.py

    diff --git a/tests/regressiontests/m2m_through_regress/tests.py b/tests/regressiontests/m2m_through_regress/tests.py
    new file mode 100644
    index 0000000..5937bb8
    - +  
     1try:
     2    from cStringIO import StringIO
     3except ImportError:
     4    from StringIO import StringIO
     5
     6from django.core import management
     7from django.contrib.auth.models import User
     8from django.test import TestCase
     9
     10from models import Person, Group, Membership, UserMembership
     11
     12
     13class M2MThroughTestCase(TestCase):
     14    def test_everything(self):
     15        bob = Person.objects.create(name="Bob")
     16        jim = Person.objects.create(name="Jim")
     17       
     18        rock = Group.objects.create(name="Rock")
     19        roll = Group.objects.create(name="Roll")
     20       
     21        frank = User.objects.create_user("frank", "frank@example.com", "password")
     22        jane = User.objects.create_user("jane", "jane@example.com", "password")
     23       
     24        Membership.objects.create(person=bob, group=rock)
     25        Membership.objects.create(person=bob, group=roll)
     26        Membership.objects.create(person=jim, group=rock)
     27       
     28        self.assertQuerysetEqual(
     29            bob.group_set.all(), [
     30                "Rock",
     31                "Roll",
     32            ],
     33            lambda g: g.name,
     34        )
     35       
     36        self.assertQuerysetEqual(
     37            roll.members.all(), [
     38                "Bob",
     39            ],
     40            lambda p: p.name
     41        )
     42       
     43        self.assertRaises(AttributeError, setattr, bob, "group_set", [])
     44        self.assertRaises(AttributeError, setattr, roll, "members", [])
     45       
     46        self.assertRaises(AttributeError, rock.members.create, name="Anne")
     47        self.assertRaises(AttributeError, bob.group_set.create, name="Funk")
     48       
     49        UserMembership.objects.create(user=frank, group=rock)
     50        UserMembership.objects.create(user=frank, group=roll)
     51        UserMembership.objects.create(user=jane, group=rock)
     52       
     53        self.assertQuerysetEqual(
     54            frank.group_set.all(), [
     55                "Rock",
     56                "Roll",
     57            ],
     58            lambda g: g.name
     59        )
     60       
     61        self.assertQuerysetEqual(
     62            roll.user_members.all(), [
     63                "frank",
     64            ],
     65            lambda u: u.username,
     66        )
     67   
     68    def test_serialization(self):
     69        p = Person.objects.create(name="Bob")
     70        g = Group.objects.create(name="Roll")
     71        Membership.objects.create(person=p, group=g)
     72       
     73        out = StringIO()
     74        management.call_command("dumpdata", "m2m_through_regress",
     75            format="json", indent=2, stdout=out)
     76        self.assertEqual(out.getvalue().strip(), """
     77[
     78  {
     79    "pk": 1,
     80    "model": "m2m_through_regress.membership",
     81    "fields": {
     82      "person": 1,
     83      "price": 100,
     84      "group": 1
     85    }
     86  },
     87  {
     88    "pk": 1,
     89    "model": "m2m_through_regress.person",
     90    "fields": {
     91      "name": "Bob"
     92    }
     93  },
     94  {
     95    "pk": 1,
     96    "model": "m2m_through_regress.group",
     97    "fields": {
     98      "name": "Roll"
     99    }
     100  }
     101]
     102        """.strip())
     103   
     104        out = StringIO()
     105        management.call_command("dumpdata", "m2m_through_regress", format="xml",
     106            indent=2, stdout=out)
     107        self.assertEqual(out.getvalue().strip(), """
     108<?xml version="1.0" encoding="utf-8"?>
     109<django-objects version="1.0">
     110  <object pk="1" model="m2m_through_regress.membership">
     111    <field to="m2m_through_regress.person" name="person" rel="ManyToOneRel">1</field>
     112    <field to="m2m_through_regress.group" name="group" rel="ManyToOneRel">1</field>
     113    <field type="IntegerField" name="price">100</field>
     114  </object>
     115  <object pk="1" model="m2m_through_regress.person">
     116    <field type="CharField" name="name">Bob</field>
     117  </object>
     118  <object pk="1" model="m2m_through_regress.group">
     119    <field type="CharField" name="name">Roll</field>
     120  </object>
     121</django-objects>
     122        """.strip())
     123   
     124    def test_join_trimming(self):
     125        bob  = Person.objects.create(name="Bob")
     126        jim = Person.objects.create(name="Jim")
     127
     128        rock = Group.objects.create(name="Rock")
     129        roll = Group.objects.create(name="Roll")
     130       
     131        Membership.objects.create(person=bob, group=rock)
     132        Membership.objects.create(person=jim, group=rock, price=50)
     133        Membership.objects.create(person=bob, group=roll, price=50)
     134       
     135        self.assertQuerysetEqual(
     136            rock.members.filter(membership__price=50), [
     137                "Jim",
     138            ],
     139            lambda p: p.name
     140        )
     141       
     142        self.assertQuerysetEqual(
     143            bob.group_set.filter(membership__price=50), [
     144                "Roll",
     145            ],
     146            lambda g: g.name
     147        )
     148   
     149class ThroughLoadDataTestCase(TestCase):
     150    fixtures = ["m2m_through"]
     151   
     152    def test_dumpdata(self):
     153        out = StringIO()
     154        management.call_command("dumpdata", "m2m_through_regress", format="json",
     155            stdout=out)
     156       
     157        self.assertEqual(out.getvalue().strip(), """[{"pk": 1, "model": "m2m_through_regress.usermembership", "fields": {"price": 100, "group": 1, "user": 1}}, {"pk": 1, "model": "m2m_through_regress.person", "fields": {"name": "Guido"}}, {"pk": 1, "model": "m2m_through_regress.group", "fields": {"name": "Python Core Group"}}]""")
Back to Top