id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
3,300
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/proxy_model_inheritance/app1/models.py
from app2.models import NiceModel class ProxyModel(NiceModel): class Meta: proxy = True
101
Python
.py
4
21
33
0.739583
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,301
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/signals/models.py
""" Testing signals before/after saving and deleting. """ from django.db import models class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) def __unicode__(self): return u"%s %s" % (self.first_name, self.last_name)
303
Python
.py
9
30
59
0.706897
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,302
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/signals/tests.py
from django.db.models import signals from django.test import TestCase from models import Person # #8285: signals can be any callable class PostDeleteHandler(object): def __init__(self, data): self.data = data def __call__(self, signal, sender, instance, **kwargs): self.data.append( (instance, instance.id is None) ) class MyReceiver(object): def __init__(self, param): self.param = param self._run = False def __call__(self, signal, sender, **kwargs): self._run = True signal.disconnect(receiver=self, sender=sender) class SignalTests(TestCase): def test_basic(self): # Save up the number of connected signals so that we can check at the # end that all the signals we register get properly unregistered (#9989) pre_signals = ( len(signals.pre_save.receivers), len(signals.post_save.receivers), len(signals.pre_delete.receivers), len(signals.post_delete.receivers), ) data = [] def pre_save_test(signal, sender, instance, **kwargs): data.append( (instance, kwargs.get("raw", False)) ) signals.pre_save.connect(pre_save_test) def post_save_test(signal, sender, instance, **kwargs): data.append( (instance, kwargs.get("created"), kwargs.get("raw", False)) ) signals.post_save.connect(post_save_test) def pre_delete_test(signal, sender, instance, **kwargs): data.append( (instance, instance.id is None) ) signals.pre_delete.connect(pre_delete_test) post_delete_test = PostDeleteHandler(data) signals.post_delete.connect(post_delete_test) p1 = Person(first_name="John", last_name="Smith") self.assertEqual(data, []) p1.save() self.assertEqual(data, [ (p1, False), (p1, True, False), ]) data[:] = [] p1.first_name = "Tom" p1.save() self.assertEqual(data, [ (p1, False), (p1, False, False), ]) data[:] = [] # Calling an internal method purely so that we can trigger a "raw" save. p1.save_base(raw=True) self.assertEqual(data, [ (p1, True), (p1, False, True), ]) data[:] = [] p1.delete() self.assertEqual(data, [ (p1, False), (p1, False), ]) data[:] = [] p2 = Person(first_name="James", last_name="Jones") p2.id = 99999 p2.save() self.assertEqual(data, [ (p2, False), (p2, True, False), ]) data[:] = [] p2.id = 99998 p2.save() self.assertEqual(data, [ (p2, False), (p2, True, False), ]) data[:] = [] p2.delete() self.assertEqual(data, [ (p2, False), (p2, False) ]) self.assertQuerysetEqual( Person.objects.all(), [ "James Jones", ], unicode ) signals.post_delete.disconnect(post_delete_test) signals.pre_delete.disconnect(pre_delete_test) signals.post_save.disconnect(post_save_test) signals.pre_save.disconnect(pre_save_test) # Check that all our signals got disconnected properly. post_signals = ( len(signals.pre_save.receivers), len(signals.post_save.receivers), len(signals.pre_delete.receivers), len(signals.post_delete.receivers), ) self.assertEqual(pre_signals, post_signals) def test_disconnect_in_dispatch(self): """ Test that signals that disconnect when being called don't mess future dispatching. """ a, b = MyReceiver(1), MyReceiver(2) signals.post_save.connect(sender=Person, receiver=a) signals.post_save.connect(sender=Person, receiver=b) p = Person.objects.create(first_name='John', last_name='Smith') self.assertTrue(a._run) self.assertTrue(b._run) self.assertEqual(signals.post_save.receivers, [])
4,307
Python
.py
124
24.895161
80
0.558307
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,303
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/custom_pk/models.py
# -*- coding: utf-8 -*- """ 14. Using a custom primary key By default, Django adds an ``"id"`` field to each model. But you can override this behavior by explicitly adding ``primary_key=True`` to a field. """ from django.conf import settings from django.db import models, transaction, IntegrityError, DEFAULT_DB_ALIAS from fields import MyAutoField class Employee(models.Model): employee_code = models.IntegerField(primary_key=True, db_column = 'code') first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) class Meta: ordering = ('last_name', 'first_name') def __unicode__(self): return u"%s %s" % (self.first_name, self.last_name) class Business(models.Model): name = models.CharField(max_length=20, primary_key=True) employees = models.ManyToManyField(Employee) class Meta: verbose_name_plural = 'businesses' def __unicode__(self): return self.name class Bar(models.Model): id = MyAutoField(primary_key=True, db_index=True) def __unicode__(self): return repr(self.pk) class Foo(models.Model): bar = models.ForeignKey(Bar)
1,160
Python
.py
30
34.333333
77
0.705725
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,304
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/custom_pk/tests.py
# -*- coding: utf-8 -*- from django.conf import settings from django.db import DEFAULT_DB_ALIAS, transaction, IntegrityError from django.test import TestCase from models import Employee, Business, Bar, Foo class CustomPKTests(TestCase): def test_custom_pk(self): dan = Employee.objects.create( employee_code=123, first_name="Dan", last_name="Jones" ) self.assertQuerysetEqual( Employee.objects.all(), [ "Dan Jones", ], unicode ) fran = Employee.objects.create( employee_code=456, first_name="Fran", last_name="Bones" ) self.assertQuerysetEqual( Employee.objects.all(), [ "Fran Bones", "Dan Jones", ], unicode ) self.assertEqual(Employee.objects.get(pk=123), dan) self.assertEqual(Employee.objects.get(pk=456), fran) self.assertRaises(Employee.DoesNotExist, lambda: Employee.objects.get(pk=42) ) # Use the name of the primary key, rather than pk. self.assertEqual(Employee.objects.get(employee_code=123), dan) # pk can be used as a substitute for the primary key. self.assertQuerysetEqual( Employee.objects.filter(pk__in=[123, 456]), [ "Fran Bones", "Dan Jones", ], unicode ) # The primary key can be accessed via the pk property on the model. e = Employee.objects.get(pk=123) self.assertEqual(e.pk, 123) # Or we can use the real attribute name for the primary key: self.assertEqual(e.employee_code, 123) # Fran got married and changed her last name. fran = Employee.objects.get(pk=456) fran.last_name = "Jones" fran.save() self.assertQuerysetEqual( Employee.objects.filter(last_name="Jones"), [ "Dan Jones", "Fran Jones", ], unicode ) emps = Employee.objects.in_bulk([123, 456]) self.assertEqual(emps[123], dan) b = Business.objects.create(name="Sears") b.employees.add(dan, fran) self.assertQuerysetEqual( b.employees.all(), [ "Dan Jones", "Fran Jones", ], unicode ) self.assertQuerysetEqual( fran.business_set.all(), [ "Sears", ], lambda b: b.name ) self.assertEqual(Business.objects.in_bulk(["Sears"]), { "Sears": b, }) self.assertQuerysetEqual( Business.objects.filter(name="Sears"), [ "Sears" ], lambda b: b.name ) self.assertQuerysetEqual( Business.objects.filter(pk="Sears"), [ "Sears", ], lambda b: b.name ) # Queries across tables, involving primary key self.assertQuerysetEqual( Employee.objects.filter(business__name="Sears"), [ "Dan Jones", "Fran Jones", ], unicode, ) self.assertQuerysetEqual( Employee.objects.filter(business__pk="Sears"), [ "Dan Jones", "Fran Jones", ], unicode, ) self.assertQuerysetEqual( Business.objects.filter(employees__employee_code=123), [ "Sears", ], lambda b: b.name ) self.assertQuerysetEqual( Business.objects.filter(employees__pk=123), [ "Sears", ], lambda b: b.name, ) self.assertQuerysetEqual( Business.objects.filter(employees__first_name__startswith="Fran"), [ "Sears", ], lambda b: b.name ) def test_unicode_pk(self): # Primary key may be unicode string bus = Business.objects.create(name=u'jaźń') def test_unique_pk(self): # The primary key must also obviously be unique, so trying to create a # new object with the same primary key will fail. e = Employee.objects.create( employee_code=123, first_name="Frank", last_name="Jones" ) sid = transaction.savepoint() self.assertRaises(IntegrityError, Employee.objects.create, employee_code=123, first_name="Fred", last_name="Jones" ) transaction.savepoint_rollback(sid) def test_custom_field_pk(self): # Regression for #10785 -- Custom fields can be used for primary keys. new_bar = Bar.objects.create() new_foo = Foo.objects.create(bar=new_bar) f = Foo.objects.get(bar=new_bar.pk) self.assertEqual(f, new_foo) self.assertEqual(f.bar, new_bar) f = Foo.objects.get(bar=new_bar) self.assertEqual(f, new_foo), self.assertEqual(f.bar, new_bar) # SQLite lets objects be saved with an empty primary key, even though an # integer is expected. So we can't check for an error being raised in that # case for SQLite. Remove it from the suite for this next bit. if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.sqlite3': def test_required_pk(self): # The primary key must be specified, so an error is raised if you # try to create an object without it. sid = transaction.savepoint() self.assertRaises(IntegrityError, Employee.objects.create, first_name="Tom", last_name="Smith" ) transaction.savepoint_rollback(sid)
5,798
Python
.py
158
25.740506
92
0.560641
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,305
fields.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/custom_pk/fields.py
import random import string from django.db import models class MyWrapper(object): def __init__(self, value): self.value = value def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self.value) def __unicode__(self): return self.value def __eq__(self, other): if isinstance(other, self.__class__): return self.value == other.value return self.value == other class MyAutoField(models.CharField): __metaclass__ = models.SubfieldBase def __init__(self, *args, **kwargs): kwargs['max_length'] = 10 super(MyAutoField, self).__init__(*args, **kwargs) def pre_save(self, instance, add): value = getattr(instance, self.attname, None) if not value: value = MyWrapper(''.join(random.sample(string.lowercase, 10))) setattr(instance, self.attname, value) return value def to_python(self, value): if not value: return if not isinstance(value, MyWrapper): value = MyWrapper(value) return value def get_db_prep_save(self, value): if not value: return if isinstance(value, MyWrapper): return unicode(value) return value def get_db_prep_value(self, value): if not value: return if isinstance(value, MyWrapper): return unicode(value) return value
1,453
Python
.py
43
25.534884
75
0.593705
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,306
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/m2m_through/models.py
from django.db import models from datetime import datetime # M2M described on one of the models class Person(models.Model): name = models.CharField(max_length=128) class Meta: ordering = ('name',) def __unicode__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') custom_members = models.ManyToManyField(Person, through='CustomMembership', related_name="custom") nodefaultsnonulls = models.ManyToManyField(Person, through='TestNoDefaultsOrNulls', related_name="testnodefaultsnonulls") class Meta: ordering = ('name',) def __unicode__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) date_joined = models.DateTimeField(default=datetime.now) invite_reason = models.CharField(max_length=64, null=True) class Meta: ordering = ('date_joined', 'invite_reason', 'group') def __unicode__(self): return "%s is a member of %s" % (self.person.name, self.group.name) class CustomMembership(models.Model): person = models.ForeignKey(Person, db_column="custom_person_column", related_name="custom_person_related_name") group = models.ForeignKey(Group) weird_fk = models.ForeignKey(Membership, null=True) date_joined = models.DateTimeField(default=datetime.now) def __unicode__(self): return "%s is a member of %s" % (self.person.name, self.group.name) class Meta: db_table = "test_table" class TestNoDefaultsOrNulls(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) nodefaultnonull = models.CharField(max_length=5) class PersonSelfRefM2M(models.Model): name = models.CharField(max_length=5) friends = models.ManyToManyField('self', through="Friendship", symmetrical=False) def __unicode__(self): return self.name class Friendship(models.Model): first = models.ForeignKey(PersonSelfRefM2M, related_name="rel_from_set") second = models.ForeignKey(PersonSelfRefM2M, related_name="rel_to_set") date_friended = models.DateTimeField()
2,234
Python
.py
49
40.346939
125
0.723375
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,307
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/m2m_through/tests.py
from datetime import datetime from operator import attrgetter from django.test import TestCase from models import Person, Group, Membership, CustomMembership, \ TestNoDefaultsOrNulls, PersonSelfRefM2M, Friendship class M2mThroughTests(TestCase): def setUp(self): self.bob = Person.objects.create(name='Bob') self.jim = Person.objects.create(name='Jim') self.jane = Person.objects.create(name='Jane') self.rock = Group.objects.create(name='Rock') self.roll = Group.objects.create(name='Roll') def test_m2m_through(self): # We start out by making sure that the Group 'rock' has no members. self.assertQuerysetEqual( self.rock.members.all(), [] ) # To make Jim a member of Group Rock, simply create a Membership object. m1 = Membership.objects.create(person=self.jim, group=self.rock) # We can do the same for Jane and Rock. m2 = Membership.objects.create(person=self.jane, group=self.rock) # Let's check to make sure that it worked. Jane and Jim should be members of Rock. self.assertQuerysetEqual( self.rock.members.all(), [ 'Jane', 'Jim' ], attrgetter("name") ) # Now we can add a bunch more Membership objects to test with. m3 = Membership.objects.create(person=self.bob, group=self.roll) m4 = Membership.objects.create(person=self.jim, group=self.roll) m5 = Membership.objects.create(person=self.jane, group=self.roll) # We can get Jim's Group membership as with any ForeignKey. self.assertQuerysetEqual( self.jim.group_set.all(), [ 'Rock', 'Roll' ], attrgetter("name") ) # Querying the intermediary model works like normal. self.assertEqual( repr(Membership.objects.get(person=self.jane, group=self.rock)), '<Membership: Jane is a member of Rock>' ) # It's not only get that works. Filter works like normal as well. self.assertQuerysetEqual( Membership.objects.filter(person=self.jim), [ '<Membership: Jim is a member of Rock>', '<Membership: Jim is a member of Roll>' ] ) self.rock.members.clear() # Now there will be no members of Rock. self.assertQuerysetEqual( self.rock.members.all(), [] ) def test_forward_descriptors(self): # Due to complications with adding via an intermediary model, # the add method is not provided. self.assertRaises(AttributeError, lambda: self.rock.members.add(self.bob)) # Create is also disabled as it suffers from the same problems as add. self.assertRaises(AttributeError, lambda: self.rock.members.create(name='Anne')) # Remove has similar complications, and is not provided either. self.assertRaises(AttributeError, lambda: self.rock.members.remove(self.jim)) m1 = Membership.objects.create(person=self.jim, group=self.rock) m2 = Membership.objects.create(person=self.jane, group=self.rock) # Here we back up the list of all members of Rock. backup = list(self.rock.members.all()) # ...and we verify that it has worked. self.assertEqual( [p.name for p in backup], ['Jane', 'Jim'] ) # The clear function should still work. self.rock.members.clear() # Now there will be no members of Rock. self.assertQuerysetEqual( self.rock.members.all(), [] ) # Assignment should not work with models specifying a through model for many of # the same reasons as adding. self.assertRaises(AttributeError, setattr, self.rock, "members", backup) # Let's re-save those instances that we've cleared. m1.save() m2.save() # Verifying that those instances were re-saved successfully. self.assertQuerysetEqual( self.rock.members.all(),[ 'Jane', 'Jim' ], attrgetter("name") ) def test_reverse_descriptors(self): # Due to complications with adding via an intermediary model, # the add method is not provided. self.assertRaises(AttributeError, lambda: self.bob.group_set.add(self.rock)) # Create is also disabled as it suffers from the same problems as add. self.assertRaises(AttributeError, lambda: self.bob.group_set.create(name="funk")) # Remove has similar complications, and is not provided either. self.assertRaises(AttributeError, lambda: self.jim.group_set.remove(self.rock)) m1 = Membership.objects.create(person=self.jim, group=self.rock) m2 = Membership.objects.create(person=self.jim, group=self.roll) # Here we back up the list of all of Jim's groups. backup = list(self.jim.group_set.all()) self.assertEqual( [g.name for g in backup], ['Rock', 'Roll'] ) # The clear function should still work. self.jim.group_set.clear() # Now Jim will be in no groups. self.assertQuerysetEqual( self.jim.group_set.all(), [] ) # Assignment should not work with models specifying a through model for many of # the same reasons as adding. self.assertRaises(AttributeError, setattr, self.jim, "group_set", backup) # Let's re-save those instances that we've cleared. m1.save() m2.save() # Verifying that those instances were re-saved successfully. self.assertQuerysetEqual( self.jim.group_set.all(),[ 'Rock', 'Roll' ], attrgetter("name") ) def test_custom_tests(self): # Let's see if we can query through our second relationship. self.assertQuerysetEqual( self.rock.custom_members.all(), [] ) # We can query in the opposite direction as well. self.assertQuerysetEqual( self.bob.custom.all(), [] ) cm1 = CustomMembership.objects.create(person=self.bob, group=self.rock) cm2 = CustomMembership.objects.create(person=self.jim, group=self.rock) # If we get the number of people in Rock, it should be both Bob and Jim. self.assertQuerysetEqual( self.rock.custom_members.all(),[ 'Bob', 'Jim' ], attrgetter("name") ) # Bob should only be in one custom group. self.assertQuerysetEqual( self.bob.custom.all(),[ 'Rock' ], attrgetter("name") ) # Let's make sure our new descriptors don't conflict with the FK related_name. self.assertQuerysetEqual( self.bob.custom_person_related_name.all(),[ '<CustomMembership: Bob is a member of Rock>' ] ) def test_self_referential_tests(self): # Let's first create a person who has no friends. tony = PersonSelfRefM2M.objects.create(name="Tony") self.assertQuerysetEqual( tony.friends.all(), [] ) chris = PersonSelfRefM2M.objects.create(name="Chris") f = Friendship.objects.create(first=tony, second=chris, date_friended=datetime.now()) # Tony should now show that Chris is his friend. self.assertQuerysetEqual( tony.friends.all(),[ 'Chris' ], attrgetter("name") ) # But we haven't established that Chris is Tony's Friend. self.assertQuerysetEqual( chris.friends.all(), [] ) f2 = Friendship.objects.create(first=chris, second=tony, date_friended=datetime.now()) # Having added Chris as a friend, let's make sure that his friend set reflects # that addition. self.assertQuerysetEqual( chris.friends.all(),[ 'Tony' ], attrgetter("name") ) # Chris gets mad and wants to get rid of all of his friends. chris.friends.clear() # Now he should not have any more friends. self.assertQuerysetEqual( chris.friends.all(), [] ) # Since this isn't a symmetrical relation, Tony's friend link still exists. self.assertQuerysetEqual( tony.friends.all(),[ 'Chris' ], attrgetter("name") ) def test_query_tests(self): m1 = Membership.objects.create(person=self.jim, group=self.rock) m2 = Membership.objects.create(person=self.jane, group=self.rock) m3 = Membership.objects.create(person=self.bob, group=self.roll) m4 = Membership.objects.create(person=self.jim, group=self.roll) m5 = Membership.objects.create(person=self.jane, group=self.roll) m2.invite_reason = "She was just awesome." m2.date_joined = datetime(2006, 1, 1) m2.save() m3.date_joined = datetime(2004, 1, 1) m3.save() m5.date_joined = datetime(2004, 1, 1) m5.save() # We can query for the related model by using its attribute name (members, in # this case). self.assertQuerysetEqual( Group.objects.filter(members__name='Bob'),[ 'Roll' ], attrgetter("name") ) # To query through the intermediary model, we specify its model name. # In this case, membership. self.assertQuerysetEqual( Group.objects.filter(membership__invite_reason="She was just awesome."),[ 'Rock' ], attrgetter("name") ) # If we want to query in the reverse direction by the related model, use its # model name (group, in this case). self.assertQuerysetEqual( Person.objects.filter(group__name="Rock"),[ 'Jane', 'Jim' ], attrgetter("name") ) cm1 = CustomMembership.objects.create(person=self.bob, group=self.rock) cm2 = CustomMembership.objects.create(person=self.jim, group=self.rock) # If the m2m field has specified a related_name, using that will work. self.assertQuerysetEqual( Person.objects.filter(custom__name="Rock"),[ 'Bob', 'Jim' ], attrgetter("name") ) # To query through the intermediary model in the reverse direction, we again # specify its model name (membership, in this case). self.assertQuerysetEqual( Person.objects.filter(membership__invite_reason="She was just awesome."),[ 'Jane' ], attrgetter("name") ) # Let's see all of the groups that Jane joined after 1 Jan 2005: self.assertQuerysetEqual( Group.objects.filter(membership__date_joined__gt=datetime(2005, 1, 1), membership__person=self.jane),[ 'Rock' ], attrgetter("name") ) # Queries also work in the reverse direction: Now let's see all of the people # that have joined Rock since 1 Jan 2005: self.assertQuerysetEqual( Person.objects.filter(membership__date_joined__gt=datetime(2005, 1, 1), membership__group=self.rock),[ 'Jane', 'Jim' ], attrgetter("name") ) # Conceivably, queries through membership could return correct, but non-unique # querysets. To demonstrate this, we query for all people who have joined a # group after 2004: self.assertQuerysetEqual( Person.objects.filter(membership__date_joined__gt=datetime(2004, 1, 1)),[ 'Jane', 'Jim', 'Jim' ], attrgetter("name") ) # Jim showed up twice, because he joined two groups ('Rock', and 'Roll'): self.assertEqual( [(m.person.name, m.group.name) for m in Membership.objects.filter(date_joined__gt=datetime(2004, 1, 1))], [(u'Jane', u'Rock'), (u'Jim', u'Rock'), (u'Jim', u'Roll')] ) # QuerySet's distinct() method can correct this problem. self.assertQuerysetEqual( Person.objects.filter(membership__date_joined__gt=datetime(2004, 1, 1)).distinct(),[ 'Jane', 'Jim' ], attrgetter("name") )
12,896
Python
.py
309
30.941748
117
0.590934
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,308
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/mutually_referential/models.py
""" 24. Mutually referential many-to-one relationships Strings can be used instead of model literals to set up "lazy" relations. """ from django.db.models import * class Parent(Model): name = CharField(max_length=100) # Use a simple string for forward declarations. bestchild = ForeignKey("Child", null=True, related_name="favoured_by") class Child(Model): name = CharField(max_length=100) # You can also explicitally specify the related app. parent = ForeignKey("mutually_referential.Parent")
524
Python
.py
13
37
74
0.752475
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,309
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/mutually_referential/tests.py
from django.test import TestCase from models import Parent, Child class MutuallyReferentialTests(TestCase): def test_mutually_referential(self): # Create a Parent q = Parent(name='Elizabeth') q.save() # Create some children c = q.child_set.create(name='Charles') e = q.child_set.create(name='Edward') # Set the best child # No assertion require here; if basic assignment and # deletion works, the test passes. q.bestchild = c q.save() q.delete()
550
Python
.py
16
26.875
60
0.635849
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,310
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/m2o_recursive/models.py
""" 11. Relating an object to itself, many-to-one To define a many-to-one relationship between a model and itself, use ``ForeignKey('self')``. In this example, a ``Category`` is related to itself. That is, each ``Category`` has a parent ``Category``. Set ``related_name`` to designate what the reverse relationship is called. """ from django.db import models class Category(models.Model): name = models.CharField(max_length=20) parent = models.ForeignKey('self', blank=True, null=True, related_name='child_set') def __unicode__(self): return self.name class Person(models.Model): full_name = models.CharField(max_length=20) mother = models.ForeignKey('self', null=True, related_name='mothers_child_set') father = models.ForeignKey('self', null=True, related_name='fathers_child_set') def __unicode__(self): return self.full_name
881
Python
.py
20
40.45
87
0.719812
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,311
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/m2o_recursive/tests.py
from django.test import TestCase from models import Category, Person class ManyToOneRecursiveTests(TestCase): def setUp(self): self.r = Category(id=None, name='Root category', parent=None) self.r.save() self.c = Category(id=None, name='Child category', parent=self.r) self.c.save() def test_m2o_recursive(self): self.assertQuerysetEqual(self.r.child_set.all(), ['<Category: Child category>']) self.assertEqual(self.r.child_set.get(name__startswith='Child').id, self.c.id) self.assertEqual(self.r.parent, None) self.assertQuerysetEqual(self.c.child_set.all(), []) self.assertEqual(self.c.parent.id, self.r.id) class MultipleManyToOneRecursiveTests(TestCase): def setUp(self): self.dad = Person(full_name='John Smith Senior', mother=None, father=None) self.dad.save() self.mom = Person(full_name='Jane Smith', mother=None, father=None) self.mom.save() self.kid = Person(full_name='John Smith Junior', mother=self.mom, father=self.dad) self.kid.save() def test_m2o_recursive2(self): self.assertEqual(self.kid.mother.id, self.mom.id) self.assertEqual(self.kid.father.id, self.dad.id) self.assertQuerysetEqual(self.dad.fathers_child_set.all(), ['<Person: John Smith Junior>']) self.assertQuerysetEqual(self.mom.mothers_child_set.all(), ['<Person: John Smith Junior>']) self.assertQuerysetEqual(self.kid.mothers_child_set.all(), []) self.assertQuerysetEqual(self.kid.fathers_child_set.all(), [])
1,679
Python
.py
32
42.4375
90
0.642901
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,312
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/pagination/models.py
""" 30. Object pagination Django provides a framework for paginating a list of objects in a few lines of code. This is often useful for dividing search results or long lists of objects into easily readable pages. """ from django.db import models class Article(models.Model): headline = models.CharField(max_length=100, default='Default headline') pub_date = models.DateTimeField() def __unicode__(self): return self.headline
450
Python
.py
12
34.416667
75
0.766744
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,313
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/pagination/tests.py
from datetime import datetime from operator import attrgetter from django.core.paginator import Paginator, InvalidPage, EmptyPage from django.test import TestCase from models import Article class CountContainer(object): def count(self): return 42 class LenContainer(object): def __len__(self): return 42 class PaginationTests(TestCase): def setUp(self): # Prepare a list of objects for pagination. for x in range(1, 10): a = Article(headline='Article %s' % x, pub_date=datetime(2005, 7, 29)) a.save() def test_paginator(self): paginator = Paginator(Article.objects.all(), 5) self.assertEqual(9, paginator.count) self.assertEqual(2, paginator.num_pages) self.assertEqual([1, 2], paginator.page_range) def test_first_page(self): paginator = Paginator(Article.objects.all(), 5) p = paginator.page(1) self.assertEqual(u"<Page 1 of 2>", unicode(p)) self.assertQuerysetEqual(p.object_list, [ "<Article: Article 1>", "<Article: Article 2>", "<Article: Article 3>", "<Article: Article 4>", "<Article: Article 5>" ] ) self.assertTrue(p.has_next()) self.assertFalse(p.has_previous()) self.assertTrue(p.has_other_pages()) self.assertEqual(2, p.next_page_number()) self.assertEqual(0, p.previous_page_number()) self.assertEqual(1, p.start_index()) self.assertEqual(5, p.end_index()) def test_last_page(self): paginator = Paginator(Article.objects.all(), 5) p = paginator.page(2) self.assertEqual(u"<Page 2 of 2>", unicode(p)) self.assertQuerysetEqual(p.object_list, [ "<Article: Article 6>", "<Article: Article 7>", "<Article: Article 8>", "<Article: Article 9>" ] ) self.assertFalse(p.has_next()) self.assertTrue(p.has_previous()) self.assertTrue(p.has_other_pages()) self.assertEqual(3, p.next_page_number()) self.assertEqual(1, p.previous_page_number()) self.assertEqual(6, p.start_index()) self.assertEqual(9, p.end_index()) def test_empty_page(self): paginator = Paginator(Article.objects.all(), 5) self.assertRaises(EmptyPage, paginator.page, 0) self.assertRaises(EmptyPage, paginator.page, 3) # Empty paginators with allow_empty_first_page=True. paginator = Paginator(Article.objects.filter(id=0), 5, allow_empty_first_page=True) self.assertEqual(0, paginator.count) self.assertEqual(1, paginator.num_pages) self.assertEqual([1], paginator.page_range) # Empty paginators with allow_empty_first_page=False. paginator = Paginator(Article.objects.filter(id=0), 5, allow_empty_first_page=False) self.assertEqual(0, paginator.count) self.assertEqual(0, paginator.num_pages) self.assertEqual([], paginator.page_range) def test_invalid_page(self): paginator = Paginator(Article.objects.all(), 5) self.assertRaises(InvalidPage, paginator.page, 7) def test_orphans(self): # Add a few more records to test out the orphans feature. for x in range(10, 13): Article(headline="Article %s" % x, pub_date=datetime(2006, 10, 6)).save() # With orphans set to 3 and 10 items per page, we should get all 12 items on a single page. paginator = Paginator(Article.objects.all(), 10, orphans=3) self.assertEqual(1, paginator.num_pages) # With orphans only set to 1, we should get two pages. paginator = Paginator(Article.objects.all(), 10, orphans=1) self.assertEqual(2, paginator.num_pages) def test_paginate_list(self): # Paginators work with regular lists/tuples, too -- not just with QuerySets. paginator = Paginator([1, 2, 3, 4, 5, 6, 7, 8, 9], 5) self.assertEqual(9, paginator.count) self.assertEqual(2, paginator.num_pages) self.assertEqual([1, 2], paginator.page_range) p = paginator.page(1) self.assertEqual(u"<Page 1 of 2>", unicode(p)) self.assertEqual([1, 2, 3, 4, 5], p.object_list) self.assertTrue(p.has_next()) self.assertFalse(p.has_previous()) self.assertTrue(p.has_other_pages()) self.assertEqual(2, p.next_page_number()) self.assertEqual(0, p.previous_page_number()) self.assertEqual(1, p.start_index()) self.assertEqual(5, p.end_index()) def test_paginate_misc_classes(self): # Paginator can be passed other objects with a count() method. paginator = Paginator(CountContainer(), 10) self.assertEqual(42, paginator.count) self.assertEqual(5, paginator.num_pages) self.assertEqual([1, 2, 3, 4, 5], paginator.page_range) # Paginator can be passed other objects that implement __len__. paginator = Paginator(LenContainer(), 10) self.assertEqual(42, paginator.count) self.assertEqual(5, paginator.num_pages) self.assertEqual([1, 2, 3, 4, 5], paginator.page_range)
5,341
Python
.py
113
37.495575
99
0.634341
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,314
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/proxy_models/models.py
""" By specifying the 'proxy' Meta attribute, model subclasses can specify that they will take data directly from the table of their base class table rather than using a new table of their own. This allows them to act as simple proxies, providing a modified interface to the data from the base class. """ from django.contrib.contenttypes.models import ContentType from django.db import models # A couple of managers for testing managing overriding in proxy model cases. class PersonManager(models.Manager): def get_query_set(self): return super(PersonManager, self).get_query_set().exclude(name="fred") class SubManager(models.Manager): def get_query_set(self): return super(SubManager, self).get_query_set().exclude(name="wilma") class Person(models.Model): """ A simple concrete base class. """ name = models.CharField(max_length=50) objects = PersonManager() def __unicode__(self): return self.name class Abstract(models.Model): """ A simple abstract base class, to be used for error checking. """ data = models.CharField(max_length=10) class Meta: abstract = True class MyPerson(Person): """ A proxy subclass, this should not get a new table. Overrides the default manager. """ class Meta: proxy = True ordering = ["name"] objects = SubManager() other = PersonManager() def has_special_name(self): return self.name.lower() == "special" class ManagerMixin(models.Model): excluder = SubManager() class Meta: abstract = True class OtherPerson(Person, ManagerMixin): """ A class with the default manager from Person, plus an secondary manager. """ class Meta: proxy = True ordering = ["name"] class StatusPerson(MyPerson): """ A non-proxy subclass of a proxy, it should get a new table. """ status = models.CharField(max_length=80) # We can even have proxies of proxies (and subclass of those). class MyPersonProxy(MyPerson): class Meta: proxy = True class LowerStatusPerson(MyPersonProxy): status = models.CharField(max_length=80) class User(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name class UserProxy(User): class Meta: proxy = True class UserProxyProxy(UserProxy): class Meta: proxy = True # We can still use `select_related()` to include related models in our querysets. class Country(models.Model): name = models.CharField(max_length=50) class State(models.Model): name = models.CharField(max_length=50) country = models.ForeignKey(Country) def __unicode__(self): return self.name class StateProxy(State): class Meta: proxy = True # Proxy models still works with filters (on related fields) # and select_related, even when mixed with model inheritance class BaseUser(models.Model): name = models.CharField(max_length=255) class TrackerUser(BaseUser): status = models.CharField(max_length=50) class ProxyTrackerUser(TrackerUser): class Meta: proxy = True class Issue(models.Model): summary = models.CharField(max_length=255) assignee = models.ForeignKey(TrackerUser) def __unicode__(self): return ':'.join((self.__class__.__name__,self.summary,)) class Bug(Issue): version = models.CharField(max_length=50) reporter = models.ForeignKey(BaseUser) class ProxyBug(Bug): """ Proxy of an inherited class """ class Meta: proxy = True class ProxyProxyBug(ProxyBug): """ A proxy of proxy model with related field """ class Meta: proxy = True class Improvement(Issue): """ A model that has relation to a proxy model or to a proxy of proxy model """ version = models.CharField(max_length=50) reporter = models.ForeignKey(ProxyTrackerUser) associated_bug = models.ForeignKey(ProxyProxyBug) class ProxyImprovement(Improvement): class Meta: proxy = True
4,066
Python
.py
125
27.768
81
0.703049
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,315
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/proxy_models/tests.py
from django.test import TestCase from django.db import models, DEFAULT_DB_ALIAS from django.db.models import signals from django.core import management from django.core.exceptions import FieldError from django.contrib.contenttypes.models import ContentType from models import MyPerson, Person, StatusPerson, LowerStatusPerson from models import MyPersonProxy, Abstract, OtherPerson, User, UserProxy from models import UserProxyProxy, Country, State, StateProxy, TrackerUser from models import BaseUser, Bug, ProxyTrackerUser, Improvement, ProxyProxyBug from models import ProxyBug, ProxyImprovement class ProxyModelTests(TestCase): def test_same_manager_queries(self): """ The MyPerson model should be generating the same database queries as the Person model (when the same manager is used in each case). """ my_person_sql = MyPerson.other.all().query.get_compiler( DEFAULT_DB_ALIAS).as_sql() person_sql = Person.objects.order_by("name").query.get_compiler( DEFAULT_DB_ALIAS).as_sql() self.assertEqual(my_person_sql, person_sql) def test_inheretance_new_table(self): """ The StatusPerson models should have its own table (it's using ORM-level inheritance). """ sp_sql = StatusPerson.objects.all().query.get_compiler( DEFAULT_DB_ALIAS).as_sql() p_sql = Person.objects.all().query.get_compiler( DEFAULT_DB_ALIAS).as_sql() self.assertNotEqual(sp_sql, p_sql) def test_basic_proxy(self): """ Creating a Person makes them accessible through the MyPerson proxy. """ Person.objects.create(name="Foo McBar") self.assertEqual(len(Person.objects.all()), 1) self.assertEqual(len(MyPerson.objects.all()), 1) self.assertEqual(MyPerson.objects.get(name="Foo McBar").id, 1) self.assertFalse(MyPerson.objects.get(id=1).has_special_name()) def test_no_proxy(self): """ Person is not proxied by StatusPerson subclass. """ Person.objects.create(name="Foo McBar") self.assertEqual(list(StatusPerson.objects.all()), []) def test_basic_proxy_reverse(self): """ A new MyPerson also shows up as a standard Person. """ MyPerson.objects.create(name="Bazza del Frob") self.assertEqual(len(MyPerson.objects.all()), 1) self.assertEqual(len(Person.objects.all()), 1) LowerStatusPerson.objects.create(status="low", name="homer") lsps = [lsp.name for lsp in LowerStatusPerson.objects.all()] self.assertEqual(lsps, ["homer"]) def test_correct_type_proxy_of_proxy(self): """ Correct type when querying a proxy of proxy """ Person.objects.create(name="Foo McBar") MyPerson.objects.create(name="Bazza del Frob") LowerStatusPerson.objects.create(status="low", name="homer") pp = sorted([mpp.name for mpp in MyPersonProxy.objects.all()]) self.assertEqual(pp, ['Bazza del Frob', 'Foo McBar', 'homer']) def test_proxy_included_in_ancestors(self): """ Proxy models are included in the ancestors for a model's DoesNotExist and MultipleObjectsReturned """ Person.objects.create(name="Foo McBar") MyPerson.objects.create(name="Bazza del Frob") LowerStatusPerson.objects.create(status="low", name="homer") max_id = Person.objects.aggregate(max_id=models.Max('id'))['max_id'] self.assertRaises(Person.DoesNotExist, MyPersonProxy.objects.get, name='Zathras' ) self.assertRaises(Person.MultipleObjectsReturned, MyPersonProxy.objects.get, id__lt=max_id+1 ) self.assertRaises(Person.DoesNotExist, StatusPerson.objects.get, name='Zathras' ) sp1 = StatusPerson.objects.create(name='Bazza Jr.') sp2 = StatusPerson.objects.create(name='Foo Jr.') max_id = Person.objects.aggregate(max_id=models.Max('id'))['max_id'] self.assertRaises(Person.MultipleObjectsReturned, StatusPerson.objects.get, id__lt=max_id+1 ) def test_abc(self): """ All base classes must be non-abstract """ def build_abc(): class NoAbstract(Abstract): class Meta: proxy = True self.assertRaises(TypeError, build_abc) def test_no_cbc(self): """ The proxy must actually have one concrete base class """ def build_no_cbc(): class TooManyBases(Person, Abstract): class Meta: proxy = True self.assertRaises(TypeError, build_no_cbc) def test_no_base_classes(self): def build_no_base_classes(): class NoBaseClasses(models.Model): class Meta: proxy = True self.assertRaises(TypeError, build_no_base_classes) def test_new_fields(self): def build_new_fields(): class NoNewFields(Person): newfield = models.BooleanField() class Meta: proxy = True self.assertRaises(FieldError, build_new_fields) def test_myperson_manager(self): Person.objects.create(name="fred") Person.objects.create(name="wilma") Person.objects.create(name="barney") resp = [p.name for p in MyPerson.objects.all()] self.assertEqual(resp, ['barney', 'fred']) resp = [p.name for p in MyPerson._default_manager.all()] self.assertEqual(resp, ['barney', 'fred']) def test_otherperson_manager(self): Person.objects.create(name="fred") Person.objects.create(name="wilma") Person.objects.create(name="barney") resp = [p.name for p in OtherPerson.objects.all()] self.assertEqual(resp, ['barney', 'wilma']) resp = [p.name for p in OtherPerson.excluder.all()] self.assertEqual(resp, ['barney', 'fred']) resp = [p.name for p in OtherPerson._default_manager.all()] self.assertEqual(resp, ['barney', 'wilma']) def test_proxy_model_signals(self): """ Test save signals for proxy models """ output = [] def make_handler(model, event): def _handler(*args, **kwargs): output.append('%s %s save' % (model, event)) return _handler h1 = make_handler('MyPerson', 'pre') h2 = make_handler('MyPerson', 'post') h3 = make_handler('Person', 'pre') h4 = make_handler('Person', 'post') signals.pre_save.connect(h1, sender=MyPerson) signals.post_save.connect(h2, sender=MyPerson) signals.pre_save.connect(h3, sender=Person) signals.post_save.connect(h4, sender=Person) dino = MyPerson.objects.create(name=u"dino") self.assertEqual(output, [ 'MyPerson pre save', 'MyPerson post save' ]) output = [] h5 = make_handler('MyPersonProxy', 'pre') h6 = make_handler('MyPersonProxy', 'post') signals.pre_save.connect(h5, sender=MyPersonProxy) signals.post_save.connect(h6, sender=MyPersonProxy) dino = MyPersonProxy.objects.create(name=u"pebbles") self.assertEqual(output, [ 'MyPersonProxy pre save', 'MyPersonProxy post save' ]) signals.pre_save.disconnect(h1, sender=MyPerson) signals.post_save.disconnect(h2, sender=MyPerson) signals.pre_save.disconnect(h3, sender=Person) signals.post_save.disconnect(h4, sender=Person) signals.pre_save.disconnect(h5, sender=MyPersonProxy) signals.post_save.disconnect(h6, sender=MyPersonProxy) def test_content_type(self): ctype = ContentType.objects.get_for_model self.assertTrue(ctype(Person) is ctype(OtherPerson)) def test_user_userproxy_userproxyproxy(self): User.objects.create(name='Bruce') resp = [u.name for u in User.objects.all()] self.assertEqual(resp, ['Bruce']) resp = [u.name for u in UserProxy.objects.all()] self.assertEqual(resp, ['Bruce']) resp = [u.name for u in UserProxyProxy.objects.all()] self.assertEqual(resp, ['Bruce']) def test_proxy_delete(self): """ Proxy objects can be deleted """ User.objects.create(name='Bruce') u2 = UserProxy.objects.create(name='George') resp = [u.name for u in UserProxy.objects.all()] self.assertEqual(resp, ['Bruce', 'George']) u2.delete() resp = [u.name for u in UserProxy.objects.all()] self.assertEqual(resp, ['Bruce']) def test_select_related(self): """ We can still use `select_related()` to include related models in our querysets. """ country = Country.objects.create(name='Australia') state = State.objects.create(name='New South Wales', country=country) resp = [s.name for s in State.objects.select_related()] self.assertEqual(resp, ['New South Wales']) resp = [s.name for s in StateProxy.objects.select_related()] self.assertEqual(resp, ['New South Wales']) self.assertEqual(StateProxy.objects.get(name='New South Wales').name, 'New South Wales') resp = StateProxy.objects.select_related().get(name='New South Wales') self.assertEqual(resp.name, 'New South Wales') def test_proxy_bug(self): contributor = TrackerUser.objects.create(name='Contributor', status='contrib') someone = BaseUser.objects.create(name='Someone') Bug.objects.create(summary='fix this', version='1.1beta', assignee=contributor, reporter=someone) pcontributor = ProxyTrackerUser.objects.create(name='OtherContributor', status='proxy') Improvement.objects.create(summary='improve that', version='1.1beta', assignee=contributor, reporter=pcontributor, associated_bug=ProxyProxyBug.objects.all()[0]) # Related field filter on proxy resp = ProxyBug.objects.get(version__icontains='beta') self.assertEqual(repr(resp), '<ProxyBug: ProxyBug:fix this>') # Select related + filter on proxy resp = ProxyBug.objects.select_related().get(version__icontains='beta') self.assertEqual(repr(resp), '<ProxyBug: ProxyBug:fix this>') # Proxy of proxy, select_related + filter resp = ProxyProxyBug.objects.select_related().get( version__icontains='beta' ) self.assertEqual(repr(resp), '<ProxyProxyBug: ProxyProxyBug:fix this>') # Select related + filter on a related proxy field resp = ProxyImprovement.objects.select_related().get( reporter__name__icontains='butor' ) self.assertEqual(repr(resp), '<ProxyImprovement: ProxyImprovement:improve that>' ) # Select related + filter on a related proxy of proxy field resp = ProxyImprovement.objects.select_related().get( associated_bug__summary__icontains='fix' ) self.assertEqual(repr(resp), '<ProxyImprovement: ProxyImprovement:improve that>' ) def test_proxy_load_from_fixture(self): management.call_command('loaddata', 'mypeople.json', verbosity=0, commit=False) p = MyPerson.objects.get(pk=100) self.assertEqual(p.name, 'Elvis Presley')
11,648
Python
.py
258
35.728682
87
0.63658
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,316
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/expressions/models.py
""" Tests for F() query expression syntax. """ from django.db import models class Employee(models.Model): firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) def __unicode__(self): return u'%s %s' % (self.firstname, self.lastname) class Company(models.Model): name = models.CharField(max_length=100) num_employees = models.PositiveIntegerField() num_chairs = models.PositiveIntegerField() ceo = models.ForeignKey( Employee, related_name='company_ceo_set') point_of_contact = models.ForeignKey( Employee, related_name='company_point_of_contact_set', null=True) def __unicode__(self): return self.name
732
Python
.py
22
27.863636
57
0.683688
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,317
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/expressions/tests.py
from django.core.exceptions import FieldError from django.db.models import F from django.test import TestCase from models import Company, Employee class ExpressionsTests(TestCase): def test_filter(self): Company.objects.create( name="Example Inc.", num_employees=2300, num_chairs=5, ceo=Employee.objects.create(firstname="Joe", lastname="Smith") ) Company.objects.create( name="Foobar Ltd.", num_employees=3, num_chairs=4, ceo=Employee.objects.create(firstname="Frank", lastname="Meyer") ) Company.objects.create( name="Test GmbH", num_employees=32, num_chairs=1, ceo=Employee.objects.create(firstname="Max", lastname="Mustermann") ) company_query = Company.objects.values( "name", "num_employees", "num_chairs" ).order_by( "name", "num_employees", "num_chairs" ) # We can filter for companies where the number of employees is greater # than the number of chairs. self.assertQuerysetEqual( company_query.filter(num_employees__gt=F("num_chairs")), [ { "num_chairs": 5, "name": "Example Inc.", "num_employees": 2300, }, { "num_chairs": 1, "name": "Test GmbH", "num_employees": 32 }, ], lambda o: o ) # We can set one field to have the value of another field # Make sure we have enough chairs company_query.update(num_chairs=F("num_employees")) self.assertQuerysetEqual( company_query, [ { "num_chairs": 2300, "name": "Example Inc.", "num_employees": 2300 }, { "num_chairs": 3, "name": "Foobar Ltd.", "num_employees": 3 }, { "num_chairs": 32, "name": "Test GmbH", "num_employees": 32 } ], lambda o: o ) # We can perform arithmetic operations in expressions # Make sure we have 2 spare chairs company_query.update(num_chairs=F("num_employees")+2) self.assertQuerysetEqual( company_query, [ { 'num_chairs': 2302, 'name': u'Example Inc.', 'num_employees': 2300 }, { 'num_chairs': 5, 'name': u'Foobar Ltd.', 'num_employees': 3 }, { 'num_chairs': 34, 'name': u'Test GmbH', 'num_employees': 32 } ], lambda o: o, ) # Law of order of operations is followed company_query.update( num_chairs=F('num_employees') + 2 * F('num_employees') ) self.assertQuerysetEqual( company_query, [ { 'num_chairs': 6900, 'name': u'Example Inc.', 'num_employees': 2300 }, { 'num_chairs': 9, 'name': u'Foobar Ltd.', 'num_employees': 3 }, { 'num_chairs': 96, 'name': u'Test GmbH', 'num_employees': 32 } ], lambda o: o, ) # Law of order of operations can be overridden by parentheses company_query.update( num_chairs=((F('num_employees') + 2) * F('num_employees')) ) self.assertQuerysetEqual( company_query, [ { 'num_chairs': 5294600, 'name': u'Example Inc.', 'num_employees': 2300 }, { 'num_chairs': 15, 'name': u'Foobar Ltd.', 'num_employees': 3 }, { 'num_chairs': 1088, 'name': u'Test GmbH', 'num_employees': 32 } ], lambda o: o, ) # The relation of a foreign key can become copied over to an other # foreign key. self.assertEqual( Company.objects.update(point_of_contact=F('ceo')), 3 ) self.assertQuerysetEqual( Company.objects.all(), [ "Joe Smith", "Frank Meyer", "Max Mustermann", ], lambda c: unicode(c.point_of_contact), ) c = Company.objects.all()[0] c.point_of_contact = Employee.objects.create(firstname="Guido", lastname="van Rossum") c.save() # F Expressions can also span joins self.assertQuerysetEqual( Company.objects.filter(ceo__firstname=F("point_of_contact__firstname")), [ "Foobar Ltd.", "Test GmbH", ], lambda c: c.name ) Company.objects.exclude( ceo__firstname=F("point_of_contact__firstname") ).update(name="foo") self.assertEqual( Company.objects.exclude( ceo__firstname=F('point_of_contact__firstname') ).get().name, "foo", ) self.assertRaises(FieldError, lambda: Company.objects.exclude( ceo__firstname=F('point_of_contact__firstname') ).update(name=F('point_of_contact__lastname')) ) # F expressions can be used to update attributes on single objects test_gmbh = Company.objects.get(name="Test GmbH") self.assertEqual(test_gmbh.num_employees, 32) test_gmbh.num_employees = F("num_employees") + 4 test_gmbh.save() test_gmbh = Company.objects.get(pk=test_gmbh.pk) self.assertEqual(test_gmbh.num_employees, 36) # F expressions cannot be used to update attributes which are foreign # keys, or attributes which involve joins. test_gmbh.point_of_contact = None test_gmbh.save() self.assertTrue(test_gmbh.point_of_contact is None) def test(): test_gmbh.point_of_contact = F("ceo") self.assertRaises(ValueError, test) test_gmbh.point_of_contact = test_gmbh.ceo test_gmbh.save() test_gmbh.name = F("ceo__last_name") self.assertRaises(FieldError, test_gmbh.save) # F expressions cannot be used to update attributes on objects which do # not yet exist in the database acme = Company( name="The Acme Widget Co.", num_employees=12, num_chairs=5, ceo=test_gmbh.ceo ) acme.num_employees = F("num_employees") + 16 self.assertRaises(TypeError, acme.save)
7,256
Python
.py
200
22.65
94
0.482239
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,318
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/generic_relations/models.py
""" 34. Generic relations Generic relations let an object have a foreign key to any object through a content-type/object-id field. A ``GenericForeignKey`` field can point to any object, be it animal, vegetable, or mineral. The canonical example is tags (although this example implementation is *far* from complete). """ from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.db import models class TaggedItem(models.Model): """A tag on an item.""" tag = models.SlugField() content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey() class Meta: ordering = ["tag", "content_type__name"] def __unicode__(self): return self.tag class ValuableTaggedItem(TaggedItem): value = models.PositiveIntegerField() class Comparison(models.Model): """ A model that tests having multiple GenericForeignKeys """ comparative = models.CharField(max_length=50) content_type1 = models.ForeignKey(ContentType, related_name="comparative1_set") object_id1 = models.PositiveIntegerField() content_type2 = models.ForeignKey(ContentType, related_name="comparative2_set") object_id2 = models.PositiveIntegerField() first_obj = generic.GenericForeignKey(ct_field="content_type1", fk_field="object_id1") other_obj = generic.GenericForeignKey(ct_field="content_type2", fk_field="object_id2") def __unicode__(self): return u"%s is %s than %s" % (self.first_obj, self.comparative, self.other_obj) class Animal(models.Model): common_name = models.CharField(max_length=150) latin_name = models.CharField(max_length=150) tags = generic.GenericRelation(TaggedItem) comparisons = generic.GenericRelation(Comparison, object_id_field="object_id1", content_type_field="content_type1") def __unicode__(self): return self.common_name class Vegetable(models.Model): name = models.CharField(max_length=150) is_yucky = models.BooleanField(default=True) tags = generic.GenericRelation(TaggedItem) def __unicode__(self): return self.name class Mineral(models.Model): name = models.CharField(max_length=150) hardness = models.PositiveSmallIntegerField() # note the lack of an explicit GenericRelation here... def __unicode__(self): return self.name
2,521
Python
.py
57
38.263158
90
0.71569
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,319
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/generic_relations/tests.py
from django.contrib.contenttypes.generic import generic_inlineformset_factory from django.contrib.contenttypes.models import ContentType from django.test import TestCase from models import (TaggedItem, ValuableTaggedItem, Comparison, Animal, Vegetable, Mineral) class GenericRelationsTests(TestCase): def test_generic_relations(self): # Create the world in 7 lines of code... lion = Animal.objects.create(common_name="Lion", latin_name="Panthera leo") platypus = Animal.objects.create( common_name="Platypus", latin_name="Ornithorhynchus anatinus" ) eggplant = Vegetable.objects.create(name="Eggplant", is_yucky=True) bacon = Vegetable.objects.create(name="Bacon", is_yucky=False) quartz = Mineral.objects.create(name="Quartz", hardness=7) # Objects with declared GenericRelations can be tagged directly -- the # API mimics the many-to-many API. bacon.tags.create(tag="fatty") bacon.tags.create(tag="salty") lion.tags.create(tag="yellow") lion.tags.create(tag="hairy") platypus.tags.create(tag="fatty") self.assertQuerysetEqual(lion.tags.all(), [ "<TaggedItem: hairy>", "<TaggedItem: yellow>" ]) self.assertQuerysetEqual(bacon.tags.all(), [ "<TaggedItem: fatty>", "<TaggedItem: salty>" ]) # You can easily access the content object like a foreign key. t = TaggedItem.objects.get(tag="salty") self.assertEqual(t.content_object, bacon) # Recall that the Mineral class doesn't have an explicit GenericRelation # defined. That's OK, because you can create TaggedItems explicitly. tag1 = TaggedItem.objects.create(content_object=quartz, tag="shiny") tag2 = TaggedItem.objects.create(content_object=quartz, tag="clearish") # However, excluding GenericRelations means your lookups have to be a # bit more explicit. ctype = ContentType.objects.get_for_model(quartz) q = TaggedItem.objects.filter( content_type__pk=ctype.id, object_id=quartz.id ) self.assertQuerysetEqual(q, [ "<TaggedItem: clearish>", "<TaggedItem: shiny>" ]) # You can set a generic foreign key in the way you'd expect. tag1.content_object = platypus tag1.save() self.assertQuerysetEqual(platypus.tags.all(), [ "<TaggedItem: fatty>", "<TaggedItem: shiny>" ]) q = TaggedItem.objects.filter( content_type__pk=ctype.id, object_id=quartz.id ) self.assertQuerysetEqual(q, ["<TaggedItem: clearish>"]) # Queries across generic relations respect the content types. Even # though there are two TaggedItems with a tag of "fatty", this query # only pulls out the one with the content type related to Animals. self.assertQuerysetEqual(Animal.objects.order_by('common_name'), [ "<Animal: Lion>", "<Animal: Platypus>" ]) self.assertQuerysetEqual(Animal.objects.filter(tags__tag='fatty'), [ "<Animal: Platypus>" ]) self.assertQuerysetEqual(Animal.objects.exclude(tags__tag='fatty'), [ "<Animal: Lion>" ]) # If you delete an object with an explicit Generic relation, the related # objects are deleted when the source object is deleted. # Original list of tags: comp_func = lambda obj: ( obj.tag, obj.content_type.model_class(), obj.object_id ) self.assertQuerysetEqual(TaggedItem.objects.all(), [ (u'clearish', Mineral, quartz.pk), (u'fatty', Animal, platypus.pk), (u'fatty', Vegetable, bacon.pk), (u'hairy', Animal, lion.pk), (u'salty', Vegetable, bacon.pk), (u'shiny', Animal, platypus.pk), (u'yellow', Animal, lion.pk) ], comp_func ) lion.delete() self.assertQuerysetEqual(TaggedItem.objects.all(), [ (u'clearish', Mineral, quartz.pk), (u'fatty', Animal, platypus.pk), (u'fatty', Vegetable, bacon.pk), (u'salty', Vegetable, bacon.pk), (u'shiny', Animal, platypus.pk) ], comp_func ) # If Generic Relation is not explicitly defined, any related objects # remain after deletion of the source object. quartz_pk = quartz.pk quartz.delete() self.assertQuerysetEqual(TaggedItem.objects.all(), [ (u'clearish', Mineral, quartz_pk), (u'fatty', Animal, platypus.pk), (u'fatty', Vegetable, bacon.pk), (u'salty', Vegetable, bacon.pk), (u'shiny', Animal, platypus.pk) ], comp_func ) # If you delete a tag, the objects using the tag are unaffected # (other than losing a tag) tag = TaggedItem.objects.order_by("id")[0] tag.delete() self.assertQuerysetEqual(bacon.tags.all(), ["<TaggedItem: salty>"]) self.assertQuerysetEqual(TaggedItem.objects.all(), [ (u'clearish', Mineral, quartz_pk), (u'fatty', Animal, platypus.pk), (u'salty', Vegetable, bacon.pk), (u'shiny', Animal, platypus.pk) ], comp_func ) TaggedItem.objects.filter(tag='fatty').delete() ctype = ContentType.objects.get_for_model(lion) self.assertQuerysetEqual(Animal.objects.filter(tags__content_type=ctype), [ "<Animal: Platypus>" ]) def test_multiple_gfk(self): # Simple tests for multiple GenericForeignKeys # only uses one model, since the above tests should be sufficient. tiger = Animal.objects.create(common_name="tiger") cheetah = Animal.objects.create(common_name="cheetah") bear = Animal.objects.create(common_name="bear") # Create directly Comparison.objects.create( first_obj=cheetah, other_obj=tiger, comparative="faster" ) Comparison.objects.create( first_obj=tiger, other_obj=cheetah, comparative="cooler" ) # Create using GenericRelation tiger.comparisons.create(other_obj=bear, comparative="cooler") tiger.comparisons.create(other_obj=cheetah, comparative="stronger") self.assertQuerysetEqual(cheetah.comparisons.all(), [ "<Comparison: cheetah is faster than tiger>" ]) # Filtering works self.assertQuerysetEqual(tiger.comparisons.filter(comparative="cooler"), [ "<Comparison: tiger is cooler than cheetah>", "<Comparison: tiger is cooler than bear>" ]) # Filtering and deleting works subjective = ["cooler"] tiger.comparisons.filter(comparative__in=subjective).delete() self.assertQuerysetEqual(Comparison.objects.all(), [ "<Comparison: cheetah is faster than tiger>", "<Comparison: tiger is stronger than cheetah>" ]) # If we delete cheetah, Comparisons with cheetah as 'first_obj' will be # deleted since Animal has an explicit GenericRelation to Comparison # through first_obj. Comparisons with cheetah as 'other_obj' will not # be deleted. cheetah.delete() self.assertQuerysetEqual(Comparison.objects.all(), [ "<Comparison: tiger is stronger than None>" ]) def test_gfk_subclasses(self): # GenericForeignKey should work with subclasses (see #8309) quartz = Mineral.objects.create(name="Quartz", hardness=7) valuedtag = ValuableTaggedItem.objects.create( content_object=quartz, tag="shiny", value=10 ) self.assertEqual(valuedtag.content_object, quartz) def test_generic_inline_formsets(self): GenericFormSet = generic_inlineformset_factory(TaggedItem, extra=1) formset = GenericFormSet() self.assertEqual(u''.join(form.as_p() for form in formset.forms), u"""<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" maxlength="50" /></p> <p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" id="id_generic_relations-taggeditem-content_type-object_id-0-id" /></p>""") formset = GenericFormSet(instance=Animal()) self.assertEqual(u''.join(form.as_p() for form in formset.forms), u"""<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" maxlength="50" /></p> <p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" id="id_generic_relations-taggeditem-content_type-object_id-0-id" /></p>""") platypus = Animal.objects.create( common_name="Platypus", latin_name="Ornithorhynchus anatinus" ) platypus.tags.create(tag="shiny") GenericFormSet = generic_inlineformset_factory(TaggedItem, extra=1) formset = GenericFormSet(instance=platypus) tagged_item_id = TaggedItem.objects.get( tag='shiny', object_id=platypus.id ).id self.assertEqual(u''.join(form.as_p() for form in formset.forms), u"""<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" value="shiny" maxlength="50" /></p> <p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" value="%s" id="id_generic_relations-taggeditem-content_type-object_id-0-id" /></p><p><label for="id_generic_relations-taggeditem-content_type-object_id-1-tag">Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-1-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-1-tag" maxlength="50" /></p> <p><label for="id_generic_relations-taggeditem-content_type-object_id-1-DELETE">Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-1-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-1-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-1-id" id="id_generic_relations-taggeditem-content_type-object_id-1-id" /></p>""" % tagged_item_id) lion = Animal.objects.create(common_name="Lion", latin_name="Panthera leo") formset = GenericFormSet(instance=lion, prefix='x') self.assertEqual(u''.join(form.as_p() for form in formset.forms), u"""<p><label for="id_x-0-tag">Tag:</label> <input id="id_x-0-tag" type="text" name="x-0-tag" maxlength="50" /></p> <p><label for="id_x-0-DELETE">Delete:</label> <input type="checkbox" name="x-0-DELETE" id="id_x-0-DELETE" /><input type="hidden" name="x-0-id" id="id_x-0-id" /></p>""")
12,150
Python
.py
199
50.869347
686
0.654817
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,320
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/invalid_models/models.py
""" 26. Invalid models This example exists purely to point out errors in models. """ from django.contrib.contenttypes import generic from django.db import models class FieldErrors(models.Model): charfield = models.CharField() charfield2 = models.CharField(max_length=-1) charfield3 = models.CharField(max_length="bad") decimalfield = models.DecimalField() decimalfield2 = models.DecimalField(max_digits=-1, decimal_places=-1) decimalfield3 = models.DecimalField(max_digits="bad", decimal_places="bad") decimalfield4 = models.DecimalField(max_digits=9, decimal_places=10) decimalfield5 = models.DecimalField(max_digits=10, decimal_places=10) filefield = models.FileField() choices = models.CharField(max_length=10, choices='bad') choices2 = models.CharField(max_length=10, choices=[(1,2,3),(1,2,3)]) index = models.CharField(max_length=10, db_index='bad') field_ = models.CharField(max_length=10) nullbool = models.BooleanField(null=True) class Target(models.Model): tgt_safe = models.CharField(max_length=10) clash1 = models.CharField(max_length=10) clash2 = models.CharField(max_length=10) clash1_set = models.CharField(max_length=10) class Clash1(models.Model): src_safe = models.CharField(max_length=10) foreign = models.ForeignKey(Target) m2m = models.ManyToManyField(Target) class Clash2(models.Model): src_safe = models.CharField(max_length=10) foreign_1 = models.ForeignKey(Target, related_name='id') foreign_2 = models.ForeignKey(Target, related_name='src_safe') m2m_1 = models.ManyToManyField(Target, related_name='id') m2m_2 = models.ManyToManyField(Target, related_name='src_safe') class Target2(models.Model): clash3 = models.CharField(max_length=10) foreign_tgt = models.ForeignKey(Target) clashforeign_set = models.ForeignKey(Target) m2m_tgt = models.ManyToManyField(Target) clashm2m_set = models.ManyToManyField(Target) class Clash3(models.Model): src_safe = models.CharField(max_length=10) foreign_1 = models.ForeignKey(Target2, related_name='foreign_tgt') foreign_2 = models.ForeignKey(Target2, related_name='m2m_tgt') m2m_1 = models.ManyToManyField(Target2, related_name='foreign_tgt') m2m_2 = models.ManyToManyField(Target2, related_name='m2m_tgt') class ClashForeign(models.Model): foreign = models.ForeignKey(Target2) class ClashM2M(models.Model): m2m = models.ManyToManyField(Target2) class SelfClashForeign(models.Model): src_safe = models.CharField(max_length=10) selfclashforeign = models.CharField(max_length=10) selfclashforeign_set = models.ForeignKey("SelfClashForeign") foreign_1 = models.ForeignKey("SelfClashForeign", related_name='id') foreign_2 = models.ForeignKey("SelfClashForeign", related_name='src_safe') class ValidM2M(models.Model): src_safe = models.CharField(max_length=10) validm2m = models.CharField(max_length=10) # M2M fields are symmetrical by default. Symmetrical M2M fields # on self don't require a related accessor, so many potential # clashes are avoided. validm2m_set = models.ManyToManyField("self") m2m_1 = models.ManyToManyField("self", related_name='id') m2m_2 = models.ManyToManyField("self", related_name='src_safe') m2m_3 = models.ManyToManyField('self') m2m_4 = models.ManyToManyField('self') class SelfClashM2M(models.Model): src_safe = models.CharField(max_length=10) selfclashm2m = models.CharField(max_length=10) # Non-symmetrical M2M fields _do_ have related accessors, so # there is potential for clashes. selfclashm2m_set = models.ManyToManyField("self", symmetrical=False) m2m_1 = models.ManyToManyField("self", related_name='id', symmetrical=False) m2m_2 = models.ManyToManyField("self", related_name='src_safe', symmetrical=False) m2m_3 = models.ManyToManyField('self', symmetrical=False) m2m_4 = models.ManyToManyField('self', symmetrical=False) class Model(models.Model): "But it's valid to call a model Model." year = models.PositiveIntegerField() #1960 make = models.CharField(max_length=10) #Aston Martin name = models.CharField(max_length=10) #DB 4 GT class Car(models.Model): colour = models.CharField(max_length=5) model = models.ForeignKey(Model) class MissingRelations(models.Model): rel1 = models.ForeignKey("Rel1") rel2 = models.ManyToManyField("Rel2") class MissingManualM2MModel(models.Model): name = models.CharField(max_length=5) missing_m2m = models.ManyToManyField(Model, through="MissingM2MModel") class Person(models.Model): name = models.CharField(max_length=5) class Group(models.Model): name = models.CharField(max_length=5) primary = models.ManyToManyField(Person, through="Membership", related_name="primary") secondary = models.ManyToManyField(Person, through="Membership", related_name="secondary") tertiary = models.ManyToManyField(Person, through="RelationshipDoubleFK", related_name="tertiary") class GroupTwo(models.Model): name = models.CharField(max_length=5) primary = models.ManyToManyField(Person, through="Membership") secondary = models.ManyToManyField(Group, through="MembershipMissingFK") class Membership(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) not_default_or_null = models.CharField(max_length=5) class MembershipMissingFK(models.Model): person = models.ForeignKey(Person) class PersonSelfRefM2M(models.Model): name = models.CharField(max_length=5) friends = models.ManyToManyField('self', through="Relationship") too_many_friends = models.ManyToManyField('self', through="RelationshipTripleFK") class PersonSelfRefM2MExplicit(models.Model): name = models.CharField(max_length=5) friends = models.ManyToManyField('self', through="ExplicitRelationship", symmetrical=True) class Relationship(models.Model): first = models.ForeignKey(PersonSelfRefM2M, related_name="rel_from_set") second = models.ForeignKey(PersonSelfRefM2M, related_name="rel_to_set") date_added = models.DateTimeField() class ExplicitRelationship(models.Model): first = models.ForeignKey(PersonSelfRefM2MExplicit, related_name="rel_from_set") second = models.ForeignKey(PersonSelfRefM2MExplicit, related_name="rel_to_set") date_added = models.DateTimeField() class RelationshipTripleFK(models.Model): first = models.ForeignKey(PersonSelfRefM2M, related_name="rel_from_set_2") second = models.ForeignKey(PersonSelfRefM2M, related_name="rel_to_set_2") third = models.ForeignKey(PersonSelfRefM2M, related_name="too_many_by_far") date_added = models.DateTimeField() class RelationshipDoubleFK(models.Model): first = models.ForeignKey(Person, related_name="first_related_name") second = models.ForeignKey(Person, related_name="second_related_name") third = models.ForeignKey(Group, related_name="rel_to_set") date_added = models.DateTimeField() class AbstractModel(models.Model): name = models.CharField(max_length=10) class Meta: abstract = True class AbstractRelationModel(models.Model): fk1 = models.ForeignKey('AbstractModel') fk2 = models.ManyToManyField('AbstractModel') class UniqueM2M(models.Model): """ Model to test for unique ManyToManyFields, which are invalid. """ unique_people = models.ManyToManyField(Person, unique=True) class NonUniqueFKTarget1(models.Model): """ Model to test for non-unique FK target in yet-to-be-defined model: expect an error """ tgt = models.ForeignKey('FKTarget', to_field='bad') class UniqueFKTarget1(models.Model): """ Model to test for unique FK target in yet-to-be-defined model: expect no error """ tgt = models.ForeignKey('FKTarget', to_field='good') class FKTarget(models.Model): bad = models.IntegerField() good = models.IntegerField(unique=True) class NonUniqueFKTarget2(models.Model): """ Model to test for non-unique FK target in previously seen model: expect an error """ tgt = models.ForeignKey(FKTarget, to_field='bad') class UniqueFKTarget2(models.Model): """ Model to test for unique FK target in previously seen model: expect no error """ tgt = models.ForeignKey(FKTarget, to_field='good') class NonExistingOrderingWithSingleUnderscore(models.Model): class Meta: ordering = ("does_not_exist",) class Tag(models.Model): name = models.CharField("name", max_length=20) class TaggedObject(models.Model): object_id = models.PositiveIntegerField("Object ID") tag = models.ForeignKey(Tag) content_object = generic.GenericForeignKey() class UserTaggedObject(models.Model): object_tag = models.ForeignKey(TaggedObject) class ArticleAttachment(models.Model): tags = generic.GenericRelation(TaggedObject) user_tags = generic.GenericRelation(UserTaggedObject) model_errors = """invalid_models.fielderrors: "charfield": CharFields require a "max_length" attribute that is a positive integer. invalid_models.fielderrors: "charfield2": CharFields require a "max_length" attribute that is a positive integer. invalid_models.fielderrors: "charfield3": CharFields require a "max_length" attribute that is a positive integer. invalid_models.fielderrors: "decimalfield": DecimalFields require a "decimal_places" attribute that is a non-negative integer. invalid_models.fielderrors: "decimalfield": DecimalFields require a "max_digits" attribute that is a positive integer. invalid_models.fielderrors: "decimalfield2": DecimalFields require a "decimal_places" attribute that is a non-negative integer. invalid_models.fielderrors: "decimalfield2": DecimalFields require a "max_digits" attribute that is a positive integer. invalid_models.fielderrors: "decimalfield3": DecimalFields require a "decimal_places" attribute that is a non-negative integer. invalid_models.fielderrors: "decimalfield3": DecimalFields require a "max_digits" attribute that is a positive integer. invalid_models.fielderrors: "decimalfield4": DecimalFields require a "max_digits" attribute value that is greater than the value of the "decimal_places" attribute. invalid_models.fielderrors: "decimalfield5": DecimalFields require a "max_digits" attribute value that is greater than the value of the "decimal_places" attribute. invalid_models.fielderrors: "filefield": FileFields require an "upload_to" attribute. invalid_models.fielderrors: "choices": "choices" should be iterable (e.g., a tuple or list). invalid_models.fielderrors: "choices2": "choices" should be a sequence of two-tuples. invalid_models.fielderrors: "choices2": "choices" should be a sequence of two-tuples. invalid_models.fielderrors: "index": "db_index" should be either None, True or False. invalid_models.fielderrors: "field_": Field names cannot end with underscores, because this would lead to ambiguous queryset filters. invalid_models.fielderrors: "nullbool": BooleanFields do not accept null values. Use a NullBooleanField instead. invalid_models.clash1: Accessor for field 'foreign' clashes with field 'Target.clash1_set'. Add a related_name argument to the definition for 'foreign'. invalid_models.clash1: Accessor for field 'foreign' clashes with related m2m field 'Target.clash1_set'. Add a related_name argument to the definition for 'foreign'. invalid_models.clash1: Reverse query name for field 'foreign' clashes with field 'Target.clash1'. Add a related_name argument to the definition for 'foreign'. invalid_models.clash1: Accessor for m2m field 'm2m' clashes with field 'Target.clash1_set'. Add a related_name argument to the definition for 'm2m'. invalid_models.clash1: Accessor for m2m field 'm2m' clashes with related field 'Target.clash1_set'. Add a related_name argument to the definition for 'm2m'. invalid_models.clash1: Reverse query name for m2m field 'm2m' clashes with field 'Target.clash1'. Add a related_name argument to the definition for 'm2m'. invalid_models.clash2: Accessor for field 'foreign_1' clashes with field 'Target.id'. Add a related_name argument to the definition for 'foreign_1'. invalid_models.clash2: Accessor for field 'foreign_1' clashes with related m2m field 'Target.id'. Add a related_name argument to the definition for 'foreign_1'. invalid_models.clash2: Reverse query name for field 'foreign_1' clashes with field 'Target.id'. Add a related_name argument to the definition for 'foreign_1'. invalid_models.clash2: Reverse query name for field 'foreign_1' clashes with related m2m field 'Target.id'. Add a related_name argument to the definition for 'foreign_1'. invalid_models.clash2: Accessor for field 'foreign_2' clashes with related m2m field 'Target.src_safe'. Add a related_name argument to the definition for 'foreign_2'. invalid_models.clash2: Reverse query name for field 'foreign_2' clashes with related m2m field 'Target.src_safe'. Add a related_name argument to the definition for 'foreign_2'. invalid_models.clash2: Accessor for m2m field 'm2m_1' clashes with field 'Target.id'. Add a related_name argument to the definition for 'm2m_1'. invalid_models.clash2: Accessor for m2m field 'm2m_1' clashes with related field 'Target.id'. Add a related_name argument to the definition for 'm2m_1'. invalid_models.clash2: Reverse query name for m2m field 'm2m_1' clashes with field 'Target.id'. Add a related_name argument to the definition for 'm2m_1'. invalid_models.clash2: Reverse query name for m2m field 'm2m_1' clashes with related field 'Target.id'. Add a related_name argument to the definition for 'm2m_1'. invalid_models.clash2: Accessor for m2m field 'm2m_2' clashes with related field 'Target.src_safe'. Add a related_name argument to the definition for 'm2m_2'. invalid_models.clash2: Reverse query name for m2m field 'm2m_2' clashes with related field 'Target.src_safe'. Add a related_name argument to the definition for 'm2m_2'. invalid_models.clash3: Accessor for field 'foreign_1' clashes with field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'foreign_1'. invalid_models.clash3: Accessor for field 'foreign_1' clashes with related m2m field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'foreign_1'. invalid_models.clash3: Reverse query name for field 'foreign_1' clashes with field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'foreign_1'. invalid_models.clash3: Reverse query name for field 'foreign_1' clashes with related m2m field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'foreign_1'. invalid_models.clash3: Accessor for field 'foreign_2' clashes with m2m field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'foreign_2'. invalid_models.clash3: Accessor for field 'foreign_2' clashes with related m2m field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'foreign_2'. invalid_models.clash3: Reverse query name for field 'foreign_2' clashes with m2m field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'foreign_2'. invalid_models.clash3: Reverse query name for field 'foreign_2' clashes with related m2m field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'foreign_2'. invalid_models.clash3: Accessor for m2m field 'm2m_1' clashes with field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'm2m_1'. invalid_models.clash3: Accessor for m2m field 'm2m_1' clashes with related field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'm2m_1'. invalid_models.clash3: Reverse query name for m2m field 'm2m_1' clashes with field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'm2m_1'. invalid_models.clash3: Reverse query name for m2m field 'm2m_1' clashes with related field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'm2m_1'. invalid_models.clash3: Accessor for m2m field 'm2m_2' clashes with m2m field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'm2m_2'. invalid_models.clash3: Accessor for m2m field 'm2m_2' clashes with related field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'm2m_2'. invalid_models.clash3: Reverse query name for m2m field 'm2m_2' clashes with m2m field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'm2m_2'. invalid_models.clash3: Reverse query name for m2m field 'm2m_2' clashes with related field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'm2m_2'. invalid_models.clashforeign: Accessor for field 'foreign' clashes with field 'Target2.clashforeign_set'. Add a related_name argument to the definition for 'foreign'. invalid_models.clashm2m: Accessor for m2m field 'm2m' clashes with m2m field 'Target2.clashm2m_set'. Add a related_name argument to the definition for 'm2m'. invalid_models.target2: Accessor for field 'foreign_tgt' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'foreign_tgt'. invalid_models.target2: Accessor for field 'foreign_tgt' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'foreign_tgt'. invalid_models.target2: Accessor for field 'foreign_tgt' clashes with related field 'Target.target2_set'. Add a related_name argument to the definition for 'foreign_tgt'. invalid_models.target2: Accessor for field 'clashforeign_set' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'clashforeign_set'. invalid_models.target2: Accessor for field 'clashforeign_set' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'clashforeign_set'. invalid_models.target2: Accessor for field 'clashforeign_set' clashes with related field 'Target.target2_set'. Add a related_name argument to the definition for 'clashforeign_set'. invalid_models.target2: Accessor for m2m field 'm2m_tgt' clashes with related field 'Target.target2_set'. Add a related_name argument to the definition for 'm2m_tgt'. invalid_models.target2: Accessor for m2m field 'm2m_tgt' clashes with related field 'Target.target2_set'. Add a related_name argument to the definition for 'm2m_tgt'. invalid_models.target2: Accessor for m2m field 'm2m_tgt' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'm2m_tgt'. invalid_models.target2: Accessor for m2m field 'm2m_tgt' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'm2m_tgt'. invalid_models.target2: Accessor for m2m field 'm2m_tgt' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'm2m_tgt'. invalid_models.target2: Accessor for m2m field 'clashm2m_set' clashes with related field 'Target.target2_set'. Add a related_name argument to the definition for 'clashm2m_set'. invalid_models.target2: Accessor for m2m field 'clashm2m_set' clashes with related field 'Target.target2_set'. Add a related_name argument to the definition for 'clashm2m_set'. invalid_models.target2: Accessor for m2m field 'clashm2m_set' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'clashm2m_set'. invalid_models.target2: Accessor for m2m field 'clashm2m_set' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'clashm2m_set'. invalid_models.target2: Accessor for m2m field 'clashm2m_set' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'clashm2m_set'. invalid_models.selfclashforeign: Accessor for field 'selfclashforeign_set' clashes with field 'SelfClashForeign.selfclashforeign_set'. Add a related_name argument to the definition for 'selfclashforeign_set'. invalid_models.selfclashforeign: Reverse query name for field 'selfclashforeign_set' clashes with field 'SelfClashForeign.selfclashforeign'. Add a related_name argument to the definition for 'selfclashforeign_set'. invalid_models.selfclashforeign: Accessor for field 'foreign_1' clashes with field 'SelfClashForeign.id'. Add a related_name argument to the definition for 'foreign_1'. invalid_models.selfclashforeign: Reverse query name for field 'foreign_1' clashes with field 'SelfClashForeign.id'. Add a related_name argument to the definition for 'foreign_1'. invalid_models.selfclashforeign: Accessor for field 'foreign_2' clashes with field 'SelfClashForeign.src_safe'. Add a related_name argument to the definition for 'foreign_2'. invalid_models.selfclashforeign: Reverse query name for field 'foreign_2' clashes with field 'SelfClashForeign.src_safe'. Add a related_name argument to the definition for 'foreign_2'. invalid_models.selfclashm2m: Accessor for m2m field 'selfclashm2m_set' clashes with m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'selfclashm2m_set'. invalid_models.selfclashm2m: Reverse query name for m2m field 'selfclashm2m_set' clashes with field 'SelfClashM2M.selfclashm2m'. Add a related_name argument to the definition for 'selfclashm2m_set'. invalid_models.selfclashm2m: Accessor for m2m field 'selfclashm2m_set' clashes with related m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'selfclashm2m_set'. invalid_models.selfclashm2m: Accessor for m2m field 'm2m_1' clashes with field 'SelfClashM2M.id'. Add a related_name argument to the definition for 'm2m_1'. invalid_models.selfclashm2m: Accessor for m2m field 'm2m_2' clashes with field 'SelfClashM2M.src_safe'. Add a related_name argument to the definition for 'm2m_2'. invalid_models.selfclashm2m: Reverse query name for m2m field 'm2m_1' clashes with field 'SelfClashM2M.id'. Add a related_name argument to the definition for 'm2m_1'. invalid_models.selfclashm2m: Reverse query name for m2m field 'm2m_2' clashes with field 'SelfClashM2M.src_safe'. Add a related_name argument to the definition for 'm2m_2'. invalid_models.selfclashm2m: Accessor for m2m field 'm2m_3' clashes with m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'm2m_3'. invalid_models.selfclashm2m: Accessor for m2m field 'm2m_3' clashes with related m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'm2m_3'. invalid_models.selfclashm2m: Accessor for m2m field 'm2m_3' clashes with related m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'm2m_3'. invalid_models.selfclashm2m: Accessor for m2m field 'm2m_4' clashes with m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'm2m_4'. invalid_models.selfclashm2m: Accessor for m2m field 'm2m_4' clashes with related m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'm2m_4'. invalid_models.selfclashm2m: Accessor for m2m field 'm2m_4' clashes with related m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'm2m_4'. invalid_models.selfclashm2m: Reverse query name for m2m field 'm2m_3' clashes with field 'SelfClashM2M.selfclashm2m'. Add a related_name argument to the definition for 'm2m_3'. invalid_models.selfclashm2m: Reverse query name for m2m field 'm2m_4' clashes with field 'SelfClashM2M.selfclashm2m'. Add a related_name argument to the definition for 'm2m_4'. invalid_models.missingrelations: 'rel1' has a relation with model Rel1, which has either not been installed or is abstract. invalid_models.missingrelations: 'rel2' has an m2m relation with model Rel2, which has either not been installed or is abstract. invalid_models.grouptwo: 'primary' is a manually-defined m2m relation through model Membership, which does not have foreign keys to Person and GroupTwo invalid_models.grouptwo: 'secondary' is a manually-defined m2m relation through model MembershipMissingFK, which does not have foreign keys to Group and GroupTwo invalid_models.missingmanualm2mmodel: 'missing_m2m' specifies an m2m relation through model MissingM2MModel, which has not been installed invalid_models.group: The model Group has two manually-defined m2m relations through the model Membership, which is not permitted. Please consider using an extra field on your intermediary model instead. invalid_models.group: Intermediary model RelationshipDoubleFK has more than one foreign key to Person, which is ambiguous and is not permitted. invalid_models.personselfrefm2m: Many-to-many fields with intermediate tables cannot be symmetrical. invalid_models.personselfrefm2m: Intermediary model RelationshipTripleFK has more than two foreign keys to PersonSelfRefM2M, which is ambiguous and is not permitted. invalid_models.personselfrefm2mexplicit: Many-to-many fields with intermediate tables cannot be symmetrical. invalid_models.abstractrelationmodel: 'fk1' has a relation with model AbstractModel, which has either not been installed or is abstract. invalid_models.abstractrelationmodel: 'fk2' has an m2m relation with model AbstractModel, which has either not been installed or is abstract. invalid_models.uniquem2m: ManyToManyFields cannot be unique. Remove the unique argument on 'unique_people'. invalid_models.nonuniquefktarget1: Field 'bad' under model 'FKTarget' must have a unique=True constraint. invalid_models.nonuniquefktarget2: Field 'bad' under model 'FKTarget' must have a unique=True constraint. invalid_models.nonexistingorderingwithsingleunderscore: "ordering" refers to "does_not_exist", a field that doesn't exist. invalid_models.articleattachment: Model 'UserTaggedObject' must have a GenericForeignKey in order to create a GenericRelation that points to it. """
25,802
Python
.py
283
88.14841
214
0.786278
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,321
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/model_forms/models.py
""" XX. Generating HTML forms from models This is mostly just a reworking of the ``form_for_model``/``form_for_instance`` tests to use ``ModelForm``. As such, the text may not make sense in all cases, and the examples are probably a poor fit for the ``ModelForm`` syntax. In other words, most of these tests should be rewritten. """ import os import tempfile from django.db import models from django.core.files.storage import FileSystemStorage temp_storage_dir = tempfile.mkdtemp() temp_storage = FileSystemStorage(temp_storage_dir) ARTICLE_STATUS = ( (1, 'Draft'), (2, 'Pending'), (3, 'Live'), ) ARTICLE_STATUS_CHAR = ( ('d', 'Draft'), ('p', 'Pending'), ('l', 'Live'), ) class Category(models.Model): name = models.CharField(max_length=20) slug = models.SlugField(max_length=20) url = models.CharField('The URL', max_length=40) def __unicode__(self): return self.name class Writer(models.Model): name = models.CharField(max_length=50, help_text='Use both first and last names.') def __unicode__(self): return self.name class Article(models.Model): headline = models.CharField(max_length=50) slug = models.SlugField() pub_date = models.DateField() created = models.DateField(editable=False) writer = models.ForeignKey(Writer) article = models.TextField() categories = models.ManyToManyField(Category, blank=True) status = models.PositiveIntegerField(choices=ARTICLE_STATUS, blank=True, null=True) def save(self): import datetime if not self.id: self.created = datetime.date.today() return super(Article, self).save() def __unicode__(self): return self.headline class ImprovedArticle(models.Model): article = models.OneToOneField(Article) class ImprovedArticleWithParentLink(models.Model): article = models.OneToOneField(Article, parent_link=True) class BetterWriter(Writer): score = models.IntegerField() class WriterProfile(models.Model): writer = models.OneToOneField(Writer, primary_key=True) age = models.PositiveIntegerField() def __unicode__(self): return "%s is %s" % (self.writer, self.age) from django.contrib.localflavor.us.models import PhoneNumberField class PhoneNumber(models.Model): phone = PhoneNumberField() description = models.CharField(max_length=20) def __unicode__(self): return self.phone class TextFile(models.Model): description = models.CharField(max_length=20) file = models.FileField(storage=temp_storage, upload_to='tests', max_length=15) def __unicode__(self): return self.description try: # If PIL is available, try testing ImageFields. Checking for the existence # of Image is enough for CPython, but for PyPy, you need to check for the # underlying modules If PIL is not available, ImageField tests are omitted. # Try to import PIL in either of the two ways it can end up installed. try: from PIL import Image, _imaging except ImportError: import Image, _imaging test_images = True class ImageFile(models.Model): def custom_upload_path(self, filename): path = self.path or 'tests' return '%s/%s' % (path, filename) description = models.CharField(max_length=20) # Deliberately put the image field *after* the width/height fields to # trigger the bug in #10404 with width/height not getting assigned. width = models.IntegerField(editable=False) height = models.IntegerField(editable=False) image = models.ImageField(storage=temp_storage, upload_to=custom_upload_path, width_field='width', height_field='height') path = models.CharField(max_length=16, blank=True, default='') def __unicode__(self): return self.description class OptionalImageFile(models.Model): def custom_upload_path(self, filename): path = self.path or 'tests' return '%s/%s' % (path, filename) description = models.CharField(max_length=20) image = models.ImageField(storage=temp_storage, upload_to=custom_upload_path, width_field='width', height_field='height', blank=True, null=True) width = models.IntegerField(editable=False, null=True) height = models.IntegerField(editable=False, null=True) path = models.CharField(max_length=16, blank=True, default='') def __unicode__(self): return self.description except ImportError: test_images = False class CommaSeparatedInteger(models.Model): field = models.CommaSeparatedIntegerField(max_length=20) def __unicode__(self): return self.field class Product(models.Model): slug = models.SlugField(unique=True) def __unicode__(self): return self.slug class Price(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField() def __unicode__(self): return u"%s for %s" % (self.quantity, self.price) class Meta: unique_together = (('price', 'quantity'),) class ArticleStatus(models.Model): status = models.CharField(max_length=2, choices=ARTICLE_STATUS_CHAR, blank=True, null=True) class Inventory(models.Model): barcode = models.PositiveIntegerField(unique=True) parent = models.ForeignKey('self', to_field='barcode', blank=True, null=True) name = models.CharField(blank=False, max_length=20) def __unicode__(self): return self.name class Book(models.Model): title = models.CharField(max_length=40) author = models.ForeignKey(Writer, blank=True, null=True) special_id = models.IntegerField(blank=True, null=True, unique=True) class Meta: unique_together = ('title', 'author') class BookXtra(models.Model): isbn = models.CharField(max_length=16, unique=True) suffix1 = models.IntegerField(blank=True, default=0) suffix2 = models.IntegerField(blank=True, default=0) class Meta: unique_together = (('suffix1', 'suffix2')) abstract = True class DerivedBook(Book, BookXtra): pass class ExplicitPK(models.Model): key = models.CharField(max_length=20, primary_key=True) desc = models.CharField(max_length=20, blank=True, unique=True) class Meta: unique_together = ('key', 'desc') def __unicode__(self): return self.key class Post(models.Model): title = models.CharField(max_length=50, unique_for_date='posted', blank=True) slug = models.CharField(max_length=50, unique_for_year='posted', blank=True) subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True) posted = models.DateField() def __unicode__(self): return self.name class DerivedPost(Post): pass class BigInt(models.Model): biggie = models.BigIntegerField() def __unicode__(self): return unicode(self.biggie) class MarkupField(models.CharField): def __init__(self, *args, **kwargs): kwargs["max_length"] = 20 super(MarkupField, self).__init__(*args, **kwargs) def formfield(self, **kwargs): # don't allow this field to be used in form (real use-case might be # that you know the markup will always be X, but it is among an app # that allows the user to say it could be something else) # regressed at r10062 return None class CustomFieldForExclusionModel(models.Model): name = models.CharField(max_length=10) markup = MarkupField() class FlexibleDatePost(models.Model): title = models.CharField(max_length=50, unique_for_date='posted', blank=True) slug = models.CharField(max_length=50, unique_for_year='posted', blank=True) subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True) posted = models.DateField(blank=True, null=True) __test__ = {'API_TESTS': """ >>> from django import forms >>> from django.forms.models import ModelForm, model_to_dict >>> from django.core.files.uploadedfile import SimpleUploadedFile The bare bones, absolutely nothing custom, basic case. >>> class CategoryForm(ModelForm): ... class Meta: ... model = Category >>> CategoryForm.base_fields.keys() ['name', 'slug', 'url'] Extra fields. >>> class CategoryForm(ModelForm): ... some_extra_field = forms.BooleanField() ... ... class Meta: ... model = Category >>> CategoryForm.base_fields.keys() ['name', 'slug', 'url', 'some_extra_field'] Extra field that has a name collision with a related object accessor. >>> class WriterForm(ModelForm): ... book = forms.CharField(required=False) ... ... class Meta: ... model = Writer >>> wf = WriterForm({'name': 'Richard Lockridge'}) >>> wf.is_valid() True Replacing a field. >>> class CategoryForm(ModelForm): ... url = forms.BooleanField() ... ... class Meta: ... model = Category >>> CategoryForm.base_fields['url'].__class__ <class 'django.forms.fields.BooleanField'> Using 'fields'. >>> class CategoryForm(ModelForm): ... ... class Meta: ... model = Category ... fields = ['url'] >>> CategoryForm.base_fields.keys() ['url'] Using 'exclude' >>> class CategoryForm(ModelForm): ... ... class Meta: ... model = Category ... exclude = ['url'] >>> CategoryForm.base_fields.keys() ['name', 'slug'] Using 'fields' *and* 'exclude'. Not sure why you'd want to do this, but uh, "be liberal in what you accept" and all. >>> class CategoryForm(ModelForm): ... ... class Meta: ... model = Category ... fields = ['name', 'url'] ... exclude = ['url'] >>> CategoryForm.base_fields.keys() ['name'] Using 'widgets' >>> class CategoryForm(ModelForm): ... ... class Meta: ... model = Category ... fields = ['name', 'url', 'slug'] ... widgets = { ... 'name': forms.Textarea, ... 'url': forms.TextInput(attrs={'class': 'url'}) ... } >>> str(CategoryForm()['name']) '<textarea id="id_name" rows="10" cols="40" name="name"></textarea>' >>> str(CategoryForm()['url']) '<input id="id_url" type="text" class="url" name="url" maxlength="40" />' >>> str(CategoryForm()['slug']) '<input id="id_slug" type="text" name="slug" maxlength="20" />' Don't allow more than one 'model' definition in the inheritance hierarchy. Technically, it would generate a valid form, but the fact that the resulting save method won't deal with multiple objects is likely to trip up people not familiar with the mechanics. >>> class CategoryForm(ModelForm): ... class Meta: ... model = Category >>> class OddForm(CategoryForm): ... class Meta: ... model = Article OddForm is now an Article-related thing, because BadForm.Meta overrides CategoryForm.Meta. >>> OddForm.base_fields.keys() ['headline', 'slug', 'pub_date', 'writer', 'article', 'status', 'categories'] >>> class ArticleForm(ModelForm): ... class Meta: ... model = Article First class with a Meta class wins. >>> class BadForm(ArticleForm, CategoryForm): ... pass >>> OddForm.base_fields.keys() ['headline', 'slug', 'pub_date', 'writer', 'article', 'status', 'categories'] Subclassing without specifying a Meta on the class will use the parent's Meta (or the first parent in the MRO if there are multiple parent classes). >>> class CategoryForm(ModelForm): ... class Meta: ... model = Category >>> class SubCategoryForm(CategoryForm): ... pass >>> SubCategoryForm.base_fields.keys() ['name', 'slug', 'url'] We can also subclass the Meta inner class to change the fields list. >>> class CategoryForm(ModelForm): ... checkbox = forms.BooleanField() ... ... class Meta: ... model = Category >>> class SubCategoryForm(CategoryForm): ... class Meta(CategoryForm.Meta): ... exclude = ['url'] >>> print SubCategoryForm() <tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="20" /></td></tr> <tr><th><label for="id_slug">Slug:</label></th><td><input id="id_slug" type="text" name="slug" maxlength="20" /></td></tr> <tr><th><label for="id_checkbox">Checkbox:</label></th><td><input type="checkbox" name="checkbox" id="id_checkbox" /></td></tr> # test using fields to provide ordering to the fields >>> class CategoryForm(ModelForm): ... class Meta: ... model = Category ... fields = ['url', 'name'] >>> CategoryForm.base_fields.keys() ['url', 'name'] >>> print CategoryForm() <tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr> <tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="20" /></td></tr> >>> class CategoryForm(ModelForm): ... class Meta: ... model = Category ... fields = ['slug', 'url', 'name'] ... exclude = ['url'] >>> CategoryForm.base_fields.keys() ['slug', 'name'] # Old form_for_x tests ####################################################### >>> from django.forms import ModelForm, CharField >>> import datetime >>> Category.objects.all() [] >>> class CategoryForm(ModelForm): ... class Meta: ... model = Category >>> f = CategoryForm() >>> print f <tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="20" /></td></tr> <tr><th><label for="id_slug">Slug:</label></th><td><input id="id_slug" type="text" name="slug" maxlength="20" /></td></tr> <tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr> >>> print f.as_ul() <li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="20" /></li> <li><label for="id_slug">Slug:</label> <input id="id_slug" type="text" name="slug" maxlength="20" /></li> <li><label for="id_url">The URL:</label> <input id="id_url" type="text" name="url" maxlength="40" /></li> >>> print f['name'] <input id="id_name" type="text" name="name" maxlength="20" /> >>> f = CategoryForm(auto_id=False) >>> print f.as_ul() <li>Name: <input type="text" name="name" maxlength="20" /></li> <li>Slug: <input type="text" name="slug" maxlength="20" /></li> <li>The URL: <input type="text" name="url" maxlength="40" /></li> >>> f = CategoryForm({'name': 'Entertainment', 'slug': 'entertainment', 'url': 'entertainment'}) >>> f.is_valid() True >>> f.cleaned_data['url'] u'entertainment' >>> f.cleaned_data['name'] u'Entertainment' >>> f.cleaned_data['slug'] u'entertainment' >>> obj = f.save() >>> obj <Category: Entertainment> >>> Category.objects.all() [<Category: Entertainment>] >>> f = CategoryForm({'name': "It's a test", 'slug': 'its-test', 'url': 'test'}) >>> f.is_valid() True >>> f.cleaned_data['url'] u'test' >>> f.cleaned_data['name'] u"It's a test" >>> f.cleaned_data['slug'] u'its-test' >>> obj = f.save() >>> obj <Category: It's a test> >>> Category.objects.order_by('name') [<Category: Entertainment>, <Category: It's a test>] If you call save() with commit=False, then it will return an object that hasn't yet been saved to the database. In this case, it's up to you to call save() on the resulting model instance. >>> f = CategoryForm({'name': 'Third test', 'slug': 'third-test', 'url': 'third'}) >>> f.is_valid() True >>> f.cleaned_data['url'] u'third' >>> f.cleaned_data['name'] u'Third test' >>> f.cleaned_data['slug'] u'third-test' >>> obj = f.save(commit=False) >>> obj <Category: Third test> >>> Category.objects.order_by('name') [<Category: Entertainment>, <Category: It's a test>] >>> obj.save() >>> Category.objects.order_by('name') [<Category: Entertainment>, <Category: It's a test>, <Category: Third test>] If you call save() with invalid data, you'll get a ValueError. >>> f = CategoryForm({'name': '', 'slug': 'not a slug!', 'url': 'foo'}) >>> f.errors['name'] [u'This field is required.'] >>> f.errors['slug'] [u"Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."] >>> f.cleaned_data Traceback (most recent call last): ... AttributeError: 'CategoryForm' object has no attribute 'cleaned_data' >>> f.save() Traceback (most recent call last): ... ValueError: The Category could not be created because the data didn't validate. >>> f = CategoryForm({'name': '', 'slug': '', 'url': 'foo'}) >>> f.save() Traceback (most recent call last): ... ValueError: The Category could not be created because the data didn't validate. Create a couple of Writers. >>> w_royko = Writer(name='Mike Royko') >>> w_royko.save() >>> w_woodward = Writer(name='Bob Woodward') >>> w_woodward.save() ManyToManyFields are represented by a MultipleChoiceField, ForeignKeys and any fields with the 'choices' attribute are represented by a ChoiceField. >>> class ArticleForm(ModelForm): ... class Meta: ... model = Article >>> f = ArticleForm(auto_id=False) >>> print f <tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" /></td></tr> <tr><th>Slug:</th><td><input type="text" name="slug" maxlength="50" /></td></tr> <tr><th>Pub date:</th><td><input type="text" name="pub_date" /></td></tr> <tr><th>Writer:</th><td><select name="writer"> <option value="" selected="selected">---------</option> <option value="...">Mike Royko</option> <option value="...">Bob Woodward</option> </select></td></tr> <tr><th>Article:</th><td><textarea rows="10" cols="40" name="article"></textarea></td></tr> <tr><th>Status:</th><td><select name="status"> <option value="" selected="selected">---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></td></tr> <tr><th>Categories:</th><td><select multiple="multiple" name="categories"> <option value="1">Entertainment</option> <option value="2">It&#39;s a test</option> <option value="3">Third test</option> </select><br /> Hold down "Control", or "Command" on a Mac, to select more than one.</td></tr> You can restrict a form to a subset of the complete list of fields by providing a 'fields' argument. If you try to save a model created with such a form, you need to ensure that the fields that are _not_ on the form have default values, or are allowed to have a value of None. If a field isn't specified on a form, the object created from the form can't provide a value for that field! >>> class PartialArticleForm(ModelForm): ... class Meta: ... model = Article ... fields = ('headline','pub_date') >>> f = PartialArticleForm(auto_id=False) >>> print f <tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" /></td></tr> <tr><th>Pub date:</th><td><input type="text" name="pub_date" /></td></tr> When the ModelForm is passed an instance, that instance's current values are inserted as 'initial' data in each Field. >>> w = Writer.objects.get(name='Mike Royko') >>> class RoykoForm(ModelForm): ... class Meta: ... model = Writer >>> f = RoykoForm(auto_id=False, instance=w) >>> print f <tr><th>Name:</th><td><input type="text" name="name" value="Mike Royko" maxlength="50" /><br />Use both first and last names.</td></tr> >>> art = Article(headline='Test article', slug='test-article', pub_date=datetime.date(1988, 1, 4), writer=w, article='Hello.') >>> art.save() >>> art.id 1 >>> class TestArticleForm(ModelForm): ... class Meta: ... model = Article >>> f = TestArticleForm(auto_id=False, instance=art) >>> print f.as_ul() <li>Headline: <input type="text" name="headline" value="Test article" maxlength="50" /></li> <li>Slug: <input type="text" name="slug" value="test-article" maxlength="50" /></li> <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" /></li> <li>Writer: <select name="writer"> <option value="">---------</option> <option value="..." selected="selected">Mike Royko</option> <option value="...">Bob Woodward</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article">Hello.</textarea></li> <li>Status: <select name="status"> <option value="" selected="selected">---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li> <li>Categories: <select multiple="multiple" name="categories"> <option value="1">Entertainment</option> <option value="2">It&#39;s a test</option> <option value="3">Third test</option> </select> Hold down "Control", or "Command" on a Mac, to select more than one.</li> >>> f = TestArticleForm({'headline': u'Test headline', 'slug': 'test-headline', 'pub_date': u'1984-02-06', 'writer': unicode(w_royko.pk), 'article': 'Hello.'}, instance=art) >>> f.errors {} >>> f.is_valid() True >>> test_art = f.save() >>> test_art.id 1 >>> test_art = Article.objects.get(id=1) >>> test_art.headline u'Test headline' You can create a form over a subset of the available fields by specifying a 'fields' argument to form_for_instance. >>> class PartialArticleForm(ModelForm): ... class Meta: ... model = Article ... fields=('headline', 'slug', 'pub_date') >>> f = PartialArticleForm({'headline': u'New headline', 'slug': 'new-headline', 'pub_date': u'1988-01-04'}, auto_id=False, instance=art) >>> print f.as_ul() <li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" /></li> <li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" /></li> <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" /></li> >>> f.is_valid() True >>> new_art = f.save() >>> new_art.id 1 >>> new_art = Article.objects.get(id=1) >>> new_art.headline u'New headline' Add some categories and test the many-to-many form output. >>> new_art.categories.all() [] >>> new_art.categories.add(Category.objects.get(name='Entertainment')) >>> new_art.categories.all() [<Category: Entertainment>] >>> class TestArticleForm(ModelForm): ... class Meta: ... model = Article >>> f = TestArticleForm(auto_id=False, instance=new_art) >>> print f.as_ul() <li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" /></li> <li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" /></li> <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" /></li> <li>Writer: <select name="writer"> <option value="">---------</option> <option value="..." selected="selected">Mike Royko</option> <option value="...">Bob Woodward</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article">Hello.</textarea></li> <li>Status: <select name="status"> <option value="" selected="selected">---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li> <li>Categories: <select multiple="multiple" name="categories"> <option value="1" selected="selected">Entertainment</option> <option value="2">It&#39;s a test</option> <option value="3">Third test</option> </select> Hold down "Control", or "Command" on a Mac, to select more than one.</li> Initial values can be provided for model forms >>> f = TestArticleForm(auto_id=False, initial={'headline': 'Your headline here', 'categories': ['1','2']}) >>> print f.as_ul() <li>Headline: <input type="text" name="headline" value="Your headline here" maxlength="50" /></li> <li>Slug: <input type="text" name="slug" maxlength="50" /></li> <li>Pub date: <input type="text" name="pub_date" /></li> <li>Writer: <select name="writer"> <option value="" selected="selected">---------</option> <option value="...">Mike Royko</option> <option value="...">Bob Woodward</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article"></textarea></li> <li>Status: <select name="status"> <option value="" selected="selected">---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li> <li>Categories: <select multiple="multiple" name="categories"> <option value="1" selected="selected">Entertainment</option> <option value="2" selected="selected">It&#39;s a test</option> <option value="3">Third test</option> </select> Hold down "Control", or "Command" on a Mac, to select more than one.</li> >>> f = TestArticleForm({'headline': u'New headline', 'slug': u'new-headline', 'pub_date': u'1988-01-04', ... 'writer': unicode(w_royko.pk), 'article': u'Hello.', 'categories': [u'1', u'2']}, instance=new_art) >>> new_art = f.save() >>> new_art.id 1 >>> new_art = Article.objects.get(id=1) >>> new_art.categories.order_by('name') [<Category: Entertainment>, <Category: It's a test>] Now, submit form data with no categories. This deletes the existing categories. >>> f = TestArticleForm({'headline': u'New headline', 'slug': u'new-headline', 'pub_date': u'1988-01-04', ... 'writer': unicode(w_royko.pk), 'article': u'Hello.'}, instance=new_art) >>> new_art = f.save() >>> new_art.id 1 >>> new_art = Article.objects.get(id=1) >>> new_art.categories.all() [] Create a new article, with categories, via the form. >>> class ArticleForm(ModelForm): ... class Meta: ... model = Article >>> f = ArticleForm({'headline': u'The walrus was Paul', 'slug': u'walrus-was-paul', 'pub_date': u'1967-11-01', ... 'writer': unicode(w_royko.pk), 'article': u'Test.', 'categories': [u'1', u'2']}) >>> new_art = f.save() >>> new_art.id 2 >>> new_art = Article.objects.get(id=2) >>> new_art.categories.order_by('name') [<Category: Entertainment>, <Category: It's a test>] Create a new article, with no categories, via the form. >>> class ArticleForm(ModelForm): ... class Meta: ... model = Article >>> f = ArticleForm({'headline': u'The walrus was Paul', 'slug': u'walrus-was-paul', 'pub_date': u'1967-11-01', ... 'writer': unicode(w_royko.pk), 'article': u'Test.'}) >>> new_art = f.save() >>> new_art.id 3 >>> new_art = Article.objects.get(id=3) >>> new_art.categories.all() [] Create a new article, with categories, via the form, but use commit=False. The m2m data won't be saved until save_m2m() is invoked on the form. >>> class ArticleForm(ModelForm): ... class Meta: ... model = Article >>> f = ArticleForm({'headline': u'The walrus was Paul', 'slug': 'walrus-was-paul', 'pub_date': u'1967-11-01', ... 'writer': unicode(w_royko.pk), 'article': u'Test.', 'categories': [u'1', u'2']}) >>> new_art = f.save(commit=False) # Manually save the instance >>> new_art.save() >>> new_art.id 4 # The instance doesn't have m2m data yet >>> new_art = Article.objects.get(id=4) >>> new_art.categories.all() [] # Save the m2m data on the form >>> f.save_m2m() >>> new_art.categories.order_by('name') [<Category: Entertainment>, <Category: It's a test>] Here, we define a custom ModelForm. Because it happens to have the same fields as the Category model, we can just call the form's save() to apply its changes to an existing Category instance. >>> class ShortCategory(ModelForm): ... name = CharField(max_length=5) ... slug = CharField(max_length=5) ... url = CharField(max_length=3) >>> cat = Category.objects.get(name='Third test') >>> cat <Category: Third test> >>> cat.id 3 >>> form = ShortCategory({'name': 'Third', 'slug': 'third', 'url': '3rd'}, instance=cat) >>> form.save() <Category: Third> >>> Category.objects.get(id=3) <Category: Third> Here, we demonstrate that choices for a ForeignKey ChoiceField are determined at runtime, based on the data in the database when the form is displayed, not the data in the database when the form is instantiated. >>> class ArticleForm(ModelForm): ... class Meta: ... model = Article >>> f = ArticleForm(auto_id=False) >>> print f.as_ul() <li>Headline: <input type="text" name="headline" maxlength="50" /></li> <li>Slug: <input type="text" name="slug" maxlength="50" /></li> <li>Pub date: <input type="text" name="pub_date" /></li> <li>Writer: <select name="writer"> <option value="" selected="selected">---------</option> <option value="...">Mike Royko</option> <option value="...">Bob Woodward</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article"></textarea></li> <li>Status: <select name="status"> <option value="" selected="selected">---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li> <li>Categories: <select multiple="multiple" name="categories"> <option value="1">Entertainment</option> <option value="2">It&#39;s a test</option> <option value="3">Third</option> </select> Hold down "Control", or "Command" on a Mac, to select more than one.</li> >>> Category.objects.create(name='Fourth', url='4th') <Category: Fourth> >>> Writer.objects.create(name='Carl Bernstein') <Writer: Carl Bernstein> >>> print f.as_ul() <li>Headline: <input type="text" name="headline" maxlength="50" /></li> <li>Slug: <input type="text" name="slug" maxlength="50" /></li> <li>Pub date: <input type="text" name="pub_date" /></li> <li>Writer: <select name="writer"> <option value="" selected="selected">---------</option> <option value="...">Mike Royko</option> <option value="...">Bob Woodward</option> <option value="...">Carl Bernstein</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article"></textarea></li> <li>Status: <select name="status"> <option value="" selected="selected">---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li> <li>Categories: <select multiple="multiple" name="categories"> <option value="1">Entertainment</option> <option value="2">It&#39;s a test</option> <option value="3">Third</option> <option value="4">Fourth</option> </select> Hold down "Control", or "Command" on a Mac, to select more than one.</li> # ModelChoiceField ############################################################ >>> from django.forms import ModelChoiceField, ModelMultipleChoiceField >>> f = ModelChoiceField(Category.objects.all()) >>> list(f.choices) [(u'', u'---------'), (1, u'Entertainment'), (2, u"It's a test"), (3, u'Third'), (4, u'Fourth')] >>> f.clean('') Traceback (most recent call last): ... ValidationError: [u'This field is required.'] >>> f.clean(None) Traceback (most recent call last): ... ValidationError: [u'This field is required.'] >>> f.clean(0) Traceback (most recent call last): ... ValidationError: [u'Select a valid choice. That choice is not one of the available choices.'] >>> f.clean(3) <Category: Third> >>> f.clean(2) <Category: It's a test> # Add a Category object *after* the ModelChoiceField has already been # instantiated. This proves clean() checks the database during clean() rather # than caching it at time of instantiation. >>> Category.objects.create(name='Fifth', url='5th') <Category: Fifth> >>> f.clean(5) <Category: Fifth> # Delete a Category object *after* the ModelChoiceField has already been # instantiated. This proves clean() checks the database during clean() rather # than caching it at time of instantiation. >>> Category.objects.get(url='5th').delete() >>> f.clean(5) Traceback (most recent call last): ... ValidationError: [u'Select a valid choice. That choice is not one of the available choices.'] >>> f = ModelChoiceField(Category.objects.filter(pk=1), required=False) >>> print f.clean('') None >>> f.clean('') >>> f.clean('1') <Category: Entertainment> >>> f.clean('100') Traceback (most recent call last): ... ValidationError: [u'Select a valid choice. That choice is not one of the available choices.'] # queryset can be changed after the field is created. >>> f.queryset = Category.objects.exclude(name='Fourth') >>> list(f.choices) [(u'', u'---------'), (1, u'Entertainment'), (2, u"It's a test"), (3, u'Third')] >>> f.clean(3) <Category: Third> >>> f.clean(4) Traceback (most recent call last): ... ValidationError: [u'Select a valid choice. That choice is not one of the available choices.'] # check that we can safely iterate choices repeatedly >>> gen_one = list(f.choices) >>> gen_two = f.choices >>> gen_one[2] (2L, u"It's a test") >>> list(gen_two) [(u'', u'---------'), (1L, u'Entertainment'), (2L, u"It's a test"), (3L, u'Third')] # check that we can override the label_from_instance method to print custom labels (#4620) >>> f.queryset = Category.objects.all() >>> f.label_from_instance = lambda obj: "category " + str(obj) >>> list(f.choices) [(u'', u'---------'), (1L, 'category Entertainment'), (2L, "category It's a test"), (3L, 'category Third'), (4L, 'category Fourth')] # ModelMultipleChoiceField #################################################### >>> f = ModelMultipleChoiceField(Category.objects.all()) >>> list(f.choices) [(1, u'Entertainment'), (2, u"It's a test"), (3, u'Third'), (4, u'Fourth')] >>> f.clean(None) Traceback (most recent call last): ... ValidationError: [u'This field is required.'] >>> f.clean([]) Traceback (most recent call last): ... ValidationError: [u'This field is required.'] >>> f.clean([1]) [<Category: Entertainment>] >>> f.clean([2]) [<Category: It's a test>] >>> f.clean(['1']) [<Category: Entertainment>] >>> f.clean(['1', '2']) [<Category: Entertainment>, <Category: It's a test>] >>> f.clean([1, '2']) [<Category: Entertainment>, <Category: It's a test>] >>> f.clean((1, '2')) [<Category: Entertainment>, <Category: It's a test>] >>> f.clean(['100']) Traceback (most recent call last): ... ValidationError: [u'Select a valid choice. 100 is not one of the available choices.'] >>> f.clean('hello') Traceback (most recent call last): ... ValidationError: [u'Enter a list of values.'] >>> f.clean(['fail']) Traceback (most recent call last): ... ValidationError: [u'"fail" is not a valid value for a primary key.'] # Add a Category object *after* the ModelMultipleChoiceField has already been # instantiated. This proves clean() checks the database during clean() rather # than caching it at time of instantiation. >>> Category.objects.create(id=6, name='Sixth', url='6th') <Category: Sixth> >>> f.clean([6]) [<Category: Sixth>] # Delete a Category object *after* the ModelMultipleChoiceField has already been # instantiated. This proves clean() checks the database during clean() rather # than caching it at time of instantiation. >>> Category.objects.get(url='6th').delete() >>> f.clean([6]) Traceback (most recent call last): ... ValidationError: [u'Select a valid choice. 6 is not one of the available choices.'] >>> f = ModelMultipleChoiceField(Category.objects.all(), required=False) >>> f.clean([]) [] >>> f.clean(()) [] >>> f.clean(['10']) Traceback (most recent call last): ... ValidationError: [u'Select a valid choice. 10 is not one of the available choices.'] >>> f.clean(['3', '10']) Traceback (most recent call last): ... ValidationError: [u'Select a valid choice. 10 is not one of the available choices.'] >>> f.clean(['1', '10']) Traceback (most recent call last): ... ValidationError: [u'Select a valid choice. 10 is not one of the available choices.'] # queryset can be changed after the field is created. >>> f.queryset = Category.objects.exclude(name='Fourth') >>> list(f.choices) [(1, u'Entertainment'), (2, u"It's a test"), (3, u'Third')] >>> f.clean([3]) [<Category: Third>] >>> f.clean([4]) Traceback (most recent call last): ... ValidationError: [u'Select a valid choice. 4 is not one of the available choices.'] >>> f.clean(['3', '4']) Traceback (most recent call last): ... ValidationError: [u'Select a valid choice. 4 is not one of the available choices.'] >>> f.queryset = Category.objects.all() >>> f.label_from_instance = lambda obj: "multicategory " + str(obj) >>> list(f.choices) [(1L, 'multicategory Entertainment'), (2L, "multicategory It's a test"), (3L, 'multicategory Third'), (4L, 'multicategory Fourth')] # OneToOneField ############################################################### >>> class ImprovedArticleForm(ModelForm): ... class Meta: ... model = ImprovedArticle >>> ImprovedArticleForm.base_fields.keys() ['article'] >>> class ImprovedArticleWithParentLinkForm(ModelForm): ... class Meta: ... model = ImprovedArticleWithParentLink >>> ImprovedArticleWithParentLinkForm.base_fields.keys() [] >>> bw = BetterWriter(name=u'Joe Better', score=10) >>> bw.save() >>> sorted(model_to_dict(bw).keys()) ['id', 'name', 'score', 'writer_ptr'] >>> class BetterWriterForm(ModelForm): ... class Meta: ... model = BetterWriter >>> form = BetterWriterForm({'name': 'Some Name', 'score': 12}) >>> form.is_valid() True >>> bw2 = form.save() >>> bw2.delete() >>> class WriterProfileForm(ModelForm): ... class Meta: ... model = WriterProfile >>> form = WriterProfileForm() >>> print form.as_p() <p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer"> <option value="" selected="selected">---------</option> <option value="...">Mike Royko</option> <option value="...">Bob Woodward</option> <option value="...">Carl Bernstein</option> <option value="...">Joe Better</option> </select></p> <p><label for="id_age">Age:</label> <input type="text" name="age" id="id_age" /></p> >>> data = { ... 'writer': unicode(w_woodward.pk), ... 'age': u'65', ... } >>> form = WriterProfileForm(data) >>> instance = form.save() >>> instance <WriterProfile: Bob Woodward is 65> >>> form = WriterProfileForm(instance=instance) >>> print form.as_p() <p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer"> <option value="">---------</option> <option value="...">Mike Royko</option> <option value="..." selected="selected">Bob Woodward</option> <option value="...">Carl Bernstein</option> <option value="...">Joe Better</option> </select></p> <p><label for="id_age">Age:</label> <input type="text" name="age" value="65" id="id_age" /></p> # PhoneNumberField ############################################################ >>> class PhoneNumberForm(ModelForm): ... class Meta: ... model = PhoneNumber >>> f = PhoneNumberForm({'phone': '(312) 555-1212', 'description': 'Assistance'}) >>> f.is_valid() True >>> f.cleaned_data['phone'] u'312-555-1212' >>> f.cleaned_data['description'] u'Assistance' # FileField ################################################################### # File forms. >>> class TextFileForm(ModelForm): ... class Meta: ... model = TextFile # Test conditions when files is either not given or empty. >>> f = TextFileForm(data={'description': u'Assistance'}) >>> f.is_valid() False >>> f = TextFileForm(data={'description': u'Assistance'}, files={}) >>> f.is_valid() False # Upload a file and ensure it all works as expected. >>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': SimpleUploadedFile('test1.txt', 'hello world')}) >>> f.is_valid() True >>> type(f.cleaned_data['file']) <class 'django.core.files.uploadedfile.SimpleUploadedFile'> >>> instance = f.save() >>> instance.file <FieldFile: tests/test1.txt> >>> instance.file.delete() >>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': SimpleUploadedFile('test1.txt', 'hello world')}) >>> f.is_valid() True >>> type(f.cleaned_data['file']) <class 'django.core.files.uploadedfile.SimpleUploadedFile'> >>> instance = f.save() >>> instance.file <FieldFile: tests/test1.txt> # Check if the max_length attribute has been inherited from the model. >>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': SimpleUploadedFile('test-maxlength.txt', 'hello world')}) >>> f.is_valid() False # Edit an instance that already has the file defined in the model. This will not # save the file again, but leave it exactly as it is. >>> f = TextFileForm(data={'description': u'Assistance'}, instance=instance) >>> f.is_valid() True >>> f.cleaned_data['file'] <FieldFile: tests/test1.txt> >>> instance = f.save() >>> instance.file <FieldFile: tests/test1.txt> # Delete the current file since this is not done by Django. >>> instance.file.delete() # Override the file by uploading a new one. >>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': SimpleUploadedFile('test2.txt', 'hello world')}, instance=instance) >>> f.is_valid() True >>> instance = f.save() >>> instance.file <FieldFile: tests/test2.txt> # Delete the current file since this is not done by Django. >>> instance.file.delete() >>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': SimpleUploadedFile('test2.txt', 'hello world')}) >>> f.is_valid() True >>> instance = f.save() >>> instance.file <FieldFile: tests/test2.txt> # Delete the current file since this is not done by Django. >>> instance.file.delete() >>> instance.delete() # Test the non-required FileField >>> f = TextFileForm(data={'description': u'Assistance'}) >>> f.fields['file'].required = False >>> f.is_valid() True >>> instance = f.save() >>> instance.file <FieldFile: None> >>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': SimpleUploadedFile('test3.txt', 'hello world')}, instance=instance) >>> f.is_valid() True >>> instance = f.save() >>> instance.file <FieldFile: tests/test3.txt> # Instance can be edited w/out re-uploading the file and existing file should be preserved. >>> f = TextFileForm(data={'description': u'New Description'}, instance=instance) >>> f.fields['file'].required = False >>> f.is_valid() True >>> instance = f.save() >>> instance.description u'New Description' >>> instance.file <FieldFile: tests/test3.txt> # Delete the current file since this is not done by Django. >>> instance.file.delete() >>> instance.delete() >>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': SimpleUploadedFile('test3.txt', 'hello world')}) >>> f.is_valid() True >>> instance = f.save() >>> instance.file <FieldFile: tests/test3.txt> # Delete the current file since this is not done by Django. >>> instance.file.delete() >>> instance.delete() # BigIntegerField ################################################################ >>> class BigIntForm(forms.ModelForm): ... class Meta: ... model = BigInt ... >>> bif = BigIntForm({'biggie': '-9223372036854775808'}) >>> bif.is_valid() True >>> bif = BigIntForm({'biggie': '-9223372036854775809'}) >>> bif.is_valid() False >>> bif.errors {'biggie': [u'Ensure this value is greater than or equal to -9223372036854775808.']} >>> bif = BigIntForm({'biggie': '9223372036854775807'}) >>> bif.is_valid() True >>> bif = BigIntForm({'biggie': '9223372036854775808'}) >>> bif.is_valid() False >>> bif.errors {'biggie': [u'Ensure this value is less than or equal to 9223372036854775807.']} """} if test_images: __test__['API_TESTS'] += """ # ImageField ################################################################### # ImageField and FileField are nearly identical, but they differ slighty when # it comes to validation. This specifically tests that #6302 is fixed for # both file fields and image fields. >>> class ImageFileForm(ModelForm): ... class Meta: ... model = ImageFile >>> image_data = open(os.path.join(os.path.dirname(__file__), "test.png"), 'rb').read() >>> image_data2 = open(os.path.join(os.path.dirname(__file__), "test2.png"), 'rb').read() >>> f = ImageFileForm(data={'description': u'An image'}, files={'image': SimpleUploadedFile('test.png', image_data)}) >>> f.is_valid() True >>> type(f.cleaned_data['image']) <class 'django.core.files.uploadedfile.SimpleUploadedFile'> >>> instance = f.save() >>> instance.image <...FieldFile: tests/test.png> >>> instance.width 16 >>> instance.height 16 # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. >>> instance.image.delete(save=False) >>> f = ImageFileForm(data={'description': u'An image'}, files={'image': SimpleUploadedFile('test.png', image_data)}) >>> f.is_valid() True >>> type(f.cleaned_data['image']) <class 'django.core.files.uploadedfile.SimpleUploadedFile'> >>> instance = f.save() >>> instance.image <...FieldFile: tests/test.png> >>> instance.width 16 >>> instance.height 16 # Edit an instance that already has the (required) image defined in the model. This will not # save the image again, but leave it exactly as it is. >>> f = ImageFileForm(data={'description': u'Look, it changed'}, instance=instance) >>> f.is_valid() True >>> f.cleaned_data['image'] <...FieldFile: tests/test.png> >>> instance = f.save() >>> instance.image <...FieldFile: tests/test.png> >>> instance.height 16 >>> instance.width 16 # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. >>> instance.image.delete(save=False) # Override the file by uploading a new one. >>> f = ImageFileForm(data={'description': u'Changed it'}, files={'image': SimpleUploadedFile('test2.png', image_data2)}, instance=instance) >>> f.is_valid() True >>> instance = f.save() >>> instance.image <...FieldFile: tests/test2.png> >>> instance.height 32 >>> instance.width 48 # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. >>> instance.image.delete(save=False) >>> instance.delete() >>> f = ImageFileForm(data={'description': u'Changed it'}, files={'image': SimpleUploadedFile('test2.png', image_data2)}) >>> f.is_valid() True >>> instance = f.save() >>> instance.image <...FieldFile: tests/test2.png> >>> instance.height 32 >>> instance.width 48 # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. >>> instance.image.delete(save=False) >>> instance.delete() # Test the non-required ImageField >>> class OptionalImageFileForm(ModelForm): ... class Meta: ... model = OptionalImageFile >>> f = OptionalImageFileForm(data={'description': u'Test'}) >>> f.is_valid() True >>> instance = f.save() >>> instance.image <...FieldFile: None> >>> instance.width >>> instance.height >>> f = OptionalImageFileForm(data={'description': u'And a final one'}, files={'image': SimpleUploadedFile('test3.png', image_data)}, instance=instance) >>> f.is_valid() True >>> instance = f.save() >>> instance.image <...FieldFile: tests/test3.png> >>> instance.width 16 >>> instance.height 16 # Editing the instance without re-uploading the image should not affect the image or its width/height properties >>> f = OptionalImageFileForm(data={'description': u'New Description'}, instance=instance) >>> f.is_valid() True >>> instance = f.save() >>> instance.description u'New Description' >>> instance.image <...FieldFile: tests/test3.png> >>> instance.width 16 >>> instance.height 16 # Delete the current file since this is not done by Django. >>> instance.image.delete() >>> instance.delete() >>> f = OptionalImageFileForm(data={'description': u'And a final one'}, files={'image': SimpleUploadedFile('test4.png', image_data2)}) >>> f.is_valid() True >>> instance = f.save() >>> instance.image <...FieldFile: tests/test4.png> >>> instance.width 48 >>> instance.height 32 >>> instance.delete() # Test callable upload_to behavior that's dependent on the value of another field in the model >>> f = ImageFileForm(data={'description': u'And a final one', 'path': 'foo'}, files={'image': SimpleUploadedFile('test4.png', image_data)}) >>> f.is_valid() True >>> instance = f.save() >>> instance.image <...FieldFile: foo/test4.png> >>> instance.delete() """ __test__['API_TESTS'] += """ # Media on a ModelForm ######################################################## # Similar to a regular Form class you can define custom media to be used on # the ModelForm. >>> class ModelFormWithMedia(ModelForm): ... class Media: ... js = ('/some/form/javascript',) ... css = { ... 'all': ('/some/form/css',) ... } ... class Meta: ... model = PhoneNumber >>> f = ModelFormWithMedia() >>> print f.media <link href="/some/form/css" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/some/form/javascript"></script> >>> class CommaSeparatedIntegerForm(ModelForm): ... class Meta: ... model = CommaSeparatedInteger >>> f = CommaSeparatedIntegerForm({'field': '1,2,3'}) >>> f.is_valid() True >>> f.cleaned_data {'field': u'1,2,3'} >>> f = CommaSeparatedIntegerForm({'field': '1a,2'}) >>> f.errors {'field': [u'Enter only digits separated by commas.']} >>> f = CommaSeparatedIntegerForm({'field': ',,,,'}) >>> f.is_valid() True >>> f.cleaned_data {'field': u',,,,'} >>> f = CommaSeparatedIntegerForm({'field': '1.2'}) >>> f.errors {'field': [u'Enter only digits separated by commas.']} >>> f = CommaSeparatedIntegerForm({'field': '1,a,2'}) >>> f.errors {'field': [u'Enter only digits separated by commas.']} >>> f = CommaSeparatedIntegerForm({'field': '1,,2'}) >>> f.is_valid() True >>> f.cleaned_data {'field': u'1,,2'} >>> f = CommaSeparatedIntegerForm({'field': '1'}) >>> f.is_valid() True >>> f.cleaned_data {'field': u'1'} This Price instance generated by this form is not valid because the quantity field is required, but the form is valid because the field is excluded from the form. This is for backwards compatibility. >>> class PriceForm(ModelForm): ... class Meta: ... model = Price ... exclude = ('quantity',) >>> form = PriceForm({'price': '6.00'}) >>> form.is_valid() True >>> price = form.save(commit=False) >>> price.full_clean() Traceback (most recent call last): ... ValidationError: {'quantity': [u'This field cannot be null.']} The form should not validate fields that it doesn't contain even if they are specified using 'fields', not 'exclude'. ... class Meta: ... model = Price ... fields = ('price',) >>> form = PriceForm({'price': '6.00'}) >>> form.is_valid() True The form should still have an instance of a model that is not complete and not saved into a DB yet. >>> form.instance.price Decimal('6.00') >>> form.instance.quantity is None True >>> form.instance.pk is None True # Choices on CharField and IntegerField >>> class ArticleForm(ModelForm): ... class Meta: ... model = Article >>> f = ArticleForm() >>> f.fields['status'].clean('42') Traceback (most recent call last): ... ValidationError: [u'Select a valid choice. 42 is not one of the available choices.'] >>> class ArticleStatusForm(ModelForm): ... class Meta: ... model = ArticleStatus >>> f = ArticleStatusForm() >>> f.fields['status'].clean('z') Traceback (most recent call last): ... ValidationError: [u'Select a valid choice. z is not one of the available choices.'] # Foreign keys which use to_field ############################################# >>> apple = Inventory.objects.create(barcode=86, name='Apple') >>> pear = Inventory.objects.create(barcode=22, name='Pear') >>> core = Inventory.objects.create(barcode=87, name='Core', parent=apple) >>> field = ModelChoiceField(Inventory.objects.all(), to_field_name='barcode') >>> for choice in field.choices: ... print choice (u'', u'---------') (86, u'Apple') (22, u'Pear') (87, u'Core') >>> class InventoryForm(ModelForm): ... class Meta: ... model = Inventory >>> form = InventoryForm(instance=core) >>> print form['parent'] <select name="parent" id="id_parent"> <option value="">---------</option> <option value="86" selected="selected">Apple</option> <option value="22">Pear</option> <option value="87">Core</option> </select> >>> data = model_to_dict(core) >>> data['parent'] = '22' >>> form = InventoryForm(data=data, instance=core) >>> core = form.save() >>> core.parent <Inventory: Pear> >>> class CategoryForm(ModelForm): ... description = forms.CharField() ... class Meta: ... model = Category ... fields = ['description', 'url'] >>> CategoryForm.base_fields.keys() ['description', 'url'] >>> print CategoryForm() <tr><th><label for="id_description">Description:</label></th><td><input type="text" name="description" id="id_description" /></td></tr> <tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr> # Model field that returns None to exclude itself with explicit fields ######## >>> class CustomFieldForExclusionForm(ModelForm): ... class Meta: ... model = CustomFieldForExclusionModel ... fields = ['name', 'markup'] >>> CustomFieldForExclusionForm.base_fields.keys() ['name'] >>> print CustomFieldForExclusionForm() <tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="10" /></td></tr> # Clean up >>> import shutil >>> shutil.rmtree(temp_storage_dir) """
52,607
Python
.py
1,346
37.242199
173
0.671932
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,322
mforms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/model_forms/mforms.py
from django import forms from django.forms import ModelForm from models import (Product, Price, Book, DerivedBook, ExplicitPK, Post, DerivedPost, Writer, FlexibleDatePost) class ProductForm(ModelForm): class Meta: model = Product class PriceForm(ModelForm): class Meta: model = Price class BookForm(ModelForm): class Meta: model = Book class DerivedBookForm(ModelForm): class Meta: model = DerivedBook class ExplicitPKForm(ModelForm): class Meta: model = ExplicitPK fields = ('key', 'desc',) class PostForm(ModelForm): class Meta: model = Post class DerivedPostForm(ModelForm): class Meta: model = DerivedPost class CustomWriterForm(ModelForm): name = forms.CharField(required=False) class Meta: model = Writer class FlexDatePostForm(ModelForm): class Meta: model = FlexibleDatePost
918
Python
.py
33
22.727273
72
0.712815
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,323
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/model_forms/tests.py
import datetime from django.test import TestCase from django import forms from models import Category, Writer, Book, DerivedBook, Post, FlexibleDatePost from mforms import (ProductForm, PriceForm, BookForm, DerivedBookForm, ExplicitPKForm, PostForm, DerivedPostForm, CustomWriterForm, FlexDatePostForm) class IncompleteCategoryFormWithFields(forms.ModelForm): """ A form that replaces the model's url field with a custom one. This should prevent the model field's validation from being called. """ url = forms.CharField(required=False) class Meta: fields = ('name', 'slug') model = Category class IncompleteCategoryFormWithExclude(forms.ModelForm): """ A form that replaces the model's url field with a custom one. This should prevent the model field's validation from being called. """ url = forms.CharField(required=False) class Meta: exclude = ['url'] model = Category class ValidationTest(TestCase): def test_validates_with_replaced_field_not_specified(self): form = IncompleteCategoryFormWithFields(data={'name': 'some name', 'slug': 'some-slug'}) assert form.is_valid() def test_validates_with_replaced_field_excluded(self): form = IncompleteCategoryFormWithExclude(data={'name': 'some name', 'slug': 'some-slug'}) assert form.is_valid() def test_notrequired_overrides_notblank(self): form = CustomWriterForm({}) assert form.is_valid() # unique/unique_together validation class UniqueTest(TestCase): def setUp(self): self.writer = Writer.objects.create(name='Mike Royko') def test_simple_unique(self): form = ProductForm({'slug': 'teddy-bear-blue'}) self.assertTrue(form.is_valid()) obj = form.save() form = ProductForm({'slug': 'teddy-bear-blue'}) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['slug'], [u'Product with this Slug already exists.']) form = ProductForm({'slug': 'teddy-bear-blue'}, instance=obj) self.assertTrue(form.is_valid()) def test_unique_together(self): """ModelForm test of unique_together constraint""" form = PriceForm({'price': '6.00', 'quantity': '1'}) self.assertTrue(form.is_valid()) form.save() form = PriceForm({'price': '6.00', 'quantity': '1'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['__all__'], [u'Price with this Price and Quantity already exists.']) def test_unique_null(self): title = 'I May Be Wrong But I Doubt It' form = BookForm({'title': title, 'author': self.writer.pk}) self.assertTrue(form.is_valid()) form.save() form = BookForm({'title': title, 'author': self.writer.pk}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['__all__'], [u'Book with this Title and Author already exists.']) form = BookForm({'title': title}) self.assertTrue(form.is_valid()) form.save() form = BookForm({'title': title}) self.assertTrue(form.is_valid()) def test_inherited_unique(self): title = 'Boss' Book.objects.create(title=title, author=self.writer, special_id=1) form = DerivedBookForm({'title': 'Other', 'author': self.writer.pk, 'special_id': u'1', 'isbn': '12345'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['special_id'], [u'Book with this Special id already exists.']) def test_inherited_unique_together(self): title = 'Boss' form = BookForm({'title': title, 'author': self.writer.pk}) self.assertTrue(form.is_valid()) form.save() form = DerivedBookForm({'title': title, 'author': self.writer.pk, 'isbn': '12345'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['__all__'], [u'Book with this Title and Author already exists.']) def test_abstract_inherited_unique(self): title = 'Boss' isbn = '12345' dbook = DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn) form = DerivedBookForm({'title': 'Other', 'author': self.writer.pk, 'isbn': isbn}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['isbn'], [u'Derived book with this Isbn already exists.']) def test_abstract_inherited_unique_together(self): title = 'Boss' isbn = '12345' dbook = DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn) form = DerivedBookForm({'title': 'Other', 'author': self.writer.pk, 'isbn': '9876', 'suffix1': u'0', 'suffix2': u'0'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['__all__'], [u'Derived book with this Suffix1 and Suffix2 already exists.']) def test_explicitpk_unspecified(self): """Test for primary_key being in the form and failing validation.""" form = ExplicitPKForm({'key': u'', 'desc': u'' }) self.assertFalse(form.is_valid()) def test_explicitpk_unique(self): """Ensure keys and blank character strings are tested for uniqueness.""" form = ExplicitPKForm({'key': u'key1', 'desc': u''}) self.assertTrue(form.is_valid()) form.save() form = ExplicitPKForm({'key': u'key1', 'desc': u''}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 3) self.assertEqual(form.errors['__all__'], [u'Explicit pk with this Key and Desc already exists.']) self.assertEqual(form.errors['desc'], [u'Explicit pk with this Desc already exists.']) self.assertEqual(form.errors['key'], [u'Explicit pk with this Key already exists.']) def test_unique_for_date(self): p = Post.objects.create(title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) form = PostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['title'], [u'Title must be unique for Posted date.']) form = PostForm({'title': "Work on Django 1.1 begins", 'posted': '2008-09-03'}) self.assertTrue(form.is_valid()) form = PostForm({'title': "Django 1.0 is released", 'posted': '2008-09-04'}) self.assertTrue(form.is_valid()) form = PostForm({'slug': "Django 1.0", 'posted': '2008-01-01'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['slug'], [u'Slug must be unique for Posted year.']) form = PostForm({'subtitle': "Finally", 'posted': '2008-09-30'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['subtitle'], [u'Subtitle must be unique for Posted month.']) form = PostForm({'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", 'posted': '2008-09-03'}, instance=p) self.assertTrue(form.is_valid()) form = PostForm({'title': "Django 1.0 is released"}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['posted'], [u'This field is required.']) def test_inherited_unique_for_date(self): p = Post.objects.create(title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) form = DerivedPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['title'], [u'Title must be unique for Posted date.']) form = DerivedPostForm({'title': "Work on Django 1.1 begins", 'posted': '2008-09-03'}) self.assertTrue(form.is_valid()) form = DerivedPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-04'}) self.assertTrue(form.is_valid()) form = DerivedPostForm({'slug': "Django 1.0", 'posted': '2008-01-01'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['slug'], [u'Slug must be unique for Posted year.']) form = DerivedPostForm({'subtitle': "Finally", 'posted': '2008-09-30'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['subtitle'], [u'Subtitle must be unique for Posted month.']) form = DerivedPostForm({'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", 'posted': '2008-09-03'}, instance=p) self.assertTrue(form.is_valid()) def test_unique_for_date_with_nullable_date(self): p = FlexibleDatePost.objects.create(title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) form = FlexDatePostForm({'title': "Django 1.0 is released"}) self.assertTrue(form.is_valid()) form = FlexDatePostForm({'slug': "Django 1.0"}) self.assertTrue(form.is_valid()) form = FlexDatePostForm({'subtitle': "Finally"}) self.assertTrue(form.is_valid()) form = FlexDatePostForm({'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0"}, instance=p) self.assertTrue(form.is_valid())
9,772
Python
.py
176
47.221591
126
0.642954
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,324
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/reserved_names/models.py
""" 18. Using SQL reserved names Need to use a reserved SQL name as a column name or table name? Need to include a hyphen in a column or table name? No problem. Django quotes names appropriately behind the scenes, so your database won't complain about reserved-name usage. """ from django.db import models class Thing(models.Model): when = models.CharField(max_length=1, primary_key=True) join = models.CharField(max_length=1) like = models.CharField(max_length=1) drop = models.CharField(max_length=1) alter = models.CharField(max_length=1) having = models.CharField(max_length=1) where = models.DateField(max_length=1) has_hyphen = models.CharField(max_length=1, db_column='has-hyphen') class Meta: db_table = 'select' def __unicode__(self): return self.when
819
Python
.py
21
35.238095
79
0.730818
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,325
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/reserved_names/tests.py
import datetime from django.test import TestCase from models import Thing class ReservedNameTests(TestCase): def generate(self): day1 = datetime.date(2005, 1, 1) t = Thing.objects.create(when='a', join='b', like='c', drop='d', alter='e', having='f', where=day1, has_hyphen='h') day2 = datetime.date(2006, 2, 2) u = Thing.objects.create(when='h', join='i', like='j', drop='k', alter='l', having='m', where=day2) def test_simple(self): day1 = datetime.date(2005, 1, 1) t = Thing.objects.create(when='a', join='b', like='c', drop='d', alter='e', having='f', where=day1, has_hyphen='h') self.assertEqual(t.when, 'a') day2 = datetime.date(2006, 2, 2) u = Thing.objects.create(when='h', join='i', like='j', drop='k', alter='l', having='m', where=day2) self.assertEqual(u.when, 'h') def test_order_by(self): self.generate() things = [t.when for t in Thing.objects.order_by('when')] self.assertEqual(things, ['a', 'h']) def test_fields(self): self.generate() v = Thing.objects.get(pk='a') self.assertEqual(v.join, 'b') self.assertEqual(v.where, datetime.date(year=2005, month=1, day=1)) def test_dates(self): self.generate() resp = Thing.objects.dates('where', 'year') self.assertEqual(list(resp), [ datetime.datetime(2005, 1, 1, 0, 0), datetime.datetime(2006, 1, 1, 0, 0), ]) def test_month_filter(self): self.generate() self.assertEqual(Thing.objects.filter(where__month=1)[0].when, 'a')
1,671
Python
.py
39
34.435897
75
0.582255
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,326
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/ordering/models.py
""" 6. Specifying ordering Specify default ordering for a model using the ``ordering`` attribute, which should be a list or tuple of field names. This tells Django how to order ``QuerySet`` results. If a field name in ``ordering`` starts with a hyphen, that field will be ordered in descending order. Otherwise, it'll be ordered in ascending order. The special-case field name ``"?"`` specifies random order. The ordering attribute is not required. If you leave it off, ordering will be undefined -- not random, just undefined. """ from django.db import models class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateTimeField() class Meta: ordering = ('-pub_date', 'headline') def __unicode__(self): return self.headline
800
Python
.py
19
39.052632
77
0.744186
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,327
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/ordering/tests.py
from datetime import datetime from operator import attrgetter from django.test import TestCase from models import Article class OrderingTests(TestCase): def test_basic(self): a1 = Article.objects.create( headline="Article 1", pub_date=datetime(2005, 7, 26) ) a2 = Article.objects.create( headline="Article 2", pub_date=datetime(2005, 7, 27) ) a3 = Article.objects.create( headline="Article 3", pub_date=datetime(2005, 7, 27) ) a4 = Article.objects.create( headline="Article 4", pub_date=datetime(2005, 7, 28) ) # By default, Article.objects.all() orders by pub_date descending, then # headline ascending. self.assertQuerysetEqual( Article.objects.all(), [ "Article 4", "Article 2", "Article 3", "Article 1", ], attrgetter("headline") ) # Override ordering with order_by, which is in the same format as the # ordering attribute in models. self.assertQuerysetEqual( Article.objects.order_by("headline"), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) self.assertQuerysetEqual( Article.objects.order_by("pub_date", "-headline"), [ "Article 1", "Article 3", "Article 2", "Article 4", ], attrgetter("headline") ) # Only the last order_by has any effect (since they each override any # previous ordering). self.assertQuerysetEqual( Article.objects.order_by("id"), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) self.assertQuerysetEqual( Article.objects.order_by("id").order_by("-headline"), [ "Article 4", "Article 3", "Article 2", "Article 1", ], attrgetter("headline") ) # Use the 'stop' part of slicing notation to limit the results. self.assertQuerysetEqual( Article.objects.order_by("headline")[:2], [ "Article 1", "Article 2", ], attrgetter("headline") ) # Use the 'stop' and 'start' parts of slicing notation to offset the # result list. self.assertQuerysetEqual( Article.objects.order_by("headline")[1:3], [ "Article 2", "Article 3", ], attrgetter("headline") ) # Getting a single item should work too: self.assertEqual(Article.objects.all()[0], a4) # Use '?' to order randomly. self.assertEqual( len(list(Article.objects.order_by("?"))), 4 ) # Ordering can be reversed using the reverse() method on a queryset. # This allows you to extract things like "the last two items" (reverse # and then take the first two). self.assertQuerysetEqual( Article.objects.all().reverse()[:2], [ "Article 1", "Article 3", ], attrgetter("headline") ) # Ordering can be based on fields included from an 'extra' clause self.assertQuerysetEqual( Article.objects.extra(select={"foo": "pub_date"}, order_by=["foo", "headline"]), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) # If the extra clause uses an SQL keyword for a name, it will be # protected by quoting. self.assertQuerysetEqual( Article.objects.extra(select={"order": "pub_date"}, order_by=["order", "headline"]), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") )
4,309
Python
.py
123
22.926829
98
0.506232
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,328
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/m2m_multiple/models.py
""" 20. Multiple many-to-many relationships between the same two tables In this example, an ``Article`` can have many "primary" ``Category`` objects and many "secondary" ``Category`` objects. Set ``related_name`` to designate what the reverse relationship is called. """ from django.db import models class Category(models.Model): name = models.CharField(max_length=20) class Meta: ordering = ('name',) def __unicode__(self): return self.name class Article(models.Model): headline = models.CharField(max_length=50) pub_date = models.DateTimeField() primary_categories = models.ManyToManyField(Category, related_name='primary_article_set') secondary_categories = models.ManyToManyField(Category, related_name='secondary_article_set') class Meta: ordering = ('pub_date',) def __unicode__(self): return self.headline
887
Python
.py
22
35.954545
97
0.722287
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,329
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/m2m_multiple/tests.py
from datetime import datetime from django.test import TestCase from models import Article, Category class M2MMultipleTests(TestCase): def test_multiple(self): c1, c2, c3, c4 = [ Category.objects.create(name=name) for name in ["Sports", "News", "Crime", "Life"] ] a1 = Article.objects.create( headline="Area man steals", pub_date=datetime(2005, 11, 27) ) a1.primary_categories.add(c2, c3) a1.secondary_categories.add(c4) a2 = Article.objects.create( headline="Area man runs", pub_date=datetime(2005, 11, 28) ) a2.primary_categories.add(c1, c2) a2.secondary_categories.add(c4) self.assertQuerysetEqual( a1.primary_categories.all(), [ "Crime", "News", ], lambda c: c.name ) self.assertQuerysetEqual( a2.primary_categories.all(), [ "News", "Sports", ], lambda c: c.name ) self.assertQuerysetEqual( a1.secondary_categories.all(), [ "Life", ], lambda c: c.name ) self.assertQuerysetEqual( c1.primary_article_set.all(), [ "Area man runs", ], lambda a: a.headline ) self.assertQuerysetEqual( c1.secondary_article_set.all(), [] ) self.assertQuerysetEqual( c2.primary_article_set.all(), [ "Area man steals", "Area man runs", ], lambda a: a.headline ) self.assertQuerysetEqual( c2.secondary_article_set.all(), [] ) self.assertQuerysetEqual( c3.primary_article_set.all(), [ "Area man steals", ], lambda a: a.headline ) self.assertQuerysetEqual( c3.secondary_article_set.all(), [] ) self.assertQuerysetEqual( c4.primary_article_set.all(), [] ) self.assertQuerysetEqual( c4.secondary_article_set.all(), [ "Area man steals", "Area man runs", ], lambda a: a.headline )
2,344
Python
.py
77
19.168831
71
0.500885
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,330
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/save_delete_hooks/models.py
""" 13. Adding hooks before/after saving and deleting To execute arbitrary code around ``save()`` and ``delete()``, just subclass the methods. """ from django.db import models class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) def __init__(self, *args, **kwargs): super(Person, self).__init__(*args, **kwargs) self.data = [] def __unicode__(self): return u"%s %s" % (self.first_name, self.last_name) def save(self, *args, **kwargs): self.data.append("Before save") # Call the "real" save() method super(Person, self).save(*args, **kwargs) self.data.append("After save") def delete(self): self.data.append("Before deletion") # Call the "real" delete() method super(Person, self).delete() self.data.append("After deletion")
909
Python
.py
24
31.833333
75
0.632839
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,331
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/save_delete_hooks/tests.py
from django.test import TestCase from models import Person class SaveDeleteHookTests(TestCase): def test_basic(self): p = Person(first_name="John", last_name="Smith") self.assertEqual(p.data, []) p.save() self.assertEqual(p.data, [ "Before save", "After save", ]) self.assertQuerysetEqual( Person.objects.all(), [ "John Smith", ], unicode ) p.delete() self.assertEqual(p.data, [ "Before save", "After save", "Before deletion", "After deletion", ]) self.assertQuerysetEqual(Person.objects.all(), [])
720
Python
.py
25
18.96
58
0.524638
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,332
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/validation/models.py
from datetime import datetime from django.core.exceptions import ValidationError from django.db import models from django.test import TestCase def validate_answer_to_universe(value): if value != 42: raise ValidationError('This is not the answer to life, universe and everything!', code='not42') class ModelToValidate(models.Model): name = models.CharField(max_length=100) created = models.DateTimeField(default=datetime.now) number = models.IntegerField(db_column='number_val') parent = models.ForeignKey('self', blank=True, null=True, limit_choices_to={'number': 10}) email = models.EmailField(blank=True) url = models.URLField(blank=True) f_with_custom_validator = models.IntegerField(blank=True, null=True, validators=[validate_answer_to_universe]) def clean(self): super(ModelToValidate, self).clean() if self.number == 11: raise ValidationError('Invalid number supplied!') class UniqueFieldsModel(models.Model): unique_charfield = models.CharField(max_length=100, unique=True) unique_integerfield = models.IntegerField(unique=True) non_unique_field = models.IntegerField() class CustomPKModel(models.Model): my_pk_field = models.CharField(max_length=100, primary_key=True) class UniqueTogetherModel(models.Model): cfield = models.CharField(max_length=100) ifield = models.IntegerField() efield = models.EmailField() class Meta: unique_together = (('ifield', 'cfield',), ['ifield', 'efield']) class UniqueForDateModel(models.Model): start_date = models.DateField() end_date = models.DateTimeField() count = models.IntegerField(unique_for_date="start_date", unique_for_year="end_date") order = models.IntegerField(unique_for_month="end_date") name = models.CharField(max_length=100) class CustomMessagesModel(models.Model): other = models.IntegerField(blank=True, null=True) number = models.IntegerField(db_column='number_val', error_messages={'null': 'NULL', 'not42': 'AAARGH', 'not_equal': '%s != me'}, validators=[validate_answer_to_universe] ) class Author(models.Model): name = models.CharField(max_length=100) class Article(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author) pub_date = models.DateTimeField(blank=True) def clean(self): if self.pub_date is None: self.pub_date = datetime.now() class Post(models.Model): title = models.CharField(max_length=50, unique_for_date='posted', blank=True) slug = models.CharField(max_length=50, unique_for_year='posted', blank=True) subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True) posted = models.DateField() def __unicode__(self): return self.name class FlexibleDatePost(models.Model): title = models.CharField(max_length=50, unique_for_date='posted', blank=True) slug = models.CharField(max_length=50, unique_for_year='posted', blank=True) subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True) posted = models.DateField(blank=True, null=True)
3,158
Python
.py
64
44.28125
114
0.725796
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,333
test_custom_messages.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/validation/test_custom_messages.py
from modeltests.validation import ValidationTestCase from models import CustomMessagesModel class CustomMessagesTest(ValidationTestCase): def test_custom_simple_validator_message(self): cmm = CustomMessagesModel(number=12) self.assertFieldFailsValidationWithMessage(cmm.full_clean, 'number', ['AAARGH']) def test_custom_null_message(self): cmm = CustomMessagesModel() self.assertFieldFailsValidationWithMessage(cmm.full_clean, 'number', ['NULL'])
491
Python
.py
9
48.666667
88
0.776151
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,334
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/validation/__init__.py
import unittest from django.core.exceptions import ValidationError class ValidationTestCase(unittest.TestCase): def assertFailsValidation(self, clean, failed_fields): self.assertRaises(ValidationError, clean) try: clean() except ValidationError, e: self.assertEquals(sorted(failed_fields), sorted(e.message_dict.keys())) def assertFieldFailsValidationWithMessage(self, clean, field_name, message): self.assertRaises(ValidationError, clean) try: clean() except ValidationError, e: self.assertTrue(field_name in e.message_dict) self.assertEquals(message, e.message_dict[field_name])
706
Python
.py
16
35.3125
83
0.700441
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,335
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/validation/tests.py
from django import forms from django.test import TestCase from django.core.exceptions import NON_FIELD_ERRORS from modeltests.validation import ValidationTestCase from modeltests.validation.models import Author, Article, ModelToValidate # Import other tests for this package. from modeltests.validation.validators import TestModelsWithValidators from modeltests.validation.test_unique import GetUniqueCheckTests, PerformUniqueChecksTest from modeltests.validation.test_custom_messages import CustomMessagesTest class BaseModelValidationTests(ValidationTestCase): def test_missing_required_field_raises_error(self): mtv = ModelToValidate(f_with_custom_validator=42) self.assertFailsValidation(mtv.full_clean, ['name', 'number']) def test_with_correct_value_model_validates(self): mtv = ModelToValidate(number=10, name='Some Name') self.assertEqual(None, mtv.full_clean()) def test_custom_validate_method(self): mtv = ModelToValidate(number=11) self.assertFailsValidation(mtv.full_clean, [NON_FIELD_ERRORS, 'name']) def test_wrong_FK_value_raises_error(self): mtv=ModelToValidate(number=10, name='Some Name', parent_id=3) self.assertFailsValidation(mtv.full_clean, ['parent']) def test_correct_FK_value_validates(self): parent = ModelToValidate.objects.create(number=10, name='Some Name') mtv = ModelToValidate(number=10, name='Some Name', parent_id=parent.pk) self.assertEqual(None, mtv.full_clean()) def test_limitted_FK_raises_error(self): # The limit_choices_to on the parent field says that a parent object's # number attribute must be 10, so this should fail validation. parent = ModelToValidate.objects.create(number=11, name='Other Name') mtv = ModelToValidate(number=10, name='Some Name', parent_id=parent.pk) self.assertFailsValidation(mtv.full_clean, ['parent']) def test_wrong_email_value_raises_error(self): mtv = ModelToValidate(number=10, name='Some Name', email='not-an-email') self.assertFailsValidation(mtv.full_clean, ['email']) def test_correct_email_value_passes(self): mtv = ModelToValidate(number=10, name='Some Name', email='[email protected]') self.assertEqual(None, mtv.full_clean()) def test_wrong_url_value_raises_error(self): mtv = ModelToValidate(number=10, name='Some Name', url='not a url') self.assertFieldFailsValidationWithMessage(mtv.full_clean, 'url', [u'Enter a valid value.']) def test_correct_url_but_nonexisting_gives_404(self): mtv = ModelToValidate(number=10, name='Some Name', url='http://google.com/we-love-microsoft.html') self.assertFieldFailsValidationWithMessage(mtv.full_clean, 'url', [u'This URL appears to be a broken link.']) def test_correct_url_value_passes(self): mtv = ModelToValidate(number=10, name='Some Name', url='http://www.djangoproject.com/') self.assertEqual(None, mtv.full_clean()) # This will fail if there's no Internet connection def test_text_greater_that_charfields_max_length_eaises_erros(self): mtv = ModelToValidate(number=10, name='Some Name'*100) self.assertFailsValidation(mtv.full_clean, ['name',]) class ArticleForm(forms.ModelForm): class Meta: model = Article exclude = ['author'] class ModelFormsTests(TestCase): def setUp(self): self.author = Author.objects.create(name='Joseph Kocherhans') def test_partial_validation(self): # Make sure the "commit=False and set field values later" idiom still # works with model validation. data = { 'title': 'The state of model validation', 'pub_date': '2010-1-10 14:49:00' } form = ArticleForm(data) self.assertEqual(form.errors.keys(), []) article = form.save(commit=False) article.author = self.author article.save() def test_validation_with_empty_blank_field(self): # Since a value for pub_date wasn't provided and the field is # blank=True, model-validation should pass. # Also, Article.clean() should be run, so pub_date will be filled after # validation, so the form should save cleanly even though pub_date is # not allowed to be null. data = { 'title': 'The state of model validation', } article = Article(author_id=self.author.id) form = ArticleForm(data, instance=article) self.assertEqual(form.errors.keys(), []) self.assertNotEqual(form.instance.pub_date, None) article = form.save() def test_validation_with_invalid_blank_field(self): # Even though pub_date is set to blank=True, an invalid value was # provided, so it should fail validation. data = { 'title': 'The state of model validation', 'pub_date': 'never' } article = Article(author_id=self.author.id) form = ArticleForm(data, instance=article) self.assertEqual(form.errors.keys(), ['pub_date'])
5,106
Python
.py
93
47.225806
117
0.696114
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,336
test_unique.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/validation/test_unique.py
import unittest import datetime from django.conf import settings from django.core.exceptions import ValidationError from django.db import connection from models import CustomPKModel, UniqueTogetherModel, UniqueFieldsModel, UniqueForDateModel, ModelToValidate, Post, FlexibleDatePost class GetUniqueCheckTests(unittest.TestCase): def test_unique_fields_get_collected(self): m = UniqueFieldsModel() self.assertEqual( ([(UniqueFieldsModel, ('id',)), (UniqueFieldsModel, ('unique_charfield',)), (UniqueFieldsModel, ('unique_integerfield',))], []), m._get_unique_checks() ) def test_unique_together_gets_picked_up_and_converted_to_tuple(self): m = UniqueTogetherModel() self.assertEqual( ([(UniqueTogetherModel, ('ifield', 'cfield',)), (UniqueTogetherModel, ('ifield', 'efield')), (UniqueTogetherModel, ('id',)), ], []), m._get_unique_checks() ) def test_primary_key_is_considered_unique(self): m = CustomPKModel() self.assertEqual(([(CustomPKModel, ('my_pk_field',))], []), m._get_unique_checks()) def test_unique_for_date_gets_picked_up(self): m = UniqueForDateModel() self.assertEqual(( [(UniqueForDateModel, ('id',))], [(UniqueForDateModel, 'date', 'count', 'start_date'), (UniqueForDateModel, 'year', 'count', 'end_date'), (UniqueForDateModel, 'month', 'order', 'end_date')] ), m._get_unique_checks() ) def test_unique_for_date_exclusion(self): m = UniqueForDateModel() self.assertEqual(( [(UniqueForDateModel, ('id',))], [(UniqueForDateModel, 'year', 'count', 'end_date'), (UniqueForDateModel, 'month', 'order', 'end_date')] ), m._get_unique_checks(exclude='start_date') ) class PerformUniqueChecksTest(unittest.TestCase): def setUp(self): # Set debug to True to gain access to connection.queries. self._old_debug, settings.DEBUG = settings.DEBUG, True super(PerformUniqueChecksTest, self).setUp() def tearDown(self): # Restore old debug value. settings.DEBUG = self._old_debug super(PerformUniqueChecksTest, self).tearDown() def test_primary_key_unique_check_not_performed_when_adding_and_pk_not_specified(self): # Regression test for #12560 query_count = len(connection.queries) mtv = ModelToValidate(number=10, name='Some Name') setattr(mtv, '_adding', True) mtv.full_clean() self.assertEqual(query_count, len(connection.queries)) def test_primary_key_unique_check_performed_when_adding_and_pk_specified(self): # Regression test for #12560 query_count = len(connection.queries) mtv = ModelToValidate(number=10, name='Some Name', id=123) setattr(mtv, '_adding', True) mtv.full_clean() self.assertEqual(query_count + 1, len(connection.queries)) def test_primary_key_unique_check_not_performed_when_not_adding(self): # Regression test for #12132 query_count= len(connection.queries) mtv = ModelToValidate(number=10, name='Some Name') mtv.full_clean() self.assertEqual(query_count, len(connection.queries)) def test_unique_for_date(self): p1 = Post.objects.create(title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) p = Post(title="Django 1.0 is released", posted=datetime.date(2008, 9, 3)) try: p.full_clean() except ValidationError, e: self.assertEqual(e.message_dict, {'title': [u'Title must be unique for Posted date.']}) else: self.fail('unique_for_date checks should catch this.') # Should work without errors p = Post(title="Work on Django 1.1 begins", posted=datetime.date(2008, 9, 3)) p.full_clean() # Should work without errors p = Post(title="Django 1.0 is released", posted=datetime.datetime(2008, 9,4)) p.full_clean() p = Post(slug="Django 1.0", posted=datetime.datetime(2008, 1, 1)) try: p.full_clean() except ValidationError, e: self.assertEqual(e.message_dict, {'slug': [u'Slug must be unique for Posted year.']}) else: self.fail('unique_for_year checks should catch this.') p = Post(subtitle="Finally", posted=datetime.datetime(2008, 9, 30)) try: p.full_clean() except ValidationError, e: self.assertEqual(e.message_dict, {'subtitle': [u'Subtitle must be unique for Posted month.']}) else: self.fail('unique_for_month checks should catch this.') p = Post(title="Django 1.0 is released") try: p.full_clean() except ValidationError, e: self.assertEqual(e.message_dict, {'posted': [u'This field cannot be null.']}) else: self.fail("Model validation shouldn't allow an absent value for a DateField without null=True.") def test_unique_for_date_with_nullable_date(self): p1 = FlexibleDatePost.objects.create(title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) p = FlexibleDatePost(title="Django 1.0 is released") try: p.full_clean() except ValidationError, e: self.fail("unique_for_date checks shouldn't trigger when the associated DateField is None.") except: self.fail("unique_for_date checks shouldn't explode when the associated DateField is None.") p = FlexibleDatePost(slug="Django 1.0") try: p.full_clean() except ValidationError, e: self.fail("unique_for_year checks shouldn't trigger when the associated DateField is None.") except: self.fail("unique_for_year checks shouldn't explode when the associated DateField is None.") p = FlexibleDatePost(subtitle="Finally") try: p.full_clean() except ValidationError, e: self.fail("unique_for_month checks shouldn't trigger when the associated DateField is None.") except: self.fail("unique_for_month checks shouldn't explode when the associated DateField is None.")
6,508
Python
.py
135
38.533333
133
0.630294
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,337
validators.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/validation/validators.py
from unittest import TestCase from modeltests.validation import ValidationTestCase from models import * class TestModelsWithValidators(ValidationTestCase): def test_custom_validator_passes_for_correct_value(self): mtv = ModelToValidate(number=10, name='Some Name', f_with_custom_validator=42) self.assertEqual(None, mtv.full_clean()) def test_custom_validator_raises_error_for_incorrect_value(self): mtv = ModelToValidate(number=10, name='Some Name', f_with_custom_validator=12) self.assertFailsValidation(mtv.full_clean, ['f_with_custom_validator']) self.assertFieldFailsValidationWithMessage( mtv.full_clean, 'f_with_custom_validator', [u'This is not the answer to life, universe and everything!'] )
797
Python
.py
15
45.8
86
0.725289
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,338
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/lookup/models.py
""" 7. The lookup API This demonstrates features of the database API. """ from django.db import models class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateTimeField() class Meta: ordering = ('-pub_date', 'headline') def __unicode__(self): return self.headline
339
Python
.py
12
24.25
47
0.696594
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,339
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/lookup/tests.py
from datetime import datetime from operator import attrgetter from django.conf import settings from django.core.exceptions import FieldError from django.db import connection, DEFAULT_DB_ALIAS from django.test import TestCase from models import Article class LookupTests(TestCase): #def setUp(self): def setUp(self): # Create a couple of Articles. self.a1 = Article(headline='Article 1', pub_date=datetime(2005, 7, 26)) self.a1.save() self.a2 = Article(headline='Article 2', pub_date=datetime(2005, 7, 27)) self.a2.save() self.a3 = Article(headline='Article 3', pub_date=datetime(2005, 7, 27)) self.a3.save() self.a4 = Article(headline='Article 4', pub_date=datetime(2005, 7, 28)) self.a4.save() self.a5 = Article(headline='Article 5', pub_date=datetime(2005, 8, 1, 9, 0)) self.a5.save() self.a6 = Article(headline='Article 6', pub_date=datetime(2005, 8, 1, 8, 0)) self.a6.save() self.a7 = Article(headline='Article 7', pub_date=datetime(2005, 7, 27)) self.a7.save() def test_exists(self): # We can use .exists() to check that there are some self.assertTrue(Article.objects.exists()) for a in Article.objects.all(): a.delete() # There should be none now! self.assertFalse(Article.objects.exists()) def test_lookup_int_as_str(self): # Integer value can be queried using string self.assertQuerysetEqual(Article.objects.filter(id__iexact=str(self.a1.id)), ['<Article: Article 1>']) if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] in ( 'django.db.backends.postgresql', 'django.db.backends.postgresql_psycopg2'): def test_lookup_date_as_str(self): # A date lookup can be performed using a string search self.assertQuerysetEqual(Article.objects.filter(pub_date__startswith='2005'), [ '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 7>', '<Article: Article 1>', ]) def test_iterator(self): # Each QuerySet gets iterator(), which is a generator that "lazily" # returns results using database-level iteration. self.assertQuerysetEqual(Article.objects.iterator(), [ 'Article 5', 'Article 6', 'Article 4', 'Article 2', 'Article 3', 'Article 7', 'Article 1', ], transform=attrgetter('headline')) # iterator() can be used on any QuerySet. self.assertQuerysetEqual( Article.objects.filter(headline__endswith='4').iterator(), ['Article 4'], transform=attrgetter('headline')) def test_count(self): # count() returns the number of objects matching search criteria. self.assertEqual(Article.objects.count(), 7) self.assertEqual(Article.objects.filter(pub_date__exact=datetime(2005, 7, 27)).count(), 3) self.assertEqual(Article.objects.filter(headline__startswith='Blah blah').count(), 0) # count() should respect sliced query sets. articles = Article.objects.all() self.assertEqual(articles.count(), 7) self.assertEqual(articles[:4].count(), 4) self.assertEqual(articles[1:100].count(), 6) self.assertEqual(articles[10:100].count(), 0) # Date and date/time lookups can also be done with strings. self.assertEqual(Article.objects.filter(pub_date__exact='2005-07-27 00:00:00').count(), 3) def test_in_bulk(self): # in_bulk() takes a list of IDs and returns a dictionary mapping IDs to objects. arts = Article.objects.in_bulk([self.a1.id, self.a2.id]) self.assertEqual(arts[self.a1.id], self.a1) self.assertEqual(arts[self.a2.id], self.a2) self.assertEqual(Article.objects.in_bulk([self.a3.id]), {self.a3.id: self.a3}) self.assertEqual(Article.objects.in_bulk(set([self.a3.id])), {self.a3.id: self.a3}) self.assertEqual(Article.objects.in_bulk(frozenset([self.a3.id])), {self.a3.id: self.a3}) self.assertEqual(Article.objects.in_bulk((self.a3.id,)), {self.a3.id: self.a3}) self.assertEqual(Article.objects.in_bulk([1000]), {}) self.assertEqual(Article.objects.in_bulk([]), {}) self.assertRaises(AssertionError, Article.objects.in_bulk, 'foo') self.assertRaises(TypeError, Article.objects.in_bulk) self.assertRaises(TypeError, Article.objects.in_bulk, headline__startswith='Blah') def test_values(self): # values() returns a list of dictionaries instead of object instances -- # and you can specify which fields you want to retrieve. identity = lambda x:x self.assertQuerysetEqual(Article.objects.values('headline'), [ {'headline': u'Article 5'}, {'headline': u'Article 6'}, {'headline': u'Article 4'}, {'headline': u'Article 2'}, {'headline': u'Article 3'}, {'headline': u'Article 7'}, {'headline': u'Article 1'}, ], transform=identity) self.assertQuerysetEqual( Article.objects.filter(pub_date__exact=datetime(2005, 7, 27)).values('id'), [{'id': self.a2.id}, {'id': self.a3.id}, {'id': self.a7.id}], transform=identity) self.assertQuerysetEqual(Article.objects.values('id', 'headline'), [ {'id': self.a5.id, 'headline': 'Article 5'}, {'id': self.a6.id, 'headline': 'Article 6'}, {'id': self.a4.id, 'headline': 'Article 4'}, {'id': self.a2.id, 'headline': 'Article 2'}, {'id': self.a3.id, 'headline': 'Article 3'}, {'id': self.a7.id, 'headline': 'Article 7'}, {'id': self.a1.id, 'headline': 'Article 1'}, ], transform=identity) # You can use values() with iterator() for memory savings, # because iterator() uses database-level iteration. self.assertQuerysetEqual(Article.objects.values('id', 'headline').iterator(), [ {'headline': u'Article 5', 'id': self.a5.id}, {'headline': u'Article 6', 'id': self.a6.id}, {'headline': u'Article 4', 'id': self.a4.id}, {'headline': u'Article 2', 'id': self.a2.id}, {'headline': u'Article 3', 'id': self.a3.id}, {'headline': u'Article 7', 'id': self.a7.id}, {'headline': u'Article 1', 'id': self.a1.id}, ], transform=identity) # The values() method works with "extra" fields specified in extra(select). self.assertQuerysetEqual( Article.objects.extra(select={'id_plus_one': 'id + 1'}).values('id', 'id_plus_one'), [ {'id': self.a5.id, 'id_plus_one': self.a5.id + 1}, {'id': self.a6.id, 'id_plus_one': self.a6.id + 1}, {'id': self.a4.id, 'id_plus_one': self.a4.id + 1}, {'id': self.a2.id, 'id_plus_one': self.a2.id + 1}, {'id': self.a3.id, 'id_plus_one': self.a3.id + 1}, {'id': self.a7.id, 'id_plus_one': self.a7.id + 1}, {'id': self.a1.id, 'id_plus_one': self.a1.id + 1}, ], transform=identity) data = { 'id_plus_one': 'id+1', 'id_plus_two': 'id+2', 'id_plus_three': 'id+3', 'id_plus_four': 'id+4', 'id_plus_five': 'id+5', 'id_plus_six': 'id+6', 'id_plus_seven': 'id+7', 'id_plus_eight': 'id+8', } self.assertQuerysetEqual( Article.objects.filter(id=self.a1.id).extra(select=data).values(*data.keys()), [{ 'id_plus_one': self.a1.id + 1, 'id_plus_two': self.a1.id + 2, 'id_plus_three': self.a1.id + 3, 'id_plus_four': self.a1.id + 4, 'id_plus_five': self.a1.id + 5, 'id_plus_six': self.a1.id + 6, 'id_plus_seven': self.a1.id + 7, 'id_plus_eight': self.a1.id + 8, }], transform=identity) # However, an exception FieldDoesNotExist will be thrown if you specify # a non-existent field name in values() (a field that is neither in the # model nor in extra(select)). self.assertRaises(FieldError, Article.objects.extra(select={'id_plus_one': 'id + 1'}).values, 'id', 'id_plus_two') # If you don't specify field names to values(), all are returned. self.assertQuerysetEqual(Article.objects.filter(id=self.a5.id).values(), [{ 'id': self.a5.id, 'headline': 'Article 5', 'pub_date': datetime(2005, 8, 1, 9, 0) }], transform=identity) def test_values_list(self): # values_list() is similar to values(), except that the results are # returned as a list of tuples, rather than a list of dictionaries. # Within each tuple, the order of the elemnts is the same as the order # of fields in the values_list() call. identity = lambda x:x self.assertQuerysetEqual(Article.objects.values_list('headline'), [ (u'Article 5',), (u'Article 6',), (u'Article 4',), (u'Article 2',), (u'Article 3',), (u'Article 7',), (u'Article 1',), ], transform=identity) self.assertQuerysetEqual(Article.objects.values_list('id').order_by('id'), [(self.a1.id,), (self.a2.id,), (self.a3.id,), (self.a4.id,), (self.a5.id,), (self.a6.id,), (self.a7.id,)], transform=identity) self.assertQuerysetEqual( Article.objects.values_list('id', flat=True).order_by('id'), [self.a1.id, self.a2.id, self.a3.id, self.a4.id, self.a5.id, self.a6.id, self.a7.id], transform=identity) self.assertQuerysetEqual( Article.objects.extra(select={'id_plus_one': 'id+1'}) .order_by('id').values_list('id'), [(self.a1.id,), (self.a2.id,), (self.a3.id,), (self.a4.id,), (self.a5.id,), (self.a6.id,), (self.a7.id,)], transform=identity) self.assertQuerysetEqual( Article.objects.extra(select={'id_plus_one': 'id+1'}) .order_by('id').values_list('id_plus_one', 'id'), [ (self.a1.id+1, self.a1.id), (self.a2.id+1, self.a2.id), (self.a3.id+1, self.a3.id), (self.a4.id+1, self.a4.id), (self.a5.id+1, self.a5.id), (self.a6.id+1, self.a6.id), (self.a7.id+1, self.a7.id) ], transform=identity) self.assertQuerysetEqual( Article.objects.extra(select={'id_plus_one': 'id+1'}) .order_by('id').values_list('id', 'id_plus_one'), [ (self.a1.id, self.a1.id+1), (self.a2.id, self.a2.id+1), (self.a3.id, self.a3.id+1), (self.a4.id, self.a4.id+1), (self.a5.id, self.a5.id+1), (self.a6.id, self.a6.id+1), (self.a7.id, self.a7.id+1) ], transform=identity) self.assertRaises(TypeError, Article.objects.values_list, 'id', 'headline', flat=True) def test_get_next_previous_by(self): # Every DateField and DateTimeField creates get_next_by_FOO() and # get_previous_by_FOO() methods. In the case of identical date values, # these methods will use the ID as a fallback check. This guarantees # that no records are skipped or duplicated. self.assertEqual(repr(self.a1.get_next_by_pub_date()), '<Article: Article 2>') self.assertEqual(repr(self.a2.get_next_by_pub_date()), '<Article: Article 3>') self.assertEqual(repr(self.a2.get_next_by_pub_date(headline__endswith='6')), '<Article: Article 6>') self.assertEqual(repr(self.a3.get_next_by_pub_date()), '<Article: Article 7>') self.assertEqual(repr(self.a4.get_next_by_pub_date()), '<Article: Article 6>') self.assertRaises(Article.DoesNotExist, self.a5.get_next_by_pub_date) self.assertEqual(repr(self.a6.get_next_by_pub_date()), '<Article: Article 5>') self.assertEqual(repr(self.a7.get_next_by_pub_date()), '<Article: Article 4>') self.assertEqual(repr(self.a7.get_previous_by_pub_date()), '<Article: Article 3>') self.assertEqual(repr(self.a6.get_previous_by_pub_date()), '<Article: Article 4>') self.assertEqual(repr(self.a5.get_previous_by_pub_date()), '<Article: Article 6>') self.assertEqual(repr(self.a4.get_previous_by_pub_date()), '<Article: Article 7>') self.assertEqual(repr(self.a3.get_previous_by_pub_date()), '<Article: Article 2>') self.assertEqual(repr(self.a2.get_previous_by_pub_date()), '<Article: Article 1>') def test_escaping(self): # Underscores, percent signs and backslashes have special meaning in the # underlying SQL code, but Django handles the quoting of them automatically. a8 = Article(headline='Article_ with underscore', pub_date=datetime(2005, 11, 20)) a8.save() self.assertQuerysetEqual(Article.objects.filter(headline__startswith='Article'), [ '<Article: Article_ with underscore>', '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 7>', '<Article: Article 1>', ]) self.assertQuerysetEqual(Article.objects.filter(headline__startswith='Article_'), ['<Article: Article_ with underscore>']) a9 = Article(headline='Article% with percent sign', pub_date=datetime(2005, 11, 21)) a9.save() self.assertQuerysetEqual(Article.objects.filter(headline__startswith='Article'), [ '<Article: Article% with percent sign>', '<Article: Article_ with underscore>', '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 7>', '<Article: Article 1>', ]) self.assertQuerysetEqual(Article.objects.filter(headline__startswith='Article%'), ['<Article: Article% with percent sign>']) a10 = Article(headline='Article with \\ backslash', pub_date=datetime(2005, 11, 22)) a10.save() self.assertQuerysetEqual(Article.objects.filter(headline__contains='\\'), ['<Article: Article with \ backslash>']) def test_exclude(self): a8 = Article.objects.create(headline='Article_ with underscore', pub_date=datetime(2005, 11, 20)) a9 = Article.objects.create(headline='Article% with percent sign', pub_date=datetime(2005, 11, 21)) a10 = Article.objects.create(headline='Article with \\ backslash', pub_date=datetime(2005, 11, 22)) # exclude() is the opposite of filter() when doing lookups: self.assertQuerysetEqual( Article.objects.filter(headline__contains='Article').exclude(headline__contains='with'), [ '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 7>', '<Article: Article 1>', ]) self.assertQuerysetEqual(Article.objects.exclude(headline__startswith="Article_"), [ '<Article: Article with \\ backslash>', '<Article: Article% with percent sign>', '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 7>', '<Article: Article 1>', ]) self.assertQuerysetEqual(Article.objects.exclude(headline="Article 7"), [ '<Article: Article with \\ backslash>', '<Article: Article% with percent sign>', '<Article: Article_ with underscore>', '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 1>', ]) def test_none(self): # none() returns an EmptyQuerySet that behaves like any other QuerySet object self.assertQuerysetEqual(Article.objects.none(), []) self.assertQuerysetEqual( Article.objects.none().filter(headline__startswith='Article'), []) self.assertQuerysetEqual( Article.objects.filter(headline__startswith='Article').none(), []) self.assertEqual(Article.objects.none().count(), 0) self.assertEqual( Article.objects.none().update(headline="This should not take effect"), 0) self.assertQuerysetEqual( [article for article in Article.objects.none().iterator()], []) def test_in(self): # using __in with an empty list should return an empty query set self.assertQuerysetEqual(Article.objects.filter(id__in=[]), []) self.assertQuerysetEqual(Article.objects.exclude(id__in=[]), [ '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 7>', '<Article: Article 1>', ]) def test_error_messages(self): # Programming errors are pointed out with nice error messages try: Article.objects.filter(pub_date_year='2005').count() self.fail('FieldError not raised') except FieldError, ex: self.assertEqual(str(ex), "Cannot resolve keyword 'pub_date_year' " "into field. Choices are: headline, id, pub_date") try: Article.objects.filter(headline__starts='Article') self.fail('FieldError not raised') except FieldError, ex: self.assertEqual(str(ex), "Join on field 'headline' not permitted. " "Did you misspell 'starts' for the lookup type?") def test_regex(self): # Create some articles with a bit more interesting headlines for testing field lookups: for a in Article.objects.all(): a.delete() now = datetime.now() a1 = Article(pub_date=now, headline='f') a1.save() a2 = Article(pub_date=now, headline='fo') a2.save() a3 = Article(pub_date=now, headline='foo') a3.save() a4 = Article(pub_date=now, headline='fooo') a4.save() a5 = Article(pub_date=now, headline='hey-Foo') a5.save() a6 = Article(pub_date=now, headline='bar') a6.save() a7 = Article(pub_date=now, headline='AbBa') a7.save() a8 = Article(pub_date=now, headline='baz') a8.save() a9 = Article(pub_date=now, headline='baxZ') a9.save() # zero-or-more self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'fo*'), ['<Article: f>', '<Article: fo>', '<Article: foo>', '<Article: fooo>']) self.assertQuerysetEqual(Article.objects.filter(headline__iregex=r'fo*'), [ '<Article: f>', '<Article: fo>', '<Article: foo>', '<Article: fooo>', '<Article: hey-Foo>', ]) # one-or-more self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'fo+'), ['<Article: fo>', '<Article: foo>', '<Article: fooo>']) # wildcard self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'fooo?'), ['<Article: foo>', '<Article: fooo>']) # leading anchor self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'^b'), ['<Article: bar>', '<Article: baxZ>', '<Article: baz>']) self.assertQuerysetEqual(Article.objects.filter(headline__iregex=r'^a'), ['<Article: AbBa>']) # trailing anchor self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'z$'), ['<Article: baz>']) self.assertQuerysetEqual(Article.objects.filter(headline__iregex=r'z$'), ['<Article: baxZ>', '<Article: baz>']) # character sets self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'ba[rz]'), ['<Article: bar>', '<Article: baz>']) self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'ba.[RxZ]'), ['<Article: baxZ>']) self.assertQuerysetEqual(Article.objects.filter(headline__iregex=r'ba[RxZ]'), ['<Article: bar>', '<Article: baxZ>', '<Article: baz>']) # and more articles: a10 = Article(pub_date=now, headline='foobar') a10.save() a11 = Article(pub_date=now, headline='foobaz') a11.save() a12 = Article(pub_date=now, headline='ooF') a12.save() a13 = Article(pub_date=now, headline='foobarbaz') a13.save() a14 = Article(pub_date=now, headline='zoocarfaz') a14.save() a15 = Article(pub_date=now, headline='barfoobaz') a15.save() a16 = Article(pub_date=now, headline='bazbaRFOO') a16.save() # alternation self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'oo(f|b)'), [ '<Article: barfoobaz>', '<Article: foobar>', '<Article: foobarbaz>', '<Article: foobaz>', ]) self.assertQuerysetEqual(Article.objects.filter(headline__iregex=r'oo(f|b)'), [ '<Article: barfoobaz>', '<Article: foobar>', '<Article: foobarbaz>', '<Article: foobaz>', '<Article: ooF>', ]) self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'^foo(f|b)'), ['<Article: foobar>', '<Article: foobarbaz>', '<Article: foobaz>']) # greedy matching self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'b.*az'), [ '<Article: barfoobaz>', '<Article: baz>', '<Article: bazbaRFOO>', '<Article: foobarbaz>', '<Article: foobaz>', ]) self.assertQuerysetEqual(Article.objects.filter(headline__iregex=r'b.*ar'), [ '<Article: bar>', '<Article: barfoobaz>', '<Article: bazbaRFOO>', '<Article: foobar>', '<Article: foobarbaz>', ]) if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.mysql': def test_regex_backreferencing(self): # grouping and backreferences now = datetime.now() a10 = Article(pub_date=now, headline='foobar') a10.save() a11 = Article(pub_date=now, headline='foobaz') a11.save() a12 = Article(pub_date=now, headline='ooF') a12.save() a13 = Article(pub_date=now, headline='foobarbaz') a13.save() a14 = Article(pub_date=now, headline='zoocarfaz') a14.save() a15 = Article(pub_date=now, headline='barfoobaz') a15.save() a16 = Article(pub_date=now, headline='bazbaRFOO') a16.save() self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'b(.).*b\1'), ['<Article: barfoobaz>', '<Article: bazbaRFOO>', '<Article: foobarbaz>'])
25,276
Python
.py
520
35.703846
118
0.545756
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,340
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/many_to_one/models.py
""" 4. Many-to-one relationships To define a many-to-one relationship, use ``ForeignKey()``. """ from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __unicode__(self): return u"%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter) def __unicode__(self): return self.headline class Meta: ordering = ('headline',)
638
Python
.py
19
29.052632
59
0.687908
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,341
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/many_to_one/tests.py
from datetime import datetime from django.test import TestCase from django.core.exceptions import FieldError from models import Article, Reporter class ManyToOneTests(TestCase): def setUp(self): # Create a few Reporters. self.r = Reporter(first_name='John', last_name='Smith', email='[email protected]') self.r.save() self.r2 = Reporter(first_name='Paul', last_name='Jones', email='[email protected]') self.r2.save() # Create an Article. self.a = Article(id=None, headline="This is a test", pub_date=datetime(2005, 7, 27), reporter=self.r) self.a.save() def test_get(self): # Article objects have access to their related Reporter objects. r = self.a.reporter self.assertEqual(r.id, self.r.id) # These are strings instead of unicode strings because that's what was used in # the creation of this reporter (and we haven't refreshed the data from the # database, which always returns unicode strings). self.assertEqual((r.first_name, self.r.last_name), ('John', 'Smith')) def test_create(self): # You can also instantiate an Article by passing the Reporter's ID # instead of a Reporter object. a3 = Article(id=None, headline="Third article", pub_date=datetime(2005, 7, 27), reporter_id=self.r.id) a3.save() self.assertEqual(a3.reporter.id, self.r.id) # Similarly, the reporter ID can be a string. a4 = Article(id=None, headline="Fourth article", pub_date=datetime(2005, 7, 27), reporter_id=str(self.r.id)) a4.save() self.assertEqual(repr(a4.reporter), "<Reporter: John Smith>") def test_add(self): # Create an Article via the Reporter object. new_article = self.r.article_set.create(headline="John's second story", pub_date=datetime(2005, 7, 29)) self.assertEqual(repr(new_article), "<Article: John's second story>") self.assertEqual(new_article.reporter.id, self.r.id) # Create a new article, and add it to the article set. new_article2 = Article(headline="Paul's story", pub_date=datetime(2006, 1, 17)) self.r.article_set.add(new_article2) self.assertEqual(new_article2.reporter.id, self.r.id) self.assertQuerysetEqual(self.r.article_set.all(), [ "<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>", ]) # Add the same article to a different article set - check that it moves. self.r2.article_set.add(new_article2) self.assertEqual(new_article2.reporter.id, self.r2.id) self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"]) # Adding an object of the wrong type raises TypeError. self.assertRaises(TypeError, self.r.article_set.add, self.r2) self.assertQuerysetEqual(self.r.article_set.all(), [ "<Article: John's second story>", "<Article: This is a test>", ]) def test_assign(self): new_article = self.r.article_set.create(headline="John's second story", pub_date=datetime(2005, 7, 29)) new_article2 = self.r2.article_set.create(headline="Paul's story", pub_date=datetime(2006, 1, 17)) # Assign the article to the reporter directly using the descriptor. new_article2.reporter = self.r new_article2.save() self.assertEqual(repr(new_article2.reporter), "<Reporter: John Smith>") self.assertEqual(new_article2.reporter.id, self.r.id) self.assertQuerysetEqual(self.r.article_set.all(), [ "<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>", ]) self.assertQuerysetEqual(self.r2.article_set.all(), []) # Set the article back again using set descriptor. self.r2.article_set = [new_article, new_article2] self.assertQuerysetEqual(self.r.article_set.all(), ["<Article: This is a test>"]) self.assertQuerysetEqual(self.r2.article_set.all(), [ "<Article: John's second story>", "<Article: Paul's story>", ]) # Funny case - assignment notation can only go so far; because the # ForeignKey cannot be null, existing members of the set must remain. self.r.article_set = [new_article] self.assertQuerysetEqual(self.r.article_set.all(), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"]) # Reporter cannot be null - there should not be a clear or remove method self.assertFalse(hasattr(self.r2.article_set, 'remove')) self.assertFalse(hasattr(self.r2.article_set, 'clear')) def test_selects(self): new_article = self.r.article_set.create(headline="John's second story", pub_date=datetime(2005, 7, 29)) new_article2 = self.r2.article_set.create(headline="Paul's story", pub_date=datetime(2006, 1, 17)) # Reporter objects have access to their related Article objects. self.assertQuerysetEqual(self.r.article_set.all(), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual(self.r.article_set.filter(headline__startswith='This'), ["<Article: This is a test>"]) self.assertEqual(self.r.article_set.count(), 2) self.assertEqual(self.r2.article_set.count(), 1) # Get articles by id self.assertQuerysetEqual(Article.objects.filter(id__exact=self.a.id), ["<Article: This is a test>"]) self.assertQuerysetEqual(Article.objects.filter(pk=self.a.id), ["<Article: This is a test>"]) # Query on an article property self.assertQuerysetEqual(Article.objects.filter(headline__startswith='This'), ["<Article: This is a test>"]) # The API automatically follows relationships as far as you need. # Use double underscores to separate relationships. # This works as many levels deep as you want. There's no limit. # Find all Articles for any Reporter whose first name is "John". self.assertQuerysetEqual(Article.objects.filter(reporter__first_name__exact='John'), [ "<Article: John's second story>", "<Article: This is a test>", ]) # Check that implied __exact also works self.assertQuerysetEqual(Article.objects.filter(reporter__first_name='John'), [ "<Article: John's second story>", "<Article: This is a test>", ]) # Query twice over the related field. self.assertQuerysetEqual( Article.objects.filter(reporter__first_name__exact='John', reporter__last_name__exact='Smith'), [ "<Article: John's second story>", "<Article: This is a test>", ]) # The underlying query only makes one join when a related table is referenced twice. queryset = Article.objects.filter(reporter__first_name__exact='John', reporter__last_name__exact='Smith') self.assertEqual(queryset.query.get_compiler(queryset.db).as_sql()[0].count('INNER JOIN'), 1) # The automatically joined table has a predictable name. self.assertQuerysetEqual( Article.objects.filter(reporter__first_name__exact='John').extra( where=["many_to_one_reporter.last_name='Smith'"]), [ "<Article: John's second story>", "<Article: This is a test>", ]) # ... and should work fine with the unicode that comes out of forms.Form.cleaned_data self.assertQuerysetEqual( Article.objects.filter(reporter__first_name__exact='John' ).extra(where=["many_to_one_reporter.last_name='%s'" % u'Smith']), [ "<Article: John's second story>", "<Article: This is a test>", ]) # Find all Articles for a Reporter. # Use direct ID check, pk check, and object comparison self.assertQuerysetEqual( Article.objects.filter(reporter__id__exact=self.r.id), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter__pk=self.r.id), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter=self.r.id), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter=self.r), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter__in=[self.r.id,self.r2.id]).distinct(), [ "<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter__in=[self.r,self.r2]).distinct(), [ "<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>", ]) # You can also use a queryset instead of a literal list of instances. # The queryset must be reduced to a list of values using values(), # then converted into a query self.assertQuerysetEqual( Article.objects.filter( reporter__in=Reporter.objects.filter(first_name='John').values('pk').query ).distinct(), [ "<Article: John's second story>", "<Article: This is a test>", ]) # You need two underscores between "reporter" and "id" -- not one. self.assertRaises(FieldError, Article.objects.filter, reporter_id__exact=self.r.id) # You need to specify a comparison clause self.assertRaises(FieldError, Article.objects.filter, reporter_id=self.r.id) def test_reverse_selects(self): a3 = Article.objects.create(id=None, headline="Third article", pub_date=datetime(2005, 7, 27), reporter_id=self.r.id) a4 = Article.objects.create(id=None, headline="Fourth article", pub_date=datetime(2005, 7, 27), reporter_id=str(self.r.id)) # Reporters can be queried self.assertQuerysetEqual(Reporter.objects.filter(id__exact=self.r.id), ["<Reporter: John Smith>"]) self.assertQuerysetEqual(Reporter.objects.filter(pk=self.r.id), ["<Reporter: John Smith>"]) self.assertQuerysetEqual(Reporter.objects.filter(first_name__startswith='John'), ["<Reporter: John Smith>"]) # Reporters can query in opposite direction of ForeignKey definition self.assertQuerysetEqual(Reporter.objects.filter(article__id__exact=self.a.id), ["<Reporter: John Smith>"]) self.assertQuerysetEqual(Reporter.objects.filter(article__pk=self.a.id), ["<Reporter: John Smith>"]) self.assertQuerysetEqual(Reporter.objects.filter(article=self.a.id), ["<Reporter: John Smith>"]) self.assertQuerysetEqual(Reporter.objects.filter(article=self.a), ["<Reporter: John Smith>"]) self.assertQuerysetEqual( Reporter.objects.filter(article__in=[self.a.id,a3.id]).distinct(), ["<Reporter: John Smith>"]) self.assertQuerysetEqual( Reporter.objects.filter(article__in=[self.a.id,a3]).distinct(), ["<Reporter: John Smith>"]) self.assertQuerysetEqual( Reporter.objects.filter(article__in=[self.a,a3]).distinct(), ["<Reporter: John Smith>"]) self.assertQuerysetEqual( Reporter.objects.filter(article__headline__startswith='T'), ["<Reporter: John Smith>", "<Reporter: John Smith>"]) self.assertQuerysetEqual( Reporter.objects.filter(article__headline__startswith='T').distinct(), ["<Reporter: John Smith>"]) # Counting in the opposite direction works in conjunction with distinct() self.assertEqual( Reporter.objects.filter(article__headline__startswith='T').count(), 2) self.assertEqual( Reporter.objects.filter(article__headline__startswith='T').distinct().count(), 1) # Queries can go round in circles. self.assertQuerysetEqual( Reporter.objects.filter(article__reporter__first_name__startswith='John'), [ "<Reporter: John Smith>", "<Reporter: John Smith>", "<Reporter: John Smith>", ]) self.assertQuerysetEqual( Reporter.objects.filter(article__reporter__first_name__startswith='John').distinct(), ["<Reporter: John Smith>"]) self.assertQuerysetEqual( Reporter.objects.filter(article__reporter__exact=self.r).distinct(), ["<Reporter: John Smith>"]) # Check that implied __exact also works. self.assertQuerysetEqual( Reporter.objects.filter(article__reporter=self.r).distinct(), ["<Reporter: John Smith>"]) # It's possible to use values() calls across many-to-one relations. # (Note, too, that we clear the ordering here so as not to drag the # 'headline' field into the columns being used to determine uniqueness) d = {'reporter__first_name': u'John', 'reporter__last_name': u'Smith'} self.assertEqual([d], list(Article.objects.filter(reporter=self.r).distinct().order_by() .values('reporter__first_name', 'reporter__last_name'))) def test_select_related(self): # Check that Article.objects.select_related().dates() works properly when # there are multiple Articles with the same date but different foreign-key # objects (Reporters). r1 = Reporter.objects.create(first_name='Mike', last_name='Royko', email='[email protected]') r2 = Reporter.objects.create(first_name='John', last_name='Kass', email='[email protected]') a1 = Article.objects.create(headline='First', pub_date=datetime(1980, 4, 23), reporter=r1) a2 = Article.objects.create(headline='Second', pub_date=datetime(1980, 4, 23), reporter=r2) self.assertEqual(list(Article.objects.select_related().dates('pub_date', 'day')), [ datetime(1980, 4, 23, 0, 0), datetime(2005, 7, 27, 0, 0), ]) self.assertEqual(list(Article.objects.select_related().dates('pub_date', 'month')), [ datetime(1980, 4, 1, 0, 0), datetime(2005, 7, 1, 0, 0), ]) self.assertEqual(list(Article.objects.select_related().dates('pub_date', 'year')), [ datetime(1980, 1, 1, 0, 0), datetime(2005, 1, 1, 0, 0), ]) def test_delete(self): new_article = self.r.article_set.create(headline="John's second story", pub_date=datetime(2005, 7, 29)) new_article2 = self.r2.article_set.create(headline="Paul's story", pub_date=datetime(2006, 1, 17)) a3 = Article.objects.create(id=None, headline="Third article", pub_date=datetime(2005, 7, 27), reporter_id=self.r.id) a4 = Article.objects.create(id=None, headline="Fourth article", pub_date=datetime(2005, 7, 27), reporter_id=str(self.r.id)) # If you delete a reporter, his articles will be deleted. self.assertQuerysetEqual(Article.objects.all(), [ "<Article: Fourth article>", "<Article: John's second story>", "<Article: Paul's story>", "<Article: Third article>", "<Article: This is a test>", ]) self.assertQuerysetEqual(Reporter.objects.order_by('first_name'), [ "<Reporter: John Smith>", "<Reporter: Paul Jones>", ]) self.r2.delete() self.assertQuerysetEqual(Article.objects.all(), [ "<Article: Fourth article>", "<Article: John's second story>", "<Article: Third article>", "<Article: This is a test>", ]) self.assertQuerysetEqual(Reporter.objects.order_by('first_name'), ["<Reporter: John Smith>"]) # You can delete using a JOIN in the query. Reporter.objects.filter(article__headline__startswith='This').delete() self.assertQuerysetEqual(Reporter.objects.all(), []) self.assertQuerysetEqual(Article.objects.all(), []) def test_regression_12876(self): # Regression for #12876 -- Model methods that include queries that # recursive don't cause recursion depth problems under deepcopy. self.r.cached_query = Article.objects.filter(reporter=self.r) from copy import deepcopy self.assertEqual(repr(deepcopy(self.r)), "<Reporter: John Smith>")
18,563
Python
.py
350
39.502857
102
0.576737
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,342
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/select_related/models.py
""" 41. Tests for select_related() ``select_related()`` follows all relationships and pre-caches any foreign key values so that complex trees can be fetched in a single query. However, this isn't always a good idea, so the ``depth`` argument control how many "levels" the select-related behavior will traverse. """ from django.db import models # Who remembers high school biology? class Domain(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class Kingdom(models.Model): name = models.CharField(max_length=50) domain = models.ForeignKey(Domain) def __unicode__(self): return self.name class Phylum(models.Model): name = models.CharField(max_length=50) kingdom = models.ForeignKey(Kingdom) def __unicode__(self): return self.name class Klass(models.Model): name = models.CharField(max_length=50) phylum = models.ForeignKey(Phylum) def __unicode__(self): return self.name class Order(models.Model): name = models.CharField(max_length=50) klass = models.ForeignKey(Klass) def __unicode__(self): return self.name class Family(models.Model): name = models.CharField(max_length=50) order = models.ForeignKey(Order) def __unicode__(self): return self.name class Genus(models.Model): name = models.CharField(max_length=50) family = models.ForeignKey(Family) def __unicode__(self): return self.name class Species(models.Model): name = models.CharField(max_length=50) genus = models.ForeignKey(Genus) def __unicode__(self): return self.name
1,643
Python
.py
48
29.770833
77
0.707886
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,343
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/select_related/tests.py
from django.test import TestCase from django.conf import settings from django import db from models import Domain, Kingdom, Phylum, Klass, Order, Family, Genus, Species class SelectRelatedTests(TestCase): def create_tree(self, stringtree): """ Helper to create a complete tree. """ names = stringtree.split() models = [Domain, Kingdom, Phylum, Klass, Order, Family, Genus, Species] assert len(names) == len(models), (names, models) parent = None for name, model in zip(names, models): try: obj = model.objects.get(name=name) except model.DoesNotExist: obj = model(name=name) if parent: setattr(obj, parent.__class__.__name__.lower(), parent) obj.save() parent = obj def create_base_data(self): self.create_tree("Eukaryota Animalia Anthropoda Insecta Diptera Drosophilidae Drosophila melanogaster") self.create_tree("Eukaryota Animalia Chordata Mammalia Primates Hominidae Homo sapiens") self.create_tree("Eukaryota Plantae Magnoliophyta Magnoliopsida Fabales Fabaceae Pisum sativum") self.create_tree("Eukaryota Fungi Basidiomycota Homobasidiomycatae Agaricales Amanitacae Amanita muscaria") def setUp(self): # The test runner sets settings.DEBUG to False, but we want to gather # queries so we'll set it to True here and reset it at the end of the # test case. self.create_base_data() settings.DEBUG = True db.reset_queries() def tearDown(self): settings.DEBUG = False def test_access_fks_without_select_related(self): """ Normally, accessing FKs doesn't fill in related objects """ fly = Species.objects.get(name="melanogaster") domain = fly.genus.family.order.klass.phylum.kingdom.domain self.assertEqual(domain.name, 'Eukaryota') self.assertEqual(len(db.connection.queries), 8) def test_access_fks_with_select_related(self): """ A select_related() call will fill in those related objects without any extra queries """ person = Species.objects.select_related(depth=10).get(name="sapiens") domain = person.genus.family.order.klass.phylum.kingdom.domain self.assertEqual(domain.name, 'Eukaryota') self.assertEqual(len(db.connection.queries), 1) def test_list_without_select_related(self): """ select_related() also of course applies to entire lists, not just items. This test verifies the expected behavior without select_related. """ world = Species.objects.all() families = [o.genus.family.name for o in world] self.assertEqual(sorted(families), [ 'Amanitacae', 'Drosophilidae', 'Fabaceae', 'Hominidae', ]) self.assertEqual(len(db.connection.queries), 9) def test_list_with_select_related(self): """ select_related() also of course applies to entire lists, not just items. This test verifies the expected behavior with select_related. """ world = Species.objects.all().select_related() families = [o.genus.family.name for o in world] self.assertEqual(sorted(families), [ 'Amanitacae', 'Drosophilidae', 'Fabaceae', 'Hominidae', ]) self.assertEqual(len(db.connection.queries), 1) def test_depth(self, depth=1, expected=7): """ The "depth" argument to select_related() will stop the descent at a particular level. """ pea = Species.objects.select_related(depth=depth).get(name="sativum") self.assertEqual( pea.genus.family.order.klass.phylum.kingdom.domain.name, 'Eukaryota' ) # Notice: one fewer queries than above because of depth=1 self.assertEqual(len(db.connection.queries), expected) def test_larger_depth(self): """ The "depth" argument to select_related() will stop the descent at a particular level. This tests a larger depth value. """ self.test_depth(depth=5, expected=3) def test_list_with_depth(self): """ The "depth" argument to select_related() will stop the descent at a particular level. This can be used on lists as well. """ world = Species.objects.all().select_related(depth=2) orders = [o.genus.family.order.name for o in world] self.assertEqual(sorted(orders), ['Agaricales', 'Diptera', 'Fabales', 'Primates']) self.assertEqual(len(db.connection.queries), 5) def test_select_related_with_extra(self): s = Species.objects.all().select_related(depth=1)\ .extra(select={'a': 'select_related_species.id + 10'})[0] self.assertEqual(s.id + 10, s.a) def test_certain_fields(self): """ The optional fields passed to select_related() control which related models we pull in. This allows for smaller queries and can act as an alternative (or, in addition to) the depth parameter. In this case, we explicitly say to select the 'genus' and 'genus.family' models, leading to the same number of queries as before. """ world = Species.objects.select_related('genus__family') families = [o.genus.family.name for o in world] self.assertEqual(sorted(families), ['Amanitacae', 'Drosophilidae', 'Fabaceae', 'Hominidae']) self.assertEqual(len(db.connection.queries), 1) def test_more_certain_fields(self): """ In this case, we explicitly say to select the 'genus' and 'genus.family' models, leading to the same number of queries as before. """ world = Species.objects.filter(genus__name='Amanita')\ .select_related('genus__family') orders = [o.genus.family.order.name for o in world] self.assertEqual(orders, [u'Agaricales']) self.assertEqual(len(db.connection.queries), 2) def test_field_traversal(self): s = Species.objects.all().select_related('genus__family__order' ).order_by('id')[0:1].get().genus.family.order.name self.assertEqual(s, u'Diptera') self.assertEqual(len(db.connection.queries), 1) def test_depth_fields_fails(self): self.assertRaises(TypeError, Species.objects.select_related, 'genus__family__order', depth=4 )
6,630
Python
.py
146
36.219178
115
0.639078
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,344
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/m2m_recursive/models.py
""" 28. Many-to-many relationships between the same two tables In this example, a ``Person`` can have many friends, who are also ``Person`` objects. Friendship is a symmetrical relationship - if I am your friend, you are my friend. Here, ``friends`` is an example of a symmetrical ``ManyToManyField``. A ``Person`` can also have many idols - but while I may idolize you, you may not think the same of me. Here, ``idols`` is an example of a non-symmetrical ``ManyToManyField``. Only recursive ``ManyToManyField`` fields may be non-symmetrical, and they are symmetrical by default. This test validates that the many-to-many table is created using a mangled name if there is a name clash, and tests that symmetry is preserved where appropriate. """ from django.db import models class Person(models.Model): name = models.CharField(max_length=20) friends = models.ManyToManyField('self') idols = models.ManyToManyField('self', symmetrical=False, related_name='stalkers') def __unicode__(self): return self.name
1,037
Python
.py
21
46.904762
86
0.759167
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,345
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/m2m_recursive/tests.py
from operator import attrgetter from django.test import TestCase from models import Person class RecursiveM2MTests(TestCase): def test_recursive_m2m(self): a, b, c, d = [ Person.objects.create(name=name) for name in ["Anne", "Bill", "Chuck", "David"] ] # Add some friends in the direction of field definition # Anne is friends with Bill and Chuck a.friends.add(b, c) # David is friends with Anne and Chuck - add in reverse direction d.friends.add(a,c) # Who is friends with Anne? self.assertQuerysetEqual( a.friends.all(), [ "Bill", "Chuck", "David" ], attrgetter("name") ) # Who is friends with Bill? self.assertQuerysetEqual( b.friends.all(), [ "Anne", ], attrgetter("name") ) # Who is friends with Chuck? self.assertQuerysetEqual( c.friends.all(), [ "Anne", "David" ], attrgetter("name") ) # Who is friends with David? self.assertQuerysetEqual( d.friends.all(), [ "Anne", "Chuck", ], attrgetter("name") ) # Bill is already friends with Anne - add Anne again, but in the # reverse direction b.friends.add(a) # Who is friends with Anne? self.assertQuerysetEqual( a.friends.all(), [ "Bill", "Chuck", "David", ], attrgetter("name") ) # Who is friends with Bill? self.assertQuerysetEqual( b.friends.all(), [ "Anne", ], attrgetter("name") ) # Remove Anne from Bill's friends b.friends.remove(a) # Who is friends with Anne? self.assertQuerysetEqual( a.friends.all(), [ "Chuck", "David", ], attrgetter("name") ) # Who is friends with Bill? self.assertQuerysetEqual( b.friends.all(), [] ) # Clear Anne's group of friends a.friends.clear() # Who is friends with Anne? self.assertQuerysetEqual( a.friends.all(), [] ) # Reverse relationships should also be gone # Who is friends with Chuck? self.assertQuerysetEqual( c.friends.all(), [ "David", ], attrgetter("name") ) # Who is friends with David? self.assertQuerysetEqual( d.friends.all(), [ "Chuck", ], attrgetter("name") ) # Add some idols in the direction of field definition # Anne idolizes Bill and Chuck a.idols.add(b, c) # Bill idolizes Anne right back b.idols.add(a) # David is idolized by Anne and Chuck - add in reverse direction d.stalkers.add(a, c) # Who are Anne's idols? self.assertQuerysetEqual( a.idols.all(), [ "Bill", "Chuck", "David", ], attrgetter("name") ) # Who is stalking Anne? self.assertQuerysetEqual( a.stalkers.all(), [ "Bill", ], attrgetter("name") ) # Who are Bill's idols? self.assertQuerysetEqual( b.idols.all(), [ "Anne", ], attrgetter("name") ) # Who is stalking Bill? self.assertQuerysetEqual( b.stalkers.all(), [ "Anne", ], attrgetter("name") ) # Who are Chuck's idols? self.assertQuerysetEqual( c.idols.all(), [ "David", ], attrgetter("name"), ) # Who is stalking Chuck? self.assertQuerysetEqual( c.stalkers.all(), [ "Anne", ], attrgetter("name") ) # Who are David's idols? self.assertQuerysetEqual( d.idols.all(), [] ) # Who is stalking David self.assertQuerysetEqual( d.stalkers.all(), [ "Anne", "Chuck", ], attrgetter("name") ) # Bill is already being stalked by Anne - add Anne again, but in the # reverse direction b.stalkers.add(a) # Who are Anne's idols? self.assertQuerysetEqual( a.idols.all(), [ "Bill", "Chuck", "David", ], attrgetter("name") ) # Who is stalking Anne? self.assertQuerysetEqual( a.stalkers.all(), [ "Bill", ], attrgetter("name") ) # Who are Bill's idols self.assertQuerysetEqual( b.idols.all(), [ "Anne", ], attrgetter("name") ) # Who is stalking Bill? self.assertQuerysetEqual( b.stalkers.all(), [ "Anne", ], attrgetter("name"), ) # Remove Anne from Bill's list of stalkers b.stalkers.remove(a) # Who are Anne's idols? self.assertQuerysetEqual( a.idols.all(), [ "Chuck", "David", ], attrgetter("name") ) # Who is stalking Anne? self.assertQuerysetEqual( a.stalkers.all(), [ "Bill", ], attrgetter("name") ) # Who are Bill's idols? self.assertQuerysetEqual( b.idols.all(), [ "Anne", ], attrgetter("name") ) # Who is stalking Bill? self.assertQuerysetEqual( b.stalkers.all(), [] ) # Clear Anne's group of idols a.idols.clear() # Who are Anne's idols self.assertQuerysetEqual( a.idols.all(), [] ) # Reverse relationships should also be gone # Who is stalking Chuck? self.assertQuerysetEqual( c.stalkers.all(), [] ) # Who is friends with David? self.assertQuerysetEqual( d.stalkers.all(), [ "Chuck", ], attrgetter("name") )
6,784
Python
.py
242
16.458678
76
0.456532
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,346
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/delete/models.py
# coding: utf-8 """ Tests for some corner cases with deleting. """ from django.db import models class DefaultRepr(object): def __repr__(self): return u"<%s: %s>" % (self.__class__.__name__, self.__dict__) class A(DefaultRepr, models.Model): pass class B(DefaultRepr, models.Model): a = models.ForeignKey(A) class C(DefaultRepr, models.Model): b = models.ForeignKey(B) class D(DefaultRepr, models.Model): c = models.ForeignKey(C) a = models.ForeignKey(A) # Simplified, we have: # A # B -> A # C -> B # D -> C # D -> A # So, we must delete Ds first of all, then Cs then Bs then As. # However, if we start at As, we might find Bs first (in which # case things will be nice), or find Ds first. # Some mutually dependent models, but nullable class E(DefaultRepr, models.Model): f = models.ForeignKey('F', null=True, related_name='e_rel') class F(DefaultRepr, models.Model): e = models.ForeignKey(E, related_name='f_rel')
967
Python
.py
31
28.548387
69
0.686486
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,347
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/delete/tests.py
from django.db.models import sql from django.db.models.loading import cache from django.db.models.query import CollectedObjects from django.db.models.query_utils import CyclicDependency from django.test import TestCase from models import A, B, C, D, E, F class DeleteTests(TestCase): def clear_rel_obj_caches(self, *models): for m in models: if hasattr(m._meta, '_related_objects_cache'): del m._meta._related_objects_cache def order_models(self, *models): cache.app_models["delete"].keyOrder = models def setUp(self): self.order_models("a", "b", "c", "d", "e", "f") self.clear_rel_obj_caches(A, B, C, D, E, F) def tearDown(self): self.order_models("a", "b", "c", "d", "e", "f") self.clear_rel_obj_caches(A, B, C, D, E, F) def test_collected_objects(self): g = CollectedObjects() self.assertFalse(g.add("key1", 1, "item1", None)) self.assertEqual(g["key1"], {1: "item1"}) self.assertFalse(g.add("key2", 1, "item1", "key1")) self.assertFalse(g.add("key2", 2, "item2", "key1")) self.assertEqual(g["key2"], {1: "item1", 2: "item2"}) self.assertFalse(g.add("key3", 1, "item1", "key1")) self.assertTrue(g.add("key3", 1, "item1", "key2")) self.assertEqual(g.ordered_keys(), ["key3", "key2", "key1"]) self.assertTrue(g.add("key2", 1, "item1", "key3")) self.assertRaises(CyclicDependency, g.ordered_keys) def test_delete(self): ## Second, test the usage of CollectedObjects by Model.delete() # Due to the way that transactions work in the test harness, doing # m.delete() here can work but fail in a real situation, since it may # delete all objects, but not in the right order. So we manually check # that the order of deletion is correct. # Also, it is possible that the order is correct 'accidentally', due # solely to order of imports etc. To check this, we set the order that # 'get_models()' will retrieve to a known 'nice' order, and then try # again with a known 'tricky' order. Slightly naughty access to # internals here :-) # If implementation changes, then the tests may need to be simplified: # - remove the lines that set the .keyOrder and clear the related # object caches # - remove the second set of tests (with a2, b2 etc) a1 = A.objects.create() b1 = B.objects.create(a=a1) c1 = C.objects.create(b=b1) d1 = D.objects.create(c=c1, a=a1) o = CollectedObjects() a1._collect_sub_objects(o) self.assertEqual(o.keys(), [D, C, B, A]) a1.delete() # Same again with a known bad order self.order_models("d", "c", "b", "a") self.clear_rel_obj_caches(A, B, C, D) a2 = A.objects.create() b2 = B.objects.create(a=a2) c2 = C.objects.create(b=b2) d2 = D.objects.create(c=c2, a=a2) o = CollectedObjects() a2._collect_sub_objects(o) self.assertEqual(o.keys(), [D, C, B, A]) a2.delete() def test_collected_objects_null(self): g = CollectedObjects() self.assertFalse(g.add("key1", 1, "item1", None)) self.assertFalse(g.add("key2", 1, "item1", "key1", nullable=True)) self.assertTrue(g.add("key1", 1, "item1", "key2")) self.assertEqual(g.ordered_keys(), ["key1", "key2"]) def test_delete_nullable(self): e1 = E.objects.create() f1 = F.objects.create(e=e1) e1.f = f1 e1.save() # Since E.f is nullable, we should delete F first (after nulling out # the E.f field), then E. o = CollectedObjects() e1._collect_sub_objects(o) self.assertEqual(o.keys(), [F, E]) # temporarily replace the UpdateQuery class to verify that E.f is # actually nulled out first logged = [] class LoggingUpdateQuery(sql.UpdateQuery): def clear_related(self, related_field, pk_list, using): logged.append(related_field.name) return super(LoggingUpdateQuery, self).clear_related(related_field, pk_list, using) original = sql.UpdateQuery sql.UpdateQuery = LoggingUpdateQuery e1.delete() self.assertEqual(logged, ["f"]) logged = [] e2 = E.objects.create() f2 = F.objects.create(e=e2) e2.f = f2 e2.save() # Same deal as before, though we are starting from the other object. o = CollectedObjects() f2._collect_sub_objects(o) self.assertEqual(o.keys(), [F, E]) f2.delete() self.assertEqual(logged, ["f"]) logged = [] sql.UpdateQuery = original
4,819
Python
.py
105
37.142857
99
0.604611
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,348
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/custom_managers/models.py
""" 23. Giving models a custom manager You can use a custom ``Manager`` in a particular model by extending the base ``Manager`` class and instantiating your custom ``Manager`` in your model. There are two reasons you might want to customize a ``Manager``: to add extra ``Manager`` methods, and/or to modify the initial ``QuerySet`` the ``Manager`` returns. """ from django.db import models # An example of a custom manager called "objects". class PersonManager(models.Manager): def get_fun_people(self): return self.filter(fun=True) class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) fun = models.BooleanField() objects = PersonManager() def __unicode__(self): return u"%s %s" % (self.first_name, self.last_name) # An example of a custom manager that sets get_query_set(). class PublishedBookManager(models.Manager): def get_query_set(self): return super(PublishedBookManager, self).get_query_set().filter(is_published=True) class Book(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=30) is_published = models.BooleanField() published_objects = PublishedBookManager() authors = models.ManyToManyField(Person, related_name='books') def __unicode__(self): return self.title # An example of providing multiple custom managers. class FastCarManager(models.Manager): def get_query_set(self): return super(FastCarManager, self).get_query_set().filter(top_speed__gt=150) class Car(models.Model): name = models.CharField(max_length=10) mileage = models.IntegerField() top_speed = models.IntegerField(help_text="In miles per hour.") cars = models.Manager() fast_cars = FastCarManager() def __unicode__(self): return self.name
1,870
Python
.py
44
38.25
90
0.725014
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,349
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/custom_managers/tests.py
from django.test import TestCase from models import Person, Book, Car, PersonManager, PublishedBookManager class CustomManagerTests(TestCase): def test_manager(self): p1 = Person.objects.create(first_name="Bugs", last_name="Bunny", fun=True) p2 = Person.objects.create(first_name="Droopy", last_name="Dog", fun=False) self.assertQuerysetEqual( Person.objects.get_fun_people(), [ "Bugs Bunny" ], unicode ) # The RelatedManager used on the 'books' descriptor extends the default # manager self.assertTrue(isinstance(p2.books, PublishedBookManager)) b1 = Book.published_objects.create( title="How to program", author="Rodney Dangerfield", is_published=True ) b2 = Book.published_objects.create( title="How to be smart", author="Albert Einstein", is_published=False ) # The default manager, "objects", doesn't exist, because a custom one # was provided. self.assertRaises(AttributeError, lambda: Book.objects) # The RelatedManager used on the 'authors' descriptor extends the # default manager self.assertTrue(isinstance(b2.authors, PersonManager)) self.assertQuerysetEqual( Book.published_objects.all(), [ "How to program", ], lambda b: b.title ) c1 = Car.cars.create(name="Corvette", mileage=21, top_speed=180) c2 = Car.cars.create(name="Neon", mileage=31, top_speed=100) self.assertQuerysetEqual( Car.cars.order_by("name"), [ "Corvette", "Neon", ], lambda c: c.name ) self.assertQuerysetEqual( Car.fast_cars.all(), [ "Corvette", ], lambda c: c.name ) # Each model class gets a "_default_manager" attribute, which is a # reference to the first manager defined in the class. In this case, # it's "cars". self.assertQuerysetEqual( Car._default_manager.order_by("name"), [ "Corvette", "Neon", ], lambda c: c.name )
2,283
Python
.py
58
28.482759
83
0.580018
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,350
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/get_or_create/models.py
""" 33. get_or_create() ``get_or_create()`` does what it says: it tries to look up an object with the given parameters. If an object isn't found, it creates one with the given parameters. """ from django.db import models, IntegrityError class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) birthday = models.DateField() def __unicode__(self): return u'%s %s' % (self.first_name, self.last_name) class ManualPrimaryKeyTest(models.Model): id = models.IntegerField(primary_key=True) data = models.CharField(max_length=100)
623
Python
.py
16
35.625
77
0.729236
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,351
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/get_or_create/tests.py
from datetime import date from django.db import IntegrityError from django.test import TransactionTestCase from models import Person, ManualPrimaryKeyTest class GetOrCreateTests(TransactionTestCase): def test_get_or_create(self): p = Person.objects.create( first_name='John', last_name='Lennon', birthday=date(1940, 10, 9) ) p, created = Person.objects.get_or_create( first_name="John", last_name="Lennon", defaults={ "birthday": date(1940, 10, 9) } ) self.assertFalse(created) self.assertEqual(Person.objects.count(), 1) p, created = Person.objects.get_or_create( first_name='George', last_name='Harrison', defaults={ 'birthday': date(1943, 2, 25) } ) self.assertTrue(created) self.assertEqual(Person.objects.count(), 2) # If we execute the exact same statement, it won't create a Person. p, created = Person.objects.get_or_create( first_name='George', last_name='Harrison', defaults={ 'birthday': date(1943, 2, 25) } ) self.assertFalse(created) self.assertEqual(Person.objects.count(), 2) # If you don't specify a value or default value for all required # fields, you will get an error. self.assertRaises(IntegrityError, Person.objects.get_or_create, first_name="Tom", last_name="Smith" ) # If you specify an existing primary key, but different other fields, # then you will get an error and data will not be updated. m = ManualPrimaryKeyTest.objects.create(id=1, data="Original") self.assertRaises(IntegrityError, ManualPrimaryKeyTest.objects.get_or_create, id=1, data="Different" ) self.assertEqual(ManualPrimaryKeyTest.objects.get(id=1).data, "Original")
1,929
Python
.py
43
35.27907
81
0.634523
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,352
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/unmanaged_models/models.py
""" Models can have a ``managed`` attribute, which specifies whether the SQL code is generated for the table on various manage.py operations. """ from django.db import models # All of these models are creatd in the database by Django. class A01(models.Model): f_a = models.CharField(max_length=10, db_index=True) f_b = models.IntegerField() class Meta: db_table = 'A01' def __unicode__(self): return self.f_a class B01(models.Model): fk_a = models.ForeignKey(A01) f_a = models.CharField(max_length=10, db_index=True) f_b = models.IntegerField() class Meta: db_table = 'B01' # 'managed' is True by default. This tests we can set it explicitly. managed = True def __unicode__(self): return self.f_a class C01(models.Model): mm_a = models.ManyToManyField(A01, db_table='D01') f_a = models.CharField(max_length=10, db_index=True) f_b = models.IntegerField() class Meta: db_table = 'C01' def __unicode__(self): return self.f_a # All of these models use the same tables as the previous set (they are shadows # of possibly a subset of the columns). There should be no creation errors, # since we have told Django they aren't managed by Django. class A02(models.Model): f_a = models.CharField(max_length=10, db_index=True) class Meta: db_table = 'A01' managed = False def __unicode__(self): return self.f_a class B02(models.Model): class Meta: db_table = 'B01' managed = False fk_a = models.ForeignKey(A02) f_a = models.CharField(max_length=10, db_index=True) f_b = models.IntegerField() def __unicode__(self): return self.f_a # To re-use the many-to-many intermediate table, we need to manually set up # things up. class C02(models.Model): mm_a = models.ManyToManyField(A02, through="Intermediate") f_a = models.CharField(max_length=10, db_index=True) f_b = models.IntegerField() class Meta: db_table = 'C01' managed = False def __unicode__(self): return self.f_a class Intermediate(models.Model): a02 = models.ForeignKey(A02, db_column="a01_id") c02 = models.ForeignKey(C02, db_column="c01_id") class Meta: db_table = 'D01' managed = False # # These next models test the creation (or not) of many to many join tables # between managed and unmanaged models. A join table between two unmanaged # models shouldn't be automatically created (see #10647). # # Firstly, we need some models that will create the tables, purely so that the # tables are created. This is a test setup, not a requirement for unmanaged # models. class Proxy1(models.Model): class Meta: db_table = "unmanaged_models_proxy1" class Proxy2(models.Model): class Meta: db_table = "unmanaged_models_proxy2" class Unmanaged1(models.Model): class Meta: managed = False db_table = "unmanaged_models_proxy1" # Unmanged with an m2m to unmanaged: the intermediary table won't be created. class Unmanaged2(models.Model): mm = models.ManyToManyField(Unmanaged1) class Meta: managed = False db_table = "unmanaged_models_proxy2" # Here's an unmanaged model with an m2m to a managed one; the intermediary # table *will* be created (unless given a custom `through` as for C02 above). class Managed1(models.Model): mm = models.ManyToManyField(Unmanaged1)
3,475
Python
.py
95
31.642105
79
0.687761
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,353
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/unmanaged_models/tests.py
from django.test import TestCase from django.db import connection from models import Unmanaged1, Unmanaged2, Managed1 from models import A01, A02, B01, B02, C01, C02 class SimpleTests(TestCase): def test_simple(self): """ The main test here is that the all the models can be created without any database errors. We can also do some more simple insertion and lookup tests whilst we're here to show that the second of models do refer to the tables from the first set. """ # Insert some data into one set of models. a = A01.objects.create(f_a="foo", f_b=42) B01.objects.create(fk_a=a, f_a="fred", f_b=1729) c = C01.objects.create(f_a="barney", f_b=1) c.mm_a = [a] # ... and pull it out via the other set. a2 = A02.objects.all()[0] self.assertTrue(isinstance(a2, A02)) self.assertEqual(a2.f_a, "foo") b2 = B02.objects.all()[0] self.assertTrue(isinstance(b2, B02)) self.assertEqual(b2.f_a, "fred") self.assertTrue(isinstance(b2.fk_a, A02)) self.assertEqual(b2.fk_a.f_a, "foo") self.assertEqual(list(C02.objects.filter(f_a=None)), []) resp = list(C02.objects.filter(mm_a=a.id)) self.assertEqual(len(resp), 1) self.assertTrue(isinstance(resp[0], C02)) self.assertEqual(resp[0].f_a, 'barney') class ManyToManyUnmanagedTests(TestCase): def test_many_to_many_between_unmanaged(self): """ The intermediary table between two unmanaged models should not be created. """ table = Unmanaged2._meta.get_field('mm').m2m_db_table() tables = connection.introspection.table_names() self.assert_(table not in tables, "Table '%s' should not exist, but it does." % table) def test_many_to_many_between_unmanaged_and_managed(self): """ An intermediary table between a managed and an unmanaged model should be created. """ table = Managed1._meta.get_field('mm').m2m_db_table() tables = connection.introspection.table_names() self.assert_(table in tables, "Table '%s' does not exist." % table)
2,187
Python
.py
46
39.586957
94
0.646313
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,354
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/reverse_lookup/models.py
""" 25. Reverse lookups This demonstrates the reverse lookup features of the database API. """ from django.db import models class User(models.Model): name = models.CharField(max_length=200) def __unicode__(self): return self.name class Poll(models.Model): question = models.CharField(max_length=200) creator = models.ForeignKey(User) def __unicode__(self): return self.question class Choice(models.Model): name = models.CharField(max_length=100) poll = models.ForeignKey(Poll, related_name="poll_choice") related_poll = models.ForeignKey(Poll, related_name="related_choice") def __unicode__(self): return self.name
683
Python
.py
20
29.75
73
0.717557
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,355
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/reverse_lookup/tests.py
from django.test import TestCase from django.core.exceptions import FieldError from models import User, Poll, Choice class ReverseLookupTests(TestCase): def setUp(self): john = User.objects.create(name="John Doe") jim = User.objects.create(name="Jim Bo") first_poll = Poll.objects.create( question="What's the first question?", creator=john ) second_poll = Poll.objects.create( question="What's the second question?", creator=jim ) new_choice = Choice.objects.create( poll=first_poll, related_poll=second_poll, name="This is the answer." ) def test_reverse_by_field(self): u1 = User.objects.get( poll__question__exact="What's the first question?" ) self.assertEqual(u1.name, "John Doe") u2 = User.objects.get( poll__question__exact="What's the second question?" ) self.assertEqual(u2.name, "Jim Bo") def test_reverse_by_related_name(self): p1 = Poll.objects.get(poll_choice__name__exact="This is the answer.") self.assertEqual(p1.question, "What's the first question?") p2 = Poll.objects.get( related_choice__name__exact="This is the answer.") self.assertEqual(p2.question, "What's the second question?") def test_reverse_field_name_disallowed(self): """ If a related_name is given you can't use the field name instead """ self.assertRaises(FieldError, Poll.objects.get, choice__name__exact="This is the answer")
1,645
Python
.py
41
31.02439
77
0.619048
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,356
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/empty/models.py
""" 40. Empty model tests These test that things behave sensibly for the rare corner-case of a model with no fields. """ from django.db import models class Empty(models.Model): pass
190
Python
.py
8
21.75
79
0.780899
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,357
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/empty/tests.py
from django.test import TestCase from models import Empty class EmptyModelTests(TestCase): def test_empty(self): m = Empty() self.assertEqual(m.id, None) m.save() m2 = Empty.objects.create() self.assertEqual(len(Empty.objects.all()), 2) self.assertTrue(m.id is not None) existing = Empty(m.id) existing.save()
381
Python
.py
12
24.833333
53
0.639344
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,358
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/many_to_many/models.py
""" 5. Many-to-many relationships To define a many-to-many relationship, use ``ManyToManyField()``. In this example, an ``Article`` can be published in multiple ``Publication`` objects, and a ``Publication`` has multiple ``Article`` objects. """ from django.db import models class Publication(models.Model): title = models.CharField(max_length=30) def __unicode__(self): return self.title class Meta: ordering = ('title',) class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) def __unicode__(self): return self.headline class Meta: ordering = ('headline',)
697
Python
.py
20
30.4
76
0.702096
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,359
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/many_to_many/tests.py
from django.test import TestCase from models import Article, Publication class ManyToManyTests(TestCase): def setUp(self): # Create a couple of Publications. self.p1 = Publication.objects.create(id=None, title='The Python Journal') self.p2 = Publication.objects.create(id=None, title='Science News') self.p3 = Publication.objects.create(id=None, title='Science Weekly') self.p4 = Publication.objects.create(title='Highlights for Children') self.a1 = Article.objects.create(id=None, headline='Django lets you build Web apps easily') self.a1.publications.add(self.p1) self.a2 = Article.objects.create(id=None, headline='NASA uses Python') self.a2.publications.add(self.p1, self.p2, self.p3, self.p4) self.a3 = Article.objects.create(headline='NASA finds intelligent life on Earth') self.a3.publications.add(self.p2) self.a4 = Article.objects.create(headline='Oxygen-free diet works wonders') self.a4.publications.add(self.p2) def test_add(self): # Create an Article. a5 = Article(id=None, headline='Django lets you reate Web apps easily') # You can't associate it with a Publication until it's been saved. self.assertRaises(ValueError, getattr, a5, 'publications') # Save it! a5.save() # Associate the Article with a Publication. a5.publications.add(self.p1) self.assertQuerysetEqual(a5.publications.all(), ['<Publication: The Python Journal>']) # Create another Article, and set it to appear in both Publications. a6 = Article(id=None, headline='ESA uses Python') a6.save() a6.publications.add(self.p1, self.p2) a6.publications.add(self.p3) # Adding a second time is OK a6.publications.add(self.p3) self.assertQuerysetEqual(a6.publications.all(), [ '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ]) # Adding an object of the wrong type raises TypeError self.assertRaises(TypeError, a6.publications.add, a5) # Add a Publication directly via publications.add by using keyword arguments. p4 = a6.publications.create(title='Highlights for Adults') self.assertQuerysetEqual(a6.publications.all(), [ '<Publication: Highlights for Adults>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ]) def test_reverse_add(self): # Adding via the 'other' end of an m2m a5 = Article(headline='NASA finds intelligent life on Mars') a5.save() self.p2.article_set.add(a5) self.assertQuerysetEqual(self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: NASA finds intelligent life on Mars>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ]) self.assertQuerysetEqual(a5.publications.all(), ['<Publication: Science News>']) # Adding via the other end using keywords new_article = self.p2.article_set.create(headline='Carbon-free diet works wonders') self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: Carbon-free diet works wonders>', '<Article: NASA finds intelligent life on Earth>', '<Article: NASA finds intelligent life on Mars>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ]) a6 = self.p2.article_set.all()[3] self.assertQuerysetEqual(a6.publications.all(), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ]) def test_related_sets(self): # Article objects have access to their related Publication objects. self.assertQuerysetEqual(self.a1.publications.all(), ['<Publication: The Python Journal>']) self.assertQuerysetEqual(self.a2.publications.all(), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ]) # Publication objects have access to their related Article objects. self.assertQuerysetEqual(self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ]) self.assertQuerysetEqual(self.p1.article_set.all(), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA uses Python>', ]) self.assertQuerysetEqual(Publication.objects.get(id=self.p4.id).article_set.all(), ['<Article: NASA uses Python>']) def test_selects(self): # We can perform kwarg queries across m2m relationships self.assertQuerysetEqual( Article.objects.filter(publications__id__exact=self.p1.id), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA uses Python>', ]) self.assertQuerysetEqual( Article.objects.filter(publications__pk=self.p1.id), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA uses Python>', ]) self.assertQuerysetEqual( Article.objects.filter(publications=self.p1.id), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA uses Python>', ]) self.assertQuerysetEqual( Article.objects.filter(publications=self.p1), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA uses Python>', ]) self.assertQuerysetEqual( Article.objects.filter(publications__title__startswith="Science"), [ '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ]) self.assertQuerysetEqual( Article.objects.filter(publications__title__startswith="Science").distinct(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ]) # The count() function respects distinct() as well. self.assertEqual(Article.objects.filter(publications__title__startswith="Science").count(), 4) self.assertEqual(Article.objects.filter(publications__title__startswith="Science").distinct().count(), 3) self.assertQuerysetEqual( Article.objects.filter(publications__in=[self.p1.id,self.p2.id]).distinct(), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ]) self.assertQuerysetEqual( Article.objects.filter(publications__in=[self.p1.id,self.p2]).distinct(), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ]) self.assertQuerysetEqual( Article.objects.filter(publications__in=[self.p1,self.p2]).distinct(), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ]) # Excluding a related item works as you would expect, too (although the SQL # involved is a little complex). self.assertQuerysetEqual(Article.objects.exclude(publications=self.p2), ['<Article: Django lets you build Web apps easily>']) def test_reverse_selects(self): # Reverse m2m queries are supported (i.e., starting at the table that # doesn't have a ManyToManyField). self.assertQuerysetEqual(Publication.objects.filter(id__exact=self.p1.id), ['<Publication: The Python Journal>']) self.assertQuerysetEqual(Publication.objects.filter(pk=self.p1.id), ['<Publication: The Python Journal>']) self.assertQuerysetEqual( Publication.objects.filter(article__headline__startswith="NASA"), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ]) self.assertQuerysetEqual(Publication.objects.filter(article__id__exact=self.a1.id), ['<Publication: The Python Journal>']) self.assertQuerysetEqual(Publication.objects.filter(article__pk=self.a1.id), ['<Publication: The Python Journal>']) self.assertQuerysetEqual(Publication.objects.filter(article=self.a1.id), ['<Publication: The Python Journal>']) self.assertQuerysetEqual(Publication.objects.filter(article=self.a1), ['<Publication: The Python Journal>']) self.assertQuerysetEqual( Publication.objects.filter(article__in=[self.a1.id,self.a2.id]).distinct(), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ]) self.assertQuerysetEqual( Publication.objects.filter(article__in=[self.a1.id,self.a2]).distinct(), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ]) self.assertQuerysetEqual( Publication.objects.filter(article__in=[self.a1,self.a2]).distinct(), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ]) def test_delete(self): # If we delete a Publication, its Articles won't be able to access it. self.p1.delete() self.assertQuerysetEqual(Publication.objects.all(), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science Weekly>', ]) self.assertQuerysetEqual(self.a1.publications.all(), []) # If we delete an Article, its Publications won't be able to access it. self.a2.delete() self.assertQuerysetEqual(Article.objects.all(), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA finds intelligent life on Earth>', '<Article: Oxygen-free diet works wonders>', ]) self.assertQuerysetEqual(self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: Oxygen-free diet works wonders>', ]) def test_bulk_delete(self): # Bulk delete some Publications - references to deleted publications should go Publication.objects.filter(title__startswith='Science').delete() self.assertQuerysetEqual(Publication.objects.all(), [ '<Publication: Highlights for Children>', '<Publication: The Python Journal>', ]) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ]) self.assertQuerysetEqual(self.a2.publications.all(), [ '<Publication: Highlights for Children>', '<Publication: The Python Journal>', ]) # Bulk delete some articles - references to deleted objects should go q = Article.objects.filter(headline__startswith='Django') self.assertQuerysetEqual(q, ['<Article: Django lets you build Web apps easily>']) q.delete() # After the delete, the QuerySet cache needs to be cleared, # and the referenced objects should be gone self.assertQuerysetEqual(q, []) self.assertQuerysetEqual(self.p1.article_set.all(), ['<Article: NASA uses Python>']) def test_remove(self): # Removing publication from an article: self.assertQuerysetEqual(self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ]) self.a4.publications.remove(self.p2) self.assertQuerysetEqual(self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', ]) self.assertQuerysetEqual(self.a4.publications.all(), []) # And from the other end self.p2.article_set.remove(self.a3) self.assertQuerysetEqual(self.p2.article_set.all(), [ '<Article: NASA uses Python>', ]) self.assertQuerysetEqual(self.a3.publications.all(), []) def test_assign(self): # Relation sets can be assigned. Assignment clears any existing set members self.p2.article_set = [self.a4, self.a3] self.assertQuerysetEqual(self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: Oxygen-free diet works wonders>', ]) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science News>']) self.a4.publications = [self.p3.id] self.assertQuerysetEqual(self.p2.article_set.all(), ['<Article: NASA finds intelligent life on Earth>']) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science Weekly>']) # An alternate to calling clear() is to assign the empty set self.p2.article_set = [] self.assertQuerysetEqual(self.p2.article_set.all(), []) self.a4.publications = [] self.assertQuerysetEqual(self.a4.publications.all(), []) def test_assign_ids(self): # Relation sets can also be set using primary key values self.p2.article_set = [self.a4.id, self.a3.id] self.assertQuerysetEqual(self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: Oxygen-free diet works wonders>', ]) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science News>']) self.a4.publications = [self.p3.id] self.assertQuerysetEqual(self.p2.article_set.all(), ['<Article: NASA finds intelligent life on Earth>']) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science Weekly>']) def test_clear(self): # Relation sets can be cleared: self.p2.article_set.clear() self.assertQuerysetEqual(self.p2.article_set.all(), []) self.assertQuerysetEqual(self.a4.publications.all(), []) # And you can clear from the other end self.p2.article_set.add(self.a3, self.a4) self.assertQuerysetEqual(self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: Oxygen-free diet works wonders>', ]) self.assertQuerysetEqual(self.a4.publications.all(), [ '<Publication: Science News>', ]) self.a4.publications.clear() self.assertQuerysetEqual(self.a4.publications.all(), []) self.assertQuerysetEqual(self.p2.article_set.all(), ['<Article: NASA finds intelligent life on Earth>'])
17,756
Python
.py
359
36.13649
113
0.57915
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,360
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/or_lookups/models.py
""" 19. OR lookups To perform an OR lookup, or a lookup that combines ANDs and ORs, combine ``QuerySet`` objects using ``&`` and ``|`` operators. Alternatively, use positional arguments, and pass one or more expressions of clauses using the variable ``django.db.models.Q`` (or any object with an ``add_to_query`` method). """ from django.db import models class Article(models.Model): headline = models.CharField(max_length=50) pub_date = models.DateTimeField() class Meta: ordering = ('pub_date',) def __unicode__(self): return self.headline
579
Python
.py
16
32.875
76
0.714542
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,361
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/or_lookups/tests.py
from datetime import datetime from operator import attrgetter from django.db.models import Q from django.test import TestCase from models import Article class OrLookupsTests(TestCase): def setUp(self): self.a1 = Article.objects.create( headline='Hello', pub_date=datetime(2005, 11, 27) ).pk self.a2 = Article.objects.create( headline='Goodbye', pub_date=datetime(2005, 11, 28) ).pk self.a3 = Article.objects.create( headline='Hello and goodbye', pub_date=datetime(2005, 11, 29) ).pk def test_filter_or(self): self.assertQuerysetEqual( Article.objects.filter(headline__startswith='Hello') | Article.objects.filter(headline__startswith='Goodbye'), [ 'Hello', 'Goodbye', 'Hello and goodbye' ], attrgetter("headline") ) self.assertQuerysetEqual( Article.objects.filter(headline__contains='Hello') | Article.objects.filter(headline__contains='bye'), [ 'Hello', 'Goodbye', 'Hello and goodbye' ], attrgetter("headline") ) self.assertQuerysetEqual( Article.objects.filter(headline__iexact='Hello') | Article.objects.filter(headline__contains='ood'), [ 'Hello', 'Goodbye', 'Hello and goodbye' ], attrgetter("headline") ) self.assertQuerysetEqual( Article.objects.filter(Q(headline__startswith='Hello') | Q(headline__startswith='Goodbye')), [ 'Hello', 'Goodbye', 'Hello and goodbye' ], attrgetter("headline") ) def test_stages(self): # You can shorten this syntax with code like the following, which is # especially useful if building the query in stages: articles = Article.objects.all() self.assertQuerysetEqual( articles.filter(headline__startswith='Hello') & articles.filter(headline__startswith='Goodbye'), [] ) self.assertQuerysetEqual( articles.filter(headline__startswith='Hello') & articles.filter(headline__contains='bye'), [ 'Hello and goodbye' ], attrgetter("headline") ) def test_pk_q(self): self.assertQuerysetEqual( Article.objects.filter(Q(pk=self.a1) | Q(pk=self.a2)), [ 'Hello', 'Goodbye' ], attrgetter("headline") ) self.assertQuerysetEqual( Article.objects.filter(Q(pk=self.a1) | Q(pk=self.a2) | Q(pk=self.a3)), [ 'Hello', 'Goodbye', 'Hello and goodbye' ], attrgetter("headline"), ) def test_pk_in(self): self.assertQuerysetEqual( Article.objects.filter(pk__in=[self.a1, self.a2, self.a3]), [ 'Hello', 'Goodbye', 'Hello and goodbye' ], attrgetter("headline"), ) self.assertQuerysetEqual( Article.objects.filter(pk__in=(self.a1, self.a2, self.a3)), [ 'Hello', 'Goodbye', 'Hello and goodbye' ], attrgetter("headline"), ) self.assertQuerysetEqual( Article.objects.filter(pk__in=[self.a1, self.a2, self.a3, 40000]), [ 'Hello', 'Goodbye', 'Hello and goodbye' ], attrgetter("headline"), ) def test_q_negated(self): # Q objects can be negated self.assertQuerysetEqual( Article.objects.filter(Q(pk=self.a1) | ~Q(pk=self.a2)), [ 'Hello', 'Hello and goodbye' ], attrgetter("headline") ) self.assertQuerysetEqual( Article.objects.filter(~Q(pk=self.a1) & ~Q(pk=self.a2)), [ 'Hello and goodbye' ], attrgetter("headline"), ) # This allows for more complex queries than filter() and exclude() # alone would allow self.assertQuerysetEqual( Article.objects.filter(Q(pk=self.a1) & (~Q(pk=self.a2) | Q(pk=self.a3))), [ 'Hello' ], attrgetter("headline"), ) def test_complex_filter(self): # The 'complex_filter' method supports framework features such as # 'limit_choices_to' which normally take a single dictionary of lookup # arguments but need to support arbitrary queries via Q objects too. self.assertQuerysetEqual( Article.objects.complex_filter({'pk': self.a1}), [ 'Hello' ], attrgetter("headline"), ) self.assertQuerysetEqual( Article.objects.complex_filter(Q(pk=self.a1) | Q(pk=self.a2)), [ 'Hello', 'Goodbye' ], attrgetter("headline"), ) def test_empty_in(self): # Passing "in" an empty list returns no results ... self.assertQuerysetEqual( Article.objects.filter(pk__in=[]), [] ) # ... but can return results if we OR it with another query. self.assertQuerysetEqual( Article.objects.filter(Q(pk__in=[]) | Q(headline__icontains='goodbye')), [ 'Goodbye', 'Hello and goodbye' ], attrgetter("headline"), ) def test_q_and(self): # Q arg objects are ANDed self.assertQuerysetEqual( Article.objects.filter(Q(headline__startswith='Hello'), Q(headline__contains='bye')), [ 'Hello and goodbye' ], attrgetter("headline") ) # Q arg AND order is irrelevant self.assertQuerysetEqual( Article.objects.filter(Q(headline__contains='bye'), headline__startswith='Hello'), [ 'Hello and goodbye' ], attrgetter("headline"), ) self.assertQuerysetEqual( Article.objects.filter(Q(headline__startswith='Hello') & Q(headline__startswith='Goodbye')), [] ) def test_q_exclude(self): self.assertQuerysetEqual( Article.objects.exclude(Q(headline__startswith='Hello')), [ 'Goodbye' ], attrgetter("headline") ) def test_other_arg_queries(self): # Try some arg queries with operations other than filter. self.assertEqual( Article.objects.get(Q(headline__startswith='Hello'), Q(headline__contains='bye')).headline, 'Hello and goodbye' ) self.assertEqual( Article.objects.filter(Q(headline__startswith='Hello') | Q(headline__contains='bye')).count(), 3 ) self.assertQuerysetEqual( Article.objects.filter(Q(headline__startswith='Hello'), Q(headline__contains='bye')).values(), [ {"headline": "Hello and goodbye", "id": self.a3, "pub_date": datetime(2005, 11, 29)}, ], lambda o: o, ) self.assertEqual( Article.objects.filter(Q(headline__startswith='Hello')).in_bulk([self.a1, self.a2]), {self.a1: Article.objects.get(pk=self.a1)} )
7,584
Python
.py
204
25.45098
125
0.537133
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,362
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/get_object_or_404/models.py
""" 35. DB-API Shortcuts ``get_object_or_404()`` is a shortcut function to be used in view functions for performing a ``get()`` lookup and raising a ``Http404`` exception if a ``DoesNotExist`` exception was raised during the ``get()`` call. ``get_list_or_404()`` is a shortcut function to be used in view functions for performing a ``filter()`` lookup and raising a ``Http404`` exception if a ``DoesNotExist`` exception was raised during the ``filter()`` call. """ from django.db import models from django.http import Http404 from django.shortcuts import get_object_or_404, get_list_or_404 class Author(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class ArticleManager(models.Manager): def get_query_set(self): return super(ArticleManager, self).get_query_set().filter(authors__name__icontains='sir') class Article(models.Model): authors = models.ManyToManyField(Author) title = models.CharField(max_length=50) objects = models.Manager() by_a_sir = ArticleManager() def __unicode__(self): return self.title
1,120
Python
.py
26
39.615385
97
0.725599
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,363
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/get_object_or_404/tests.py
from django.http import Http404 from django.shortcuts import get_object_or_404, get_list_or_404 from django.test import TestCase from models import Author, Article class GetObjectOr404Tests(TestCase): def test_get_object_or_404(self): a1 = Author.objects.create(name="Brave Sir Robin") a2 = Author.objects.create(name="Patsy") # No Articles yet, so we should get a Http404 error. self.assertRaises(Http404, get_object_or_404, Article, title="Foo") article = Article.objects.create(title="Run away!") article.authors = [a1, a2] # get_object_or_404 can be passed a Model to query. self.assertEqual( get_object_or_404(Article, title__contains="Run"), article ) # We can also use the Article manager through an Author object. self.assertEqual( get_object_or_404(a1.article_set, title__contains="Run"), article ) # No articles containing "Camelot". This should raise a Http404 error. self.assertRaises(Http404, get_object_or_404, a1.article_set, title__contains="Camelot" ) # Custom managers can be used too. self.assertEqual( get_object_or_404(Article.by_a_sir, title="Run away!"), article ) # QuerySets can be used too. self.assertEqual( get_object_or_404(Article.objects.all(), title__contains="Run"), article ) # Just as when using a get() lookup, you will get an error if more than # one object is returned. self.assertRaises(Author.MultipleObjectsReturned, get_object_or_404, Author.objects.all() ) # Using an EmptyQuerySet raises a Http404 error. self.assertRaises(Http404, get_object_or_404, Article.objects.none(), title__contains="Run" ) # get_list_or_404 can be used to get lists of objects self.assertEqual( get_list_or_404(a1.article_set, title__icontains="Run"), [article] ) # Http404 is returned if the list is empty. self.assertRaises(Http404, get_list_or_404, a1.article_set, title__icontains="Shrubbery" ) # Custom managers can be used too. self.assertEqual( get_list_or_404(Article.by_a_sir, title__icontains="Run"), [article] ) # QuerySets can be used too. self.assertEqual( get_list_or_404(Article.objects.all(), title__icontains="Run"), [article] )
2,623
Python
.py
64
31.296875
79
0.613842
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,364
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/m2m_signals/models.py
from django.db import models class Part(models.Model): name = models.CharField(max_length=20) class Meta: ordering = ('name',) def __unicode__(self): return self.name class Car(models.Model): name = models.CharField(max_length=20) default_parts = models.ManyToManyField(Part) optional_parts = models.ManyToManyField(Part, related_name='cars_optional') class Meta: ordering = ('name',) def __unicode__(self): return self.name class SportsCar(Car): price = models.IntegerField() class Person(models.Model): name = models.CharField(max_length=20) fans = models.ManyToManyField('self', related_name='idols', symmetrical=False) friends = models.ManyToManyField('self') class Meta: ordering = ('name',) def __unicode__(self): return self.name
852
Python
.py
25
28.48
82
0.677696
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,365
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/m2m_signals/tests.py
""" Testing signals emitted on changing m2m relations. """ from django.db import models from django.test import TestCase from models import Part, Car, SportsCar, Person class ManyToManySignalsTest(TestCase): def m2m_changed_signal_receiver(self, signal, sender, **kwargs): message = { 'instance': kwargs['instance'], 'action': kwargs['action'], 'reverse': kwargs['reverse'], 'model': kwargs['model'], } if kwargs['pk_set']: message['objects'] = list( kwargs['model'].objects.filter(pk__in=kwargs['pk_set']) ) self.m2m_changed_messages.append(message) def setUp(self): self.m2m_changed_messages = [] self.vw = Car.objects.create(name='VW') self.bmw = Car.objects.create(name='BMW') self.toyota = Car.objects.create(name='Toyota') self.wheelset = Part.objects.create(name='Wheelset') self.doors = Part.objects.create(name='Doors') self.engine = Part.objects.create(name='Engine') self.airbag = Part.objects.create(name='Airbag') self.sunroof = Part.objects.create(name='Sunroof') self.alice = Person.objects.create(name='Alice') self.bob = Person.objects.create(name='Bob') self.chuck = Person.objects.create(name='Chuck') self.daisy = Person.objects.create(name='Daisy') def tearDown(self): # disconnect all signal handlers models.signals.m2m_changed.disconnect( self.m2m_changed_signal_receiver, Car.default_parts.through ) models.signals.m2m_changed.disconnect( self.m2m_changed_signal_receiver, Car.optional_parts.through ) models.signals.m2m_changed.disconnect( self.m2m_changed_signal_receiver, Person.fans.through ) models.signals.m2m_changed.disconnect( self.m2m_changed_signal_receiver, Person.friends.through ) def test_m2m_relations_add_remove_clear(self): expected_messages = [] # Install a listener on one of the two m2m relations. models.signals.m2m_changed.connect( self.m2m_changed_signal_receiver, Car.optional_parts.through ) # Test the add, remove and clear methods on both sides of the # many-to-many relation # adding a default part to our car - no signal listener installed self.vw.default_parts.add(self.sunroof) # Now install a listener models.signals.m2m_changed.connect( self.m2m_changed_signal_receiver, Car.default_parts.through ) self.vw.default_parts.add(self.wheelset, self.doors, self.engine) expected_messages.append({ 'instance': self.vw, 'action': 'pre_add', 'reverse': False, 'model': Part, 'objects': [self.doors, self.engine, self.wheelset], }) expected_messages.append({ 'instance': self.vw, 'action': 'post_add', 'reverse': False, 'model': Part, 'objects': [self.doors, self.engine, self.wheelset], }) self.assertEqual(self.m2m_changed_messages, expected_messages) # give the BMW and Toyata some doors as well self.doors.car_set.add(self.bmw, self.toyota) expected_messages.append({ 'instance': self.doors, 'action': 'pre_add', 'reverse': True, 'model': Car, 'objects': [self.bmw, self.toyota], }) expected_messages.append({ 'instance': self.doors, 'action': 'post_add', 'reverse': True, 'model': Car, 'objects': [self.bmw, self.toyota], }) self.assertEqual(self.m2m_changed_messages, expected_messages) # remove the engine from the self.vw and the airbag (which is not set # but is returned) self.vw.default_parts.remove(self.engine, self.airbag) expected_messages.append({ 'instance': self.vw, 'action': 'pre_remove', 'reverse': False, 'model': Part, 'objects': [self.airbag, self.engine], }) expected_messages.append({ 'instance': self.vw, 'action': 'post_remove', 'reverse': False, 'model': Part, 'objects': [self.airbag, self.engine], }) self.assertEqual(self.m2m_changed_messages, expected_messages) # give the self.vw some optional parts (second relation to same model) self.vw.optional_parts.add(self.airbag, self.sunroof) expected_messages.append({ 'instance': self.vw, 'action': 'pre_add', 'reverse': False, 'model': Part, 'objects': [self.airbag, self.sunroof], }) expected_messages.append({ 'instance': self.vw, 'action': 'post_add', 'reverse': False, 'model': Part, 'objects': [self.airbag, self.sunroof], }) self.assertEqual(self.m2m_changed_messages, expected_messages) # add airbag to all the cars (even though the self.vw already has one) self.airbag.cars_optional.add(self.vw, self.bmw, self.toyota) expected_messages.append({ 'instance': self.airbag, 'action': 'pre_add', 'reverse': True, 'model': Car, 'objects': [self.bmw, self.toyota], }) expected_messages.append({ 'instance': self.airbag, 'action': 'post_add', 'reverse': True, 'model': Car, 'objects': [self.bmw, self.toyota], }) self.assertEqual(self.m2m_changed_messages, expected_messages) # remove airbag from the self.vw (reverse relation with custom # related_name) self.airbag.cars_optional.remove(self.vw) expected_messages.append({ 'instance': self.airbag, 'action': 'pre_remove', 'reverse': True, 'model': Car, 'objects': [self.vw], }) expected_messages.append({ 'instance': self.airbag, 'action': 'post_remove', 'reverse': True, 'model': Car, 'objects': [self.vw], }) self.assertEqual(self.m2m_changed_messages, expected_messages) # clear all parts of the self.vw self.vw.default_parts.clear() expected_messages.append({ 'instance': self.vw, 'action': 'pre_clear', 'reverse': False, 'model': Part, }) expected_messages.append({ 'instance': self.vw, 'action': 'post_clear', 'reverse': False, 'model': Part, }) self.assertEqual(self.m2m_changed_messages, expected_messages) # take all the doors off of cars self.doors.car_set.clear() expected_messages.append({ 'instance': self.doors, 'action': 'pre_clear', 'reverse': True, 'model': Car, }) expected_messages.append({ 'instance': self.doors, 'action': 'post_clear', 'reverse': True, 'model': Car, }) self.assertEqual(self.m2m_changed_messages, expected_messages) # take all the airbags off of cars (clear reverse relation with custom # related_name) self.airbag.cars_optional.clear() expected_messages.append({ 'instance': self.airbag, 'action': 'pre_clear', 'reverse': True, 'model': Car, }) expected_messages.append({ 'instance': self.airbag, 'action': 'post_clear', 'reverse': True, 'model': Car, }) self.assertEqual(self.m2m_changed_messages, expected_messages) # alternative ways of setting relation: self.vw.default_parts.create(name='Windows') p6 = Part.objects.get(name='Windows') expected_messages.append({ 'instance': self.vw, 'action': 'pre_add', 'reverse': False, 'model': Part, 'objects': [p6], }) expected_messages.append({ 'instance': self.vw, 'action': 'post_add', 'reverse': False, 'model': Part, 'objects': [p6], }) self.assertEqual(self.m2m_changed_messages, expected_messages) # direct assignment clears the set first, then adds self.vw.default_parts = [self.wheelset,self.doors,self.engine] expected_messages.append({ 'instance': self.vw, 'action': 'pre_clear', 'reverse': False, 'model': Part, }) expected_messages.append({ 'instance': self.vw, 'action': 'post_clear', 'reverse': False, 'model': Part, }) expected_messages.append({ 'instance': self.vw, 'action': 'pre_add', 'reverse': False, 'model': Part, 'objects': [self.doors, self.engine, self.wheelset], }) expected_messages.append({ 'instance': self.vw, 'action': 'post_add', 'reverse': False, 'model': Part, 'objects': [self.doors, self.engine, self.wheelset], }) self.assertEqual(self.m2m_changed_messages, expected_messages) # Check that signals still work when model inheritance is involved c4 = SportsCar.objects.create(name='Bugatti', price='1000000') c4b = Car.objects.get(name='Bugatti') c4.default_parts = [self.doors] expected_messages.append({ 'instance': c4, 'action': 'pre_clear', 'reverse': False, 'model': Part, }) expected_messages.append({ 'instance': c4, 'action': 'post_clear', 'reverse': False, 'model': Part, }) expected_messages.append({ 'instance': c4, 'action': 'pre_add', 'reverse': False, 'model': Part, 'objects': [self.doors], }) expected_messages.append({ 'instance': c4, 'action': 'post_add', 'reverse': False, 'model': Part, 'objects': [self.doors], }) self.assertEqual(self.m2m_changed_messages, expected_messages) self.engine.car_set.add(c4) expected_messages.append({ 'instance': self.engine, 'action': 'pre_add', 'reverse': True, 'model': Car, 'objects': [c4b], }) expected_messages.append({ 'instance': self.engine, 'action': 'post_add', 'reverse': True, 'model': Car, 'objects': [c4b], }) self.assertEqual(self.m2m_changed_messages, expected_messages) def test_m2m_relations_with_self(self): expected_messages = [] models.signals.m2m_changed.connect( self.m2m_changed_signal_receiver, Person.fans.through ) models.signals.m2m_changed.connect( self.m2m_changed_signal_receiver, Person.friends.through ) self.alice.friends = [self.bob, self.chuck] expected_messages.append({ 'instance': self.alice, 'action': 'pre_clear', 'reverse': False, 'model': Person, }) expected_messages.append({ 'instance': self.alice, 'action': 'post_clear', 'reverse': False, 'model': Person, }) expected_messages.append({ 'instance': self.alice, 'action': 'pre_add', 'reverse': False, 'model': Person, 'objects': [self.bob, self.chuck], }) expected_messages.append({ 'instance': self.alice, 'action': 'post_add', 'reverse': False, 'model': Person, 'objects': [self.bob, self.chuck], }) self.assertEqual(self.m2m_changed_messages, expected_messages) self.alice.fans = [self.daisy] expected_messages.append({ 'instance': self.alice, 'action': 'pre_clear', 'reverse': False, 'model': Person, }) expected_messages.append({ 'instance': self.alice, 'action': 'post_clear', 'reverse': False, 'model': Person, }) expected_messages.append({ 'instance': self.alice, 'action': 'pre_add', 'reverse': False, 'model': Person, 'objects': [self.daisy], }) expected_messages.append({ 'instance': self.alice, 'action': 'post_add', 'reverse': False, 'model': Person, 'objects': [self.daisy], }) self.assertEqual(self.m2m_changed_messages, expected_messages) self.chuck.idols = [self.alice,self.bob] expected_messages.append({ 'instance': self.chuck, 'action': 'pre_clear', 'reverse': True, 'model': Person, }) expected_messages.append({ 'instance': self.chuck, 'action': 'post_clear', 'reverse': True, 'model': Person, }) expected_messages.append({ 'instance': self.chuck, 'action': 'pre_add', 'reverse': True, 'model': Person, 'objects': [self.alice, self.bob], }) expected_messages.append({ 'instance': self.chuck, 'action': 'post_add', 'reverse': True, 'model': Person, 'objects': [self.alice, self.bob], }) self.assertEqual(self.m2m_changed_messages, expected_messages)
14,283
Python
.py
396
25.060606
78
0.538034
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,366
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/custom_columns/models.py
""" 17. Custom column/table names If your database column name is different than your model attribute, use the ``db_column`` parameter. Note that you'll use the field's name, not its column name, in API usage. If your database table name is different than your model name, use the ``db_table`` Meta attribute. This has no effect on the API used to query the database. If you need to use a table name for a many-to-many relationship that differs from the default generated name, use the ``db_table`` parameter on the ``ManyToManyField``. This has no effect on the API for querying the database. """ from django.db import models class Author(models.Model): first_name = models.CharField(max_length=30, db_column='firstname') last_name = models.CharField(max_length=30, db_column='last') def __unicode__(self): return u'%s %s' % (self.first_name, self.last_name) class Meta: db_table = 'my_author_table' ordering = ('last_name','first_name') class Article(models.Model): headline = models.CharField(max_length=100) authors = models.ManyToManyField(Author, db_table='my_m2m_table') def __unicode__(self): return self.headline class Meta: ordering = ('headline',)
1,243
Python
.py
28
40.392857
78
0.72153
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,367
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/custom_columns/tests.py
from django.core.exceptions import FieldError from django.test import TestCase from models import Author, Article class CustomColumnsTests(TestCase): def test_db_column(self): a1 = Author.objects.create(first_name="John", last_name="Smith") a2 = Author.objects.create(first_name="Peter", last_name="Jones") art = Article.objects.create(headline="Django lets you build Web apps easily") art.authors = [a1, a2] # Although the table and column names on Author have been set to custom # values, nothing about using the Author model has changed... # Query the available authors self.assertQuerysetEqual( Author.objects.all(), [ "Peter Jones", "John Smith", ], unicode ) self.assertQuerysetEqual( Author.objects.filter(first_name__exact="John"), [ "John Smith", ], unicode ) self.assertEqual( Author.objects.get(first_name__exact="John"), a1, ) self.assertRaises(FieldError, lambda: Author.objects.filter(firstname__exact="John") ) a = Author.objects.get(last_name__exact="Smith") a.first_name = "John" a.last_name = "Smith" self.assertRaises(AttributeError, lambda: a.firstname) self.assertRaises(AttributeError, lambda: a.last) # Although the Article table uses a custom m2m table, # nothing about using the m2m relationship has changed... # Get all the authors for an article self.assertQuerysetEqual( art.authors.all(), [ "Peter Jones", "John Smith", ], unicode ) # Get the articles for an author self.assertQuerysetEqual( a.article_set.all(), [ "Django lets you build Web apps easily", ], lambda a: a.headline ) # Query the authors across the m2m relation self.assertQuerysetEqual( art.authors.filter(last_name='Jones'), [ "Peter Jones" ], unicode )
2,224
Python
.py
60
26.483333
86
0.579192
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,368
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/m2m_intermediary/models.py
""" 9. Many-to-many relationships via an intermediary table For many-to-many relationships that need extra fields on the intermediary table, use an intermediary model. In this example, an ``Article`` can have multiple ``Reporter`` objects, and each ``Article``-``Reporter`` combination (a ``Writer``) has a ``position`` field, which specifies the ``Reporter``'s position for the given article (e.g. "Staff writer"). """ from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def __unicode__(self): return u"%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() def __unicode__(self): return self.headline class Writer(models.Model): reporter = models.ForeignKey(Reporter) article = models.ForeignKey(Article) position = models.CharField(max_length=100) def __unicode__(self): return u'%s (%s)' % (self.reporter, self.position)
1,086
Python
.py
26
37.923077
75
0.71619
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,369
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/m2m_intermediary/tests.py
from datetime import datetime from django.test import TestCase from models import Reporter, Article, Writer class M2MIntermediaryTests(TestCase): def test_intermeiary(self): r1 = Reporter.objects.create(first_name="John", last_name="Smith") r2 = Reporter.objects.create(first_name="Jane", last_name="Doe") a = Article.objects.create( headline="This is a test", pub_date=datetime(2005, 7, 27) ) w1 = Writer.objects.create(reporter=r1, article=a, position="Main writer") w2 = Writer.objects.create(reporter=r2, article=a, position="Contributor") self.assertQuerysetEqual( a.writer_set.select_related().order_by("-position"), [ ("John Smith", "Main writer"), ("Jane Doe", "Contributor"), ], lambda w: (unicode(w.reporter), w.position) ) self.assertEqual(w1.reporter, r1) self.assertEqual(w2.reporter, r2) self.assertEqual(w1.article, a) self.assertEqual(w2.article, a) self.assertQuerysetEqual( r1.writer_set.all(), [ ("John Smith", "Main writer") ], lambda w: (unicode(w.reporter), w.position) )
1,251
Python
.py
29
33.275862
82
0.610882
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,370
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/update/models.py
""" Tests for the update() queryset method that allows in-place, multi-object updates. """ from django.db import models class DataPoint(models.Model): name = models.CharField(max_length=20) value = models.CharField(max_length=20) another_value = models.CharField(max_length=20, blank=True) def __unicode__(self): return unicode(self.name) class RelatedPoint(models.Model): name = models.CharField(max_length=20) data = models.ForeignKey(DataPoint) def __unicode__(self): return unicode(self.name) class A(models.Model): x = models.IntegerField(default=10) class B(models.Model): a = models.ForeignKey(A) y = models.IntegerField(default=10) class C(models.Model): y = models.IntegerField(default=10) class D(C): a = models.ForeignKey(A)
810
Python
.py
25
28.44
73
0.72
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,371
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/update/tests.py
from django.test import TestCase from models import A, B, C, D, DataPoint, RelatedPoint class SimpleTest(TestCase): def setUp(self): self.a1 = A.objects.create() self.a2 = A.objects.create() for x in range(20): B.objects.create(a=self.a1) D.objects.create(a=self.a1) def test_nonempty_update(self): """ Test that update changes the right number of rows for a nonempty queryset """ num_updated = self.a1.b_set.update(y=100) self.assertEqual(num_updated, 20) cnt = B.objects.filter(y=100).count() self.assertEqual(cnt, 20) def test_empty_update(self): """ Test that update changes the right number of rows for an empty queryset """ num_updated = self.a2.b_set.update(y=100) self.assertEqual(num_updated, 0) cnt = B.objects.filter(y=100).count() self.assertEqual(cnt, 0) def test_nonempty_update_with_inheritance(self): """ Test that update changes the right number of rows for an empty queryset when the update affects only a base table """ num_updated = self.a1.d_set.update(y=100) self.assertEqual(num_updated, 20) cnt = D.objects.filter(y=100).count() self.assertEqual(cnt, 20) def test_empty_update_with_inheritance(self): """ Test that update changes the right number of rows for an empty queryset when the update affects only a base table """ num_updated = self.a2.d_set.update(y=100) self.assertEqual(num_updated, 0) cnt = D.objects.filter(y=100).count() self.assertEqual(cnt, 0) class AdvancedTests(TestCase): def setUp(self): self.d0 = DataPoint.objects.create(name="d0", value="apple") self.d2 = DataPoint.objects.create(name="d2", value="banana") self.d3 = DataPoint.objects.create(name="d3", value="banana") self.r1 = RelatedPoint.objects.create(name="r1", data=self.d3) def test_update(self): """ Objects are updated by first filtering the candidates into a queryset and then calling the update() method. It executes immediately and returns nothing. """ resp = DataPoint.objects.filter(value="apple").update(name="d1") self.assertEqual(resp, 1) resp = DataPoint.objects.filter(value="apple") self.assertEqual(list(resp), [self.d0]) def test_update_multiple_objects(self): """ We can update multiple objects at once. """ resp = DataPoint.objects.filter(value="banana").update( value="pineapple") self.assertEqual(resp, 2) self.assertEqual(DataPoint.objects.get(name="d2").value, u'pineapple') def test_update_fk(self): """ Foreign key fields can also be updated, although you can only update the object referred to, not anything inside the related object. """ resp = RelatedPoint.objects.filter(name="r1").update(data=self.d0) self.assertEqual(resp, 1) resp = RelatedPoint.objects.filter(data__name="d0") self.assertEqual(list(resp), [self.r1]) def test_update_multiple_fields(self): """ Multiple fields can be updated at once """ resp = DataPoint.objects.filter(value="apple").update( value="fruit", another_value="peach") self.assertEqual(resp, 1) d = DataPoint.objects.get(name="d0") self.assertEqual(d.value, u'fruit') self.assertEqual(d.another_value, u'peach') def test_update_all(self): """ In the rare case you want to update every instance of a model, update() is also a manager method. """ self.assertEqual(DataPoint.objects.update(value='thing'), 3) resp = DataPoint.objects.values('value').distinct() self.assertEqual(list(resp), [{'value': u'thing'}]) def test_update_slice_fail(self): """ We do not support update on already sliced query sets. """ method = DataPoint.objects.all()[:2].update self.assertRaises(AssertionError, method, another_value='another thing')
4,252
Python
.py
101
33.544554
81
0.631286
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,372
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/defer/models.py
""" Tests for defer() and only(). """ from django.db import models class Secondary(models.Model): first = models.CharField(max_length=50) second = models.CharField(max_length=50) class Primary(models.Model): name = models.CharField(max_length=50) value = models.CharField(max_length=50) related = models.ForeignKey(Secondary) def __unicode__(self): return self.name class Child(Primary): pass class BigChild(Primary): other = models.CharField(max_length=50)
505
Python
.py
17
25.941176
44
0.723493
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,373
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/defer/tests.py
from django.db.models.query_utils import DeferredAttribute from django.test import TestCase from models import Secondary, Primary, Child, BigChild class DeferTests(TestCase): def assert_delayed(self, obj, num): count = 0 for field in obj._meta.fields: if isinstance(obj.__class__.__dict__.get(field.attname), DeferredAttribute): count += 1 self.assertEqual(count, num) def test_defer(self): # To all outward appearances, instances with deferred fields look the # same as normal instances when we examine attribute values. Therefore # we test for the number of deferred fields on returned instances (by # poking at the internals), as a way to observe what is going on. s1 = Secondary.objects.create(first="x1", second="y1") p1 = Primary.objects.create(name="p1", value="xx", related=s1) qs = Primary.objects.all() self.assert_delayed(qs.defer("name")[0], 1) self.assert_delayed(qs.only("name")[0], 2) self.assert_delayed(qs.defer("related__first")[0], 0) obj = qs.select_related().only("related__first")[0] self.assert_delayed(obj, 2) self.assertEqual(obj.related_id, s1.pk) self.assert_delayed(qs.defer("name").extra(select={"a": 1})[0], 1) self.assert_delayed(qs.extra(select={"a": 1}).defer("name")[0], 1) self.assert_delayed(qs.defer("name").defer("value")[0], 2) self.assert_delayed(qs.only("name").only("value")[0], 2) self.assert_delayed(qs.only("name").defer("value")[0], 2) self.assert_delayed(qs.only("name", "value").defer("value")[0], 2) self.assert_delayed(qs.defer("name").only("value")[0], 2) obj = qs.only()[0] self.assert_delayed(qs.defer(None)[0], 0) self.assert_delayed(qs.only("name").defer(None)[0], 0) # User values() won't defer anything (you get the full list of # dictionaries back), but it still works. self.assertEqual(qs.defer("name").values()[0], { "id": p1.id, "name": "p1", "value": "xx", "related_id": s1.id, }) self.assertEqual(qs.only("name").values()[0], { "id": p1.id, "name": "p1", "value": "xx", "related_id": s1.id, }) # Using defer() and only() with get() is also valid. self.assert_delayed(qs.defer("name").get(pk=p1.pk), 1) self.assert_delayed(qs.only("name").get(pk=p1.pk), 2) # DOES THIS WORK? self.assert_delayed(qs.only("name").select_related("related")[0], 1) self.assert_delayed(qs.defer("related").select_related("related")[0], 0) # Saving models with deferred fields is possible (but inefficient, # since every field has to be retrieved first). obj = Primary.objects.defer("value").get(name="p1") obj.name = "a new name" obj.save() self.assertQuerysetEqual( Primary.objects.all(), [ "a new name", ], lambda p: p.name ) # Regression for #10572 - A subclass with no extra fields can defer # fields from the base class Child.objects.create(name="c1", value="foo", related=s1) # You can defer a field on a baseclass when the subclass has no fields obj = Child.objects.defer("value").get(name="c1") self.assert_delayed(obj, 1) self.assertEqual(obj.name, "c1") self.assertEqual(obj.value, "foo") obj.name = "c2" obj.save() # You can retrive a single column on a base class with no fields obj = Child.objects.only("name").get(name="c2") self.assert_delayed(obj, 3) self.assertEqual(obj.name, "c2") self.assertEqual(obj.value, "foo") obj.name = "cc" obj.save() BigChild.objects.create(name="b1", value="foo", related=s1, other="bar") # You can defer a field on a baseclass obj = BigChild.objects.defer("value").get(name="b1") self.assert_delayed(obj, 1) self.assertEqual(obj.name, "b1") self.assertEqual(obj.value, "foo") self.assertEqual(obj.other, "bar") obj.name = "b2" obj.save() # You can defer a field on a subclass obj = BigChild.objects.defer("other").get(name="b2") self.assert_delayed(obj, 1) self.assertEqual(obj.name, "b2") self.assertEqual(obj.value, "foo") self.assertEqual(obj.other, "bar") obj.name = "b3" obj.save() # You can retrieve a single field on a baseclass obj = BigChild.objects.only("name").get(name="b3") self.assert_delayed(obj, 4) self.assertEqual(obj.name, "b3") self.assertEqual(obj.value, "foo") self.assertEqual(obj.other, "bar") obj.name = "b4" obj.save() # You can retrieve a single field on a baseclass obj = BigChild.objects.only("other").get(name="b4") self.assert_delayed(obj, 4) self.assertEqual(obj.name, "b4") self.assertEqual(obj.value, "foo") self.assertEqual(obj.other, "bar") obj.name = "bb" obj.save()
5,272
Python
.py
116
35.991379
80
0.594158
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,374
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/model_package/tests.py
from django.contrib.sites.models import Site from django.db import models from django.test import TestCase from models.publication import Publication from models.article import Article class Advertisment(models.Model): customer = models.CharField(max_length=100) publications = models.ManyToManyField( "model_package.Publication", null=True, blank=True ) class Meta: app_label = 'model_package' class ModelPackageTests(TestCase): def test_model_packages(self): p = Publication.objects.create(title="FooBar") current_site = Site.objects.get_current() self.assertEqual(current_site.domain, "example.com") # Regression for #12168: models split into subpackages still get M2M # tables a = Article.objects.create(headline="a foo headline") a.publications.add(p) a.sites.add(current_site) a = Article.objects.get(id=a.pk) self.assertEqual(a.id, a.pk) self.assertEqual(a.sites.count(), 1) # Regression for #12245 - Models can exist in the test package, too ad = Advertisment.objects.create(customer="Lawrence Journal-World") ad.publications.add(p) ad = Advertisment.objects.get(id=ad.pk) self.assertEqual(ad.publications.count(), 1) # Regression for #12386 - field names on the autogenerated intermediate # class that are specified as dotted strings don't retain any path # component for the field or column name self.assertEqual( Article.publications.through._meta.fields[1].name, 'article' ) self.assertEqual( Article.publications.through._meta.fields[1].get_attname_column(), ('article_id', 'article_id') ) self.assertEqual( Article.publications.through._meta.fields[2].name, 'publication' ) self.assertEqual( Article.publications.through._meta.fields[2].get_attname_column(), ('publication_id', 'publication_id') ) # The oracle backend truncates the name to 'model_package_article_publ233f'. self.assertTrue( Article._meta.get_field('publications').m2m_db_table() in ('model_package_article_publications', 'model_package_article_publ233f') ) self.assertEqual( Article._meta.get_field('publications').m2m_column_name(), 'article_id' ) self.assertEqual( Article._meta.get_field('publications').m2m_reverse_name(), 'publication_id' )
2,570
Python
.py
58
35.689655
142
0.66293
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,375
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/model_package/models/__init__.py
# Import all the models from subpackages from article import Article from publication import Publication
105
Python
.py
3
34
40
0.872549
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,376
article.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/model_package/models/article.py
from django.db import models from django.contrib.sites.models import Site class Article(models.Model): sites = models.ManyToManyField(Site) headline = models.CharField(max_length=100) publications = models.ManyToManyField("model_package.Publication", null=True, blank=True,) class Meta: app_label = 'model_package'
341
Python
.py
8
38.375
94
0.761329
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,377
publication.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/model_package/models/publication.py
from django.db import models class Publication(models.Model): title = models.CharField(max_length=30) class Meta: app_label = 'model_package'
160
Python
.py
5
27.4
43
0.72549
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,378
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/fixtures_model_package/tests.py
from django.core import management from django.test import TestCase from models import Article class SampleTestCase(TestCase): fixtures = ['fixture1.json', 'fixture2.json'] def testClassFixtures(self): "Test cases can load fixture objects into models defined in packages" self.assertEqual(Article.objects.count(), 4) self.assertQuerysetEqual( Article.objects.all(),[ "Django conquers world!", "Copyright is fine the way it is", "Poker has no place on ESPN", "Python program becomes self aware" ], lambda a: a.headline ) class FixtureTestCase(TestCase): def test_initial_data(self): "Fixtures can load initial data into models defined in packages" #Syncdb introduces 1 initial data object from initial_data.json self.assertQuerysetEqual( Article.objects.all(), [ "Python program becomes self aware" ], lambda a: a.headline ) def test_loaddata(self): "Fixtures can load data into models defined in packages" # Load fixture 1. Single JSON file, with two objects management.call_command("loaddata", "fixture1.json", verbosity=0, commit=False) self.assertQuerysetEqual( Article.objects.all(), [ "Time to reform copyright", "Poker has no place on ESPN", "Python program becomes self aware", ], lambda a: a.headline, ) # Load fixture 2. JSON file imported by default. Overwrites some # existing objects management.call_command("loaddata", "fixture2.json", verbosity=0, commit=False) self.assertQuerysetEqual( Article.objects.all(), [ "Django conquers world!", "Copyright is fine the way it is", "Poker has no place on ESPN", "Python program becomes self aware", ], lambda a: a.headline, ) # Load a fixture that doesn't exist management.call_command("loaddata", "unknown.json", verbosity=0, commit=False) self.assertQuerysetEqual( Article.objects.all(), [ "Django conquers world!", "Copyright is fine the way it is", "Poker has no place on ESPN", "Python program becomes self aware", ], lambda a: a.headline, )
2,540
Python
.py
62
29.693548
87
0.590117
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,379
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/fixtures_model_package/models/__init__.py
from django.db import models from django.conf import settings class Article(models.Model): headline = models.CharField(max_length=100, default='Default headline') pub_date = models.DateTimeField() def __unicode__(self): return self.headline class Meta: app_label = 'fixtures_model_package' ordering = ('-pub_date', 'headline')
371
Python
.py
10
31.7
75
0.70028
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,380
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/model_formsets/models.py
import datetime from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Meta: ordering = ('name',) def __unicode__(self): return self.name class BetterAuthor(Author): write_speed = models.IntegerField() class Book(models.Model): author = models.ForeignKey(Author) title = models.CharField(max_length=100) class Meta: unique_together = ( ('author', 'title'), ) ordering = ['id'] def __unicode__(self): return self.title class BookWithCustomPK(models.Model): my_pk = models.DecimalField(max_digits=5, decimal_places=0, primary_key=True) author = models.ForeignKey(Author) title = models.CharField(max_length=100) def __unicode__(self): return u'%s: %s' % (self.my_pk, self.title) class Editor(models.Model): name = models.CharField(max_length=100) class BookWithOptionalAltEditor(models.Model): author = models.ForeignKey(Author) # Optional secondary author alt_editor = models.ForeignKey(Editor, blank=True, null=True) title = models.CharField(max_length=100) class Meta: unique_together = ( ('author', 'title', 'alt_editor'), ) def __unicode__(self): return self.title class AlternateBook(Book): notes = models.CharField(max_length=100) def __unicode__(self): return u'%s - %s' % (self.title, self.notes) class AuthorMeeting(models.Model): name = models.CharField(max_length=100) authors = models.ManyToManyField(Author) created = models.DateField(editable=False) def __unicode__(self): return self.name class CustomPrimaryKey(models.Model): my_pk = models.CharField(max_length=10, primary_key=True) some_field = models.CharField(max_length=100) # models for inheritance tests. class Place(models.Model): name = models.CharField(max_length=50) city = models.CharField(max_length=50) def __unicode__(self): return self.name class Owner(models.Model): auto_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) place = models.ForeignKey(Place) def __unicode__(self): return "%s at %s" % (self.name, self.place) class Location(models.Model): place = models.ForeignKey(Place, unique=True) # this is purely for testing the data doesn't matter here :) lat = models.CharField(max_length=100) lon = models.CharField(max_length=100) class OwnerProfile(models.Model): owner = models.OneToOneField(Owner, primary_key=True) age = models.PositiveIntegerField() def __unicode__(self): return "%s is %d" % (self.owner.name, self.age) class Restaurant(Place): serves_pizza = models.BooleanField() def __unicode__(self): return self.name class Product(models.Model): slug = models.SlugField(unique=True) def __unicode__(self): return self.slug class Price(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField() def __unicode__(self): return u"%s for %s" % (self.quantity, self.price) class Meta: unique_together = (('price', 'quantity'),) class MexicanRestaurant(Restaurant): serves_tacos = models.BooleanField() class ClassyMexicanRestaurant(MexicanRestaurant): restaurant = models.OneToOneField(MexicanRestaurant, parent_link=True, primary_key=True) tacos_are_yummy = models.BooleanField() # models for testing unique_together validation when a fk is involved and # using inlineformset_factory. class Repository(models.Model): name = models.CharField(max_length=25) def __unicode__(self): return self.name class Revision(models.Model): repository = models.ForeignKey(Repository) revision = models.CharField(max_length=40) class Meta: unique_together = (("repository", "revision"),) def __unicode__(self): return u"%s (%s)" % (self.revision, unicode(self.repository)) # models for testing callable defaults (see bug #7975). If you define a model # with a callable default value, you cannot rely on the initial value in a # form. class Person(models.Model): name = models.CharField(max_length=128) class Membership(models.Model): person = models.ForeignKey(Person) date_joined = models.DateTimeField(default=datetime.datetime.now) karma = models.IntegerField() # models for testing a null=True fk to a parent class Team(models.Model): name = models.CharField(max_length=100) class Player(models.Model): team = models.ForeignKey(Team, null=True) name = models.CharField(max_length=100) def __unicode__(self): return self.name # Models for testing custom ModelForm save methods in formsets and inline formsets class Poet(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name class Poem(models.Model): poet = models.ForeignKey(Poet) name = models.CharField(max_length=100) def __unicode__(self): return self.name class Post(models.Model): title = models.CharField(max_length=50, unique_for_date='posted', blank=True) slug = models.CharField(max_length=50, unique_for_year='posted', blank=True) subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True) posted = models.DateField() def __unicode__(self): return self.name
5,488
Python
.py
141
33.751773
92
0.701416
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,381
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/model_formsets/tests.py
import datetime import re from datetime import date from decimal import Decimal from django import forms from django.db import models from django.forms.models import (_get_foreign_key, inlineformset_factory, modelformset_factory, modelformset_factory) from django.test import TestCase from modeltests.model_formsets.models import ( Author, BetterAuthor, Book, BookWithCustomPK, Editor, BookWithOptionalAltEditor, AlternateBook, AuthorMeeting, CustomPrimaryKey, Place, Owner, Location, OwnerProfile, Restaurant, Product, Price, MexicanRestaurant, ClassyMexicanRestaurant, Repository, Revision, Person, Membership, Team, Player, Poet, Poem, Post) class DeletionTests(TestCase): def test_deletion(self): PoetFormSet = modelformset_factory(Poet, can_delete=True) poet = Poet.objects.create(name='test') data = { 'form-TOTAL_FORMS': u'1', 'form-INITIAL_FORMS': u'1', 'form-MAX_NUM_FORMS': u'0', 'form-0-id': str(poet.pk), 'form-0-name': u'test', 'form-0-DELETE': u'on', } formset = PoetFormSet(data, queryset=Poet.objects.all()) formset.save() self.assertTrue(formset.is_valid()) self.assertEqual(Poet.objects.count(), 0) def test_add_form_deletion_when_invalid(self): """ Make sure that an add form that is filled out, but marked for deletion doesn't cause validation errors. """ PoetFormSet = modelformset_factory(Poet, can_delete=True) data = { 'form-TOTAL_FORMS': u'1', 'form-INITIAL_FORMS': u'0', 'form-MAX_NUM_FORMS': u'0', 'form-0-id': u'', 'form-0-name': u'x' * 1000, } formset = PoetFormSet(data, queryset=Poet.objects.all()) # Make sure this form doesn't pass validation. self.assertEqual(formset.is_valid(), False) self.assertEqual(Poet.objects.count(), 0) # Then make sure that it *does* pass validation and delete the object, # even though the data isn't actually valid. data['form-0-DELETE'] = 'on' formset = PoetFormSet(data, queryset=Poet.objects.all()) self.assertEqual(formset.is_valid(), True) formset.save() self.assertEqual(Poet.objects.count(), 0) def test_change_form_deletion_when_invalid(self): """ Make sure that an add form that is filled out, but marked for deletion doesn't cause validation errors. """ PoetFormSet = modelformset_factory(Poet, can_delete=True) poet = Poet.objects.create(name='test') data = { 'form-TOTAL_FORMS': u'1', 'form-INITIAL_FORMS': u'1', 'form-MAX_NUM_FORMS': u'0', 'form-0-id': u'1', 'form-0-name': u'x' * 1000, } formset = PoetFormSet(data, queryset=Poet.objects.all()) # Make sure this form doesn't pass validation. self.assertEqual(formset.is_valid(), False) self.assertEqual(Poet.objects.count(), 1) # Then make sure that it *does* pass validation and delete the object, # even though the data isn't actually valid. data['form-0-DELETE'] = 'on' formset = PoetFormSet(data, queryset=Poet.objects.all()) self.assertEqual(formset.is_valid(), True) formset.save() self.assertEqual(Poet.objects.count(), 0) class ModelFormsetTest(TestCase): def test_simple_save(self): qs = Author.objects.all() AuthorFormSet = modelformset_factory(Author, extra=3) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 3) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" type="text" name="form-0-name" maxlength="100" /><input type="hidden" name="form-0-id" id="id_form-0-id" /></p>') self.assertEqual(formset.forms[1].as_p(), '<p><label for="id_form-1-name">Name:</label> <input id="id_form-1-name" type="text" name="form-1-name" maxlength="100" /><input type="hidden" name="form-1-id" id="id_form-1-id" /></p>') self.assertEqual(formset.forms[2].as_p(), '<p><label for="id_form-2-name">Name:</label> <input id="id_form-2-name" type="text" name="form-2-name" maxlength="100" /><input type="hidden" name="form-2-id" id="id_form-2-id" /></p>') data = { 'form-TOTAL_FORMS': '3', # the number of forms rendered 'form-INITIAL_FORMS': '0', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-name': 'Charles Baudelaire', 'form-1-name': 'Arthur Rimbaud', 'form-2-name': '', } formset = AuthorFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 2) author1, author2 = saved self.assertEqual(author1, Author.objects.get(name='Charles Baudelaire')) self.assertEqual(author2, Author.objects.get(name='Arthur Rimbaud')) authors = list(Author.objects.order_by('name')) self.assertEqual(authors, [author2, author1]) # Gah! We forgot Paul Verlaine. Let's create a formset to edit the # existing authors with an extra form to add him. We *could* pass in a # queryset to restrict the Author objects we edit, but in this case # we'll use it to display them in alphabetical order by name. qs = Author.objects.order_by('name') AuthorFormSet = modelformset_factory(Author, extra=1, can_delete=False) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 3) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" type="text" name="form-0-name" value="Arthur Rimbaud" maxlength="100" /><input type="hidden" name="form-0-id" value="%d" id="id_form-0-id" /></p>' % author2.id) self.assertEqual(formset.forms[1].as_p(), '<p><label for="id_form-1-name">Name:</label> <input id="id_form-1-name" type="text" name="form-1-name" value="Charles Baudelaire" maxlength="100" /><input type="hidden" name="form-1-id" value="%d" id="id_form-1-id" /></p>' % author1.id) self.assertEqual(formset.forms[2].as_p(), '<p><label for="id_form-2-name">Name:</label> <input id="id_form-2-name" type="text" name="form-2-name" maxlength="100" /><input type="hidden" name="form-2-id" id="id_form-2-id" /></p>') data = { 'form-TOTAL_FORMS': '3', # the number of forms rendered 'form-INITIAL_FORMS': '2', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(author2.id), 'form-0-name': 'Arthur Rimbaud', 'form-1-id': str(author1.id), 'form-1-name': 'Charles Baudelaire', 'form-2-name': 'Paul Verlaine', } formset = AuthorFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) # Only changed or new objects are returned from formset.save() saved = formset.save() self.assertEqual(len(saved), 1) author3 = saved[0] self.assertEqual(author3, Author.objects.get(name='Paul Verlaine')) authors = list(Author.objects.order_by('name')) self.assertEqual(authors, [author2, author1, author3]) # This probably shouldn't happen, but it will. If an add form was # marked for deletion, make sure we don't save that form. qs = Author.objects.order_by('name') AuthorFormSet = modelformset_factory(Author, extra=1, can_delete=True) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 4) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" type="text" name="form-0-name" value="Arthur Rimbaud" maxlength="100" /></p>\n' '<p><label for="id_form-0-DELETE">Delete:</label> <input type="checkbox" name="form-0-DELETE" id="id_form-0-DELETE" /><input type="hidden" name="form-0-id" value="%d" id="id_form-0-id" /></p>' % author2.id) self.assertEqual(formset.forms[1].as_p(), '<p><label for="id_form-1-name">Name:</label> <input id="id_form-1-name" type="text" name="form-1-name" value="Charles Baudelaire" maxlength="100" /></p>\n' '<p><label for="id_form-1-DELETE">Delete:</label> <input type="checkbox" name="form-1-DELETE" id="id_form-1-DELETE" /><input type="hidden" name="form-1-id" value="%d" id="id_form-1-id" /></p>' % author1.id) self.assertEqual(formset.forms[2].as_p(), '<p><label for="id_form-2-name">Name:</label> <input id="id_form-2-name" type="text" name="form-2-name" value="Paul Verlaine" maxlength="100" /></p>\n' '<p><label for="id_form-2-DELETE">Delete:</label> <input type="checkbox" name="form-2-DELETE" id="id_form-2-DELETE" /><input type="hidden" name="form-2-id" value="%d" id="id_form-2-id" /></p>' % author3.id) self.assertEqual(formset.forms[3].as_p(), '<p><label for="id_form-3-name">Name:</label> <input id="id_form-3-name" type="text" name="form-3-name" maxlength="100" /></p>\n' '<p><label for="id_form-3-DELETE">Delete:</label> <input type="checkbox" name="form-3-DELETE" id="id_form-3-DELETE" /><input type="hidden" name="form-3-id" id="id_form-3-id" /></p>') data = { 'form-TOTAL_FORMS': '4', # the number of forms rendered 'form-INITIAL_FORMS': '3', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(author2.id), 'form-0-name': 'Arthur Rimbaud', 'form-1-id': str(author1.id), 'form-1-name': 'Charles Baudelaire', 'form-2-id': str(author3.id), 'form-2-name': 'Paul Verlaine', 'form-3-name': 'Walt Whitman', 'form-3-DELETE': 'on', } formset = AuthorFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) # No objects were changed or saved so nothing will come back. self.assertEqual(formset.save(), []) authors = list(Author.objects.order_by('name')) self.assertEqual(authors, [author2, author1, author3]) # Let's edit a record to ensure save only returns that one record. data = { 'form-TOTAL_FORMS': '4', # the number of forms rendered 'form-INITIAL_FORMS': '3', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(author2.id), 'form-0-name': 'Walt Whitman', 'form-1-id': str(author1.id), 'form-1-name': 'Charles Baudelaire', 'form-2-id': str(author3.id), 'form-2-name': 'Paul Verlaine', 'form-3-name': '', 'form-3-DELETE': '', } formset = AuthorFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) # One record has changed. saved = formset.save() self.assertEqual(len(saved), 1) self.assertEqual(saved[0], Author.objects.get(name='Walt Whitman')) def test_commit_false(self): # Test the behavior of commit=False and save_m2m author1 = Author.objects.create(name='Charles Baudelaire') author2 = Author.objects.create(name='Paul Verlaine') author3 = Author.objects.create(name='Walt Whitman') meeting = AuthorMeeting.objects.create(created=date.today()) meeting.authors = Author.objects.all() # create an Author instance to add to the meeting. author4 = Author.objects.create(name=u'John Steinbeck') AuthorMeetingFormSet = modelformset_factory(AuthorMeeting, extra=1, can_delete=True) data = { 'form-TOTAL_FORMS': '2', # the number of forms rendered 'form-INITIAL_FORMS': '1', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': '1', 'form-0-name': '2nd Tuesday of the Week Meeting', 'form-0-authors': [2, 1, 3, 4], 'form-1-name': '', 'form-1-authors': '', 'form-1-DELETE': '', } formset = AuthorMeetingFormSet(data=data, queryset=AuthorMeeting.objects.all()) self.assertTrue(formset.is_valid()) instances = formset.save(commit=False) for instance in instances: instance.created = date.today() instance.save() formset.save_m2m() self.assertQuerysetEqual(instances[0].authors.all(), [ '<Author: Charles Baudelaire>', '<Author: John Steinbeck>', '<Author: Paul Verlaine>', '<Author: Walt Whitman>', ]) def test_max_num(self): # Test the behavior of max_num with model formsets. It should allow # all existing related objects/inlines for a given object to be # displayed, but not allow the creation of new inlines beyond max_num. author1 = Author.objects.create(name='Charles Baudelaire') author2 = Author.objects.create(name='Paul Verlaine') author3 = Author.objects.create(name='Walt Whitman') qs = Author.objects.order_by('name') AuthorFormSet = modelformset_factory(Author, max_num=None, extra=3) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 6) self.assertEqual(len(formset.extra_forms), 3) AuthorFormSet = modelformset_factory(Author, max_num=4, extra=3) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 4) self.assertEqual(len(formset.extra_forms), 1) AuthorFormSet = modelformset_factory(Author, max_num=0, extra=3) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 3) self.assertEqual(len(formset.extra_forms), 0) AuthorFormSet = modelformset_factory(Author, max_num=None) formset = AuthorFormSet(queryset=qs) self.assertQuerysetEqual(formset.get_queryset(), [ '<Author: Charles Baudelaire>', '<Author: Paul Verlaine>', '<Author: Walt Whitman>', ]) AuthorFormSet = modelformset_factory(Author, max_num=0) formset = AuthorFormSet(queryset=qs) self.assertQuerysetEqual(formset.get_queryset(), [ '<Author: Charles Baudelaire>', '<Author: Paul Verlaine>', '<Author: Walt Whitman>', ]) AuthorFormSet = modelformset_factory(Author, max_num=4) formset = AuthorFormSet(queryset=qs) self.assertQuerysetEqual(formset.get_queryset(), [ '<Author: Charles Baudelaire>', '<Author: Paul Verlaine>', '<Author: Walt Whitman>', ]) def test_custom_save_method(self): class PoetForm(forms.ModelForm): def save(self, commit=True): # change the name to "Vladimir Mayakovsky" just to be a jerk. author = super(PoetForm, self).save(commit=False) author.name = u"Vladimir Mayakovsky" if commit: author.save() return author PoetFormSet = modelformset_factory(Poet, form=PoetForm) data = { 'form-TOTAL_FORMS': '3', # the number of forms rendered 'form-INITIAL_FORMS': '0', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-name': 'Walt Whitman', 'form-1-name': 'Charles Baudelaire', 'form-2-name': '', } qs = Poet.objects.all() formset = PoetFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) poets = formset.save() self.assertEqual(len(poets), 2) poet1, poet2 = poets self.assertEqual(poet1.name, 'Vladimir Mayakovsky') self.assertEqual(poet2.name, 'Vladimir Mayakovsky') def test_model_inheritance(self): BetterAuthorFormSet = modelformset_factory(BetterAuthor) formset = BetterAuthorFormSet() self.assertEqual(len(formset.forms), 1) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" type="text" name="form-0-name" maxlength="100" /></p>\n' '<p><label for="id_form-0-write_speed">Write speed:</label> <input type="text" name="form-0-write_speed" id="id_form-0-write_speed" /><input type="hidden" name="form-0-author_ptr" id="id_form-0-author_ptr" /></p>') data = { 'form-TOTAL_FORMS': '1', # the number of forms rendered 'form-INITIAL_FORMS': '0', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-author_ptr': '', 'form-0-name': 'Ernest Hemingway', 'form-0-write_speed': '10', } formset = BetterAuthorFormSet(data) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) author1, = saved self.assertEqual(author1, BetterAuthor.objects.get(name='Ernest Hemingway')) hemingway_id = BetterAuthor.objects.get(name="Ernest Hemingway").pk formset = BetterAuthorFormSet() self.assertEqual(len(formset.forms), 2) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" type="text" name="form-0-name" value="Ernest Hemingway" maxlength="100" /></p>\n' '<p><label for="id_form-0-write_speed">Write speed:</label> <input type="text" name="form-0-write_speed" value="10" id="id_form-0-write_speed" /><input type="hidden" name="form-0-author_ptr" value="%d" id="id_form-0-author_ptr" /></p>' % hemingway_id) self.assertEqual(formset.forms[1].as_p(), '<p><label for="id_form-1-name">Name:</label> <input id="id_form-1-name" type="text" name="form-1-name" maxlength="100" /></p>\n' '<p><label for="id_form-1-write_speed">Write speed:</label> <input type="text" name="form-1-write_speed" id="id_form-1-write_speed" /><input type="hidden" name="form-1-author_ptr" id="id_form-1-author_ptr" /></p>') data = { 'form-TOTAL_FORMS': '2', # the number of forms rendered 'form-INITIAL_FORMS': '1', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-author_ptr': hemingway_id, 'form-0-name': 'Ernest Hemingway', 'form-0-write_speed': '10', 'form-1-author_ptr': '', 'form-1-name': '', 'form-1-write_speed': '', } formset = BetterAuthorFormSet(data) self.assertTrue(formset.is_valid()) self.assertEqual(formset.save(), []) def test_inline_formsets(self): # We can also create a formset that is tied to a parent model. This is # how the admin system's edit inline functionality works. AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=3) author = Author.objects.create(name='Charles Baudelaire') formset = AuthorBooksFormSet(instance=author) self.assertEqual(len(formset.forms), 3) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_book_set-0-title">Title:</label> <input id="id_book_set-0-title" type="text" name="book_set-0-title" maxlength="100" /><input type="hidden" name="book_set-0-author" value="%d" id="id_book_set-0-author" /><input type="hidden" name="book_set-0-id" id="id_book_set-0-id" /></p>' % author.id) self.assertEqual(formset.forms[1].as_p(), '<p><label for="id_book_set-1-title">Title:</label> <input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100" /><input type="hidden" name="book_set-1-author" value="%d" id="id_book_set-1-author" /><input type="hidden" name="book_set-1-id" id="id_book_set-1-id" /></p>' % author.id) self.assertEqual(formset.forms[2].as_p(), '<p><label for="id_book_set-2-title">Title:</label> <input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100" /><input type="hidden" name="book_set-2-author" value="%d" id="id_book_set-2-author" /><input type="hidden" name="book_set-2-id" id="id_book_set-2-id" /></p>' % author.id) data = { 'book_set-TOTAL_FORMS': '3', # the number of forms rendered 'book_set-INITIAL_FORMS': '0', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-title': 'Les Fleurs du Mal', 'book_set-1-title': '', 'book_set-2-title': '', } formset = AuthorBooksFormSet(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) book1, = saved self.assertEqual(book1, Book.objects.get(title='Les Fleurs du Mal')) self.assertQuerysetEqual(author.book_set.all(), ['<Book: Les Fleurs du Mal>']) # Now that we've added a book to Charles Baudelaire, let's try adding # another one. This time though, an edit form will be available for # every existing book. AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=2) author = Author.objects.get(name='Charles Baudelaire') formset = AuthorBooksFormSet(instance=author) self.assertEqual(len(formset.forms), 3) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_book_set-0-title">Title:</label> <input id="id_book_set-0-title" type="text" name="book_set-0-title" value="Les Fleurs du Mal" maxlength="100" /><input type="hidden" name="book_set-0-author" value="%d" id="id_book_set-0-author" /><input type="hidden" name="book_set-0-id" value="%d" id="id_book_set-0-id" /></p>' % (author.id, book1.id)) self.assertEqual(formset.forms[1].as_p(), '<p><label for="id_book_set-1-title">Title:</label> <input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100" /><input type="hidden" name="book_set-1-author" value="%d" id="id_book_set-1-author" /><input type="hidden" name="book_set-1-id" id="id_book_set-1-id" /></p>' % author.id) self.assertEqual(formset.forms[2].as_p(), '<p><label for="id_book_set-2-title">Title:</label> <input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100" /><input type="hidden" name="book_set-2-author" value="%d" id="id_book_set-2-author" /><input type="hidden" name="book_set-2-id" id="id_book_set-2-id" /></p>' % author.id) data = { 'book_set-TOTAL_FORMS': '3', # the number of forms rendered 'book_set-INITIAL_FORMS': '1', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': '1', 'book_set-0-title': 'Les Fleurs du Mal', 'book_set-1-title': 'Les Paradis Artificiels', 'book_set-2-title': '', } formset = AuthorBooksFormSet(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) book2, = saved self.assertEqual(book2, Book.objects.get(title='Les Paradis Artificiels')) # As you can see, 'Les Paradis Artificiels' is now a book belonging to # Charles Baudelaire. self.assertQuerysetEqual(author.book_set.order_by('title'), [ '<Book: Les Fleurs du Mal>', '<Book: Les Paradis Artificiels>', ]) def test_inline_formsets_save_as_new(self): # The save_as_new parameter lets you re-associate the data to a new # instance. This is used in the admin for save_as functionality. AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=2) author = Author.objects.create(name='Charles Baudelaire') data = { 'book_set-TOTAL_FORMS': '3', # the number of forms rendered 'book_set-INITIAL_FORMS': '2', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': '1', 'book_set-0-title': 'Les Fleurs du Mal', 'book_set-1-id': '2', 'book_set-1-title': 'Les Paradis Artificiels', 'book_set-2-title': '', } formset = AuthorBooksFormSet(data, instance=Author(), save_as_new=True) self.assertTrue(formset.is_valid()) new_author = Author.objects.create(name='Charles Baudelaire') formset = AuthorBooksFormSet(data, instance=new_author, save_as_new=True) saved = formset.save() self.assertEqual(len(saved), 2) book1, book2 = saved self.assertEqual(book1.title, 'Les Fleurs du Mal') self.assertEqual(book2.title, 'Les Paradis Artificiels') # Test using a custom prefix on an inline formset. formset = AuthorBooksFormSet(prefix="test") self.assertEqual(len(formset.forms), 2) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_test-0-title">Title:</label> <input id="id_test-0-title" type="text" name="test-0-title" maxlength="100" /><input type="hidden" name="test-0-author" id="id_test-0-author" /><input type="hidden" name="test-0-id" id="id_test-0-id" /></p>') self.assertEqual(formset.forms[1].as_p(), '<p><label for="id_test-1-title">Title:</label> <input id="id_test-1-title" type="text" name="test-1-title" maxlength="100" /><input type="hidden" name="test-1-author" id="id_test-1-author" /><input type="hidden" name="test-1-id" id="id_test-1-id" /></p>') def test_inline_formsets_with_custom_pk(self): # Test inline formsets where the inline-edited object has a custom # primary key that is not the fk to the parent object. AuthorBooksFormSet2 = inlineformset_factory(Author, BookWithCustomPK, can_delete=False, extra=1) author = Author.objects.create(pk=1, name='Charles Baudelaire') formset = AuthorBooksFormSet2(instance=author) self.assertEqual(len(formset.forms), 1) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_bookwithcustompk_set-0-my_pk">My pk:</label> <input type="text" name="bookwithcustompk_set-0-my_pk" id="id_bookwithcustompk_set-0-my_pk" /></p>\n' '<p><label for="id_bookwithcustompk_set-0-title">Title:</label> <input id="id_bookwithcustompk_set-0-title" type="text" name="bookwithcustompk_set-0-title" maxlength="100" /><input type="hidden" name="bookwithcustompk_set-0-author" value="1" id="id_bookwithcustompk_set-0-author" /></p>') data = { 'bookwithcustompk_set-TOTAL_FORMS': '1', # the number of forms rendered 'bookwithcustompk_set-INITIAL_FORMS': '0', # the number of forms with initial data 'bookwithcustompk_set-MAX_NUM_FORMS': '', # the max number of forms 'bookwithcustompk_set-0-my_pk': '77777', 'bookwithcustompk_set-0-title': 'Les Fleurs du Mal', } formset = AuthorBooksFormSet2(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) book1, = saved self.assertEqual(book1.pk, 77777) book1 = author.bookwithcustompk_set.get() self.assertEqual(book1.title, 'Les Fleurs du Mal') def test_inline_formsets_with_multi_table_inheritance(self): # Test inline formsets where the inline-edited object uses multi-table # inheritance, thus has a non AutoField yet auto-created primary key. AuthorBooksFormSet3 = inlineformset_factory(Author, AlternateBook, can_delete=False, extra=1) author = Author.objects.create(pk=1, name='Charles Baudelaire') formset = AuthorBooksFormSet3(instance=author) self.assertEqual(len(formset.forms), 1) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_alternatebook_set-0-title">Title:</label> <input id="id_alternatebook_set-0-title" type="text" name="alternatebook_set-0-title" maxlength="100" /></p>\n' '<p><label for="id_alternatebook_set-0-notes">Notes:</label> <input id="id_alternatebook_set-0-notes" type="text" name="alternatebook_set-0-notes" maxlength="100" /><input type="hidden" name="alternatebook_set-0-author" value="1" id="id_alternatebook_set-0-author" /><input type="hidden" name="alternatebook_set-0-book_ptr" id="id_alternatebook_set-0-book_ptr" /></p>') data = { 'alternatebook_set-TOTAL_FORMS': '1', # the number of forms rendered 'alternatebook_set-INITIAL_FORMS': '0', # the number of forms with initial data 'alternatebook_set-MAX_NUM_FORMS': '', # the max number of forms 'alternatebook_set-0-title': 'Flowers of Evil', 'alternatebook_set-0-notes': 'English translation of Les Fleurs du Mal' } formset = AuthorBooksFormSet3(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) book1, = saved self.assertEqual(book1.title, 'Flowers of Evil') self.assertEqual(book1.notes, 'English translation of Les Fleurs du Mal') # Test inline formsets where the inline-edited object has a # unique_together constraint with a nullable member AuthorBooksFormSet4 = inlineformset_factory(Author, BookWithOptionalAltEditor, can_delete=False, extra=2) data = { 'bookwithoptionalalteditor_set-TOTAL_FORMS': '2', # the number of forms rendered 'bookwithoptionalalteditor_set-INITIAL_FORMS': '0', # the number of forms with initial data 'bookwithoptionalalteditor_set-MAX_NUM_FORMS': '', # the max number of forms 'bookwithoptionalalteditor_set-0-author': '1', 'bookwithoptionalalteditor_set-0-title': 'Les Fleurs du Mal', 'bookwithoptionalalteditor_set-1-author': '1', 'bookwithoptionalalteditor_set-1-title': 'Les Fleurs du Mal', } formset = AuthorBooksFormSet4(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 2) book1, book2 = saved self.assertEqual(book1.author_id, 1) self.assertEqual(book1.title, 'Les Fleurs du Mal') self.assertEqual(book2.author_id, 1) self.assertEqual(book2.title, 'Les Fleurs du Mal') def test_inline_formsets_with_custom_save_method(self): AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=2) author = Author.objects.create(pk=1, name='Charles Baudelaire') book1 = Book.objects.create(pk=1, author=author, title='Les Paradis Artificiels') book2 = Book.objects.create(pk=2, author=author, title='Les Fleurs du Mal') book3 = Book.objects.create(pk=3, author=author, title='Flowers of Evil') class PoemForm(forms.ModelForm): def save(self, commit=True): # change the name to "Brooklyn Bridge" just to be a jerk. poem = super(PoemForm, self).save(commit=False) poem.name = u"Brooklyn Bridge" if commit: poem.save() return poem PoemFormSet = inlineformset_factory(Poet, Poem, form=PoemForm) data = { 'poem_set-TOTAL_FORMS': '3', # the number of forms rendered 'poem_set-INITIAL_FORMS': '0', # the number of forms with initial data 'poem_set-MAX_NUM_FORMS': '', # the max number of forms 'poem_set-0-name': 'The Cloud in Trousers', 'poem_set-1-name': 'I', 'poem_set-2-name': '', } poet = Poet.objects.create(name='Vladimir Mayakovsky') formset = PoemFormSet(data=data, instance=poet) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 2) poem1, poem2 = saved self.assertEqual(poem1.name, 'Brooklyn Bridge') self.assertEqual(poem2.name, 'Brooklyn Bridge') # We can provide a custom queryset to our InlineFormSet: custom_qs = Book.objects.order_by('-title') formset = AuthorBooksFormSet(instance=author, queryset=custom_qs) self.assertEqual(len(formset.forms), 5) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_book_set-0-title">Title:</label> <input id="id_book_set-0-title" type="text" name="book_set-0-title" value="Les Paradis Artificiels" maxlength="100" /><input type="hidden" name="book_set-0-author" value="1" id="id_book_set-0-author" /><input type="hidden" name="book_set-0-id" value="1" id="id_book_set-0-id" /></p>') self.assertEqual(formset.forms[1].as_p(), '<p><label for="id_book_set-1-title">Title:</label> <input id="id_book_set-1-title" type="text" name="book_set-1-title" value="Les Fleurs du Mal" maxlength="100" /><input type="hidden" name="book_set-1-author" value="1" id="id_book_set-1-author" /><input type="hidden" name="book_set-1-id" value="2" id="id_book_set-1-id" /></p>') self.assertEqual(formset.forms[2].as_p(), '<p><label for="id_book_set-2-title">Title:</label> <input id="id_book_set-2-title" type="text" name="book_set-2-title" value="Flowers of Evil" maxlength="100" /><input type="hidden" name="book_set-2-author" value="1" id="id_book_set-2-author" /><input type="hidden" name="book_set-2-id" value="3" id="id_book_set-2-id" /></p>') self.assertEqual(formset.forms[3].as_p(), '<p><label for="id_book_set-3-title">Title:</label> <input id="id_book_set-3-title" type="text" name="book_set-3-title" maxlength="100" /><input type="hidden" name="book_set-3-author" value="1" id="id_book_set-3-author" /><input type="hidden" name="book_set-3-id" id="id_book_set-3-id" /></p>') self.assertEqual(formset.forms[4].as_p(), '<p><label for="id_book_set-4-title">Title:</label> <input id="id_book_set-4-title" type="text" name="book_set-4-title" maxlength="100" /><input type="hidden" name="book_set-4-author" value="1" id="id_book_set-4-author" /><input type="hidden" name="book_set-4-id" id="id_book_set-4-id" /></p>') data = { 'book_set-TOTAL_FORMS': '5', # the number of forms rendered 'book_set-INITIAL_FORMS': '3', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': str(book1.id), 'book_set-0-title': 'Les Paradis Artificiels', 'book_set-1-id': str(book2.id), 'book_set-1-title': 'Les Fleurs du Mal', 'book_set-2-id': str(book3.id), 'book_set-2-title': 'Flowers of Evil', 'book_set-3-title': 'Revue des deux mondes', 'book_set-4-title': '', } formset = AuthorBooksFormSet(data, instance=author, queryset=custom_qs) self.assertTrue(formset.is_valid()) custom_qs = Book.objects.filter(title__startswith='F') formset = AuthorBooksFormSet(instance=author, queryset=custom_qs) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_book_set-0-title">Title:</label> <input id="id_book_set-0-title" type="text" name="book_set-0-title" value="Flowers of Evil" maxlength="100" /><input type="hidden" name="book_set-0-author" value="1" id="id_book_set-0-author" /><input type="hidden" name="book_set-0-id" value="3" id="id_book_set-0-id" /></p>') self.assertEqual(formset.forms[1].as_p(), '<p><label for="id_book_set-1-title">Title:</label> <input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100" /><input type="hidden" name="book_set-1-author" value="1" id="id_book_set-1-author" /><input type="hidden" name="book_set-1-id" id="id_book_set-1-id" /></p>') self.assertEqual(formset.forms[2].as_p(), '<p><label for="id_book_set-2-title">Title:</label> <input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100" /><input type="hidden" name="book_set-2-author" value="1" id="id_book_set-2-author" /><input type="hidden" name="book_set-2-id" id="id_book_set-2-id" /></p>') data = { 'book_set-TOTAL_FORMS': '3', # the number of forms rendered 'book_set-INITIAL_FORMS': '1', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': str(book3.id), 'book_set-0-title': 'Flowers of Evil', 'book_set-1-title': 'Revue des deux mondes', 'book_set-2-title': '', } formset = AuthorBooksFormSet(data, instance=author, queryset=custom_qs) self.assertTrue(formset.is_valid()) def test_custom_pk(self): # We need to ensure that it is displayed CustomPrimaryKeyFormSet = modelformset_factory(CustomPrimaryKey) formset = CustomPrimaryKeyFormSet() self.assertEqual(len(formset.forms), 1) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_form-0-my_pk">My pk:</label> <input id="id_form-0-my_pk" type="text" name="form-0-my_pk" maxlength="10" /></p>\n' '<p><label for="id_form-0-some_field">Some field:</label> <input id="id_form-0-some_field" type="text" name="form-0-some_field" maxlength="100" /></p>') # Custom primary keys with ForeignKey, OneToOneField and AutoField ############ place = Place.objects.create(pk=1, name=u'Giordanos', city=u'Chicago') FormSet = inlineformset_factory(Place, Owner, extra=2, can_delete=False) formset = FormSet(instance=place) self.assertEqual(len(formset.forms), 2) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_owner_set-0-name">Name:</label> <input id="id_owner_set-0-name" type="text" name="owner_set-0-name" maxlength="100" /><input type="hidden" name="owner_set-0-place" value="1" id="id_owner_set-0-place" /><input type="hidden" name="owner_set-0-auto_id" id="id_owner_set-0-auto_id" /></p>') self.assertEqual(formset.forms[1].as_p(), '<p><label for="id_owner_set-1-name">Name:</label> <input id="id_owner_set-1-name" type="text" name="owner_set-1-name" maxlength="100" /><input type="hidden" name="owner_set-1-place" value="1" id="id_owner_set-1-place" /><input type="hidden" name="owner_set-1-auto_id" id="id_owner_set-1-auto_id" /></p>') data = { 'owner_set-TOTAL_FORMS': '2', 'owner_set-INITIAL_FORMS': '0', 'owner_set-MAX_NUM_FORMS': '', 'owner_set-0-auto_id': '', 'owner_set-0-name': u'Joe Perry', 'owner_set-1-auto_id': '', 'owner_set-1-name': '', } formset = FormSet(data, instance=place) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) owner, = saved self.assertEqual(owner.name, 'Joe Perry') self.assertEqual(owner.place.name, 'Giordanos') formset = FormSet(instance=place) self.assertEqual(len(formset.forms), 3) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_owner_set-0-name">Name:</label> <input id="id_owner_set-0-name" type="text" name="owner_set-0-name" value="Joe Perry" maxlength="100" /><input type="hidden" name="owner_set-0-place" value="1" id="id_owner_set-0-place" /><input type="hidden" name="owner_set-0-auto_id" value="1" id="id_owner_set-0-auto_id" /></p>') self.assertEqual(formset.forms[1].as_p(), '<p><label for="id_owner_set-1-name">Name:</label> <input id="id_owner_set-1-name" type="text" name="owner_set-1-name" maxlength="100" /><input type="hidden" name="owner_set-1-place" value="1" id="id_owner_set-1-place" /><input type="hidden" name="owner_set-1-auto_id" id="id_owner_set-1-auto_id" /></p>') self.assertEqual(formset.forms[2].as_p(), '<p><label for="id_owner_set-2-name">Name:</label> <input id="id_owner_set-2-name" type="text" name="owner_set-2-name" maxlength="100" /><input type="hidden" name="owner_set-2-place" value="1" id="id_owner_set-2-place" /><input type="hidden" name="owner_set-2-auto_id" id="id_owner_set-2-auto_id" /></p>') data = { 'owner_set-TOTAL_FORMS': '3', 'owner_set-INITIAL_FORMS': '1', 'owner_set-MAX_NUM_FORMS': '', 'owner_set-0-auto_id': u'1', 'owner_set-0-name': u'Joe Perry', 'owner_set-1-auto_id': '', 'owner_set-1-name': u'Jack Berry', 'owner_set-2-auto_id': '', 'owner_set-2-name': '', } formset = FormSet(data, instance=place) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) owner, = saved self.assertEqual(owner.name, 'Jack Berry') self.assertEqual(owner.place.name, 'Giordanos') # Ensure a custom primary key that is a ForeignKey or OneToOneField get rendered for the user to choose. FormSet = modelformset_factory(OwnerProfile) formset = FormSet() self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_form-0-owner">Owner:</label> <select name="form-0-owner" id="id_form-0-owner">\n' '<option value="" selected="selected">---------</option>\n' '<option value="1">Joe Perry at Giordanos</option>\n' '<option value="2">Jack Berry at Giordanos</option>\n' '</select></p>\n' '<p><label for="id_form-0-age">Age:</label> <input type="text" name="form-0-age" id="id_form-0-age" /></p>') owner = Owner.objects.get(name=u'Joe Perry') FormSet = inlineformset_factory(Owner, OwnerProfile, max_num=1, can_delete=False) self.assertEqual(FormSet.max_num, 1) formset = FormSet(instance=owner) self.assertEqual(len(formset.forms), 1) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_ownerprofile-0-age">Age:</label> <input type="text" name="ownerprofile-0-age" id="id_ownerprofile-0-age" /><input type="hidden" name="ownerprofile-0-owner" value="1" id="id_ownerprofile-0-owner" /></p>') data = { 'ownerprofile-TOTAL_FORMS': '1', 'ownerprofile-INITIAL_FORMS': '0', 'ownerprofile-MAX_NUM_FORMS': '1', 'ownerprofile-0-owner': '', 'ownerprofile-0-age': u'54', } formset = FormSet(data, instance=owner) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) profile1, = saved self.assertEqual(profile1.owner, owner) self.assertEqual(profile1.age, 54) formset = FormSet(instance=owner) self.assertEqual(len(formset.forms), 1) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_ownerprofile-0-age">Age:</label> <input type="text" name="ownerprofile-0-age" value="54" id="id_ownerprofile-0-age" /><input type="hidden" name="ownerprofile-0-owner" value="1" id="id_ownerprofile-0-owner" /></p>') data = { 'ownerprofile-TOTAL_FORMS': '1', 'ownerprofile-INITIAL_FORMS': '1', 'ownerprofile-MAX_NUM_FORMS': '1', 'ownerprofile-0-owner': u'1', 'ownerprofile-0-age': u'55', } formset = FormSet(data, instance=owner) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) profile1, = saved self.assertEqual(profile1.owner, owner) self.assertEqual(profile1.age, 55) def test_unique_true_enforces_max_num_one(self): # ForeignKey with unique=True should enforce max_num=1 place = Place.objects.create(pk=1, name=u'Giordanos', city=u'Chicago') FormSet = inlineformset_factory(Place, Location, can_delete=False) self.assertEqual(FormSet.max_num, 1) formset = FormSet(instance=place) self.assertEqual(len(formset.forms), 1) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_location_set-0-lat">Lat:</label> <input id="id_location_set-0-lat" type="text" name="location_set-0-lat" maxlength="100" /></p>\n' '<p><label for="id_location_set-0-lon">Lon:</label> <input id="id_location_set-0-lon" type="text" name="location_set-0-lon" maxlength="100" /><input type="hidden" name="location_set-0-place" value="1" id="id_location_set-0-place" /><input type="hidden" name="location_set-0-id" id="id_location_set-0-id" /></p>') def test_foreign_keys_in_parents(self): self.assertEqual(type(_get_foreign_key(Restaurant, Owner)), models.ForeignKey) self.assertEqual(type(_get_foreign_key(MexicanRestaurant, Owner)), models.ForeignKey) def test_unique_validation(self): FormSet = modelformset_factory(Product, extra=1) data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-slug': 'car-red', } formset = FormSet(data) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) product1, = saved self.assertEqual(product1.slug, 'car-red') data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-slug': 'car-red', } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{'slug': [u'Product with this Slug already exists.']}]) def test_unique_together_validation(self): FormSet = modelformset_factory(Price, extra=1) data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-price': u'12.00', 'form-0-quantity': '1', } formset = FormSet(data) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) price1, = saved self.assertEqual(price1.price, Decimal('12.00')) self.assertEqual(price1.quantity, 1) data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-price': u'12.00', 'form-0-quantity': '1', } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{'__all__': [u'Price with this Price and Quantity already exists.']}]) def test_unique_together_with_inlineformset_factory(self): # Also see bug #8882. repository = Repository.objects.create(name=u'Test Repo') FormSet = inlineformset_factory(Repository, Revision, extra=1) data = { 'revision_set-TOTAL_FORMS': '1', 'revision_set-INITIAL_FORMS': '0', 'revision_set-MAX_NUM_FORMS': '', 'revision_set-0-repository': repository.pk, 'revision_set-0-revision': '146239817507f148d448db38840db7c3cbf47c76', 'revision_set-0-DELETE': '', } formset = FormSet(data, instance=repository) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) revision1, = saved self.assertEqual(revision1.repository, repository) self.assertEqual(revision1.revision, '146239817507f148d448db38840db7c3cbf47c76') # attempt to save the same revision against against the same repo. data = { 'revision_set-TOTAL_FORMS': '1', 'revision_set-INITIAL_FORMS': '0', 'revision_set-MAX_NUM_FORMS': '', 'revision_set-0-repository': repository.pk, 'revision_set-0-revision': '146239817507f148d448db38840db7c3cbf47c76', 'revision_set-0-DELETE': '', } formset = FormSet(data, instance=repository) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{'__all__': [u'Revision with this Repository and Revision already exists.']}]) # unique_together with inlineformset_factory with overridden form fields # Also see #9494 FormSet = inlineformset_factory(Repository, Revision, fields=('revision',), extra=1) data = { 'revision_set-TOTAL_FORMS': '1', 'revision_set-INITIAL_FORMS': '0', 'revision_set-MAX_NUM_FORMS': '', 'revision_set-0-repository': repository.pk, 'revision_set-0-revision': '146239817507f148d448db38840db7c3cbf47c76', 'revision_set-0-DELETE': '', } formset = FormSet(data, instance=repository) self.assertFalse(formset.is_valid()) def test_callable_defaults(self): # Use of callable defaults (see bug #7975). person = Person.objects.create(name='Ringo') FormSet = inlineformset_factory(Person, Membership, can_delete=False, extra=1) formset = FormSet(instance=person) # Django will render a hidden field for model fields that have a callable # default. This is required to ensure the value is tested for change correctly # when determine what extra forms have changed to save. self.assertEquals(len(formset.forms), 1) # this formset only has one form form = formset.forms[0] now = form.fields['date_joined'].initial() result = form.as_p() result = re.sub(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d+)?', '__DATETIME__', result) self.assertEqual(result, '<p><label for="id_membership_set-0-date_joined">Date joined:</label> <input type="text" name="membership_set-0-date_joined" value="__DATETIME__" id="id_membership_set-0-date_joined" /><input type="hidden" name="initial-membership_set-0-date_joined" value="__DATETIME__" id="initial-membership_set-0-id_membership_set-0-date_joined" /></p>\n' '<p><label for="id_membership_set-0-karma">Karma:</label> <input type="text" name="membership_set-0-karma" id="id_membership_set-0-karma" /><input type="hidden" name="membership_set-0-person" value="1" id="id_membership_set-0-person" /><input type="hidden" name="membership_set-0-id" id="id_membership_set-0-id" /></p>') # test for validation with callable defaults. Validations rely on hidden fields data = { 'membership_set-TOTAL_FORMS': '1', 'membership_set-INITIAL_FORMS': '0', 'membership_set-MAX_NUM_FORMS': '', 'membership_set-0-date_joined': unicode(now.strftime('%Y-%m-%d %H:%M:%S')), 'initial-membership_set-0-date_joined': unicode(now.strftime('%Y-%m-%d %H:%M:%S')), 'membership_set-0-karma': '', } formset = FormSet(data, instance=person) self.assertTrue(formset.is_valid()) # now test for when the data changes one_day_later = now + datetime.timedelta(days=1) filled_data = { 'membership_set-TOTAL_FORMS': '1', 'membership_set-INITIAL_FORMS': '0', 'membership_set-MAX_NUM_FORMS': '', 'membership_set-0-date_joined': unicode(one_day_later.strftime('%Y-%m-%d %H:%M:%S')), 'initial-membership_set-0-date_joined': unicode(now.strftime('%Y-%m-%d %H:%M:%S')), 'membership_set-0-karma': '', } formset = FormSet(filled_data, instance=person) self.assertFalse(formset.is_valid()) # now test with split datetime fields class MembershipForm(forms.ModelForm): date_joined = forms.SplitDateTimeField(initial=now) class Meta: model = Membership def __init__(self, **kwargs): super(MembershipForm, self).__init__(**kwargs) self.fields['date_joined'].widget = forms.SplitDateTimeWidget() FormSet = inlineformset_factory(Person, Membership, form=MembershipForm, can_delete=False, extra=1) data = { 'membership_set-TOTAL_FORMS': '1', 'membership_set-INITIAL_FORMS': '0', 'membership_set-MAX_NUM_FORMS': '', 'membership_set-0-date_joined_0': unicode(now.strftime('%Y-%m-%d')), 'membership_set-0-date_joined_1': unicode(now.strftime('%H:%M:%S')), 'initial-membership_set-0-date_joined': unicode(now.strftime('%Y-%m-%d %H:%M:%S')), 'membership_set-0-karma': '', } formset = FormSet(data, instance=person) self.assertTrue(formset.is_valid()) def test_inlineformset_factory_with_null_fk(self): # inlineformset_factory tests with fk having null=True. see #9462. # create some data that will exbit the issue team = Team.objects.create(name=u"Red Vipers") Player(name="Timmy").save() Player(name="Bobby", team=team).save() PlayerInlineFormSet = inlineformset_factory(Team, Player) formset = PlayerInlineFormSet() self.assertQuerysetEqual(formset.get_queryset(), []) formset = PlayerInlineFormSet(instance=team) players = formset.get_queryset() self.assertEqual(len(players), 1) player1, = players self.assertEqual(player1.team, team) self.assertEqual(player1.name, 'Bobby') def test_model_formset_with_custom_pk(self): # a formset for a Model that has a custom primary key that still needs to be # added to the formset automatically FormSet = modelformset_factory(ClassyMexicanRestaurant, fields=["tacos_are_yummy"]) self.assertEqual(sorted(FormSet().forms[0].fields.keys()), ['restaurant', 'tacos_are_yummy']) def test_prevent_duplicates_from_with_the_same_formset(self): FormSet = modelformset_factory(Product, extra=2) data = { 'form-TOTAL_FORMS': 2, 'form-INITIAL_FORMS': 0, 'form-MAX_NUM_FORMS': '', 'form-0-slug': 'red_car', 'form-1-slug': 'red_car', } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, [u'Please correct the duplicate data for slug.']) FormSet = modelformset_factory(Price, extra=2) data = { 'form-TOTAL_FORMS': 2, 'form-INITIAL_FORMS': 0, 'form-MAX_NUM_FORMS': '', 'form-0-price': '25', 'form-0-quantity': '7', 'form-1-price': '25', 'form-1-quantity': '7', } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, [u'Please correct the duplicate data for price and quantity, which must be unique.']) # Only the price field is specified, this should skip any unique checks since # the unique_together is not fulfilled. This will fail with a KeyError if broken. FormSet = modelformset_factory(Price, fields=("price",), extra=2) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-price': '24', 'form-1-price': '24', } formset = FormSet(data) self.assertTrue(formset.is_valid()) FormSet = inlineformset_factory(Author, Book, extra=0) author = Author.objects.create(pk=1, name='Charles Baudelaire') book1 = Book.objects.create(pk=1, author=author, title='Les Paradis Artificiels') book2 = Book.objects.create(pk=2, author=author, title='Les Fleurs du Mal') book3 = Book.objects.create(pk=3, author=author, title='Flowers of Evil') book_ids = author.book_set.order_by('id').values_list('id', flat=True) data = { 'book_set-TOTAL_FORMS': '2', 'book_set-INITIAL_FORMS': '2', 'book_set-MAX_NUM_FORMS': '', 'book_set-0-title': 'The 2008 Election', 'book_set-0-author': str(author.id), 'book_set-0-id': str(book_ids[0]), 'book_set-1-title': 'The 2008 Election', 'book_set-1-author': str(author.id), 'book_set-1-id': str(book_ids[1]), } formset = FormSet(data=data, instance=author) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, [u'Please correct the duplicate data for title.']) self.assertEqual(formset.errors, [{}, {'__all__': [u'Please correct the duplicate values below.']}]) FormSet = modelformset_factory(Post, extra=2) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-title': 'blah', 'form-0-slug': 'Morning', 'form-0-subtitle': 'foo', 'form-0-posted': '2009-01-01', 'form-1-title': 'blah', 'form-1-slug': 'Morning in Prague', 'form-1-subtitle': 'rawr', 'form-1-posted': '2009-01-01' } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, [u'Please correct the duplicate data for title which must be unique for the date in posted.']) self.assertEqual(formset.errors, [{}, {'__all__': [u'Please correct the duplicate values below.']}]) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-title': 'foo', 'form-0-slug': 'Morning in Prague', 'form-0-subtitle': 'foo', 'form-0-posted': '2009-01-01', 'form-1-title': 'blah', 'form-1-slug': 'Morning in Prague', 'form-1-subtitle': 'rawr', 'form-1-posted': '2009-08-02' } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, [u'Please correct the duplicate data for slug which must be unique for the year in posted.']) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-title': 'foo', 'form-0-slug': 'Morning in Prague', 'form-0-subtitle': 'rawr', 'form-0-posted': '2008-08-01', 'form-1-title': 'blah', 'form-1-slug': 'Prague', 'form-1-subtitle': 'rawr', 'form-1-posted': '2009-08-02' } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, [u'Please correct the duplicate data for subtitle which must be unique for the month in posted.'])
59,812
Python
.py
995
49.524623
381
0.613114
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,382
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/serializers/models.py
# -*- coding: utf-8 -*- """ 42. Serialization ``django.core.serializers`` provides interfaces to converting Django ``QuerySet`` objects to and from "flat" data (i.e. strings). """ from decimal import Decimal from django.db import models class Category(models.Model): name = models.CharField(max_length=20) class Meta: ordering = ('name',) def __unicode__(self): return self.name class Author(models.Model): name = models.CharField(max_length=20) class Meta: ordering = ('name',) def __unicode__(self): return self.name class Article(models.Model): author = models.ForeignKey(Author) headline = models.CharField(max_length=50) pub_date = models.DateTimeField() categories = models.ManyToManyField(Category) class Meta: ordering = ('pub_date',) def __unicode__(self): return self.headline class AuthorProfile(models.Model): author = models.OneToOneField(Author, primary_key=True) date_of_birth = models.DateField() def __unicode__(self): return u"Profile of %s" % self.author class Actor(models.Model): name = models.CharField(max_length=20, primary_key=True) class Meta: ordering = ('name',) def __unicode__(self): return self.name class Movie(models.Model): actor = models.ForeignKey(Actor) title = models.CharField(max_length=50) price = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal('0.00')) class Meta: ordering = ('title',) def __unicode__(self): return self.title class Score(models.Model): score = models.FloatField() class Team(object): def __init__(self, title): self.title = title def __unicode__(self): raise NotImplementedError("Not so simple") def __str__(self): raise NotImplementedError("Not so simple") def to_string(self): return "%s" % self.title class TeamField(models.CharField): __metaclass__ = models.SubfieldBase def __init__(self): super(TeamField, self).__init__(max_length=100) def get_db_prep_save(self, value): return unicode(value.title) def to_python(self, value): if isinstance(value, Team): return value return Team(value) def value_to_string(self, obj): return self._get_val_from_obj(obj).to_string() class Player(models.Model): name = models.CharField(max_length=50) rank = models.IntegerField() team = TeamField() def __unicode__(self): return u'%s (%d) playing for %s' % (self.name, self.rank, self.team.to_string())
2,639
Python
.py
77
28.532468
88
0.660983
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,383
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/serializers/tests.py
# -*- coding: utf-8 -*- from datetime import datetime from StringIO import StringIO import unittest from xml.dom import minidom from django.conf import settings from django.core import serializers from django.db import transaction from django.test import TestCase, TransactionTestCase, Approximate from django.utils import simplejson from models import Category, Author, Article, AuthorProfile, Actor, \ Movie, Score, Player, Team class SerializerRegistrationTests(unittest.TestCase): def setUp(self): self.old_SERIALIZATION_MODULES = getattr(settings, 'SERIALIZATION_MODULES', None) self.old_serializers = serializers._serializers serializers._serializers = {} settings.SERIALIZATION_MODULES = { "json2" : "django.core.serializers.json", } def tearDown(self): serializers._serializers = self.old_serializers if self.old_SERIALIZATION_MODULES: settings.SERIALIZATION_MODULES = self.old_SERIALIZATION_MODULES else: delattr(settings, 'SERIALIZATION_MODULES') def test_register(self): "Registering a new serializer populates the full registry. Refs #14823" serializers.register_serializer('json3', 'django.core.serializers.json') public_formats = serializers.get_public_serializer_formats() self.assertTrue('json3' in public_formats) self.assertTrue('json2' in public_formats) self.assertTrue('xml' in public_formats) def test_unregister(self): "Unregistering a serializer doesn't cause the registry to be repopulated. Refs #14823" serializers.unregister_serializer('xml') serializers.register_serializer('json3', 'django.core.serializers.json') public_formats = serializers.get_public_serializer_formats() self.assertFalse('xml' in public_formats) self.assertTrue('json3' in public_formats) def test_builtin_serializers(self): "Requesting a list of serializer formats popuates the registry" all_formats = set(serializers.get_serializer_formats()) public_formats = set(serializers.get_public_serializer_formats()) self.assertTrue('xml' in all_formats), self.assertTrue('xml' in public_formats) self.assertTrue('json2' in all_formats) self.assertTrue('json2' in public_formats) self.assertTrue('python' in all_formats) self.assertFalse('python' in public_formats) class SerializersTestBase(object): @staticmethod def _comparison_value(value): return value def setUp(self): sports = Category.objects.create(name="Sports") music = Category.objects.create(name="Music") op_ed = Category.objects.create(name="Op-Ed") self.joe = Author.objects.create(name="Joe") self.jane = Author.objects.create(name="Jane") self.a1 = Article( author=self.jane, headline="Poker has no place on ESPN", pub_date=datetime(2006, 6, 16, 11, 00) ) self.a1.save() self.a1.categories = [sports, op_ed] self.a2 = Article( author=self.joe, headline="Time to reform copyright", pub_date=datetime(2006, 6, 16, 13, 00, 11, 345) ) self.a2.save() self.a2.categories = [music, op_ed] def test_serialize(self): """Tests that basic serialization works.""" serial_str = serializers.serialize(self.serializer_name, Article.objects.all()) self.assertTrue(self._validate_output(serial_str)) def test_serializer_roundtrip(self): """Tests that serialized content can be deserialized.""" serial_str = serializers.serialize(self.serializer_name, Article.objects.all()) models = list(serializers.deserialize(self.serializer_name, serial_str)) self.assertEqual(len(models), 2) def test_altering_serialized_output(self): """ Tests the ability to create new objects by modifying serialized content. """ old_headline = "Poker has no place on ESPN" new_headline = "Poker has no place on television" serial_str = serializers.serialize(self.serializer_name, Article.objects.all()) serial_str = serial_str.replace(old_headline, new_headline) models = list(serializers.deserialize(self.serializer_name, serial_str)) # Prior to saving, old headline is in place self.assertTrue(Article.objects.filter(headline=old_headline)) self.assertFalse(Article.objects.filter(headline=new_headline)) for model in models: model.save() # After saving, new headline is in place self.assertTrue(Article.objects.filter(headline=new_headline)) self.assertFalse(Article.objects.filter(headline=old_headline)) def test_one_to_one_as_pk(self): """ Tests that if you use your own primary key field (such as a OneToOneField), it doesn't appear in the serialized field list - it replaces the pk identifier. """ profile = AuthorProfile(author=self.joe, date_of_birth=datetime(1970,1,1)) profile.save() serial_str = serializers.serialize(self.serializer_name, AuthorProfile.objects.all()) self.assertFalse(self._get_field_values(serial_str, 'author')) for obj in serializers.deserialize(self.serializer_name, serial_str): self.assertEqual(obj.object.pk, self._comparison_value(self.joe.pk)) def test_serialize_field_subset(self): """Tests that output can be restricted to a subset of fields""" valid_fields = ('headline','pub_date') invalid_fields = ("author", "categories") serial_str = serializers.serialize(self.serializer_name, Article.objects.all(), fields=valid_fields) for field_name in invalid_fields: self.assertFalse(self._get_field_values(serial_str, field_name)) for field_name in valid_fields: self.assertTrue(self._get_field_values(serial_str, field_name)) def test_serialize_unicode(self): """Tests that unicode makes the roundtrip intact""" actor_name = u"Za\u017c\u00f3\u0142\u0107" movie_title = u'G\u0119\u015bl\u0105 ja\u017a\u0144' ac = Actor(name=actor_name) mv = Movie(title=movie_title, actor=ac) ac.save() mv.save() serial_str = serializers.serialize(self.serializer_name, [mv]) self.assertEqual(self._get_field_values(serial_str, "title")[0], movie_title) self.assertEqual(self._get_field_values(serial_str, "actor")[0], actor_name) obj_list = list(serializers.deserialize(self.serializer_name, serial_str)) mv_obj = obj_list[0].object self.assertEqual(mv_obj.title, movie_title) def test_serialize_with_null_pk(self): """ Tests that serialized data with no primary key results in a model instance with no id """ category = Category(name="Reference") serial_str = serializers.serialize(self.serializer_name, [category]) pk_value = self._get_pk_values(serial_str)[0] self.assertFalse(pk_value) cat_obj = list(serializers.deserialize(self.serializer_name, serial_str))[0].object self.assertEqual(cat_obj.id, None) def test_float_serialization(self): """Tests that float values serialize and deserialize intact""" sc = Score(score=3.4) sc.save() serial_str = serializers.serialize(self.serializer_name, [sc]) deserial_objs = list(serializers.deserialize(self.serializer_name, serial_str)) self.assertEqual(deserial_objs[0].object.score, Approximate(3.4, places=1)) def test_custom_field_serialization(self): """Tests that custom fields serialize and deserialize intact""" team_str = "Spartak Moskva" player = Player() player.name = "Soslan Djanaev" player.rank = 1 player.team = Team(team_str) player.save() serial_str = serializers.serialize(self.serializer_name, Player.objects.all()) team = self._get_field_values(serial_str, "team") self.assertTrue(team) self.assertEqual(team[0], team_str) deserial_objs = list(serializers.deserialize(self.serializer_name, serial_str)) self.assertEqual(deserial_objs[0].object.team.to_string(), player.team.to_string()) def test_pre_1000ad_date(self): """Tests that year values before 1000AD are properly formatted""" # Regression for #12524 -- dates before 1000AD get prefixed # 0's on the year a = Article.objects.create( author = self.jane, headline = "Nobody remembers the early years", pub_date = datetime(1, 2, 3, 4, 5, 6)) serial_str = serializers.serialize(self.serializer_name, [a]) date_values = self._get_field_values(serial_str, "pub_date") self.assertEquals(date_values[0], "0001-02-03 04:05:06") def test_pkless_serialized_strings(self): """ Tests that serialized strings without PKs can be turned into models """ deserial_objs = list(serializers.deserialize(self.serializer_name, self.pkless_str)) for obj in deserial_objs: self.assertFalse(obj.object.id) obj.save() self.assertEqual(Category.objects.all().count(), 4) class SerializersTransactionTestBase(object): def test_forward_refs(self): """ Tests that objects ids can be referenced before they are defined in the serialization data. """ # The deserialization process needs to be contained # within a transaction in order to test forward reference # handling. transaction.enter_transaction_management() transaction.managed(True) objs = serializers.deserialize(self.serializer_name, self.fwd_ref_str) for obj in objs: obj.save() transaction.commit() transaction.leave_transaction_management() for model_cls in (Category, Author, Article): self.assertEqual(model_cls.objects.all().count(), 1) art_obj = Article.objects.all()[0] self.assertEqual(art_obj.categories.all().count(), 1) self.assertEqual(art_obj.author.name, "Agnes") class XmlSerializerTestCase(SerializersTestBase, TestCase): serializer_name = "xml" pkless_str = """<?xml version="1.0" encoding="utf-8"?> <django-objects version="1.0"> <object model="serializers.category"> <field type="CharField" name="name">Reference</field> </object> </django-objects>""" @staticmethod def _comparison_value(value): # The XML serializer handles everything as strings, so comparisons # need to be performed on the stringified value return unicode(value) @staticmethod def _validate_output(serial_str): try: minidom.parseString(serial_str) except Exception: return False else: return True @staticmethod def _get_pk_values(serial_str): ret_list = [] dom = minidom.parseString(serial_str) fields = dom.getElementsByTagName("object") for field in fields: ret_list.append(field.getAttribute("pk")) return ret_list @staticmethod def _get_field_values(serial_str, field_name): ret_list = [] dom = minidom.parseString(serial_str) fields = dom.getElementsByTagName("field") for field in fields: if field.getAttribute("name") == field_name: temp = [] for child in field.childNodes: temp.append(child.nodeValue) ret_list.append("".join(temp)) return ret_list class XmlSerializerTransactionTestCase(SerializersTransactionTestBase, TransactionTestCase): serializer_name = "xml" fwd_ref_str = """<?xml version="1.0" encoding="utf-8"?> <django-objects version="1.0"> <object pk="1" model="serializers.article"> <field to="serializers.author" name="author" rel="ManyToOneRel">1</field> <field type="CharField" name="headline">Forward references pose no problem</field> <field type="DateTimeField" name="pub_date">2006-06-16 15:00:00</field> <field to="serializers.category" name="categories" rel="ManyToManyRel"> <object pk="1"></object> </field> </object> <object pk="1" model="serializers.author"> <field type="CharField" name="name">Agnes</field> </object> <object pk="1" model="serializers.category"> <field type="CharField" name="name">Reference</field></object> </django-objects>""" class JsonSerializerTestCase(SerializersTestBase, TestCase): serializer_name = "json" pkless_str = """[{"pk": null, "model": "serializers.category", "fields": {"name": "Reference"}}]""" @staticmethod def _validate_output(serial_str): try: simplejson.loads(serial_str) except Exception: return False else: return True @staticmethod def _get_pk_values(serial_str): ret_list = [] serial_list = simplejson.loads(serial_str) for obj_dict in serial_list: ret_list.append(obj_dict["pk"]) return ret_list @staticmethod def _get_field_values(serial_str, field_name): ret_list = [] serial_list = simplejson.loads(serial_str) for obj_dict in serial_list: if field_name in obj_dict["fields"]: ret_list.append(obj_dict["fields"][field_name]) return ret_list class JsonSerializerTransactionTestCase(SerializersTransactionTestBase, TransactionTestCase): serializer_name = "json" fwd_ref_str = """[ { "pk": 1, "model": "serializers.article", "fields": { "headline": "Forward references pose no problem", "pub_date": "2006-06-16 15:00:00", "categories": [1], "author": 1 } }, { "pk": 1, "model": "serializers.category", "fields": { "name": "Reference" } }, { "pk": 1, "model": "serializers.author", "fields": { "name": "Agnes" } }]""" try: import yaml except ImportError: pass else: class YamlSerializerTestCase(SerializersTestBase, TestCase): serializer_name = "yaml" fwd_ref_str = """- fields: headline: Forward references pose no problem pub_date: 2006-06-16 15:00:00 categories: [1] author: 1 pk: 1 model: serializers.article - fields: name: Reference pk: 1 model: serializers.category - fields: name: Agnes pk: 1 model: serializers.author""" pkless_str = """- fields: name: Reference pk: null model: serializers.category""" @staticmethod def _validate_output(serial_str): try: yaml.load(StringIO(serial_str)) except Exception: return False else: return True @staticmethod def _get_pk_values(serial_str): ret_list = [] stream = StringIO(serial_str) for obj_dict in yaml.load(stream): ret_list.append(obj_dict["pk"]) return ret_list @staticmethod def _get_field_values(serial_str, field_name): ret_list = [] stream = StringIO(serial_str) for obj_dict in yaml.load(stream): if "fields" in obj_dict and field_name in obj_dict["fields"]: field_value = obj_dict["fields"][field_name] # yaml.load will return non-string objects for some # of the fields we are interested in, this ensures that # everything comes back as a string if isinstance(field_value, basestring): ret_list.append(field_value) else: ret_list.append(str(field_value)) return ret_list class YamlSerializerTransactionTestCase(SerializersTransactionTestBase, TransactionTestCase): serializer_name = "yaml" fwd_ref_str = """- fields: headline: Forward references pose no problem pub_date: 2006-06-16 15:00:00 categories: [1] author: 1 pk: 1 model: serializers.article - fields: name: Reference pk: 1 model: serializers.category - fields: name: Agnes pk: 1 model: serializers.author"""
17,204
Python
.py
407
32.65602
103
0.625276
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,384
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/fixtures/models.py
""" 37. Fixtures. Fixtures are a way of loading data into the database in bulk. Fixure data can be stored in any serializable format (including JSON and XML). Fixtures are identified by name, and are stored in either a directory named 'fixtures' in the application directory, on in one of the directories named in the ``FIXTURE_DIRS`` setting. """ from django.contrib.auth.models import Permission from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.db import models, DEFAULT_DB_ALIAS from django.conf import settings class Category(models.Model): title = models.CharField(max_length=100) description = models.TextField() def __unicode__(self): return self.title class Meta: ordering = ('title',) class Article(models.Model): headline = models.CharField(max_length=100, default='Default headline') pub_date = models.DateTimeField() def __unicode__(self): return self.headline class Meta: ordering = ('-pub_date', 'headline') class Blog(models.Model): name = models.CharField(max_length=100) featured = models.ForeignKey(Article, related_name='fixtures_featured_set') articles = models.ManyToManyField(Article, blank=True, related_name='fixtures_articles_set') def __unicode__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=100) tagged_type = models.ForeignKey(ContentType, related_name="fixtures_tag_set") tagged_id = models.PositiveIntegerField(default=0) tagged = generic.GenericForeignKey(ct_field='tagged_type', fk_field='tagged_id') def __unicode__(self): return '<%s: %s> tagged "%s"' % (self.tagged.__class__.__name__, self.tagged, self.name) class PersonManager(models.Manager): def get_by_natural_key(self, name): return self.get(name=name) class Person(models.Model): objects = PersonManager() name = models.CharField(max_length=100) def __unicode__(self): return self.name class Meta: ordering = ('name',) def natural_key(self): return (self.name,) class Visa(models.Model): person = models.ForeignKey(Person) permissions = models.ManyToManyField(Permission, blank=True) def __unicode__(self): return '%s %s' % (self.person.name, ', '.join(p.name for p in self.permissions.all())) class Book(models.Model): name = models.CharField(max_length=100) authors = models.ManyToManyField(Person) def __unicode__(self): return '%s by %s' % (self.name, ' and '.join(a.name for a in self.authors.all())) class Meta: ordering = ('name',)
2,858
Python
.py
69
34.376812
81
0.665221
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,385
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/fixtures/tests.py
import StringIO import sys from django.test import TestCase, TransactionTestCase from django.conf import settings from django.core import management from django.db import DEFAULT_DB_ALIAS from models import Article, Blog, Book, Category, Person, Tag, Visa class TestCaseFixtureLoadingTests(TestCase): fixtures = ['fixture1.json', 'fixture2.json'] def testClassFixtures(self): "Check that test case has installed 4 fixture objects" self.assertEqual(Article.objects.count(), 4) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: Django conquers world!>', '<Article: Copyright is fine the way it is>', '<Article: Poker has no place on ESPN>', '<Article: Python program becomes self aware>' ]) class FixtureLoadingTests(TestCase): def _dumpdata_assert(self, args, output, format='json', natural_keys=False): new_io = StringIO.StringIO() management.call_command('dumpdata', *args, **{'format':format, 'stdout':new_io, 'use_natural_keys':natural_keys}) command_output = new_io.getvalue().strip() self.assertEqual(command_output, output) def test_initial_data(self): # Syncdb introduces 1 initial data object from initial_data.json. self.assertQuerysetEqual(Article.objects.all(), [ '<Article: Python program becomes self aware>' ]) def test_loading_and_dumping(self): new_io = StringIO.StringIO() # Load fixture 1. Single JSON file, with two objects. management.call_command('loaddata', 'fixture1.json', verbosity=0, commit=False) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: Time to reform copyright>', '<Article: Poker has no place on ESPN>', '<Article: Python program becomes self aware>' ]) # Dump the current contents of the database as a JSON fixture self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}]') # Try just dumping the contents of fixtures.Category self._dumpdata_assert(['fixtures.Category'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}]') # ...and just fixtures.Article self._dumpdata_assert(['fixtures.Article'], '[{"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}]') # ...and both self._dumpdata_assert(['fixtures.Category', 'fixtures.Article'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}]') # Specify a specific model twice self._dumpdata_assert(['fixtures.Article', 'fixtures.Article'], '[{"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}]') # Specify a dump that specifies Article both explicitly and implicitly self._dumpdata_assert(['fixtures.Article', 'fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}]') # Same again, but specify in the reverse order self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}]') # Specify one model from one application, and an entire other application. self._dumpdata_assert(['fixtures.Category', 'sites'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}]') # Load fixture 2. JSON file imported by default. Overwrites some existing objects management.call_command('loaddata', 'fixture2.json', verbosity=0, commit=False) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: Django conquers world!>', '<Article: Copyright is fine the way it is>', '<Article: Poker has no place on ESPN>', '<Article: Python program becomes self aware>' ]) # Load fixture 3, XML format. management.call_command('loaddata', 'fixture3.xml', verbosity=0, commit=False) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: XML identified as leading cause of cancer>', '<Article: Django conquers world!>', '<Article: Copyright is fine the way it is>', '<Article: Poker on TV is great!>', '<Article: Python program becomes self aware>' ]) # Load fixture 6, JSON file with dynamic ContentType fields. Testing ManyToOne. management.call_command('loaddata', 'fixture6.json', verbosity=0, commit=False) self.assertQuerysetEqual(Tag.objects.all(), [ '<Tag: <Article: Copyright is fine the way it is> tagged "copyright">', '<Tag: <Article: Copyright is fine the way it is> tagged "law">' ]) # Load fixture 7, XML file with dynamic ContentType fields. Testing ManyToOne. management.call_command('loaddata', 'fixture7.xml', verbosity=0, commit=False) self.assertQuerysetEqual(Tag.objects.all(), [ '<Tag: <Article: Copyright is fine the way it is> tagged "copyright">', '<Tag: <Article: Copyright is fine the way it is> tagged "legal">', '<Tag: <Article: Django conquers world!> tagged "django">', '<Tag: <Article: Django conquers world!> tagged "world domination">' ]) # Load fixture 8, JSON file with dynamic Permission fields. Testing ManyToMany. management.call_command('loaddata', 'fixture8.json', verbosity=0, commit=False) self.assertQuerysetEqual(Visa.objects.all(), [ '<Visa: Django Reinhardt Can add user, Can change user, Can delete user>', '<Visa: Stephane Grappelli Can add user>', '<Visa: Prince >' ]) # Load fixture 9, XML file with dynamic Permission fields. Testing ManyToMany. management.call_command('loaddata', 'fixture9.xml', verbosity=0, commit=False) self.assertQuerysetEqual(Visa.objects.all(), [ '<Visa: Django Reinhardt Can add user, Can change user, Can delete user>', '<Visa: Stephane Grappelli Can add user, Can delete user>', '<Visa: Artist formerly known as "Prince" Can change user>' ]) self.assertQuerysetEqual(Book.objects.all(), [ '<Book: Music for all ages by Artist formerly known as "Prince" and Django Reinhardt>' ]) # Load a fixture that doesn't exist management.call_command('loaddata', 'unknown.json', verbosity=0, commit=False) # object list is unaffected self.assertQuerysetEqual(Article.objects.all(), [ '<Article: XML identified as leading cause of cancer>', '<Article: Django conquers world!>', '<Article: Copyright is fine the way it is>', '<Article: Poker on TV is great!>', '<Article: Python program becomes self aware>' ]) # By default, you get raw keys on dumpdata self._dumpdata_assert(['fixtures.book'], '[{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [3, 1]}}]') # But you can get natural keys if you ask for them and they are available self._dumpdata_assert(['fixtures.book'], '[{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [["Artist formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]', natural_keys=True) # Dump the current contents of the database as a JSON fixture self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 5, "model": "fixtures.article", "fields": {"headline": "XML identified as leading cause of cancer", "pub_date": "2006-06-16 16:00:00"}}, {"pk": 4, "model": "fixtures.article", "fields": {"headline": "Django conquers world!", "pub_date": "2006-06-16 15:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16 14:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker on TV is great!", "pub_date": "2006-06-16 11:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}, {"pk": 1, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "copyright", "tagged_id": 3}}, {"pk": 2, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "legal", "tagged_id": 3}}, {"pk": 3, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "django", "tagged_id": 4}}, {"pk": 4, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "world domination", "tagged_id": 4}}, {"pk": 3, "model": "fixtures.person", "fields": {"name": "Artist formerly known as \\"Prince\\""}}, {"pk": 1, "model": "fixtures.person", "fields": {"name": "Django Reinhardt"}}, {"pk": 2, "model": "fixtures.person", "fields": {"name": "Stephane Grappelli"}}, {"pk": 1, "model": "fixtures.visa", "fields": {"person": ["Django Reinhardt"], "permissions": [["add_user", "auth", "user"], ["change_user", "auth", "user"], ["delete_user", "auth", "user"]]}}, {"pk": 2, "model": "fixtures.visa", "fields": {"person": ["Stephane Grappelli"], "permissions": [["add_user", "auth", "user"], ["delete_user", "auth", "user"]]}}, {"pk": 3, "model": "fixtures.visa", "fields": {"person": ["Artist formerly known as \\"Prince\\""], "permissions": [["change_user", "auth", "user"]]}}, {"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [["Artist formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]', natural_keys=True) # Dump the current contents of the database as an XML fixture self._dumpdata_assert(['fixtures'], """<?xml version="1.0" encoding="utf-8"?> <django-objects version="1.0"><object pk="1" model="fixtures.category"><field type="CharField" name="title">News Stories</field><field type="TextField" name="description">Latest news stories</field></object><object pk="5" model="fixtures.article"><field type="CharField" name="headline">XML identified as leading cause of cancer</field><field type="DateTimeField" name="pub_date">2006-06-16 16:00:00</field></object><object pk="4" model="fixtures.article"><field type="CharField" name="headline">Django conquers world!</field><field type="DateTimeField" name="pub_date">2006-06-16 15:00:00</field></object><object pk="3" model="fixtures.article"><field type="CharField" name="headline">Copyright is fine the way it is</field><field type="DateTimeField" name="pub_date">2006-06-16 14:00:00</field></object><object pk="2" model="fixtures.article"><field type="CharField" name="headline">Poker on TV is great!</field><field type="DateTimeField" name="pub_date">2006-06-16 11:00:00</field></object><object pk="1" model="fixtures.article"><field type="CharField" name="headline">Python program becomes self aware</field><field type="DateTimeField" name="pub_date">2006-06-16 11:00:00</field></object><object pk="1" model="fixtures.tag"><field type="CharField" name="name">copyright</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="2" model="fixtures.tag"><field type="CharField" name="name">legal</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="3" model="fixtures.tag"><field type="CharField" name="name">django</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">4</field></object><object pk="4" model="fixtures.tag"><field type="CharField" name="name">world domination</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">4</field></object><object pk="3" model="fixtures.person"><field type="CharField" name="name">Artist formerly known as "Prince"</field></object><object pk="1" model="fixtures.person"><field type="CharField" name="name">Django Reinhardt</field></object><object pk="2" model="fixtures.person"><field type="CharField" name="name">Stephane Grappelli</field></object><object pk="1" model="fixtures.visa"><field to="fixtures.person" name="person" rel="ManyToOneRel"><natural>Django Reinhardt</natural></field><field to="auth.permission" name="permissions" rel="ManyToManyRel"><object><natural>add_user</natural><natural>auth</natural><natural>user</natural></object><object><natural>change_user</natural><natural>auth</natural><natural>user</natural></object><object><natural>delete_user</natural><natural>auth</natural><natural>user</natural></object></field></object><object pk="2" model="fixtures.visa"><field to="fixtures.person" name="person" rel="ManyToOneRel"><natural>Stephane Grappelli</natural></field><field to="auth.permission" name="permissions" rel="ManyToManyRel"><object><natural>add_user</natural><natural>auth</natural><natural>user</natural></object><object><natural>delete_user</natural><natural>auth</natural><natural>user</natural></object></field></object><object pk="3" model="fixtures.visa"><field to="fixtures.person" name="person" rel="ManyToOneRel"><natural>Artist formerly known as "Prince"</natural></field><field to="auth.permission" name="permissions" rel="ManyToManyRel"><object><natural>change_user</natural><natural>auth</natural><natural>user</natural></object></field></object><object pk="1" model="fixtures.book"><field type="CharField" name="name">Music for all ages</field><field to="fixtures.person" name="authors" rel="ManyToManyRel"><object><natural>Artist formerly known as "Prince"</natural></object><object><natural>Django Reinhardt</natural></object></field></object></django-objects>""", format='xml', natural_keys=True) def test_compress_format_loading(self): # Load fixture 4 (compressed), using format specification management.call_command('loaddata', 'fixture4.json', verbosity=0, commit=False) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: Django pets kitten>', '<Article: Python program becomes self aware>' ]) def test_compressed_specified_loading(self): # Load fixture 5 (compressed), using format *and* compression specification management.call_command('loaddata', 'fixture5.json.zip', verbosity=0, commit=False) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: WoW subscribers now outnumber readers>', '<Article: Python program becomes self aware>' ]) def test_compressed_loading(self): # Load fixture 5 (compressed), only compression specification management.call_command('loaddata', 'fixture5.zip', verbosity=0, commit=False) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: WoW subscribers now outnumber readers>', '<Article: Python program becomes self aware>' ]) def test_ambiguous_compressed_fixture(self): # The name "fixture5" is ambigous, so loading it will raise an error new_io = StringIO.StringIO() management.call_command('loaddata', 'fixture5', verbosity=0, stderr=new_io, commit=False) output = new_io.getvalue().strip().split('\n') self.assertEqual(len(output), 1) self.assertTrue(output[0].startswith("Multiple fixtures named 'fixture5'")) def test_db_loading(self): # Load db fixtures 1 and 2. These will load using the 'default' database identifier implicitly management.call_command('loaddata', 'db_fixture_1', verbosity=0, commit=False) management.call_command('loaddata', 'db_fixture_2', verbosity=0, commit=False) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: Who needs more than one database?>', '<Article: Who needs to use compressed data?>', '<Article: Python program becomes self aware>' ]) def test_loading_using(self): # Load db fixtures 1 and 2. These will load using the 'default' database identifier explicitly management.call_command('loaddata', 'db_fixture_1', verbosity=0, using='default', commit=False) management.call_command('loaddata', 'db_fixture_2', verbosity=0, using='default', commit=False) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: Who needs more than one database?>', '<Article: Who needs to use compressed data?>', '<Article: Python program becomes self aware>' ]) def test_unmatched_identifier_loading(self): # Try to load db fixture 3. This won't load because the database identifier doesn't match management.call_command('loaddata', 'db_fixture_3', verbosity=0, commit=False) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: Python program becomes self aware>' ]) management.call_command('loaddata', 'db_fixture_3', verbosity=0, using='default', commit=False) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: Python program becomes self aware>' ]) def test_output_formats(self): # Load back in fixture 1, we need the articles from it management.call_command('loaddata', 'fixture1', verbosity=0, commit=False) # Try to load fixture 6 using format discovery management.call_command('loaddata', 'fixture6', verbosity=0, commit=False) self.assertQuerysetEqual(Tag.objects.all(), [ '<Tag: <Article: Time to reform copyright> tagged "copyright">', '<Tag: <Article: Time to reform copyright> tagged "law">' ]) # Dump the current contents of the database as a JSON fixture self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}, {"pk": 1, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "copyright", "tagged_id": 3}}, {"pk": 2, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "law", "tagged_id": 3}}, {"pk": 1, "model": "fixtures.person", "fields": {"name": "Django Reinhardt"}}, {"pk": 3, "model": "fixtures.person", "fields": {"name": "Prince"}}, {"pk": 2, "model": "fixtures.person", "fields": {"name": "Stephane Grappelli"}}]', natural_keys=True) # Dump the current contents of the database as an XML fixture self._dumpdata_assert(['fixtures'], """<?xml version="1.0" encoding="utf-8"?> <django-objects version="1.0"><object pk="1" model="fixtures.category"><field type="CharField" name="title">News Stories</field><field type="TextField" name="description">Latest news stories</field></object><object pk="3" model="fixtures.article"><field type="CharField" name="headline">Time to reform copyright</field><field type="DateTimeField" name="pub_date">2006-06-16 13:00:00</field></object><object pk="2" model="fixtures.article"><field type="CharField" name="headline">Poker has no place on ESPN</field><field type="DateTimeField" name="pub_date">2006-06-16 12:00:00</field></object><object pk="1" model="fixtures.article"><field type="CharField" name="headline">Python program becomes self aware</field><field type="DateTimeField" name="pub_date">2006-06-16 11:00:00</field></object><object pk="1" model="fixtures.tag"><field type="CharField" name="name">copyright</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="2" model="fixtures.tag"><field type="CharField" name="name">law</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="1" model="fixtures.person"><field type="CharField" name="name">Django Reinhardt</field></object><object pk="3" model="fixtures.person"><field type="CharField" name="name">Prince</field></object><object pk="2" model="fixtures.person"><field type="CharField" name="name">Stephane Grappelli</field></object></django-objects>""", format='xml', natural_keys=True) if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.mysql': class FixtureTransactionTests(TransactionTestCase): def _dumpdata_assert(self, args, output, format='json'): new_io = StringIO.StringIO() management.call_command('dumpdata', *args, **{'format':format, 'stdout':new_io}) command_output = new_io.getvalue().strip() self.assertEqual(command_output, output) def test_format_discovery(self): # Load fixture 1 again, using format discovery management.call_command('loaddata', 'fixture1', verbosity=0, commit=False) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: Time to reform copyright>', '<Article: Poker has no place on ESPN>', '<Article: Python program becomes self aware>' ]) # Try to load fixture 2 using format discovery; this will fail # because there are two fixture2's in the fixtures directory new_io = StringIO.StringIO() management.call_command('loaddata', 'fixture2', verbosity=0, stderr=new_io) output = new_io.getvalue().strip().split('\n') self.assertEqual(len(output), 1) self.assertTrue(output[0].startswith("Multiple fixtures named 'fixture2'")) # object list is unaffected self.assertQuerysetEqual(Article.objects.all(), [ '<Article: Time to reform copyright>', '<Article: Poker has no place on ESPN>', '<Article: Python program becomes self aware>' ]) # Dump the current contents of the database as a JSON fixture self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}]') # Load fixture 4 (compressed), using format discovery management.call_command('loaddata', 'fixture4', verbosity=0, commit=False) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: Django pets kitten>', '<Article: Time to reform copyright>', '<Article: Poker has no place on ESPN>', '<Article: Python program becomes self aware>' ])
26,439
Python
.py
229
105.248908
4,318
0.660768
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,386
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/__init__.py
VERSION = (1, 2, 5, 'final', 0) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': version = '%s %s %s' % (version, VERSION[3], VERSION[4]) from django.utils.version import get_svn_revision svn_rev = get_svn_revision() if svn_rev != u'SVN-unknown': version = "%s %s" % (version, svn_rev) return version
549
Python
.py
15
30.466667
68
0.553471
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,387
client.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/test/client.py
import urllib from urlparse import urlparse, urlunparse, urlsplit import sys import os import re import mimetypes try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.conf import settings from django.contrib.auth import authenticate, login from django.core.handlers.base import BaseHandler from django.core.handlers.wsgi import WSGIRequest from django.core.signals import got_request_exception from django.http import SimpleCookie, HttpRequest, QueryDict from django.template import TemplateDoesNotExist from django.test import signals from django.utils.functional import curry from django.utils.encoding import smart_str from django.utils.http import urlencode from django.utils.importlib import import_module from django.utils.itercompat import is_iterable from django.db import transaction, close_connection from django.test.utils import ContextList BOUNDARY = 'BoUnDaRyStRiNg' MULTIPART_CONTENT = 'multipart/form-data; boundary=%s' % BOUNDARY CONTENT_TYPE_RE = re.compile('.*; charset=([\w\d-]+);?') class FakePayload(object): """ A wrapper around StringIO that restricts what can be read since data from the network can't be seeked and cannot be read outside of its content length. This makes sure that views can't do anything under the test client that wouldn't work in Real Life. """ def __init__(self, content): self.__content = StringIO(content) self.__len = len(content) def read(self, num_bytes=None): if num_bytes is None: num_bytes = self.__len or 1 assert self.__len >= num_bytes, "Cannot read more than the available bytes from the HTTP incoming data." content = self.__content.read(num_bytes) self.__len -= num_bytes return content class ClientHandler(BaseHandler): """ A HTTP Handler that can be used for testing purposes. Uses the WSGI interface to compose requests, but returns the raw HttpResponse object """ def __init__(self, enforce_csrf_checks=True, *args, **kwargs): self.enforce_csrf_checks = enforce_csrf_checks super(ClientHandler, self).__init__(*args, **kwargs) def __call__(self, environ): from django.conf import settings from django.core import signals # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. if self._request_middleware is None: self.load_middleware() signals.request_started.send(sender=self.__class__) try: request = WSGIRequest(environ) # sneaky little hack so that we can easily get round # CsrfViewMiddleware. This makes life easier, and is probably # required for backwards compatibility with external tests against # admin views. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks response = self.get_response(request) # Apply response middleware. for middleware_method in self._response_middleware: response = middleware_method(request, response) response = self.apply_response_fixes(request, response) finally: signals.request_finished.disconnect(close_connection) signals.request_finished.send(sender=self.__class__) signals.request_finished.connect(close_connection) return response def store_rendered_templates(store, signal, sender, template, context, **kwargs): """ Stores templates and contexts that are rendered. """ store.setdefault('template', []).append(template) store.setdefault('context', ContextList()).append(context) def encode_multipart(boundary, data): """ Encodes multipart POST data from a dictionary of form values. The key will be used as the form data name; the value will be transmitted as content. If the value is a file, the contents of the file will be sent as an application/octet-stream; otherwise, str(value) will be sent. """ lines = [] to_str = lambda s: smart_str(s, settings.DEFAULT_CHARSET) # Not by any means perfect, but good enough for our purposes. is_file = lambda thing: hasattr(thing, "read") and callable(thing.read) # Each bit of the multipart form data could be either a form value or a # file, or a *list* of form values and/or files. Remember that HTTP field # names can be duplicated! for (key, value) in data.items(): if is_file(value): lines.extend(encode_file(boundary, key, value)) elif not isinstance(value, basestring) and is_iterable(value): for item in value: if is_file(item): lines.extend(encode_file(boundary, key, item)) else: lines.extend([ '--' + boundary, 'Content-Disposition: form-data; name="%s"' % to_str(key), '', to_str(item) ]) else: lines.extend([ '--' + boundary, 'Content-Disposition: form-data; name="%s"' % to_str(key), '', to_str(value) ]) lines.extend([ '--' + boundary + '--', '', ]) return '\r\n'.join(lines) def encode_file(boundary, key, file): to_str = lambda s: smart_str(s, settings.DEFAULT_CHARSET) content_type = mimetypes.guess_type(file.name)[0] if content_type is None: content_type = 'application/octet-stream' return [ '--' + boundary, 'Content-Disposition: form-data; name="%s"; filename="%s"' \ % (to_str(key), to_str(os.path.basename(file.name))), 'Content-Type: %s' % content_type, '', file.read() ] class Client(object): """ A class that can act as a client for testing purposes. It allows the user to compose GET and POST requests, and obtain the response that the server gave to those requests. The server Response objects are annotated with the details of the contexts and templates that were rendered during the process of serving the request. Client objects are stateful - they will retain cookie (and thus session) details for the lifetime of the Client instance. This is not intended as a replacement for Twill/Selenium or the like - it is here to allow testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """ def __init__(self, enforce_csrf_checks=False, **defaults): self.handler = ClientHandler(enforce_csrf_checks) self.defaults = defaults self.cookies = SimpleCookie() self.exc_info = None self.errors = StringIO() def store_exc_info(self, **kwargs): """ Stores exceptions when they are generated by a view. """ self.exc_info = sys.exc_info() def _session(self): """ Obtains the current session variables. """ if 'django.contrib.sessions' in settings.INSTALLED_APPS: engine = import_module(settings.SESSION_ENGINE) cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None) if cookie: return engine.SessionStore(cookie.value) return {} session = property(_session) def _get_path(self, parsed): # If there are parameters, add them if parsed[3]: return urllib.unquote(parsed[2] + ";" + parsed[3]) else: return urllib.unquote(parsed[2]) def request(self, **request): """ The master request method. Composes the environment dictionary and passes to the handler, returning the result of the handler. Assumes defaults for the query environment, which can be overridden using the arguments to the request. """ environ = { 'HTTP_COOKIE': self.cookies.output(header='', sep='; '), 'PATH_INFO': '/', 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': '', 'SERVER_NAME': 'testserver', 'SERVER_PORT': '80', 'SERVER_PROTOCOL': 'HTTP/1.1', 'wsgi.version': (1,0), 'wsgi.url_scheme': 'http', 'wsgi.errors': self.errors, 'wsgi.multiprocess': True, 'wsgi.multithread': False, 'wsgi.run_once': False, } environ.update(self.defaults) environ.update(request) # Curry a data dictionary into an instance of the template renderer # callback function. data = {} on_template_render = curry(store_rendered_templates, data) signals.template_rendered.connect(on_template_render, dispatch_uid="template-render") # Capture exceptions created by the handler. got_request_exception.connect(self.store_exc_info, dispatch_uid="request-exception") try: try: response = self.handler(environ) except TemplateDoesNotExist, e: # If the view raises an exception, Django will attempt to show # the 500.html template. If that template is not available, # we should ignore the error in favor of re-raising the # underlying exception that caused the 500 error. Any other # template found to be missing during view error handling # should be reported as-is. if e.args != ('500.html',): raise # Look for a signalled exception, clear the current context # exception data, then re-raise the signalled exception. # Also make sure that the signalled exception is cleared from # the local cache! if self.exc_info: exc_info = self.exc_info self.exc_info = None raise exc_info[1], None, exc_info[2] # Save the client and request that stimulated the response. response.client = self response.request = request # Add any rendered template detail to the response. # If there was only one template rendered (the most likely case), # flatten the list to a single element. for detail in ('template', 'context'): if data.get(detail): if len(data[detail]) == 1: setattr(response, detail, data[detail][0]); else: setattr(response, detail, data[detail]) else: setattr(response, detail, None) # Update persistent cookie data. if response.cookies: self.cookies.update(response.cookies) return response finally: signals.template_rendered.disconnect(dispatch_uid="template-render") got_request_exception.disconnect(dispatch_uid="request-exception") def get(self, path, data={}, follow=False, **extra): """ Requests a response from the server using GET. """ parsed = urlparse(path) r = { 'CONTENT_TYPE': 'text/html; charset=utf-8', 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': urlencode(data, doseq=True) or parsed[4], 'REQUEST_METHOD': 'GET', 'wsgi.input': FakePayload('') } r.update(extra) response = self.request(**r) if follow: response = self._handle_redirects(response, **extra) return response def post(self, path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra): """ Requests a response from the server using POST. """ if content_type is MULTIPART_CONTENT: post_data = encode_multipart(BOUNDARY, data) else: # Encode the content so that the byte representation is correct. match = CONTENT_TYPE_RE.match(content_type) if match: charset = match.group(1) else: charset = settings.DEFAULT_CHARSET post_data = smart_str(data, encoding=charset) parsed = urlparse(path) r = { 'CONTENT_LENGTH': len(post_data), 'CONTENT_TYPE': content_type, 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': parsed[4], 'REQUEST_METHOD': 'POST', 'wsgi.input': FakePayload(post_data), } r.update(extra) response = self.request(**r) if follow: response = self._handle_redirects(response, **extra) return response def head(self, path, data={}, follow=False, **extra): """ Request a response from the server using HEAD. """ parsed = urlparse(path) r = { 'CONTENT_TYPE': 'text/html; charset=utf-8', 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': urlencode(data, doseq=True) or parsed[4], 'REQUEST_METHOD': 'HEAD', 'wsgi.input': FakePayload('') } r.update(extra) response = self.request(**r) if follow: response = self._handle_redirects(response, **extra) return response def options(self, path, data={}, follow=False, **extra): """ Request a response from the server using OPTIONS. """ parsed = urlparse(path) r = { 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': urlencode(data, doseq=True) or parsed[4], 'REQUEST_METHOD': 'OPTIONS', 'wsgi.input': FakePayload('') } r.update(extra) response = self.request(**r) if follow: response = self._handle_redirects(response, **extra) return response def put(self, path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra): """ Send a resource to the server using PUT. """ if content_type is MULTIPART_CONTENT: post_data = encode_multipart(BOUNDARY, data) else: post_data = data # Make `data` into a querystring only if it's not already a string. If # it is a string, we'll assume that the caller has already encoded it. query_string = None if not isinstance(data, basestring): query_string = urlencode(data, doseq=True) parsed = urlparse(path) r = { 'CONTENT_LENGTH': len(post_data), 'CONTENT_TYPE': content_type, 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': query_string or parsed[4], 'REQUEST_METHOD': 'PUT', 'wsgi.input': FakePayload(post_data), } r.update(extra) response = self.request(**r) if follow: response = self._handle_redirects(response, **extra) return response def delete(self, path, data={}, follow=False, **extra): """ Send a DELETE request to the server. """ parsed = urlparse(path) r = { 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': urlencode(data, doseq=True) or parsed[4], 'REQUEST_METHOD': 'DELETE', 'wsgi.input': FakePayload('') } r.update(extra) response = self.request(**r) if follow: response = self._handle_redirects(response, **extra) return response def login(self, **credentials): """ Sets the Client to appear as if it has successfully logged into a site. Returns True if login is possible; False if the provided credentials are incorrect, or the user is inactive, or if the sessions framework is not available. """ user = authenticate(**credentials) if user and user.is_active \ and 'django.contrib.sessions' in settings.INSTALLED_APPS: engine = import_module(settings.SESSION_ENGINE) # Create a fake request to store login details. request = HttpRequest() if self.session: request.session = self.session else: request.session = engine.SessionStore() login(request, user) # Save the session values. request.session.save() # Set the cookie to represent the session. session_cookie = settings.SESSION_COOKIE_NAME self.cookies[session_cookie] = request.session.session_key cookie_data = { 'max-age': None, 'path': '/', 'domain': settings.SESSION_COOKIE_DOMAIN, 'secure': settings.SESSION_COOKIE_SECURE or None, 'expires': None, } self.cookies[session_cookie].update(cookie_data) return True else: return False def logout(self): """ Removes the authenticated user's cookies and session object. Causes the authenticated user to be logged out. """ session = import_module(settings.SESSION_ENGINE).SessionStore() session_cookie = self.cookies.get(settings.SESSION_COOKIE_NAME) if session_cookie: session.delete(session_key=session_cookie.value) self.cookies = SimpleCookie() def _handle_redirects(self, response, **extra): "Follows any redirects by requesting responses from the server using GET." response.redirect_chain = [] while response.status_code in (301, 302, 303, 307): url = response['Location'] scheme, netloc, path, query, fragment = urlsplit(url) redirect_chain = response.redirect_chain redirect_chain.append((url, response.status_code)) if scheme: extra['wsgi.url_scheme'] = scheme # The test client doesn't handle external links, # but since the situation is simulated in test_client, # we fake things here by ignoring the netloc portion of the # redirected URL. response = self.get(path, QueryDict(query), follow=False, **extra) response.redirect_chain = redirect_chain # Prevent loops if response.redirect_chain[-1] in response.redirect_chain[0:-1]: break return response
18,903
Python
.py
442
32.60181
112
0.599554
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,388
testcases.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/test/testcases.py
import re import unittest from urlparse import urlsplit, urlunsplit from xml.dom.minidom import parseString, Node from django.conf import settings from django.core import mail from django.core.management import call_command from django.core.urlresolvers import clear_url_caches from django.db import transaction, connections, DEFAULT_DB_ALIAS from django.http import QueryDict from django.test import _doctest as doctest from django.test.client import Client from django.test.utils import get_warnings_state, restore_warnings_state from django.utils import simplejson from django.utils.encoding import smart_str try: all except NameError: from django.utils.itercompat import all normalize_long_ints = lambda s: re.sub(r'(?<![\w])(\d+)L(?![\w])', '\\1', s) normalize_decimals = lambda s: re.sub(r"Decimal\('(\d+(\.\d*)?)'\)", lambda m: "Decimal(\"%s\")" % m.groups()[0], s) def to_list(value): """ Puts value into a list if it's not already one. Returns an empty list if value is None. """ if value is None: value = [] elif not isinstance(value, list): value = [value] return value real_commit = transaction.commit real_rollback = transaction.rollback real_enter_transaction_management = transaction.enter_transaction_management real_leave_transaction_management = transaction.leave_transaction_management real_savepoint_commit = transaction.savepoint_commit real_savepoint_rollback = transaction.savepoint_rollback real_managed = transaction.managed def nop(*args, **kwargs): return def disable_transaction_methods(): transaction.commit = nop transaction.rollback = nop transaction.savepoint_commit = nop transaction.savepoint_rollback = nop transaction.enter_transaction_management = nop transaction.leave_transaction_management = nop transaction.managed = nop def restore_transaction_methods(): transaction.commit = real_commit transaction.rollback = real_rollback transaction.savepoint_commit = real_savepoint_commit transaction.savepoint_rollback = real_savepoint_rollback transaction.enter_transaction_management = real_enter_transaction_management transaction.leave_transaction_management = real_leave_transaction_management transaction.managed = real_managed class OutputChecker(doctest.OutputChecker): def check_output(self, want, got, optionflags): "The entry method for doctest output checking. Defers to a sequence of child checkers" checks = (self.check_output_default, self.check_output_numeric, self.check_output_xml, self.check_output_json) for check in checks: if check(want, got, optionflags): return True return False def check_output_default(self, want, got, optionflags): "The default comparator provided by doctest - not perfect, but good for most purposes" return doctest.OutputChecker.check_output(self, want, got, optionflags) def check_output_numeric(self, want, got, optionflags): """Doctest does an exact string comparison of output, which means that some numerically equivalent values aren't equal. This check normalizes * long integers (22L) so that they equal normal integers. (22) * Decimals so that they are comparable, regardless of the change made to __repr__ in Python 2.6. """ return doctest.OutputChecker.check_output(self, normalize_decimals(normalize_long_ints(want)), normalize_decimals(normalize_long_ints(got)), optionflags) def check_output_xml(self, want, got, optionsflags): """Tries to do a 'xml-comparision' of want and got. Plain string comparision doesn't always work because, for example, attribute ordering should not be important. Based on http://codespeak.net/svn/lxml/trunk/src/lxml/doctestcompare.py """ _norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+') def norm_whitespace(v): return _norm_whitespace_re.sub(' ', v) def child_text(element): return ''.join([c.data for c in element.childNodes if c.nodeType == Node.TEXT_NODE]) def children(element): return [c for c in element.childNodes if c.nodeType == Node.ELEMENT_NODE] def norm_child_text(element): return norm_whitespace(child_text(element)) def attrs_dict(element): return dict(element.attributes.items()) def check_element(want_element, got_element): if want_element.tagName != got_element.tagName: return False if norm_child_text(want_element) != norm_child_text(got_element): return False if attrs_dict(want_element) != attrs_dict(got_element): return False want_children = children(want_element) got_children = children(got_element) if len(want_children) != len(got_children): return False for want, got in zip(want_children, got_children): if not check_element(want, got): return False return True want, got = self._strip_quotes(want, got) want = want.replace('\\n','\n') got = got.replace('\\n','\n') # If the string is not a complete xml document, we may need to add a # root element. This allow us to compare fragments, like "<foo/><bar/>" if not want.startswith('<?xml'): wrapper = '<root>%s</root>' want = wrapper % want got = wrapper % got # Parse the want and got strings, and compare the parsings. try: want_root = parseString(want).firstChild got_root = parseString(got).firstChild except: return False return check_element(want_root, got_root) def check_output_json(self, want, got, optionsflags): "Tries to compare want and got as if they were JSON-encoded data" want, got = self._strip_quotes(want, got) try: want_json = simplejson.loads(want) got_json = simplejson.loads(got) except: return False return want_json == got_json def _strip_quotes(self, want, got): """ Strip quotes of doctests output values: >>> o = OutputChecker() >>> o._strip_quotes("'foo'") "foo" >>> o._strip_quotes('"foo"') "foo" >>> o._strip_quotes("u'foo'") "foo" >>> o._strip_quotes('u"foo"') "foo" """ def is_quoted_string(s): s = s.strip() return (len(s) >= 2 and s[0] == s[-1] and s[0] in ('"', "'")) def is_quoted_unicode(s): s = s.strip() return (len(s) >= 3 and s[0] == 'u' and s[1] == s[-1] and s[1] in ('"', "'")) if is_quoted_string(want) and is_quoted_string(got): want = want.strip()[1:-1] got = got.strip()[1:-1] elif is_quoted_unicode(want) and is_quoted_unicode(got): want = want.strip()[2:-1] got = got.strip()[2:-1] return want, got class DocTestRunner(doctest.DocTestRunner): def __init__(self, *args, **kwargs): doctest.DocTestRunner.__init__(self, *args, **kwargs) self.optionflags = doctest.ELLIPSIS def report_unexpected_exception(self, out, test, example, exc_info): doctest.DocTestRunner.report_unexpected_exception(self, out, test, example, exc_info) # Rollback, in case of database errors. Otherwise they'd have # side effects on other tests. for conn in connections: transaction.rollback_unless_managed(using=conn) class TransactionTestCase(unittest.TestCase): def _pre_setup(self): """Performs any pre-test setup. This includes: * Flushing the database. * If the Test Case class has a 'fixtures' member, installing the named fixtures. * If the Test Case class has a 'urls' member, replace the ROOT_URLCONF with it. * Clearing the mail test outbox. """ self._fixture_setup() self._urlconf_setup() mail.outbox = [] def _fixture_setup(self): # If the test case has a multi_db=True flag, flush all databases. # Otherwise, just flush default. if getattr(self, 'multi_db', False): databases = connections else: databases = [DEFAULT_DB_ALIAS] for db in databases: call_command('flush', verbosity=0, interactive=False, database=db) if hasattr(self, 'fixtures'): # We have to use this slightly awkward syntax due to the fact # that we're using *args and **kwargs together. call_command('loaddata', *self.fixtures, **{'verbosity': 0, 'database': db}) def _urlconf_setup(self): if hasattr(self, 'urls'): self._old_root_urlconf = settings.ROOT_URLCONF settings.ROOT_URLCONF = self.urls clear_url_caches() def __call__(self, result=None): """ Wrapper around default __call__ method to perform common Django test set up. This means that user-defined Test Cases aren't required to include a call to super().setUp(). """ self.client = Client() try: self._pre_setup() except (KeyboardInterrupt, SystemExit): raise except Exception: import sys result.addError(self, sys.exc_info()) return super(TransactionTestCase, self).__call__(result) try: self._post_teardown() except (KeyboardInterrupt, SystemExit): raise except Exception: import sys result.addError(self, sys.exc_info()) return def _post_teardown(self): """ Performs any post-test things. This includes: * Putting back the original ROOT_URLCONF if it was changed. * Force closing the connection, so that the next test gets a clean cursor. """ self._fixture_teardown() self._urlconf_teardown() # Some DB cursors include SQL statements as part of cursor # creation. If you have a test that does rollback, the effect # of these statements is lost, which can effect the operation # of tests (e.g., losing a timezone setting causing objects to # be created with the wrong time). # To make sure this doesn't happen, get a clean connection at the # start of every test. for connection in connections.all(): connection.close() def _fixture_teardown(self): pass def _urlconf_teardown(self): if hasattr(self, '_old_root_urlconf'): settings.ROOT_URLCONF = self._old_root_urlconf clear_url_caches() def save_warnings_state(self): """ Saves the state of the warnings module """ self._warnings_state = get_warnings_state() def restore_warnings_state(self): """ Restores the sate of the warnings module to the state saved by save_warnings_state() """ restore_warnings_state(self._warnings_state) def assertRedirects(self, response, expected_url, status_code=302, target_status_code=200, host=None, msg_prefix=''): """Asserts that a response redirected to a specific URL, and that the redirect URL can be loaded. Note that assertRedirects won't work for external links since it uses TestClient to do a request. """ if msg_prefix: msg_prefix += ": " if hasattr(response, 'redirect_chain'): # The request was a followed redirect self.assertTrue(len(response.redirect_chain) > 0, msg_prefix + "Response didn't redirect as expected: Response" " code was %d (expected %d)" % (response.status_code, status_code)) self.assertEqual(response.redirect_chain[0][1], status_code, msg_prefix + "Initial response didn't redirect as expected:" " Response code was %d (expected %d)" % (response.redirect_chain[0][1], status_code)) url, status_code = response.redirect_chain[-1] self.assertEqual(response.status_code, target_status_code, msg_prefix + "Response didn't redirect as expected: Final" " Response code was %d (expected %d)" % (response.status_code, target_status_code)) else: # Not a followed redirect self.assertEqual(response.status_code, status_code, msg_prefix + "Response didn't redirect as expected: Response" " code was %d (expected %d)" % (response.status_code, status_code)) url = response['Location'] scheme, netloc, path, query, fragment = urlsplit(url) redirect_response = response.client.get(path, QueryDict(query)) # Get the redirection page, using the same client that was used # to obtain the original response. self.assertEqual(redirect_response.status_code, target_status_code, msg_prefix + "Couldn't retrieve redirection page '%s':" " response code was %d (expected %d)" % (path, redirect_response.status_code, target_status_code)) e_scheme, e_netloc, e_path, e_query, e_fragment = urlsplit(expected_url) if not (e_scheme or e_netloc): expected_url = urlunsplit(('http', host or 'testserver', e_path, e_query, e_fragment)) self.assertEqual(url, expected_url, msg_prefix + "Response redirected to '%s', expected '%s'" % (url, expected_url)) def assertContains(self, response, text, count=None, status_code=200, msg_prefix=''): """ Asserts that a response indicates that a page was retrieved successfully, (i.e., the HTTP status code was as expected), and that ``text`` occurs ``count`` times in the content of the response. If ``count`` is None, the count doesn't matter - the assertion is true if the text occurs at least once in the response. """ if msg_prefix: msg_prefix += ": " self.assertEqual(response.status_code, status_code, msg_prefix + "Couldn't retrieve page: Response code was %d" " (expected %d)" % (response.status_code, status_code)) text = smart_str(text, response._charset) real_count = response.content.count(text) if count is not None: self.assertEqual(real_count, count, msg_prefix + "Found %d instances of '%s' in response" " (expected %d)" % (real_count, text, count)) else: self.failUnless(real_count != 0, msg_prefix + "Couldn't find '%s' in response" % text) def assertNotContains(self, response, text, status_code=200, msg_prefix=''): """ Asserts that a response indicates that a page was retrieved successfully, (i.e., the HTTP status code was as expected), and that ``text`` doesn't occurs in the content of the response. """ if msg_prefix: msg_prefix += ": " self.assertEqual(response.status_code, status_code, msg_prefix + "Couldn't retrieve page: Response code was %d" " (expected %d)" % (response.status_code, status_code)) text = smart_str(text, response._charset) self.assertEqual(response.content.count(text), 0, msg_prefix + "Response should not contain '%s'" % text) def assertFormError(self, response, form, field, errors, msg_prefix=''): """ Asserts that a form used to render the response has a specific field error. """ if msg_prefix: msg_prefix += ": " # Put context(s) into a list to simplify processing. contexts = to_list(response.context) if not contexts: self.fail(msg_prefix + "Response did not use any contexts to " "render the response") # Put error(s) into a list to simplify processing. errors = to_list(errors) # Search all contexts for the error. found_form = False for i,context in enumerate(contexts): if form not in context: continue found_form = True for err in errors: if field: if field in context[form].errors: field_errors = context[form].errors[field] self.assertTrue(err in field_errors, msg_prefix + "The field '%s' on form '%s' in" " context %d does not contain the error '%s'" " (actual errors: %s)" % (field, form, i, err, repr(field_errors))) elif field in context[form].fields: self.fail(msg_prefix + "The field '%s' on form '%s'" " in context %d contains no errors" % (field, form, i)) else: self.fail(msg_prefix + "The form '%s' in context %d" " does not contain the field '%s'" % (form, i, field)) else: non_field_errors = context[form].non_field_errors() self.assertTrue(err in non_field_errors, msg_prefix + "The form '%s' in context %d does not" " contain the non-field error '%s'" " (actual errors: %s)" % (form, i, err, non_field_errors)) if not found_form: self.fail(msg_prefix + "The form '%s' was not used to render the" " response" % form) def assertTemplateUsed(self, response, template_name, msg_prefix=''): """ Asserts that the template with the provided name was used in rendering the response. """ if msg_prefix: msg_prefix += ": " template_names = [t.name for t in to_list(response.template)] if not template_names: self.fail(msg_prefix + "No templates used to render the response") self.assertTrue(template_name in template_names, msg_prefix + "Template '%s' was not a template used to render" " the response. Actual template(s) used: %s" % (template_name, u', '.join(template_names))) def assertTemplateNotUsed(self, response, template_name, msg_prefix=''): """ Asserts that the template with the provided name was NOT used in rendering the response. """ if msg_prefix: msg_prefix += ": " template_names = [t.name for t in to_list(response.template)] self.assertFalse(template_name in template_names, msg_prefix + "Template '%s' was used unexpectedly in rendering" " the response" % template_name) def assertQuerysetEqual(self, qs, values, transform=repr): return self.assertEqual(map(transform, qs), values) def connections_support_transactions(): """ Returns True if all connections support transactions. This is messy because 2.4 doesn't support any or all. """ return all(conn.settings_dict['SUPPORTS_TRANSACTIONS'] for conn in connections.all()) class TestCase(TransactionTestCase): """ Does basically the same as TransactionTestCase, but surrounds every test with a transaction, monkey-patches the real transaction management routines to do nothing, and rollsback the test transaction at the end of the test. You have to use TransactionTestCase, if you need transaction management inside a test. """ def _fixture_setup(self): if not connections_support_transactions(): return super(TestCase, self)._fixture_setup() # If the test case has a multi_db=True flag, setup all databases. # Otherwise, just use default. if getattr(self, 'multi_db', False): databases = connections else: databases = [DEFAULT_DB_ALIAS] for db in databases: transaction.enter_transaction_management(using=db) transaction.managed(True, using=db) disable_transaction_methods() from django.contrib.sites.models import Site Site.objects.clear_cache() for db in databases: if hasattr(self, 'fixtures'): call_command('loaddata', *self.fixtures, **{ 'verbosity': 0, 'commit': False, 'database': db }) def _fixture_teardown(self): if not connections_support_transactions(): return super(TestCase, self)._fixture_teardown() # If the test case has a multi_db=True flag, teardown all databases. # Otherwise, just teardown default. if getattr(self, 'multi_db', False): databases = connections else: databases = [DEFAULT_DB_ALIAS] restore_transaction_methods() for db in databases: transaction.rollback(using=db) transaction.leave_transaction_management(using=db)
22,281
Python
.py
478
35.177824
116
0.5941
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,389
_doctest.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/test/_doctest.py
# This is a slightly modified version of the doctest.py that shipped with Python 2.4 # It incorporates changes that have been submitted to the Python ticket tracker # as ticket #1521051. These changes allow for a DoctestRunner and Doctest base # class to be specified when constructing a DoctestSuite. # Module doctest. # Released to the public domain 16-Jan-2001, by Tim Peters ([email protected]). # Major enhancements and refactoring by: # Jim Fulton # Edward Loper # Provided as-is; use at your own risk; no warranty; no promises; enjoy! r"""Module doctest -- a framework for running examples in docstrings. In simplest use, end each module M to be tested with: def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test() Then running the module as a script will cause the examples in the docstrings to get executed and verified: python M.py This won't display anything unless an example fails, in which case the failing example(s) and the cause(s) of the failure(s) are printed to stdout (why not stderr? because stderr is a lame hack <0.2 wink>), and the final line of output is "Test failed.". Run it with the -v switch instead: python M.py -v and a detailed report of all examples tried is printed to stdout, along with assorted summaries at the end. You can force verbose mode by passing "verbose=True" to testmod, or prohibit it by passing "verbose=False". In either of those cases, sys.argv is not examined by testmod. There are a variety of other ways to run doctests, including integration with the unittest framework, and support for running non-Python text files containing doctests. There are also many ways to override parts of doctest's default behaviors. See the Library Reference Manual for details. """ __docformat__ = 'reStructuredText en' __all__ = [ # 0, Option Flags 'register_optionflag', 'DONT_ACCEPT_TRUE_FOR_1', 'DONT_ACCEPT_BLANKLINE', 'NORMALIZE_WHITESPACE', 'ELLIPSIS', 'IGNORE_EXCEPTION_DETAIL', 'COMPARISON_FLAGS', 'REPORT_UDIFF', 'REPORT_CDIFF', 'REPORT_NDIFF', 'REPORT_ONLY_FIRST_FAILURE', 'REPORTING_FLAGS', # 1. Utility Functions 'is_private', # 2. Example & DocTest 'Example', 'DocTest', # 3. Doctest Parser 'DocTestParser', # 4. Doctest Finder 'DocTestFinder', # 5. Doctest Runner 'DocTestRunner', 'OutputChecker', 'DocTestFailure', 'UnexpectedException', 'DebugRunner', # 6. Test Functions 'testmod', 'testfile', 'run_docstring_examples', # 7. Tester 'Tester', # 8. Unittest Support 'DocTestSuite', 'DocFileSuite', 'set_unittest_reportflags', # 9. Debugging Support 'script_from_examples', 'testsource', 'debug_src', 'debug', ] import __future__ import sys, traceback, inspect, linecache, os, re import unittest, difflib, pdb, tempfile import warnings from StringIO import StringIO if sys.platform.startswith('java'): # On Jython, isclass() reports some modules as classes. Patch it. def patch_isclass(isclass): def patched_isclass(obj): return isclass(obj) and hasattr(obj, '__module__') return patched_isclass inspect.isclass = patch_isclass(inspect.isclass) # Don't whine about the deprecated is_private function in this # module's tests. warnings.filterwarnings("ignore", "is_private", DeprecationWarning, __name__, 0) # There are 4 basic classes: # - Example: a <source, want> pair, plus an intra-docstring line number. # - DocTest: a collection of examples, parsed from a docstring, plus # info about where the docstring came from (name, filename, lineno). # - DocTestFinder: extracts DocTests from a given object's docstring and # its contained objects' docstrings. # - DocTestRunner: runs DocTest cases, and accumulates statistics. # # So the basic picture is: # # list of: # +------+ +---------+ +-------+ # |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results| # +------+ +---------+ +-------+ # | Example | # | ... | # | Example | # +---------+ # Option constants. OPTIONFLAGS_BY_NAME = {} def register_optionflag(name): flag = 1 << len(OPTIONFLAGS_BY_NAME) OPTIONFLAGS_BY_NAME[name] = flag return flag DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1') DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE') NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE') ELLIPSIS = register_optionflag('ELLIPSIS') IGNORE_EXCEPTION_DETAIL = register_optionflag('IGNORE_EXCEPTION_DETAIL') COMPARISON_FLAGS = (DONT_ACCEPT_TRUE_FOR_1 | DONT_ACCEPT_BLANKLINE | NORMALIZE_WHITESPACE | ELLIPSIS | IGNORE_EXCEPTION_DETAIL) REPORT_UDIFF = register_optionflag('REPORT_UDIFF') REPORT_CDIFF = register_optionflag('REPORT_CDIFF') REPORT_NDIFF = register_optionflag('REPORT_NDIFF') REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE') REPORTING_FLAGS = (REPORT_UDIFF | REPORT_CDIFF | REPORT_NDIFF | REPORT_ONLY_FIRST_FAILURE) # Special string markers for use in `want` strings: BLANKLINE_MARKER = '<BLANKLINE>' ELLIPSIS_MARKER = '...' ###################################################################### ## Table of Contents ###################################################################### # 1. Utility Functions # 2. Example & DocTest -- store test cases # 3. DocTest Parser -- extracts examples from strings # 4. DocTest Finder -- extracts test cases from objects # 5. DocTest Runner -- runs test cases # 6. Test Functions -- convenient wrappers for testing # 7. Tester Class -- for backwards compatibility # 8. Unittest Support # 9. Debugging Support # 10. Example Usage ###################################################################### ## 1. Utility Functions ###################################################################### def is_private(prefix, base): """prefix, base -> true iff name prefix + "." + base is "private". Prefix may be an empty string, and base does not contain a period. Prefix is ignored (although functions you write conforming to this protocol may make use of it). Return true iff base begins with an (at least one) underscore, but does not both begin and end with (at least) two underscores. >>> is_private("a.b", "my_func") False >>> is_private("____", "_my_func") True >>> is_private("someclass", "__init__") False >>> is_private("sometypo", "__init_") True >>> is_private("x.y.z", "_") True >>> is_private("_x.y.z", "__") False >>> is_private("", "") # senseless but consistent False """ warnings.warn("is_private is deprecated; it wasn't useful; " "examine DocTestFinder.find() lists instead", DeprecationWarning, stacklevel=2) return base[:1] == "_" and not base[:2] == "__" == base[-2:] def _extract_future_flags(globs): """ Return the compiler-flags associated with the future features that have been imported into the given namespace (globs). """ flags = 0 for fname in __future__.all_feature_names: feature = globs.get(fname, None) if feature is getattr(__future__, fname): flags |= feature.compiler_flag return flags def _normalize_module(module, depth=2): """ Return the module specified by `module`. In particular: - If `module` is a module, then return module. - If `module` is a string, then import and return the module with that name. - If `module` is None, then return the calling module. The calling module is assumed to be the module of the stack frame at the given depth in the call stack. """ if inspect.ismodule(module): return module elif isinstance(module, (str, unicode)): return __import__(module, globals(), locals(), ["*"]) elif module is None: return sys.modules[sys._getframe(depth).f_globals['__name__']] else: raise TypeError("Expected a module, string, or None") def _indent(s, indent=4): """ Add the given number of space characters to the beginning every non-blank line in `s`, and return the result. """ # This regexp matches the start of non-blank lines: return re.sub('(?m)^(?!$)', indent*' ', s) def _exception_traceback(exc_info): """ Return a string containing a traceback message for the given exc_info tuple (as returned by sys.exc_info()). """ # Get a traceback message. excout = StringIO() exc_type, exc_val, exc_tb = exc_info traceback.print_exception(exc_type, exc_val, exc_tb, file=excout) return excout.getvalue() # Override some StringIO methods. class _SpoofOut(StringIO): def getvalue(self): result = StringIO.getvalue(self) # If anything at all was written, make sure there's a trailing # newline. There's no way for the expected output to indicate # that a trailing newline is missing. if result and not result.endswith("\n"): result += "\n" # Prevent softspace from screwing up the next test case, in # case they used print with a trailing comma in an example. if hasattr(self, "softspace"): del self.softspace return result def truncate(self, size=None): StringIO.truncate(self, size) if hasattr(self, "softspace"): del self.softspace # Worst-case linear-time ellipsis matching. def _ellipsis_match(want, got): """ Essentially the only subtle case: >>> _ellipsis_match('aa...aa', 'aaa') False """ if ELLIPSIS_MARKER not in want: return want == got # Find "the real" strings. ws = want.split(ELLIPSIS_MARKER) assert len(ws) >= 2 # Deal with exact matches possibly needed at one or both ends. startpos, endpos = 0, len(got) w = ws[0] if w: # starts with exact match if got.startswith(w): startpos = len(w) del ws[0] else: return False w = ws[-1] if w: # ends with exact match if got.endswith(w): endpos -= len(w) del ws[-1] else: return False if startpos > endpos: # Exact end matches required more characters than we have, as in # _ellipsis_match('aa...aa', 'aaa') return False # For the rest, we only need to find the leftmost non-overlapping # match for each piece. If there's no overall match that way alone, # there's no overall match period. for w in ws: # w may be '' at times, if there are consecutive ellipses, or # due to an ellipsis at the start or end of `want`. That's OK. # Search for an empty string succeeds, and doesn't change startpos. startpos = got.find(w, startpos, endpos) if startpos < 0: return False startpos += len(w) return True def _comment_line(line): "Return a commented form of the given line" line = line.rstrip() if line: return '# '+line else: return '#' class _OutputRedirectingPdb(pdb.Pdb): """ A specialized version of the python debugger that redirects stdout to a given stream when interacting with the user. Stdout is *not* redirected when traced code is executed. """ def __init__(self, out): self.__out = out self.__debugger_used = False pdb.Pdb.__init__(self) def set_trace(self): self.__debugger_used = True pdb.Pdb.set_trace(self) def set_continue(self): # Calling set_continue unconditionally would break unit test coverage # reporting, as Bdb.set_continue calls sys.settrace(None). if self.__debugger_used: pdb.Pdb.set_continue(self) def trace_dispatch(self, *args): # Redirect stdout to the given stream. save_stdout = sys.stdout sys.stdout = self.__out # Call Pdb's trace dispatch method. try: return pdb.Pdb.trace_dispatch(self, *args) finally: sys.stdout = save_stdout # [XX] Normalize with respect to os.path.pardir? def _module_relative_path(module, path): if not inspect.ismodule(module): raise TypeError, 'Expected a module: %r' % module if path.startswith('/'): raise ValueError, 'Module-relative files may not have absolute paths' # Find the base directory for the path. if hasattr(module, '__file__'): # A normal module/package basedir = os.path.split(module.__file__)[0] elif module.__name__ == '__main__': # An interactive session. if len(sys.argv)>0 and sys.argv[0] != '': basedir = os.path.split(sys.argv[0])[0] else: basedir = os.curdir else: # A module w/o __file__ (this includes builtins) raise ValueError("Can't resolve paths relative to the module " + module + " (it has no __file__)") # Combine the base directory and the path. return os.path.join(basedir, *(path.split('/'))) ###################################################################### ## 2. Example & DocTest ###################################################################### ## - An "example" is a <source, want> pair, where "source" is a ## fragment of source code, and "want" is the expected output for ## "source." The Example class also includes information about ## where the example was extracted from. ## ## - A "doctest" is a collection of examples, typically extracted from ## a string (such as an object's docstring). The DocTest class also ## includes information about where the string was extracted from. class Example: """ A single doctest example, consisting of source code and expected output. `Example` defines the following attributes: - source: A single Python statement, always ending with a newline. The constructor adds a newline if needed. - want: The expected output from running the source code (either from stdout, or a traceback in case of exception). `want` ends with a newline unless it's empty, in which case it's an empty string. The constructor adds a newline if needed. - exc_msg: The exception message generated by the example, if the example is expected to generate an exception; or `None` if it is not expected to generate an exception. This exception message is compared against the return value of `traceback.format_exception_only()`. `exc_msg` ends with a newline unless it's `None`. The constructor adds a newline if needed. - lineno: The line number within the DocTest string containing this Example where the Example begins. This line number is zero-based, with respect to the beginning of the DocTest. - indent: The example's indentation in the DocTest string. I.e., the number of space characters that preceed the example's first prompt. - options: A dictionary mapping from option flags to True or False, which is used to override default options for this example. Any option flags not contained in this dictionary are left at their default value (as specified by the DocTestRunner's optionflags). By default, no options are set. """ def __init__(self, source, want, exc_msg=None, lineno=0, indent=0, options=None): # Normalize inputs. if not source.endswith('\n'): source += '\n' if want and not want.endswith('\n'): want += '\n' if exc_msg is not None and not exc_msg.endswith('\n'): exc_msg += '\n' # Store properties. self.source = source self.want = want self.lineno = lineno self.indent = indent if options is None: options = {} self.options = options self.exc_msg = exc_msg class DocTest: """ A collection of doctest examples that should be run in a single namespace. Each `DocTest` defines the following attributes: - examples: the list of examples. - globs: The namespace (aka globals) that the examples should be run in. - name: A name identifying the DocTest (typically, the name of the object whose docstring this DocTest was extracted from). - filename: The name of the file that this DocTest was extracted from, or `None` if the filename is unknown. - lineno: The line number within filename where this DocTest begins, or `None` if the line number is unavailable. This line number is zero-based, with respect to the beginning of the file. - docstring: The string that the examples were extracted from, or `None` if the string is unavailable. """ def __init__(self, examples, globs, name, filename, lineno, docstring): """ Create a new DocTest containing the given examples. The DocTest's globals are initialized with a copy of `globs`. """ assert not isinstance(examples, basestring), \ "DocTest no longer accepts str; use DocTestParser instead" self.examples = examples self.docstring = docstring self.globs = globs.copy() self.name = name self.filename = filename self.lineno = lineno def __repr__(self): if len(self.examples) == 0: examples = 'no examples' elif len(self.examples) == 1: examples = '1 example' else: examples = '%d examples' % len(self.examples) return ('<DocTest %s from %s:%s (%s)>' % (self.name, self.filename, self.lineno, examples)) # This lets us sort tests by name: def __cmp__(self, other): if not isinstance(other, DocTest): return -1 return cmp((self.name, self.filename, self.lineno, id(self)), (other.name, other.filename, other.lineno, id(other))) ###################################################################### ## 3. DocTestParser ###################################################################### class DocTestParser: """ A class used to parse strings containing doctest examples. """ # This regular expression is used to find doctest examples in a # string. It defines three groups: `source` is the source code # (including leading indentation and prompts); `indent` is the # indentation of the first (PS1) line of the source code; and # `want` is the expected output (including leading indentation). _EXAMPLE_RE = re.compile(r''' # Source consists of a PS1 line followed by zero or more PS2 lines. (?P<source> (?:^(?P<indent> [ ]*) >>> .*) # PS1 line (?:\n [ ]* \.\.\. .*)*) # PS2 lines \n? # Want consists of any non-blank lines that do not start with PS1. (?P<want> (?:(?![ ]*$) # Not a blank line (?![ ]*>>>) # Not a line starting with PS1 .*$\n? # But any other line )*) ''', re.MULTILINE | re.VERBOSE) # A regular expression for handling `want` strings that contain # expected exceptions. It divides `want` into three pieces: # - the traceback header line (`hdr`) # - the traceback stack (`stack`) # - the exception message (`msg`), as generated by # traceback.format_exception_only() # `msg` may have multiple lines. We assume/require that the # exception message is the first non-indented line starting with a word # character following the traceback header line. _EXCEPTION_RE = re.compile(r""" # Grab the traceback header. Different versions of Python have # said different things on the first traceback line. ^(?P<hdr> Traceback\ \( (?: most\ recent\ call\ last | innermost\ last ) \) : ) \s* $ # toss trailing whitespace on the header. (?P<stack> .*?) # don't blink: absorb stuff until... ^ (?P<msg> \w+ .*) # a line *starts* with alphanum. """, re.VERBOSE | re.MULTILINE | re.DOTALL) # A callable returning a true value iff its argument is a blank line # or contains a single comment. _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match def parse(self, string, name='<string>'): """ Divide the given string into examples and intervening text, and return them as a list of alternating Examples and strings. Line numbers for the Examples are 0-based. The optional argument `name` is a name identifying this string, and is only used for error messages. """ string = string.expandtabs() # If all lines begin with the same indentation, then strip it. min_indent = self._min_indent(string) if min_indent > 0: string = '\n'.join([l[min_indent:] for l in string.split('\n')]) output = [] charno, lineno = 0, 0 # Find all doctest examples in the string: for m in self._EXAMPLE_RE.finditer(string): # Add the pre-example text to `output`. output.append(string[charno:m.start()]) # Update lineno (lines before this example) lineno += string.count('\n', charno, m.start()) # Extract info from the regexp match. (source, options, want, exc_msg) = \ self._parse_example(m, name, lineno) # Create an Example, and add it to the list. if not self._IS_BLANK_OR_COMMENT(source): output.append( Example(source, want, exc_msg, lineno=lineno, indent=min_indent+len(m.group('indent')), options=options) ) # Update lineno (lines inside this example) lineno += string.count('\n', m.start(), m.end()) # Update charno. charno = m.end() # Add any remaining post-example text to `output`. output.append(string[charno:]) return output def get_doctest(self, string, globs, name, filename, lineno): """ Extract all doctest examples from the given string, and collect them into a `DocTest` object. `globs`, `name`, `filename`, and `lineno` are attributes for the new `DocTest` object. See the documentation for `DocTest` for more information. """ return DocTest(self.get_examples(string, name), globs, name, filename, lineno, string) def get_examples(self, string, name='<string>'): """ Extract all doctest examples from the given string, and return them as a list of `Example` objects. Line numbers are 0-based, because it's most common in doctests that nothing interesting appears on the same line as opening triple-quote, and so the first interesting line is called \"line 1\" then. The optional argument `name` is a name identifying this string, and is only used for error messages. """ return [x for x in self.parse(string, name) if isinstance(x, Example)] def _parse_example(self, m, name, lineno): """ Given a regular expression match from `_EXAMPLE_RE` (`m`), return a pair `(source, want)`, where `source` is the matched example's source code (with prompts and indentation stripped); and `want` is the example's expected output (with indentation stripped). `name` is the string's name, and `lineno` is the line number where the example starts; both are used for error messages. """ # Get the example's indentation level. indent = len(m.group('indent')) # Divide source into lines; check that they're properly # indented; and then strip their indentation & prompts. source_lines = m.group('source').split('\n') self._check_prompt_blank(source_lines, indent, name, lineno) self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno) source = '\n'.join([sl[indent+4:] for sl in source_lines]) # Divide want into lines; check that it's properly indented; and # then strip the indentation. Spaces before the last newline should # be preserved, so plain rstrip() isn't good enough. want = m.group('want') want_lines = want.split('\n') if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]): del want_lines[-1] # forget final newline & spaces after it self._check_prefix(want_lines, ' '*indent, name, lineno + len(source_lines)) want = '\n'.join([wl[indent:] for wl in want_lines]) # If `want` contains a traceback message, then extract it. m = self._EXCEPTION_RE.match(want) if m: exc_msg = m.group('msg') else: exc_msg = None # Extract options from the source. options = self._find_options(source, name, lineno) return source, options, want, exc_msg # This regular expression looks for option directives in the # source code of an example. Option directives are comments # starting with "doctest:". Warning: this may give false # positives for string-literals that contain the string # "#doctest:". Eliminating these false positives would require # actually parsing the string; but we limit them by ignoring any # line containing "#doctest:" that is *followed* by a quote mark. _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$', re.MULTILINE) def _find_options(self, source, name, lineno): """ Return a dictionary containing option overrides extracted from option directives in the given source string. `name` is the string's name, and `lineno` is the line number where the example starts; both are used for error messages. """ options = {} # (note: with the current regexp, this will match at most once:) for m in self._OPTION_DIRECTIVE_RE.finditer(source): option_strings = m.group(1).replace(',', ' ').split() for option in option_strings: if (option[0] not in '+-' or option[1:] not in OPTIONFLAGS_BY_NAME): raise ValueError('line %r of the doctest for %s ' 'has an invalid option: %r' % (lineno+1, name, option)) flag = OPTIONFLAGS_BY_NAME[option[1:]] options[flag] = (option[0] == '+') if options and self._IS_BLANK_OR_COMMENT(source): raise ValueError('line %r of the doctest for %s has an option ' 'directive on a line with no example: %r' % (lineno, name, source)) return options # This regular expression finds the indentation of every non-blank # line in a string. _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE) def _min_indent(self, s): "Return the minimum indentation of any non-blank line in `s`" indents = [len(indent) for indent in self._INDENT_RE.findall(s)] if len(indents) > 0: return min(indents) else: return 0 def _check_prompt_blank(self, lines, indent, name, lineno): """ Given the lines of a source string (including prompts and leading indentation), check to make sure that every prompt is followed by a space character. If any line is not followed by a space character, then raise ValueError. """ for i, line in enumerate(lines): if len(line) >= indent+4 and line[indent+3] != ' ': raise ValueError('line %r of the docstring for %s ' 'lacks blank after %s: %r' % (lineno+i+1, name, line[indent:indent+3], line)) def _check_prefix(self, lines, prefix, name, lineno): """ Check that every line in the given list starts with the given prefix; if any line does not, then raise a ValueError. """ for i, line in enumerate(lines): if line and not line.startswith(prefix): raise ValueError('line %r of the docstring for %s has ' 'inconsistent leading whitespace: %r' % (lineno+i+1, name, line)) ###################################################################### ## 4. DocTest Finder ###################################################################### class DocTestFinder: """ A class used to extract the DocTests that are relevant to a given object, from its docstring and the docstrings of its contained objects. Doctests can currently be extracted from the following object types: modules, functions, classes, methods, staticmethods, classmethods, and properties. """ def __init__(self, verbose=False, parser=DocTestParser(), recurse=True, _namefilter=None, exclude_empty=True): """ Create a new doctest finder. The optional argument `parser` specifies a class or function that should be used to create new DocTest objects (or objects that implement the same interface as DocTest). The signature for this factory function should match the signature of the DocTest constructor. If the optional argument `recurse` is false, then `find` will only examine the given object, and not any contained objects. If the optional argument `exclude_empty` is false, then `find` will include tests for objects with empty docstrings. """ self._parser = parser self._verbose = verbose self._recurse = recurse self._exclude_empty = exclude_empty # _namefilter is undocumented, and exists only for temporary backward- # compatibility support of testmod's deprecated isprivate mess. self._namefilter = _namefilter def find(self, obj, name=None, module=None, globs=None, extraglobs=None): """ Return a list of the DocTests that are defined by the given object's docstring, or by any of its contained objects' docstrings. The optional parameter `module` is the module that contains the given object. If the module is not specified or is None, then the test finder will attempt to automatically determine the correct module. The object's module is used: - As a default namespace, if `globs` is not specified. - To prevent the DocTestFinder from extracting DocTests from objects that are imported from other modules. - To find the name of the file containing the object. - To help find the line number of the object within its file. Contained objects whose module does not match `module` are ignored. If `module` is False, no attempt to find the module will be made. This is obscure, of use mostly in tests: if `module` is False, or is None but cannot be found automatically, then all objects are considered to belong to the (non-existent) module, so all contained objects will (recursively) be searched for doctests. The globals for each DocTest is formed by combining `globs` and `extraglobs` (bindings in `extraglobs` override bindings in `globs`). A new copy of the globals dictionary is created for each DocTest. If `globs` is not specified, then it defaults to the module's `__dict__`, if specified, or {} otherwise. If `extraglobs` is not specified, then it defaults to {}. """ # If name was not specified, then extract it from the object. if name is None: name = getattr(obj, '__name__', None) if name is None: raise ValueError("DocTestFinder.find: name must be given " "when obj.__name__ doesn't exist: %r" % (type(obj),)) # Find the module that contains the given object (if obj is # a module, then module=obj.). Note: this may fail, in which # case module will be None. if module is False: module = None elif module is None: module = inspect.getmodule(obj) # Read the module's source code. This is used by # DocTestFinder._find_lineno to find the line number for a # given object's docstring. try: file = inspect.getsourcefile(obj) or inspect.getfile(obj) source_lines = linecache.getlines(file) if not source_lines: source_lines = None except TypeError: source_lines = None # Initialize globals, and merge in extraglobs. if globs is None: if module is None: globs = {} else: globs = module.__dict__.copy() else: globs = globs.copy() if extraglobs is not None: globs.update(extraglobs) # Recursively explore `obj`, extracting DocTests. tests = [] self._find(tests, obj, name, module, source_lines, globs, {}) return tests def _filter(self, obj, prefix, base): """ Return true if the given object should not be examined. """ return (self._namefilter is not None and self._namefilter(prefix, base)) def _from_module(self, module, object): """ Return true if the given object is defined in the given module. """ if module is None: return True elif inspect.isfunction(object): return module.__dict__ is object.func_globals elif inspect.isclass(object): return module.__name__ == object.__module__ elif inspect.getmodule(object) is not None: return module is inspect.getmodule(object) elif hasattr(object, '__module__'): return module.__name__ == object.__module__ elif isinstance(object, property): return True # [XX] no way not be sure. else: raise ValueError("object must be a class or function") def _find(self, tests, obj, name, module, source_lines, globs, seen): """ Find tests for the given object and any contained objects, and add them to `tests`. """ if self._verbose: print 'Finding tests in %s' % name # If we've already processed this object, then ignore it. if id(obj) in seen: return seen[id(obj)] = 1 # Find a test for this object, and add it to the list of tests. test = self._get_test(obj, name, module, globs, source_lines) if test is not None: tests.append(test) # Look for tests in a module's contained objects. if inspect.ismodule(obj) and self._recurse: for valname, val in obj.__dict__.items(): # Check if this contained object should be ignored. if self._filter(val, name, valname): continue valname = '%s.%s' % (name, valname) # Recurse to functions & classes. if ((inspect.isfunction(val) or inspect.isclass(val)) and self._from_module(module, val)): self._find(tests, val, valname, module, source_lines, globs, seen) # Look for tests in a module's __test__ dictionary. if inspect.ismodule(obj) and self._recurse: for valname, val in getattr(obj, '__test__', {}).items(): if not isinstance(valname, basestring): raise ValueError("DocTestFinder.find: __test__ keys " "must be strings: %r" % (type(valname),)) if not (inspect.isfunction(val) or inspect.isclass(val) or inspect.ismethod(val) or inspect.ismodule(val) or isinstance(val, basestring)): raise ValueError("DocTestFinder.find: __test__ values " "must be strings, functions, methods, " "classes, or modules: %r" % (type(val),)) valname = '%s.__test__.%s' % (name, valname) self._find(tests, val, valname, module, source_lines, globs, seen) # Look for tests in a class's contained objects. if inspect.isclass(obj) and self._recurse: for valname, val in obj.__dict__.items(): # Check if this contained object should be ignored. if self._filter(val, name, valname): continue # Special handling for staticmethod/classmethod. if isinstance(val, staticmethod): val = getattr(obj, valname) if isinstance(val, classmethod): val = getattr(obj, valname).im_func # Recurse to methods, properties, and nested classes. if ((inspect.isfunction(val) or inspect.isclass(val) or isinstance(val, property)) and self._from_module(module, val)): valname = '%s.%s' % (name, valname) self._find(tests, val, valname, module, source_lines, globs, seen) def _get_test(self, obj, name, module, globs, source_lines): """ Return a DocTest for the given object, if it defines a docstring; otherwise, return None. """ # Extract the object's docstring. If it doesn't have one, # then return None (no test for this object). if isinstance(obj, basestring): docstring = obj else: try: if obj.__doc__ is None: docstring = '' else: docstring = obj.__doc__ if not isinstance(docstring, basestring): docstring = str(docstring) except (TypeError, AttributeError): docstring = '' # Find the docstring's location in the file. lineno = self._find_lineno(obj, source_lines) # Don't bother if the docstring is empty. if self._exclude_empty and not docstring: return None # Return a DocTest for this object. if module is None: filename = None else: filename = getattr(module, '__file__', module.__name__) if filename[-4:] in (".pyc", ".pyo"): filename = filename[:-1] return self._parser.get_doctest(docstring, globs, name, filename, lineno) def _find_lineno(self, obj, source_lines): """ Return a line number of the given object's docstring. Note: this method assumes that the object has a docstring. """ lineno = None # Find the line number for modules. if inspect.ismodule(obj): lineno = 0 # Find the line number for classes. # Note: this could be fooled if a class is defined multiple # times in a single file. if inspect.isclass(obj): if source_lines is None: return None pat = re.compile(r'^\s*class\s*%s\b' % getattr(obj, '__name__', '-')) for i, line in enumerate(source_lines): if pat.match(line): lineno = i break # Find the line number for functions & methods. if inspect.ismethod(obj): obj = obj.im_func if inspect.isfunction(obj): obj = obj.func_code if inspect.istraceback(obj): obj = obj.tb_frame if inspect.isframe(obj): obj = obj.f_code if inspect.iscode(obj): lineno = getattr(obj, 'co_firstlineno', None)-1 # Find the line number where the docstring starts. Assume # that it's the first line that begins with a quote mark. # Note: this could be fooled by a multiline function # signature, where a continuation line begins with a quote # mark. if lineno is not None: if source_lines is None: return lineno+1 pat = re.compile('(^|.*:)\s*\w*("|\')') for lineno in range(lineno, len(source_lines)): if pat.match(source_lines[lineno]): return lineno # We couldn't find the line number. return None ###################################################################### ## 5. DocTest Runner ###################################################################### class DocTestRunner: """ A class used to run DocTest test cases, and accumulate statistics. The `run` method is used to process a single DocTest case. It returns a tuple `(f, t)`, where `t` is the number of test cases tried, and `f` is the number of test cases that failed. >>> tests = DocTestFinder().find(_TestClass) >>> runner = DocTestRunner(verbose=False) >>> for test in tests: ... print runner.run(test) (0, 2) (0, 1) (0, 2) (0, 2) The `summarize` method prints a summary of all the test cases that have been run by the runner, and returns an aggregated `(f, t)` tuple: >>> runner.summarize(verbose=1) 4 items passed all tests: 2 tests in _TestClass 2 tests in _TestClass.__init__ 2 tests in _TestClass.get 1 tests in _TestClass.square 7 tests in 4 items. 7 passed and 0 failed. Test passed. (0, 7) The aggregated number of tried examples and failed examples is also available via the `tries` and `failures` attributes: >>> runner.tries 7 >>> runner.failures 0 The comparison between expected outputs and actual outputs is done by an `OutputChecker`. This comparison may be customized with a number of option flags; see the documentation for `testmod` for more information. If the option flags are insufficient, then the comparison may also be customized by passing a subclass of `OutputChecker` to the constructor. The test runner's display output can be controlled in two ways. First, an output function (`out) can be passed to `TestRunner.run`; this function will be called with strings that should be displayed. It defaults to `sys.stdout.write`. If capturing the output is not sufficient, then the display output can be also customized by subclassing DocTestRunner, and overriding the methods `report_start`, `report_success`, `report_unexpected_exception`, and `report_failure`. """ # This divider string is used to separate failure messages, and to # separate sections of the summary. DIVIDER = "*" * 70 def __init__(self, checker=None, verbose=None, optionflags=0): """ Create a new test runner. Optional keyword arg `checker` is the `OutputChecker` that should be used to compare the expected outputs and actual outputs of doctest examples. Optional keyword arg 'verbose' prints lots of stuff if true, only failures if false; by default, it's true iff '-v' is in sys.argv. Optional argument `optionflags` can be used to control how the test runner compares expected output to actual output, and how it displays failures. See the documentation for `testmod` for more information. """ self._checker = checker or OutputChecker() if verbose is None: verbose = '-v' in sys.argv self._verbose = verbose self.optionflags = optionflags self.original_optionflags = optionflags # Keep track of the examples we've run. self.tries = 0 self.failures = 0 self._name2ft = {} # Create a fake output target for capturing doctest output. self._fakeout = _SpoofOut() #///////////////////////////////////////////////////////////////// # Reporting methods #///////////////////////////////////////////////////////////////// def report_start(self, out, test, example): """ Report that the test runner is about to process the given example. (Only displays a message if verbose=True) """ if self._verbose: if example.want: out('Trying:\n' + _indent(example.source) + 'Expecting:\n' + _indent(example.want)) else: out('Trying:\n' + _indent(example.source) + 'Expecting nothing\n') def report_success(self, out, test, example, got): """ Report that the given example ran successfully. (Only displays a message if verbose=True) """ if self._verbose: out("ok\n") def report_failure(self, out, test, example, got): """ Report that the given example failed. """ out(self._failure_header(test, example) + self._checker.output_difference(example, got, self.optionflags)) def report_unexpected_exception(self, out, test, example, exc_info): """ Report that the given example raised an unexpected exception. """ out(self._failure_header(test, example) + 'Exception raised:\n' + _indent(_exception_traceback(exc_info))) def _failure_header(self, test, example): out = [self.DIVIDER] if test.filename: if test.lineno is not None and example.lineno is not None: lineno = test.lineno + example.lineno + 1 else: lineno = '?' out.append('File "%s", line %s, in %s' % (test.filename, lineno, test.name)) else: out.append('Line %s, in %s' % (example.lineno+1, test.name)) out.append('Failed example:') source = example.source out.append(_indent(source)) return '\n'.join(out) #///////////////////////////////////////////////////////////////// # DocTest Running #///////////////////////////////////////////////////////////////// def __run(self, test, compileflags, out): """ Run the examples in `test`. Write the outcome of each example with one of the `DocTestRunner.report_*` methods, using the writer function `out`. `compileflags` is the set of compiler flags that should be used to execute examples. Return a tuple `(f, t)`, where `t` is the number of examples tried, and `f` is the number of examples that failed. The examples are run in the namespace `test.globs`. """ # Keep track of the number of failures and tries. failures = tries = 0 # Save the option flags (since option directives can be used # to modify them). original_optionflags = self.optionflags SUCCESS, FAILURE, BOOM = range(3) # `outcome` state check = self._checker.check_output # Process each example. for examplenum, example in enumerate(test.examples): # If REPORT_ONLY_FIRST_FAILURE is set, then suppress # reporting after the first failure. quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and failures > 0) # Merge in the example's options. self.optionflags = original_optionflags if example.options: for (optionflag, val) in example.options.items(): if val: self.optionflags |= optionflag else: self.optionflags &= ~optionflag # Record that we started this example. tries += 1 if not quiet: self.report_start(out, test, example) # Use a special filename for compile(), so we can retrieve # the source code during interactive debugging (see # __patched_linecache_getlines). filename = '<doctest %s[%d]>' % (test.name, examplenum) # Run the example in the given context (globs), and record # any exception that gets raised. (But don't intercept # keyboard interrupts.) try: # Don't blink! This is where the user's code gets run. exec compile(example.source, filename, "single", compileflags, 1) in test.globs self.debugger.set_continue() # ==== Example Finished ==== exception = None except KeyboardInterrupt: raise except: exception = sys.exc_info() self.debugger.set_continue() # ==== Example Finished ==== got = self._fakeout.getvalue() # the actual output self._fakeout.truncate(0) outcome = FAILURE # guilty until proved innocent or insane # If the example executed without raising any exceptions, # verify its output. if exception is None: if check(example.want, got, self.optionflags): outcome = SUCCESS # The example raised an exception: check if it was expected. else: exc_info = sys.exc_info() exc_msg = traceback.format_exception_only(*exc_info[:2])[-1] if not quiet: got += _exception_traceback(exc_info) # If `example.exc_msg` is None, then we weren't expecting # an exception. if example.exc_msg is None: outcome = BOOM # We expected an exception: see whether it matches. elif check(example.exc_msg, exc_msg, self.optionflags): outcome = SUCCESS # Another chance if they didn't care about the detail. elif self.optionflags & IGNORE_EXCEPTION_DETAIL: m1 = re.match(r'[^:]*:', example.exc_msg) m2 = re.match(r'[^:]*:', exc_msg) if m1 and m2 and check(m1.group(0), m2.group(0), self.optionflags): outcome = SUCCESS # Report the outcome. if outcome is SUCCESS: if not quiet: self.report_success(out, test, example, got) elif outcome is FAILURE: if not quiet: self.report_failure(out, test, example, got) failures += 1 elif outcome is BOOM: if not quiet: self.report_unexpected_exception(out, test, example, exc_info) failures += 1 else: assert False, ("unknown outcome", outcome) # Restore the option flags (in case they were modified) self.optionflags = original_optionflags # Record and return the number of failures and tries. self.__record_outcome(test, failures, tries) return failures, tries def __record_outcome(self, test, f, t): """ Record the fact that the given DocTest (`test`) generated `f` failures out of `t` tried examples. """ f2, t2 = self._name2ft.get(test.name, (0,0)) self._name2ft[test.name] = (f+f2, t+t2) self.failures += f self.tries += t __LINECACHE_FILENAME_RE = re.compile(r'<doctest ' r'(?P<name>[\w\.]+)' r'\[(?P<examplenum>\d+)\]>$') def __patched_linecache_getlines(self, filename, module_globals=None): m = self.__LINECACHE_FILENAME_RE.match(filename) if m and m.group('name') == self.test.name: example = self.test.examples[int(m.group('examplenum'))] return example.source.splitlines(True) else: if sys.version_info < (2, 5, 0): return self.save_linecache_getlines(filename) else: return self.save_linecache_getlines(filename, module_globals) def run(self, test, compileflags=None, out=None, clear_globs=True): """ Run the examples in `test`, and display the results using the writer function `out`. The examples are run in the namespace `test.globs`. If `clear_globs` is true (the default), then this namespace will be cleared after the test runs, to help with garbage collection. If you would like to examine the namespace after the test completes, then use `clear_globs=False`. `compileflags` gives the set of flags that should be used by the Python compiler when running the examples. If not specified, then it will default to the set of future-import flags that apply to `globs`. The output of each example is checked using `DocTestRunner.check_output`, and the results are formatted by the `DocTestRunner.report_*` methods. """ self.test = test if compileflags is None: compileflags = _extract_future_flags(test.globs) save_stdout = sys.stdout if out is None: out = save_stdout.write sys.stdout = self._fakeout # Patch pdb.set_trace to restore sys.stdout during interactive # debugging (so it's not still redirected to self._fakeout). # Note that the interactive output will go to *our* # save_stdout, even if that's not the real sys.stdout; this # allows us to write test cases for the set_trace behavior. save_set_trace = pdb.set_trace self.debugger = _OutputRedirectingPdb(save_stdout) self.debugger.reset() pdb.set_trace = self.debugger.set_trace # Patch linecache.getlines, so we can see the example's source # when we're inside the debugger. self.save_linecache_getlines = linecache.getlines linecache.getlines = self.__patched_linecache_getlines try: return self.__run(test, compileflags, out) finally: sys.stdout = save_stdout pdb.set_trace = save_set_trace linecache.getlines = self.save_linecache_getlines if clear_globs: test.globs.clear() #///////////////////////////////////////////////////////////////// # Summarization #///////////////////////////////////////////////////////////////// def summarize(self, verbose=None): """ Print a summary of all the test cases that have been run by this DocTestRunner, and return a tuple `(f, t)`, where `f` is the total number of failed examples, and `t` is the total number of tried examples. The optional `verbose` argument controls how detailed the summary is. If the verbosity is not specified, then the DocTestRunner's verbosity is used. """ if verbose is None: verbose = self._verbose notests = [] passed = [] failed = [] totalt = totalf = 0 for x in self._name2ft.items(): name, (f, t) = x assert f <= t totalt += t totalf += f if t == 0: notests.append(name) elif f == 0: passed.append( (name, t) ) else: failed.append(x) if verbose: if notests: print len(notests), "items had no tests:" notests.sort() for thing in notests: print " ", thing if passed: print len(passed), "items passed all tests:" passed.sort() for thing, count in passed: print " %3d tests in %s" % (count, thing) if failed: print self.DIVIDER print len(failed), "items had failures:" failed.sort() for thing, (f, t) in failed: print " %3d of %3d in %s" % (f, t, thing) if verbose: print totalt, "tests in", len(self._name2ft), "items." print totalt - totalf, "passed and", totalf, "failed." if totalf: print "***Test Failed***", totalf, "failures." elif verbose: print "Test passed." return totalf, totalt #///////////////////////////////////////////////////////////////// # Backward compatibility cruft to maintain doctest.master. #///////////////////////////////////////////////////////////////// def merge(self, other): d = self._name2ft for name, (f, t) in other._name2ft.items(): if name in d: print "*** DocTestRunner.merge: '" + name + "' in both" \ " testers; summing outcomes." f2, t2 = d[name] f = f + f2 t = t + t2 d[name] = f, t class OutputChecker: """ A class used to check the whether the actual output from a doctest example matches the expected output. `OutputChecker` defines two methods: `check_output`, which compares a given pair of outputs, and returns true if they match; and `output_difference`, which returns a string describing the differences between two outputs. """ def check_output(self, want, got, optionflags): """ Return True iff the actual output from an example (`got`) matches the expected output (`want`). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. See the documentation for `TestRunner` for more information about option flags. """ # Handle the common case first, for efficiency: # if they're string-identical, always return true. if got == want: return True # The values True and False replaced 1 and 0 as the return # value for boolean comparisons in Python 2.3. if not (optionflags & DONT_ACCEPT_TRUE_FOR_1): if (got,want) == ("True\n", "1\n"): return True if (got,want) == ("False\n", "0\n"): return True # <BLANKLINE> can be used as a special sequence to signify a # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used. if not (optionflags & DONT_ACCEPT_BLANKLINE): # Replace <BLANKLINE> in want with a blank line. want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER), '', want) # If a line in got contains only spaces, then remove the # spaces. got = re.sub('(?m)^\s*?$', '', got) if got == want: return True # This flag causes doctest to ignore any differences in the # contents of whitespace strings. Note that this can be used # in conjunction with the ELLIPSIS flag. if optionflags & NORMALIZE_WHITESPACE: got = ' '.join(got.split()) want = ' '.join(want.split()) if got == want: return True # The ELLIPSIS flag says to let the sequence "..." in `want` # match any substring in `got`. if optionflags & ELLIPSIS: if _ellipsis_match(want, got): return True # We didn't find any match; return false. return False # Should we do a fancy diff? def _do_a_fancy_diff(self, want, got, optionflags): # Not unless they asked for a fancy diff. if not optionflags & (REPORT_UDIFF | REPORT_CDIFF | REPORT_NDIFF): return False # If expected output uses ellipsis, a meaningful fancy diff is # too hard ... or maybe not. In two real-life failures Tim saw, # a diff was a major help anyway, so this is commented out. # [todo] _ellipsis_match() knows which pieces do and don't match, # and could be the basis for a kick-ass diff in this case. ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want: ## return False # ndiff does intraline difference marking, so can be useful even # for 1-line differences. if optionflags & REPORT_NDIFF: return True # The other diff types need at least a few lines to be helpful. return want.count('\n') > 2 and got.count('\n') > 2 def output_difference(self, example, got, optionflags): """ Return a string describing the differences between the expected output for a given example (`example`) and the actual output (`got`). `optionflags` is the set of option flags used to compare `want` and `got`. """ want = example.want # If <BLANKLINE>s are being used, then replace blank lines # with <BLANKLINE> in the actual output string. if not (optionflags & DONT_ACCEPT_BLANKLINE): got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got) # Check if we should use diff. if self._do_a_fancy_diff(want, got, optionflags): # Split want & got into lines. want_lines = want.splitlines(True) # True == keep line ends got_lines = got.splitlines(True) # Use difflib to find their differences. if optionflags & REPORT_UDIFF: diff = difflib.unified_diff(want_lines, got_lines, n=2) diff = list(diff)[2:] # strip the diff header kind = 'unified diff with -expected +actual' elif optionflags & REPORT_CDIFF: diff = difflib.context_diff(want_lines, got_lines, n=2) diff = list(diff)[2:] # strip the diff header kind = 'context diff with expected followed by actual' elif optionflags & REPORT_NDIFF: engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK) diff = list(engine.compare(want_lines, got_lines)) kind = 'ndiff with -expected +actual' else: assert 0, 'Bad diff option' # Remove trailing whitespace on diff output. diff = [line.rstrip() + '\n' for line in diff] return 'Differences (%s):\n' % kind + _indent(''.join(diff)) # If we're not using diff, then simply list the expected # output followed by the actual output. if want and got: return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got)) elif want: return 'Expected:\n%sGot nothing\n' % _indent(want) elif got: return 'Expected nothing\nGot:\n%s' % _indent(got) else: return 'Expected nothing\nGot nothing\n' class DocTestFailure(Exception): """A DocTest example has failed in debugging mode. The exception instance has variables: - test: the DocTest object being run - excample: the Example object that failed - got: the actual output """ def __init__(self, test, example, got): self.test = test self.example = example self.got = got def __str__(self): return str(self.test) class UnexpectedException(Exception): """A DocTest example has encountered an unexpected exception The exception instance has variables: - test: the DocTest object being run - excample: the Example object that failed - exc_info: the exception info """ def __init__(self, test, example, exc_info): self.test = test self.example = example self.exc_info = exc_info def __str__(self): return str(self.test) class DebugRunner(DocTestRunner): r"""Run doc tests but raise an exception as soon as there is a failure. If an unexpected exception occurs, an UnexpectedException is raised. It contains the test, the example, and the original exception: >>> runner = DebugRunner(verbose=False) >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42', ... {}, 'foo', 'foo.py', 0) >>> try: ... runner.run(test) ... except UnexpectedException, failure: ... pass >>> failure.test is test True >>> failure.example.want '42\n' >>> exc_info = failure.exc_info >>> raise exc_info[0], exc_info[1], exc_info[2] Traceback (most recent call last): ... KeyError We wrap the original exception to give the calling application access to the test and example information. If the output doesn't match, then a DocTestFailure is raised: >>> test = DocTestParser().get_doctest(''' ... >>> x = 1 ... >>> x ... 2 ... ''', {}, 'foo', 'foo.py', 0) >>> try: ... runner.run(test) ... except DocTestFailure, failure: ... pass DocTestFailure objects provide access to the test: >>> failure.test is test True As well as to the example: >>> failure.example.want '2\n' and the actual output: >>> failure.got '1\n' If a failure or error occurs, the globals are left intact: >>> del test.globs['__builtins__'] >>> test.globs {'x': 1} >>> test = DocTestParser().get_doctest(''' ... >>> x = 2 ... >>> raise KeyError ... ''', {}, 'foo', 'foo.py', 0) >>> runner.run(test) Traceback (most recent call last): ... UnexpectedException: <DocTest foo from foo.py:0 (2 examples)> >>> del test.globs['__builtins__'] >>> test.globs {'x': 2} But the globals are cleared if there is no error: >>> test = DocTestParser().get_doctest(''' ... >>> x = 2 ... ''', {}, 'foo', 'foo.py', 0) >>> runner.run(test) (0, 1) >>> test.globs {} """ def run(self, test, compileflags=None, out=None, clear_globs=True): r = DocTestRunner.run(self, test, compileflags, out, False) if clear_globs: test.globs.clear() return r def report_unexpected_exception(self, out, test, example, exc_info): raise UnexpectedException(test, example, exc_info) def report_failure(self, out, test, example, got): raise DocTestFailure(test, example, got) ###################################################################### ## 6. Test Functions ###################################################################### # These should be backwards compatible. # For backward compatibility, a global instance of a DocTestRunner # class, updated by testmod. master = None def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False): """m=None, name=None, globs=None, verbose=None, isprivate=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False Test examples in docstrings in functions and classes reachable from module m (or the current module if m is not supplied), starting with m.__doc__. Unless isprivate is specified, private names are not skipped. Also test examples reachable from dict m.__test__ if it exists and is not None. m.__test__ maps names to functions, classes and strings; function and class docstrings are tested even if the name is private; strings are tested directly, as if they were docstrings. Return (#failures, #tests). See doctest.__doc__ for an overview. Optional keyword arg "name" gives the name of the module; by default use m.__name__. Optional keyword arg "globs" gives a dict to be used as the globals when executing examples; by default, use m.__dict__. A copy of this dict is actually used for each docstring, so that each docstring's examples start with a clean slate. Optional keyword arg "extraglobs" gives a dictionary that should be merged into the globals that are used to execute examples. By default, no extra globals are used. This is new in 2.4. Optional keyword arg "verbose" prints lots of stuff if true, prints only failures if false; by default, it's true iff "-v" is in sys.argv. Optional keyword arg "report" prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else very brief (in fact, empty if all tests passed). Optional keyword arg "optionflags" or's together module constants, and defaults to 0. This is new in 2.3. Possible values (see the docs for details): DONT_ACCEPT_TRUE_FOR_1 DONT_ACCEPT_BLANKLINE NORMALIZE_WHITESPACE ELLIPSIS IGNORE_EXCEPTION_DETAIL REPORT_UDIFF REPORT_CDIFF REPORT_NDIFF REPORT_ONLY_FIRST_FAILURE Optional keyword arg "raise_on_error" raises an exception on the first unexpected exception or failure. This allows failures to be post-mortem debugged. Deprecated in Python 2.4: Optional keyword arg "isprivate" specifies a function used to determine whether a name is private. The default function is treat all functions as public. Optionally, "isprivate" can be set to doctest.is_private to skip over functions marked as private using the underscore naming convention; see its docs for details. Advanced tomfoolery: testmod runs methods of a local instance of class doctest.Tester, then merges the results into (or creates) global Tester instance doctest.master. Methods of doctest.master can be called directly too, if you want to do something unusual. Passing report=0 to testmod is especially useful then, to delay displaying a summary. Invoke doctest.master.summarize(verbose) when you're done fiddling. """ global master if isprivate is not None: warnings.warn("the isprivate argument is deprecated; " "examine DocTestFinder.find() lists instead", DeprecationWarning) # If no module was given, then use __main__. if m is None: # DWA - m will still be None if this wasn't invoked from the command # line, in which case the following TypeError is about as good an error # as we should expect m = sys.modules.get('__main__') # Check that we were actually given a module. if not inspect.ismodule(m): raise TypeError("testmod: module required; %r" % (m,)) # If no name was given, then use the module's name. if name is None: name = m.__name__ # Find, parse, and run all tests in the given module. finder = DocTestFinder(_namefilter=isprivate, exclude_empty=exclude_empty) if raise_on_error: runner = DebugRunner(verbose=verbose, optionflags=optionflags) else: runner = DocTestRunner(verbose=verbose, optionflags=optionflags) for test in finder.find(m, name, globs=globs, extraglobs=extraglobs): runner.run(test) if report: runner.summarize() if master is None: master = runner else: master.merge(runner) return runner.failures, runner.tries def testfile(filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, parser=DocTestParser()): """ Test examples in the given file. Return (#failures, #tests). Optional keyword arg "module_relative" specifies how filenames should be interpreted: - If "module_relative" is True (the default), then "filename" specifies a module-relative path. By default, this path is relative to the calling module's directory; but if the "package" argument is specified, then it is relative to that package. To ensure os-independence, "filename" should use "/" characters to separate path segments, and should not be an absolute path (i.e., it may not begin with "/"). - If "module_relative" is False, then "filename" specifies an os-specific path. The path may be absolute or relative (to the current working directory). Optional keyword arg "name" gives the name of the test; by default use the file's basename. Optional keyword argument "package" is a Python package or the name of a Python package whose directory should be used as the base directory for a module relative filename. If no package is specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify "package" if "module_relative" is False. Optional keyword arg "globs" gives a dict to be used as the globals when executing examples; by default, use {}. A copy of this dict is actually used for each docstring, so that each docstring's examples start with a clean slate. Optional keyword arg "extraglobs" gives a dictionary that should be merged into the globals that are used to execute examples. By default, no extra globals are used. Optional keyword arg "verbose" prints lots of stuff if true, prints only failures if false; by default, it's true iff "-v" is in sys.argv. Optional keyword arg "report" prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else very brief (in fact, empty if all tests passed). Optional keyword arg "optionflags" or's together module constants, and defaults to 0. Possible values (see the docs for details): DONT_ACCEPT_TRUE_FOR_1 DONT_ACCEPT_BLANKLINE NORMALIZE_WHITESPACE ELLIPSIS IGNORE_EXCEPTION_DETAIL REPORT_UDIFF REPORT_CDIFF REPORT_NDIFF REPORT_ONLY_FIRST_FAILURE Optional keyword arg "raise_on_error" raises an exception on the first unexpected exception or failure. This allows failures to be post-mortem debugged. Optional keyword arg "parser" specifies a DocTestParser (or subclass) that should be used to extract tests from the files. Advanced tomfoolery: testmod runs methods of a local instance of class doctest.Tester, then merges the results into (or creates) global Tester instance doctest.master. Methods of doctest.master can be called directly too, if you want to do something unusual. Passing report=0 to testmod is especially useful then, to delay displaying a summary. Invoke doctest.master.summarize(verbose) when you're done fiddling. """ global master if package and not module_relative: raise ValueError("Package may only be specified for module-" "relative paths.") # Relativize the path if module_relative: package = _normalize_module(package) filename = _module_relative_path(package, filename) # If no name was given, then use the file's name. if name is None: name = os.path.basename(filename) # Assemble the globals. if globs is None: globs = {} else: globs = globs.copy() if extraglobs is not None: globs.update(extraglobs) if raise_on_error: runner = DebugRunner(verbose=verbose, optionflags=optionflags) else: runner = DocTestRunner(verbose=verbose, optionflags=optionflags) # Read the file, convert it to a test, and run it. s = open(filename).read() test = parser.get_doctest(s, globs, name, filename, 0) runner.run(test) if report: runner.summarize() if master is None: master = runner else: master.merge(runner) return runner.failures, runner.tries def run_docstring_examples(f, globs, verbose=False, name="NoName", compileflags=None, optionflags=0): """ Test examples in the given object's docstring (`f`), using `globs` as globals. Optional argument `name` is used in failure messages. If the optional argument `verbose` is true, then generate output even if there are no failures. `compileflags` gives the set of flags that should be used by the Python compiler when running the examples. If not specified, then it will default to the set of future-import flags that apply to `globs`. Optional keyword arg `optionflags` specifies options for the testing and output. See the documentation for `testmod` for more information. """ # Find, parse, and run all tests in the given module. finder = DocTestFinder(verbose=verbose, recurse=False) runner = DocTestRunner(verbose=verbose, optionflags=optionflags) for test in finder.find(f, name, globs=globs): runner.run(test, compileflags=compileflags) ###################################################################### ## 7. Tester ###################################################################### # This is provided only for backwards compatibility. It's not # actually used in any way. class Tester: def __init__(self, mod=None, globs=None, verbose=None, isprivate=None, optionflags=0): warnings.warn("class Tester is deprecated; " "use class doctest.DocTestRunner instead", DeprecationWarning, stacklevel=2) if mod is None and globs is None: raise TypeError("Tester.__init__: must specify mod or globs") if mod is not None and not inspect.ismodule(mod): raise TypeError("Tester.__init__: mod must be a module; %r" % (mod,)) if globs is None: globs = mod.__dict__ self.globs = globs self.verbose = verbose self.isprivate = isprivate self.optionflags = optionflags self.testfinder = DocTestFinder(_namefilter=isprivate) self.testrunner = DocTestRunner(verbose=verbose, optionflags=optionflags) def runstring(self, s, name): test = DocTestParser().get_doctest(s, self.globs, name, None, None) if self.verbose: print "Running string", name (f,t) = self.testrunner.run(test) if self.verbose: print f, "of", t, "examples failed in string", name return (f,t) def rundoc(self, object, name=None, module=None): f = t = 0 tests = self.testfinder.find(object, name, module=module, globs=self.globs) for test in tests: (f2, t2) = self.testrunner.run(test) (f,t) = (f+f2, t+t2) return (f,t) def rundict(self, d, name, module=None): import new m = new.module(name) m.__dict__.update(d) if module is None: module = False return self.rundoc(m, name, module) def run__test__(self, d, name): import new m = new.module(name) m.__test__ = d return self.rundoc(m, name) def summarize(self, verbose=None): return self.testrunner.summarize(verbose) def merge(self, other): self.testrunner.merge(other.testrunner) ###################################################################### ## 8. Unittest Support ###################################################################### _unittest_reportflags = 0 def set_unittest_reportflags(flags): """Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> old = _unittest_reportflags >>> set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> import doctest >>> doctest._unittest_reportflags == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True Only reporting flags can be set: >>> set_unittest_reportflags(ELLIPSIS) Traceback (most recent call last): ... ValueError: ('Only reporting flags allowed', 8) >>> set_unittest_reportflags(old) == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True """ global _unittest_reportflags if (flags & REPORTING_FLAGS) != flags: raise ValueError("Only reporting flags allowed", flags) old = _unittest_reportflags _unittest_reportflags = flags return old class DocTestCase(unittest.TestCase): def __init__(self, test, optionflags=0, setUp=None, tearDown=None, checker=None, runner=DocTestRunner): unittest.TestCase.__init__(self) self._dt_optionflags = optionflags self._dt_checker = checker self._dt_test = test self._dt_setUp = setUp self._dt_tearDown = tearDown self._dt_runner = runner def setUp(self): test = self._dt_test if self._dt_setUp is not None: self._dt_setUp(test) def tearDown(self): test = self._dt_test if self._dt_tearDown is not None: self._dt_tearDown(test) test.globs.clear() def runTest(self): test = self._dt_test old = sys.stdout new = StringIO() optionflags = self._dt_optionflags if not (optionflags & REPORTING_FLAGS): # The option flags don't include any reporting flags, # so add the default reporting flags optionflags |= _unittest_reportflags runner = self._dt_runner(optionflags=optionflags, checker=self._dt_checker, verbose=False) try: runner.DIVIDER = "-"*70 failures, tries = runner.run( test, out=new.write, clear_globs=False) finally: sys.stdout = old if failures: raise self.failureException(self.format_failure(new.getvalue())) def format_failure(self, err): test = self._dt_test if test.lineno is None: lineno = 'unknown line number' else: lineno = '%s' % test.lineno lname = '.'.join(test.name.split('.')[-1:]) return ('Failed doctest test for %s\n' ' File "%s", line %s, in %s\n\n%s' % (test.name, test.filename, lineno, lname, err) ) def debug(self): r"""Run the test case without results and without catching exceptions The unit test framework includes a debug method on test cases and test suites to support post-mortem debugging. The test code is run in such a way that errors are not caught. This way a caller can catch the errors and initiate post-mortem debugging. The DocTestCase provides a debug method that raises UnexpectedException errors if there is an unexepcted exception: >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42', ... {}, 'foo', 'foo.py', 0) >>> case = DocTestCase(test) >>> try: ... case.debug() ... except UnexpectedException, failure: ... pass The UnexpectedException contains the test, the example, and the original exception: >>> failure.test is test True >>> failure.example.want '42\n' >>> exc_info = failure.exc_info >>> raise exc_info[0], exc_info[1], exc_info[2] Traceback (most recent call last): ... KeyError If the output doesn't match, then a DocTestFailure is raised: >>> test = DocTestParser().get_doctest(''' ... >>> x = 1 ... >>> x ... 2 ... ''', {}, 'foo', 'foo.py', 0) >>> case = DocTestCase(test) >>> try: ... case.debug() ... except DocTestFailure, failure: ... pass DocTestFailure objects provide access to the test: >>> failure.test is test True As well as to the example: >>> failure.example.want '2\n' and the actual output: >>> failure.got '1\n' """ self.setUp() runner = DebugRunner(optionflags=self._dt_optionflags, checker=self._dt_checker, verbose=False) runner.run(self._dt_test) self.tearDown() def id(self): return self._dt_test.name def __repr__(self): name = self._dt_test.name.split('.') return "%s (%s)" % (name[-1], '.'.join(name[:-1])) __str__ = __repr__ def shortDescription(self): return "Doctest: " + self._dt_test.name def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, test_class=DocTestCase, **options): """ Convert doctest tests for a module to a unittest test suite. This converts each documentation string in a module that contains doctest tests to a unittest test case. If any of the tests in a doc string fail, then the test case fails. An exception is raised showing the name of the file containing the test and a (sometimes approximate) line number. The `module` argument provides the module to be tested. The argument can be either a module or a module name. If no argument is given, the calling module is used. A number of options may be provided as keyword arguments: setUp A set-up function. This is called before running the tests in each file. The setUp function will be passed a DocTest object. The setUp function can access the test globals as the globs attribute of the test passed. tearDown A tear-down function. This is called after running the tests in each file. The tearDown function will be passed a DocTest object. The tearDown function can access the test globals as the globs attribute of the test passed. globs A dictionary containing initial global variables for the tests. optionflags A set of doctest option flags expressed as an integer. """ if test_finder is None: test_finder = DocTestFinder() module = _normalize_module(module) tests = test_finder.find(module, globs=globs, extraglobs=extraglobs) if globs is None: globs = module.__dict__ if not tests: # Why do we want to do this? Because it reveals a bug that might # otherwise be hidden. raise ValueError(module, "has no tests") tests.sort() suite = unittest.TestSuite() for test in tests: if len(test.examples) == 0: continue if not test.filename: filename = module.__file__ if filename[-4:] in (".pyc", ".pyo"): filename = filename[:-1] test.filename = filename suite.addTest(test_class(test, **options)) return suite class DocFileCase(DocTestCase): def id(self): return '_'.join(self._dt_test.name.split('.')) def __repr__(self): return self._dt_test.filename __str__ = __repr__ def format_failure(self, err): return ('Failed doctest test for %s\n File "%s", line 0\n\n%s' % (self._dt_test.name, self._dt_test.filename, err) ) def DocFileTest(path, module_relative=True, package=None, globs=None, parser=DocTestParser(), **options): if globs is None: globs = {} if package and not module_relative: raise ValueError("Package may only be specified for module-" "relative paths.") # Relativize the path. if module_relative: package = _normalize_module(package) path = _module_relative_path(package, path) # Find the file and read it. name = os.path.basename(path) doc = open(path).read() # Convert it to a test, and wrap it in a DocFileCase. test = parser.get_doctest(doc, globs, name, path, 0) return DocFileCase(test, **options) def DocFileSuite(*paths, **kw): """A unittest suite for one or more doctest files. The path to each doctest file is given as a string; the interpretation of that string depends on the keyword argument "module_relative". A number of options may be provided as keyword arguments: module_relative If "module_relative" is True, then the given file paths are interpreted as os-independent module-relative paths. By default, these paths are relative to the calling module's directory; but if the "package" argument is specified, then they are relative to that package. To ensure os-independence, "filename" should use "/" characters to separate path segments, and may not be an absolute path (i.e., it may not begin with "/"). If "module_relative" is False, then the given file paths are interpreted as os-specific paths. These paths may be absolute or relative (to the current working directory). package A Python package or the name of a Python package whose directory should be used as the base directory for module relative paths. If "package" is not specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify "package" if "module_relative" is False. setUp A set-up function. This is called before running the tests in each file. The setUp function will be passed a DocTest object. The setUp function can access the test globals as the globs attribute of the test passed. tearDown A tear-down function. This is called after running the tests in each file. The tearDown function will be passed a DocTest object. The tearDown function can access the test globals as the globs attribute of the test passed. globs A dictionary containing initial global variables for the tests. optionflags A set of doctest option flags expressed as an integer. parser A DocTestParser (or subclass) that should be used to extract tests from the files. """ suite = unittest.TestSuite() # We do this here so that _normalize_module is called at the right # level. If it were called in DocFileTest, then this function # would be the caller and we might guess the package incorrectly. if kw.get('module_relative', True): kw['package'] = _normalize_module(kw.get('package')) for path in paths: suite.addTest(DocFileTest(path, **kw)) return suite ###################################################################### ## 9. Debugging Support ###################################################################### def script_from_examples(s): r"""Extract script from text with examples. Converts text with examples to a Python script. Example input is converted to regular code. Example output and all other words are converted to comments: >>> text = ''' ... Here are examples of simple math. ... ... Python has super accurate integer addition ... ... >>> 2 + 2 ... 5 ... ... And very friendly error messages: ... ... >>> 1/0 ... To Infinity ... And ... Beyond ... ... You can use logic if you want: ... ... >>> if 0: ... ... blah ... ... blah ... ... ... ... Ho hum ... ''' >>> print script_from_examples(text) # Here are examples of simple math. # # Python has super accurate integer addition # 2 + 2 # Expected: ## 5 # # And very friendly error messages: # 1/0 # Expected: ## To Infinity ## And ## Beyond # # You can use logic if you want: # if 0: blah blah # # Ho hum """ output = [] for piece in DocTestParser().parse(s): if isinstance(piece, Example): # Add the example's source code (strip trailing NL) output.append(piece.source[:-1]) # Add the expected output: want = piece.want if want: output.append('# Expected:') output += ['## '+l for l in want.split('\n')[:-1]] else: # Add non-example text. output += [_comment_line(l) for l in piece.split('\n')[:-1]] # Trim junk on both ends. while output and output[-1] == '#': output.pop() while output and output[0] == '#': output.pop(0) # Combine the output, and return it. return '\n'.join(output) def testsource(module, name): """Extract the test sources from a doctest docstring as a script. Provide the module (or dotted name of the module) containing the test to be debugged and the name (within the module) of the object with the doc string with tests to be debugged. """ module = _normalize_module(module) tests = DocTestFinder().find(module) test = [t for t in tests if t.name == name] if not test: raise ValueError(name, "not found in tests") test = test[0] testsrc = script_from_examples(test.docstring) return testsrc def debug_src(src, pm=False, globs=None): """Debug a single doctest docstring, in argument `src`'""" testsrc = script_from_examples(src) debug_script(testsrc, pm, globs) def debug_script(src, pm=False, globs=None): "Debug a test script. `src` is the script, as a string." import pdb # Note that tempfile.NameTemporaryFile() cannot be used. As the # docs say, a file so created cannot be opened by name a second time # on modern Windows boxes, and execfile() needs to open it. srcfilename = tempfile.mktemp(".py", "doctestdebug") f = open(srcfilename, 'w') f.write(src) f.close() try: if globs: globs = globs.copy() else: globs = {} if pm: try: execfile(srcfilename, globs, globs) except: print sys.exc_info()[1] pdb.post_mortem(sys.exc_info()[2]) else: # Note that %r is vital here. '%s' instead can, e.g., cause # backslashes to get treated as metacharacters on Windows. pdb.run("execfile(%r)" % srcfilename, globs, globs) finally: os.remove(srcfilename) def debug(module, name, pm=False): """Debug a single doctest docstring. Provide the module (or dotted name of the module) containing the test to be debugged and the name (within the module) of the object with the docstring with tests to be debugged. """ module = _normalize_module(module) testsrc = testsource(module, name) debug_script(testsrc, pm, module.__dict__) ###################################################################### ## 10. Example Usage ###################################################################### class _TestClass: """ A pointless class, for sanity-checking of docstring testing. Methods: square() get() >>> _TestClass(13).get() + _TestClass(-12).get() 1 >>> hex(_TestClass(13).square().get()) '0xa9' """ def __init__(self, val): """val -> _TestClass object with associated value val. >>> t = _TestClass(123) >>> print t.get() 123 """ self.val = val def square(self): """square() -> square TestClass's associated value >>> _TestClass(13).square().get() 169 """ self.val = self.val ** 2 return self def get(self): """get() -> return TestClass's associated value. >>> x = _TestClass(-42) >>> print x.get() -42 """ return self.val __test__ = {"_TestClass": _TestClass, "string": r""" Example of a string object, searched as-is. >>> x = 1; y = 2 >>> x + y, x * y (3, 2) """, "bool-int equivalence": r""" In 2.2, boolean expressions displayed 0 or 1. By default, we still accept them. This can be disabled by passing DONT_ACCEPT_TRUE_FOR_1 to the new optionflags argument. >>> 4 == 4 1 >>> 4 == 4 True >>> 4 > 4 0 >>> 4 > 4 False """, "blank lines": r""" Blank lines can be marked with <BLANKLINE>: >>> print 'foo\n\nbar\n' foo <BLANKLINE> bar <BLANKLINE> """, "ellipsis": r""" If the ellipsis flag is used, then '...' can be used to elide substrings in the desired output: >>> print range(1000) #doctest: +ELLIPSIS [0, 1, 2, ..., 999] """, "whitespace normalization": r""" If the whitespace normalization flag is used, then differences in whitespace are ignored. >>> print range(30) #doctest: +NORMALIZE_WHITESPACE [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] """, } def _test(): r = unittest.TextTestRunner() r.run(DocTestSuite()) if __name__ == "__main__": _test()
100,621
Python
.py
2,269
34.788012
84
0.587095
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,390
utils.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/test/utils.py
import sys import time import os import warnings from django.conf import settings from django.core import mail from django.core.mail.backends import locmem from django.test import signals from django.template import Template from django.utils.translation import deactivate class Approximate(object): def __init__(self, val, places=7): self.val = val self.places = places def __repr__(self): return repr(self.val) def __eq__(self, other): if self.val == other: return True return round(abs(self.val-other), self.places) == 0 class ContextList(list): """A wrapper that provides direct key access to context items contained in a list of context objects. """ def __getitem__(self, key): if isinstance(key, basestring): for subcontext in self: if key in subcontext: return subcontext[key] raise KeyError(key) else: return super(ContextList, self).__getitem__(key) def __contains__(self, key): try: value = self[key] except KeyError: return False return True def instrumented_test_render(self, context): """ An instrumented Template render method, providing a signal that can be intercepted by the test system Client """ signals.template_rendered.send(sender=self, template=self, context=context) return self.nodelist.render(context) def setup_test_environment(): """Perform any global pre-test setup. This involves: - Installing the instrumented test renderer - Set the email backend to the locmem email backend. - Setting the active locale to match the LANGUAGE_CODE setting. """ Template.original_render = Template._render Template._render = instrumented_test_render mail.original_SMTPConnection = mail.SMTPConnection mail.SMTPConnection = locmem.EmailBackend mail.original_email_backend = settings.EMAIL_BACKEND settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' mail.outbox = [] deactivate() def teardown_test_environment(): """Perform any global post-test teardown. This involves: - Restoring the original test renderer - Restoring the email sending functions """ Template._render = Template.original_render del Template.original_render mail.SMTPConnection = mail.original_SMTPConnection del mail.original_SMTPConnection settings.EMAIL_BACKEND = mail.original_email_backend del mail.original_email_backend del mail.outbox def get_warnings_state(): """ Returns an object containing the state of the warnings module """ # There is no public interface for doing this, but this implementation of # get_warnings_state and restore_warnings_state appears to work on Python # 2.4 to 2.7. return warnings.filters[:] def restore_warnings_state(state): """ Restores the state of the warnings module when passed an object that was returned by get_warnings_state() """ warnings.filters = state[:] def get_runner(settings): test_path = settings.TEST_RUNNER.split('.') # Allow for Python 2.5 relative paths if len(test_path) > 1: test_module_name = '.'.join(test_path[:-1]) else: test_module_name = '.' test_module = __import__(test_module_name, {}, {}, test_path[-1]) test_runner = getattr(test_module, test_path[-1]) return test_runner
3,526
Python
.py
95
31.052632
79
0.690476
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,391
simple.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/test/simple.py
import sys import signal import unittest from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db.models import get_app, get_apps from django.test import _doctest as doctest from django.test.utils import setup_test_environment, teardown_test_environment from django.test.testcases import OutputChecker, DocTestRunner, TestCase try: all except NameError: from django.utils.itercompat import all # The module name for tests outside models.py TEST_MODULE = 'tests' doctestOutputChecker = OutputChecker() class DjangoTestRunner(unittest.TextTestRunner): def __init__(self, verbosity=0, failfast=False, **kwargs): super(DjangoTestRunner, self).__init__(verbosity=verbosity, **kwargs) self.failfast = failfast self._keyboard_interrupt_intercepted = False def run(self, *args, **kwargs): """ Runs the test suite after registering a custom signal handler that triggers a graceful exit when Ctrl-C is pressed. """ self._default_keyboard_interrupt_handler = signal.signal(signal.SIGINT, self._keyboard_interrupt_handler) try: result = super(DjangoTestRunner, self).run(*args, **kwargs) finally: signal.signal(signal.SIGINT, self._default_keyboard_interrupt_handler) return result def _keyboard_interrupt_handler(self, signal_number, stack_frame): """ Handles Ctrl-C by setting a flag that will stop the test run when the currently running test completes. """ self._keyboard_interrupt_intercepted = True sys.stderr.write(" <Test run halted by Ctrl-C> ") # Set the interrupt handler back to the default handler, so that # another Ctrl-C press will trigger immediate exit. signal.signal(signal.SIGINT, self._default_keyboard_interrupt_handler) def _makeResult(self): result = super(DjangoTestRunner, self)._makeResult() failfast = self.failfast def stoptest_override(func): def stoptest(test): # If we were set to failfast and the unit test failed, # or if the user has typed Ctrl-C, report and quit if (failfast and not result.wasSuccessful()) or \ self._keyboard_interrupt_intercepted: result.stop() func(test) return stoptest setattr(result, 'stopTest', stoptest_override(result.stopTest)) return result def get_tests(app_module): try: app_path = app_module.__name__.split('.')[:-1] test_module = __import__('.'.join(app_path + [TEST_MODULE]), {}, {}, TEST_MODULE) except ImportError, e: # Couldn't import tests.py. Was it due to a missing file, or # due to an import error in a tests.py that actually exists? import os.path from imp import find_module try: mod = find_module(TEST_MODULE, [os.path.dirname(app_module.__file__)]) except ImportError: # 'tests' module doesn't exist. Move on. test_module = None else: # The module exists, so there must be an import error in the # test module itself. We don't need the module; so if the # module was a single file module (i.e., tests.py), close the file # handle returned by find_module. Otherwise, the test module # is a directory, and there is nothing to close. if mod[0]: mod[0].close() raise return test_module def build_suite(app_module): "Create a complete Django test suite for the provided application module" suite = unittest.TestSuite() # Load unit and doctests in the models.py module. If module has # a suite() method, use it. Otherwise build the test suite ourselves. if hasattr(app_module, 'suite'): suite.addTest(app_module.suite()) else: suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(app_module)) try: suite.addTest(doctest.DocTestSuite(app_module, checker=doctestOutputChecker, runner=DocTestRunner)) except ValueError: # No doc tests in models.py pass # Check to see if a separate 'tests' module exists parallel to the # models module test_module = get_tests(app_module) if test_module: # Load unit and doctests in the tests.py module. If module has # a suite() method, use it. Otherwise build the test suite ourselves. if hasattr(test_module, 'suite'): suite.addTest(test_module.suite()) else: suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(test_module)) try: suite.addTest(doctest.DocTestSuite(test_module, checker=doctestOutputChecker, runner=DocTestRunner)) except ValueError: # No doc tests in tests.py pass return suite def build_test(label): """Construct a test case with the specified label. Label should be of the form model.TestClass or model.TestClass.test_method. Returns an instantiated test or test suite corresponding to the label provided. """ parts = label.split('.') if len(parts) < 2 or len(parts) > 3: raise ValueError("Test label '%s' should be of the form app.TestCase or app.TestCase.test_method" % label) # # First, look for TestCase instances with a name that matches # app_module = get_app(parts[0]) test_module = get_tests(app_module) TestClass = getattr(app_module, parts[1], None) # Couldn't find the test class in models.py; look in tests.py if TestClass is None: if test_module: TestClass = getattr(test_module, parts[1], None) try: if issubclass(TestClass, unittest.TestCase): if len(parts) == 2: # label is app.TestClass try: return unittest.TestLoader().loadTestsFromTestCase(TestClass) except TypeError: raise ValueError("Test label '%s' does not refer to a test class" % label) else: # label is app.TestClass.test_method return TestClass(parts[2]) except TypeError: # TestClass isn't a TestClass - it must be a method or normal class pass # # If there isn't a TestCase, look for a doctest that matches # tests = [] for module in app_module, test_module: try: doctests = doctest.DocTestSuite(module, checker=doctestOutputChecker, runner=DocTestRunner) # Now iterate over the suite, looking for doctests whose name # matches the pattern that was given for test in doctests: if test._dt_test.name in ( '%s.%s' % (module.__name__, '.'.join(parts[1:])), '%s.__test__.%s' % (module.__name__, '.'.join(parts[1:]))): tests.append(test) except ValueError: # No doctests found. pass # If no tests were found, then we were given a bad test label. if not tests: raise ValueError("Test label '%s' does not refer to a test" % label) # Construct a suite out of the tests that matched. return unittest.TestSuite(tests) def partition_suite(suite, classes, bins): """ Partitions a test suite by test type. classes is a sequence of types bins is a sequence of TestSuites, one more than classes Tests of type classes[i] are added to bins[i], tests with no match found in classes are place in bins[-1] """ for test in suite: if isinstance(test, unittest.TestSuite): partition_suite(test, classes, bins) else: for i in range(len(classes)): if isinstance(test, classes[i]): bins[i].addTest(test) break else: bins[-1].addTest(test) def reorder_suite(suite, classes): """ Reorders a test suite by test type. classes is a sequence of types All tests of type clases[0] are placed first, then tests of type classes[1], etc. Tests with no match in classes are placed last. """ class_count = len(classes) bins = [unittest.TestSuite() for i in range(class_count+1)] partition_suite(suite, classes, bins) for i in range(class_count): bins[0].addTests(bins[i+1]) return bins[0] def dependency_ordered(test_databases, dependencies): """Reorder test_databases into an order that honors the dependencies described in TEST_DEPENDENCIES. """ ordered_test_databases = [] resolved_databases = set() while test_databases: changed = False deferred = [] while test_databases: signature, (db_name, aliases) = test_databases.pop() dependencies_satisfied = True for alias in aliases: if alias in dependencies: if all(a in resolved_databases for a in dependencies[alias]): # all dependencies for this alias are satisfied dependencies.pop(alias) resolved_databases.add(alias) else: dependencies_satisfied = False else: resolved_databases.add(alias) if dependencies_satisfied: ordered_test_databases.append((signature, (db_name, aliases))) changed = True else: deferred.append((signature, (db_name, aliases))) if not changed: raise ImproperlyConfigured("Circular dependency in TEST_DEPENDENCIES") test_databases = deferred return ordered_test_databases class DjangoTestSuiteRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def setup_test_environment(self, **kwargs): setup_test_environment() settings.DEBUG = False def build_suite(self, test_labels, extra_tests=None, **kwargs): suite = unittest.TestSuite() if test_labels: for label in test_labels: if '.' in label: suite.addTest(build_test(label)) else: app = get_app(label) suite.addTest(build_suite(app)) else: for app in get_apps(): suite.addTest(build_suite(app)) if extra_tests: for test in extra_tests: suite.addTest(test) return reorder_suite(suite, (TestCase,)) def setup_databases(self, **kwargs): from django.db import connections, DEFAULT_DB_ALIAS # First pass -- work out which databases actually need to be created, # and which ones are test mirrors or duplicate entries in DATABASES mirrored_aliases = {} test_databases = {} dependencies = {} for alias in connections: connection = connections[alias] if connection.settings_dict['TEST_MIRROR']: # If the database is marked as a test mirror, save # the alias. mirrored_aliases[alias] = connection.settings_dict['TEST_MIRROR'] else: # Store a tuple with DB parameters that uniquely identify it. # If we have two aliases with the same values for that tuple, # we only need to create the test database once. item = test_databases.setdefault( connection.creation.test_db_signature(), (connection.settings_dict['NAME'], []) ) item[1].append(alias) if 'TEST_DEPENDENCIES' in connection.settings_dict: dependencies[alias] = connection.settings_dict['TEST_DEPENDENCIES'] else: if alias != DEFAULT_DB_ALIAS: dependencies[alias] = connection.settings_dict.get('TEST_DEPENDENCIES', [DEFAULT_DB_ALIAS]) # Second pass -- actually create the databases. old_names = [] mirrors = [] for signature, (db_name, aliases) in dependency_ordered(test_databases.items(), dependencies): # Actually create the database for the first connection connection = connections[aliases[0]] old_names.append((connection, db_name, True)) test_db_name = connection.creation.create_test_db(self.verbosity, autoclobber=not self.interactive) for alias in aliases[1:]: connection = connections[alias] if db_name: old_names.append((connection, db_name, False)) connection.settings_dict['NAME'] = test_db_name else: # If settings_dict['NAME'] isn't defined, we have a backend where # the name isn't important -- e.g., SQLite, which uses :memory:. # Force create the database instead of assuming it's a duplicate. old_names.append((connection, db_name, True)) connection.creation.create_test_db(self.verbosity, autoclobber=not self.interactive) for alias, mirror_alias in mirrored_aliases.items(): mirrors.append((alias, connections[alias].settings_dict['NAME'])) connections[alias].settings_dict['NAME'] = connections[mirror_alias].settings_dict['NAME'] return old_names, mirrors def run_suite(self, suite, **kwargs): return DjangoTestRunner(verbosity=self.verbosity, failfast=self.failfast).run(suite) def teardown_databases(self, old_config, **kwargs): from django.db import connections old_names, mirrors = old_config # Point all the mirrors back to the originals for alias, old_name in mirrors: connections[alias].settings_dict['NAME'] = old_name # Destroy all the non-mirror databases for connection, old_name, destroy in old_names: if destroy: connection.creation.destroy_test_db(old_name, self.verbosity) else: connection.settings_dict['NAME'] = old_name def teardown_test_environment(self, **kwargs): teardown_test_environment() def suite_result(self, suite, result, **kwargs): return len(result.failures) + len(result.errors) def run_tests(self, test_labels, extra_tests=None, **kwargs): """ Run the unit tests for all the test labels in the provided list. Labels must be of the form: - app.TestClass.test_method Run a single specific test method - app.TestClass Run all the test methods in a given class - app Search for doctests and unittests in the named application. When looking for tests, the test runner will look in the models and tests modules for the application. A list of 'extra' tests may also be provided; these tests will be added to the test suite. Returns the number of tests that failed. """ self.setup_test_environment() suite = self.build_suite(test_labels, extra_tests) old_config = self.setup_databases() result = self.run_suite(suite) self.teardown_databases(old_config) self.teardown_test_environment() return self.suite_result(suite, result) def run_tests(test_labels, verbosity=1, interactive=True, failfast=False, extra_tests=None): import warnings warnings.warn( 'The run_tests() test runner has been deprecated in favor of DjangoTestSuiteRunner.', PendingDeprecationWarning ) test_runner = DjangoTestSuiteRunner(verbosity=verbosity, interactive=interactive, failfast=failfast) return test_runner.run_tests(test_labels, extra_tests=extra_tests)
16,447
Python
.py
354
35.432203
115
0.616598
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,392
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/test/__init__.py
""" Django Unit Test and Doctest framework. """ from django.test.client import Client from django.test.testcases import TestCase, TransactionTestCase from django.test.utils import Approximate
193
Python
.py
6
31
63
0.844086
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,393
make-messages.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/bin/make-messages.py
#!/usr/bin/env python if __name__ == "__main__": import sys name = sys.argv[0] args = ' '.join(sys.argv[1:]) print >> sys.stderr, "%s has been moved into django-admin.py" % name print >> sys.stderr, 'Please run "django-admin.py makemessages %s" instead.'% args print >> sys.stderr sys.exit(1)
323
Python
.py
9
31.555556
86
0.615385
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,394
compile-messages.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/bin/compile-messages.py
#!/usr/bin/env python if __name__ == "__main__": import sys name = sys.argv[0] args = ' '.join(sys.argv[1:]) print >> sys.stderr, "%s has been moved into django-admin.py" % name print >> sys.stderr, 'Please run "django-admin.py compilemessages %s" instead.'% args print >> sys.stderr sys.exit(1)
326
Python
.py
9
31.888889
89
0.619048
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,395
unique-messages.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/bin/unique-messages.py
#!/usr/bin/env python import os import sys def unique_messages(): basedir = None if os.path.isdir(os.path.join('conf', 'locale')): basedir = os.path.abspath(os.path.join('conf', 'locale')) elif os.path.isdir('locale'): basedir = os.path.abspath('locale') else: print "this script should be run from the django svn tree or your project or app tree" sys.exit(1) for (dirpath, dirnames, filenames) in os.walk(basedir): for f in filenames: if f.endswith('.po'): sys.stderr.write('processing file %s in %s\n' % (f, dirpath)) pf = os.path.splitext(os.path.join(dirpath, f))[0] cmd = 'msguniq "%s.po"' % pf stdout = os.popen(cmd) msg = stdout.read() open('%s.po' % pf, 'w').write(msg) if __name__ == "__main__": unique_messages()
900
Python
.py
23
30.434783
94
0.56422
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,396
daily_cleanup.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/bin/daily_cleanup.py
#!/usr/bin/env python """ Daily cleanup job. Can be run as a cronjob to clean out old data from the database (only expired sessions at the moment). """ from django.core import management if __name__ == "__main__": management.call_command('cleanup')
257
Python
.py
9
26.666667
77
0.729508
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,397
django-admin.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/bin/django-admin.py
#!/usr/bin/env python from django.core import management if __name__ == "__main__": management.execute_from_command_line()
128
Python
.py
4
29.75
42
0.707317
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,398
gather_profile_stats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/bin/profiling/gather_profile_stats.py
#!/usr/bin/env python """ gather_profile_stats.py /path/to/dir/of/profiles Note that the aggregated profiles must be read with pstats.Stats, not hotshot.stats (the formats are incompatible) """ from hotshot import stats import pstats import sys, os def gather_stats(p): profiles = {} for f in os.listdir(p): if f.endswith('.agg.prof'): path = f[:-9] prof = pstats.Stats(os.path.join(p, f)) elif f.endswith('.prof'): bits = f.split('.') path = ".".join(bits[:-3]) prof = stats.load(os.path.join(p, f)) else: continue print "Processing %s" % f if path in profiles: profiles[path].add(prof) else: profiles[path] = prof os.unlink(os.path.join(p, f)) for (path, prof) in profiles.items(): prof.dump_stats(os.path.join(p, "%s.agg.prof" % path)) if __name__ == '__main__': gather_stats(sys.argv[1])
977
Python
.py
31
24.548387
69
0.579509
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,399
saferef.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/dispatch/saferef.py
""" "Safe weakrefs", originally from pyDispatcher. Provides a way to safely weakref any function, including bound methods (which aren't handled by the core weakref module). """ import weakref, traceback def safeRef(target, onDelete = None): """Return a *safe* weak reference to a callable target target -- the object to be weakly referenced, if it's a bound method reference, will create a BoundMethodWeakref, otherwise creates a simple weakref. onDelete -- if provided, will have a hard reference stored to the callable to be called after the safe reference goes out of scope with the reference object, (either a weakref or a BoundMethodWeakref) as argument. """ if hasattr(target, 'im_self'): if target.im_self is not None: # Turn a bound method into a BoundMethodWeakref instance. # Keep track of these instances for lookup by disconnect(). assert hasattr(target, 'im_func'), """safeRef target %r has im_self, but no im_func, don't know how to create reference"""%( target,) reference = get_bound_method_weakref( target=target, onDelete=onDelete ) return reference if callable(onDelete): return weakref.ref(target, onDelete) else: return weakref.ref( target ) class BoundMethodWeakref(object): """'Safe' and reusable weak references to instance methods BoundMethodWeakref objects provide a mechanism for referencing a bound method without requiring that the method object itself (which is normally a transient object) is kept alive. Instead, the BoundMethodWeakref object keeps weak references to both the object and the function which together define the instance method. Attributes: key -- the identity key for the reference, calculated by the class's calculateKey method applied to the target instance method deletionMethods -- sequence of callable objects taking single argument, a reference to this object which will be called when *either* the target object or target function is garbage collected (i.e. when this object becomes invalid). These are specified as the onDelete parameters of safeRef calls. weakSelf -- weak reference to the target object weakFunc -- weak reference to the target function Class Attributes: _allInstances -- class attribute pointing to all live BoundMethodWeakref objects indexed by the class's calculateKey(target) method applied to the target objects. This weak value dictionary is used to short-circuit creation so that multiple references to the same (object, function) pair produce the same BoundMethodWeakref instance. """ _allInstances = weakref.WeakValueDictionary() def __new__( cls, target, onDelete=None, *arguments,**named ): """Create new instance or return current instance Basically this method of construction allows us to short-circuit creation of references to already- referenced instance methods. The key corresponding to the target is calculated, and if there is already an existing reference, that is returned, with its deletionMethods attribute updated. Otherwise the new instance is created and registered in the table of already-referenced methods. """ key = cls.calculateKey(target) current =cls._allInstances.get(key) if current is not None: current.deletionMethods.append( onDelete) return current else: base = super( BoundMethodWeakref, cls).__new__( cls ) cls._allInstances[key] = base base.__init__( target, onDelete, *arguments,**named) return base def __init__(self, target, onDelete=None): """Return a weak-reference-like instance for a bound method target -- the instance-method target for the weak reference, must have im_self and im_func attributes and be reconstructable via: target.im_func.__get__( target.im_self ) which is true of built-in instance methods. onDelete -- optional callback which will be called when this weak reference ceases to be valid (i.e. either the object or the function is garbage collected). Should take a single argument, which will be passed a pointer to this object. """ def remove(weak, self=self): """Set self.isDead to true when method or instance is destroyed""" methods = self.deletionMethods[:] del self.deletionMethods[:] try: del self.__class__._allInstances[ self.key ] except KeyError: pass for function in methods: try: if callable( function ): function( self ) except Exception, e: try: traceback.print_exc() except AttributeError, err: print '''Exception during saferef %s cleanup function %s: %s'''%( self, function, e ) self.deletionMethods = [onDelete] self.key = self.calculateKey( target ) self.weakSelf = weakref.ref(target.im_self, remove) self.weakFunc = weakref.ref(target.im_func, remove) self.selfName = str(target.im_self) self.funcName = str(target.im_func.__name__) def calculateKey( cls, target ): """Calculate the reference key for this reference Currently this is a two-tuple of the id()'s of the target object and the target function respectively. """ return (id(target.im_self),id(target.im_func)) calculateKey = classmethod( calculateKey ) def __str__(self): """Give a friendly representation of the object""" return """%s( %s.%s )"""%( self.__class__.__name__, self.selfName, self.funcName, ) __repr__ = __str__ def __nonzero__( self ): """Whether we are still a valid reference""" return self() is not None def __cmp__( self, other ): """Compare with another reference""" if not isinstance (other,self.__class__): return cmp( self.__class__, type(other) ) return cmp( self.key, other.key) def __call__(self): """Return a strong reference to the bound method If the target cannot be retrieved, then will return None, otherwise returns a bound instance method for our object and function. Note: You may call this method any number of times, as it does not invalidate the reference. """ target = self.weakSelf() if target is not None: function = self.weakFunc() if function is not None: return function.__get__(target) return None class BoundNonDescriptorMethodWeakref(BoundMethodWeakref): """A specialized BoundMethodWeakref, for platforms where instance methods are not descriptors. It assumes that the function name and the target attribute name are the same, instead of assuming that the function is a descriptor. This approach is equally fast, but not 100% reliable because functions can be stored on an attribute named differenty than the function's name such as in: class A: pass def foo(self): return "foo" A.bar = foo But this shouldn't be a common use case. So, on platforms where methods aren't descriptors (such as Jython) this implementation has the advantage of working in the most cases. """ def __init__(self, target, onDelete=None): """Return a weak-reference-like instance for a bound method target -- the instance-method target for the weak reference, must have im_self and im_func attributes and be reconstructable via: target.im_func.__get__( target.im_self ) which is true of built-in instance methods. onDelete -- optional callback which will be called when this weak reference ceases to be valid (i.e. either the object or the function is garbage collected). Should take a single argument, which will be passed a pointer to this object. """ assert getattr(target.im_self, target.__name__) == target, \ ("method %s isn't available as the attribute %s of %s" % (target, target.__name__, target.im_self)) super(BoundNonDescriptorMethodWeakref, self).__init__(target, onDelete) def __call__(self): """Return a strong reference to the bound method If the target cannot be retrieved, then will return None, otherwise returns a bound instance method for our object and function. Note: You may call this method any number of times, as it does not invalidate the reference. """ target = self.weakSelf() if target is not None: function = self.weakFunc() if function is not None: # Using curry() would be another option, but it erases the # "signature" of the function. That is, after a function is # curried, the inspect module can't be used to determine how # many arguments the function expects, nor what keyword # arguments it supports, and pydispatcher needs this # information. return getattr(target, function.__name__) return None def get_bound_method_weakref(target, onDelete): """Instantiates the appropiate BoundMethodWeakRef, depending on the details of the underlying class method implementation""" if hasattr(target, '__get__'): # target method is a descriptor, so the default implementation works: return BoundMethodWeakref(target=target, onDelete=onDelete) else: # no luck, use the alternative implementation: return BoundNonDescriptorMethodWeakref(target=target, onDelete=onDelete)
10,495
Python
.py
218
37.788991
145
0.638456
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)