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
2,000
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/localflavor/us/forms.py
from django.forms import ModelForm from models import USPlace class USPlaceForm(ModelForm): """docstring for PlaceForm""" class Meta: model = USPlace
167
Python
.py
6
24
34
0.75
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,001
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/formwizard/urls.py
from django.conf.urls.defaults import * from forms import ContactWizard, Page1, Page2, Page3 urlpatterns = patterns('', url(r'^wiz/$', ContactWizard([Page1, Page2, Page3])), )
185
Python
.py
5
34.2
57
0.72067
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,002
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/formwizard/tests.py
import re from django import forms from django.test import TestCase class FormWizardWithNullBooleanField(TestCase): urls = 'regressiontests.formwizard.urls' input_re = re.compile('name="([^"]+)" value="([^"]+)"') wizard_url = '/wiz/' wizard_step_data = ( { '0-name': 'Pony', '0-thirsty': '2', }, { '1-address1': '123 Main St', '1-address2': 'Djangoland', }, { '2-random_crap': 'blah blah', } ) def grabFieldData(self, response): """ Pull the appropriate field data from the context to pass to the next wizard step """ previous_fields = response.context['previous_fields'] fields = {'wizard_step': response.context['step0']} def grab(m): fields[m.group(1)] = m.group(2) return '' self.input_re.sub(grab, previous_fields) return fields def checkWizardStep(self, response, step_no): """ Helper function to test each step of the wizard - Make sure the call succeeded - Make sure response is the proper step number - return the result from the post for the next step """ step_count = len(self.wizard_step_data) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Step %d of %d' % (step_no, step_count)) data = self.grabFieldData(response) data.update(self.wizard_step_data[step_no - 1]) return self.client.post(self.wizard_url, data) def testWizard(self): response = self.client.get(self.wizard_url) for step_no in range(1, len(self.wizard_step_data) + 1): response = self.checkWizardStep(response, step_no)
1,813
Python
.py
48
28.708333
88
0.596532
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,003
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/formwizard/forms.py
from django import forms from django.contrib.formtools.wizard import FormWizard from django.http import HttpResponse class Page1(forms.Form): name = forms.CharField(max_length=100) thirsty = forms.NullBooleanField() class Page2(forms.Form): address1 = forms.CharField(max_length=100) address2 = forms.CharField(max_length=100) class Page3(forms.Form): random_crap = forms.CharField(max_length=100) class ContactWizard(FormWizard): def done(self, request, form_list): return HttpResponse("")
535
Python
.py
14
34.071429
54
0.770138
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,004
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/reverse_single_related/models.py
from django.db import models class SourceManager(models.Manager): def get_query_set(self): return super(SourceManager, self).get_query_set().filter(is_public=True) class Source(models.Model): is_public = models.BooleanField() objects = SourceManager() class Item(models.Model): source = models.ForeignKey(Source)
340
Python
.py
9
33.777778
80
0.75
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,005
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/reverse_single_related/tests.py
from django.test import TestCase from regressiontests.reverse_single_related.models import * class ReverseSingleRelatedTests(TestCase): """ Regression tests for an object that cannot access a single related object due to a restrictive default manager. """ def test_reverse_single_related(self): public_source = Source.objects.create(is_public=True) public_item = Item.objects.create(source=public_source) private_source = Source.objects.create(is_public=False) private_item = Item.objects.create(source=private_source) # Only one source is available via all() due to the custom default manager. self.assertQuerysetEqual( Source.objects.all(), ["<Source: Source object>"] ) self.assertEqual(public_item.source, public_source) # Make sure that an item can still access its related source even if the default # manager doesn't normally allow it. self.assertEqual(private_item.source, private_source) # If the manager is marked "use_for_related_fields", it'll get used instead # of the "bare" queryset. Usually you'd define this as a property on the class, # but this approximates that in a way that's easier in tests. Source.objects.use_for_related_fields = True private_item = Item.objects.get(pk=private_item.pk) self.assertRaises(Source.DoesNotExist, lambda: private_item.source)
1,477
Python
.py
27
46.407407
88
0.70229
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,006
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/backends/models.py
from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.db import models from django.db import connection class Square(models.Model): root = models.IntegerField() square = models.PositiveIntegerField() def __unicode__(self): return "%s ** 2 == %s" % (self.root, self.square) 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) class SchoolClass(models.Model): year = models.PositiveIntegerField() day = models.CharField(max_length=9, blank=True) last_updated = models.DateTimeField() # Unfortunately, the following model breaks MySQL hard. # Until #13711 is fixed, this test can't be run under MySQL. if connection.features.supports_long_model_names: class VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ(models.Model): class Meta: # We need to use a short actual table name or # we hit issue #8548 which we're not testing! verbose_name = 'model_with_long_table_name' primary_key_is_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz = models.AutoField(primary_key=True) charfield_is_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz = models.CharField(max_length=100) m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz = models.ManyToManyField(Person,blank=True) class Tag(models.Model): name = models.CharField(max_length=30) content_type = models.ForeignKey(ContentType, related_name='backend_tags') object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') class Post(models.Model): name = models.CharField(max_length=30) text = models.TextField() tags = generic.GenericRelation('Tag') class Meta: db_table = 'CaseSensitive_Post' 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() reporter = models.ForeignKey(Reporter) def __unicode__(self): return self.headline
2,436
Python
.py
51
42.294118
115
0.733615
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,007
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/backends/tests.py
# -*- coding: utf-8 -*- # Unit and doctests for specific database backends. import datetime from django.core.management.color import no_style from django.db import backend, connection, connections, DEFAULT_DB_ALIAS, IntegrityError from django.db.backends.signals import connection_created from django.db.backends.postgresql import version as pg_version from django.test import TestCase, skipUnlessDBFeature, TransactionTestCase from django.utils import unittest from regressiontests.backends import models class OracleChecks(unittest.TestCase): @unittest.skipUnless(connection.vendor == 'oracle', "No need to check Oracle cursor semantics") def test_dbms_session(self): # If the backend is Oracle, test that we can call a standard # stored procedure through our cursor wrapper. convert_unicode = backend.convert_unicode cursor = connection.cursor() cursor.callproc(convert_unicode('DBMS_SESSION.SET_IDENTIFIER'), [convert_unicode('_django_testing!'),]) @unittest.skipUnless(connection.vendor == 'oracle', "No need to check Oracle cursor semantics") def test_cursor_var(self): # If the backend is Oracle, test that we can pass cursor variables # as query parameters. cursor = connection.cursor() var = cursor.var(backend.Database.STRING) cursor.execute("BEGIN %s := 'X'; END; ", [var]) self.assertEqual(var.getvalue(), 'X') @unittest.skipUnless(connection.vendor == 'oracle', "No need to check Oracle cursor semantics") def test_long_string(self): # If the backend is Oracle, test that we can save a text longer # than 4000 chars and read it properly c = connection.cursor() c.execute('CREATE TABLE ltext ("TEXT" NCLOB)') long_str = ''.join([unicode(x) for x in xrange(4000)]) c.execute('INSERT INTO ltext VALUES (%s)',[long_str]) c.execute('SELECT text FROM ltext') row = c.fetchone() self.assertEqual(long_str, row[0].read()) c.execute('DROP TABLE ltext') @unittest.skipUnless(connection.vendor == 'oracle', "No need to check Oracle connection semantics") def test_client_encoding(self): # If the backend is Oracle, test that the client encoding is set # correctly. This was broken under Cygwin prior to r14781. c = connection.cursor() # Ensure the connection is initialized. self.assertEqual(connection.connection.encoding, "UTF-8") self.assertEqual(connection.connection.nencoding, "UTF-8") class DateQuotingTest(TestCase): def test_django_date_trunc(self): """ Test the custom ``django_date_trunc method``, in particular against fields which clash with strings passed to it (e.g. 'year') - see #12818__. __: http://code.djangoproject.com/ticket/12818 """ updated = datetime.datetime(2010, 2, 20) models.SchoolClass.objects.create(year=2009, last_updated=updated) years = models.SchoolClass.objects.dates('last_updated', 'year') self.assertEqual(list(years), [datetime.datetime(2010, 1, 1, 0, 0)]) def test_django_extract(self): """ Test the custom ``django_extract method``, in particular against fields which clash with strings passed to it (e.g. 'day') - see #12818__. __: http://code.djangoproject.com/ticket/12818 """ updated = datetime.datetime(2010, 2, 20) models.SchoolClass.objects.create(year=2009, last_updated=updated) classes = models.SchoolClass.objects.filter(last_updated__day=20) self.assertEqual(len(classes), 1) class ParameterHandlingTest(TestCase): def test_bad_parameter_count(self): "An executemany call with too many/not enough parameters will raise an exception (Refs #12612)" cursor = connection.cursor() query = ('INSERT INTO %s (%s, %s) VALUES (%%s, %%s)' % ( connection.introspection.table_name_converter('backends_square'), connection.ops.quote_name('root'), connection.ops.quote_name('square') )) self.assertRaises(Exception, cursor.executemany, query, [(1,2,3),]) self.assertRaises(Exception, cursor.executemany, query, [(1,),]) # Unfortunately, the following tests would be a good test to run on all # backends, but it breaks MySQL hard. Until #13711 is fixed, it can't be run # everywhere (although it would be an effective test of #13711). class LongNameTest(TestCase): """Long primary keys and model names can result in a sequence name that exceeds the database limits, which will result in truncation on certain databases (e.g., Postgres). The backend needs to use the correct sequence name in last_insert_id and other places, so check it is. Refs #8901. """ @skipUnlessDBFeature('supports_long_model_names') def test_sequence_name_length_limits_create(self): """Test creation of model with long name and long pk name doesn't error. Ref #8901""" models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create() @skipUnlessDBFeature('supports_long_model_names') def test_sequence_name_length_limits_m2m(self): """Test an m2m save of a model with a long name and a long m2m field name doesn't error as on Django >=1.2 this now uses object saves. Ref #8901""" obj = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create() rel_obj = models.Person.objects.create(first_name='Django', last_name='Reinhardt') obj.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.add(rel_obj) @skipUnlessDBFeature('supports_long_model_names') def test_sequence_name_length_limits_flush(self): """Test that sequence resetting as part of a flush with model with long name and long pk name doesn't error. Ref #8901""" # A full flush is expensive to the full test, so we dig into the # internals to generate the likely offending SQL and run it manually # Some convenience aliases VLM = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ VLM_m2m = VLM.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.through tables = [ VLM._meta.db_table, VLM_m2m._meta.db_table, ] sequences = [ { 'column': VLM._meta.pk.column, 'table': VLM._meta.db_table }, ] cursor = connection.cursor() for statement in connection.ops.sql_flush(no_style(), tables, sequences): cursor.execute(statement) class SequenceResetTest(TestCase): def test_generic_relation(self): "Sequence names are correct when resetting generic relations (Ref #13941)" # Create an object with a manually specified PK models.Post.objects.create(id=10, name='1st post', text='hello world') # Reset the sequences for the database cursor = connection.cursor() commands = connections[DEFAULT_DB_ALIAS].ops.sequence_reset_sql(no_style(), [models.Post]) for sql in commands: cursor.execute(sql) # If we create a new object now, it should have a PK greater # than the PK we specified manually. obj = models.Post.objects.create(name='New post', text='goodbye world') self.assertTrue(obj.pk > 10) class PostgresVersionTest(TestCase): def assert_parses(self, version_string, version): self.assertEqual(pg_version._parse_version(version_string), version) def test_parsing(self): self.assert_parses("PostgreSQL 8.3 beta4", (8, 3, None)) self.assert_parses("PostgreSQL 8.3", (8, 3, None)) self.assert_parses("EnterpriseDB 8.3", (8, 3, None)) self.assert_parses("PostgreSQL 8.3.6", (8, 3, 6)) self.assert_parses("PostgreSQL 8.4beta1", (8, 4, None)) self.assert_parses("PostgreSQL 8.3.1 on i386-apple-darwin9.2.2, compiled by GCC i686-apple-darwin9-gcc-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5478)", (8, 3, 1)) # Unfortunately with sqlite3 the in-memory test database cannot be # closed, and so it cannot be re-opened during testing, and so we # sadly disable this test for now. class ConnectionCreatedSignalTest(TestCase): @skipUnlessDBFeature('test_db_allows_multiple_connections') def test_signal(self): data = {} def receiver(sender, connection, **kwargs): data["connection"] = connection connection_created.connect(receiver) connection.close() cursor = connection.cursor() self.assertTrue(data["connection"] is connection) connection_created.disconnect(receiver) data.clear() cursor = connection.cursor() self.assertTrue(data == {}) class BackendTestCase(TestCase): def test_cursor_executemany(self): #4896: Test cursor.executemany cursor = connection.cursor() qn = connection.ops.quote_name opts = models.Square._meta f1, f2 = opts.get_field('root'), opts.get_field('square') query = ('INSERT INTO %s (%s, %s) VALUES (%%s, %%s)' % (connection.introspection.table_name_converter(opts.db_table), qn(f1.column), qn(f2.column))) cursor.executemany(query, [(i, i**2) for i in range(-5, 6)]) self.assertEqual(models.Square.objects.count(), 11) for i in range(-5, 6): square = models.Square.objects.get(root=i) self.assertEqual(square.square, i**2) #4765: executemany with params=[] does nothing cursor.executemany(query, []) self.assertEqual(models.Square.objects.count(), 11) def test_unicode_fetches(self): #6254: fetchone, fetchmany, fetchall return strings as unicode objects qn = connection.ops.quote_name models.Person(first_name="John", last_name="Doe").save() models.Person(first_name="Jane", last_name="Doe").save() models.Person(first_name="Mary", last_name="Agnelline").save() models.Person(first_name="Peter", last_name="Parker").save() models.Person(first_name="Clark", last_name="Kent").save() opts2 = models.Person._meta f3, f4 = opts2.get_field('first_name'), opts2.get_field('last_name') query2 = ('SELECT %s, %s FROM %s ORDER BY %s' % (qn(f3.column), qn(f4.column), connection.introspection.table_name_converter(opts2.db_table), qn(f3.column))) cursor = connection.cursor() cursor.execute(query2) self.assertEqual(cursor.fetchone(), (u'Clark', u'Kent')) self.assertEqual(list(cursor.fetchmany(2)), [(u'Jane', u'Doe'), (u'John', u'Doe')]) self.assertEqual(list(cursor.fetchall()), [(u'Mary', u'Agnelline'), (u'Peter', u'Parker')]) # We don't make these tests conditional because that means we would need to # check and differentiate between: # * MySQL+InnoDB, MySQL+MYISAM (something we currently can't do). # * if sqlite3 (if/once we get #14204 fixed) has referential integrity turned # on or not, something that would be controlled by runtime support and user # preference. # verify if its type is django.database.db.IntegrityError. class FkConstraintsTests(TransactionTestCase): def setUp(self): # Create a Reporter. self.r = models.Reporter.objects.create(first_name='John', last_name='Smith') def test_integrity_checks_on_creation(self): """ Try to create a model instance that violates a FK constraint. If it fails it should fail with IntegrityError. """ a = models.Article(headline="This is a test", pub_date=datetime.datetime(2005, 7, 27), reporter_id=30) try: a.save() except IntegrityError: pass def test_integrity_checks_on_update(self): """ Try to update a model instance introducing a FK constraint violation. If it fails it should fail with IntegrityError. """ # Create an Article. models.Article.objects.create(headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r) # Retrive it from the DB a = models.Article.objects.get(headline="Test article") a.reporter_id = 30 try: a.save() except IntegrityError: pass
12,550
Python
.py
235
45.123404
165
0.670169
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,008
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/test_client_regress/models.py
# -*- coding: utf-8 -*- """ Regression tests for the Test Client, especially the customized assertions. """ import os from django.conf import settings from django.core.exceptions import SuspiciousOperation from django.core.urlresolvers import reverse from django.template import (TemplateDoesNotExist, TemplateSyntaxError, Context, Template, loader) import django.template.context from django.test import Client, TestCase from django.test.client import encode_file from django.test.utils import ContextList class AssertContainsTests(TestCase): def setUp(self): self.old_templates = settings.TEMPLATE_DIRS settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'),) def tearDown(self): settings.TEMPLATE_DIRS = self.old_templates def test_contains(self): "Responses can be inspected for content, including counting repeated substrings" response = self.client.get('/test_client_regress/no_template_view/') self.assertNotContains(response, 'never') self.assertContains(response, 'never', 0) self.assertContains(response, 'once') self.assertContains(response, 'once', 1) self.assertContains(response, 'twice') self.assertContains(response, 'twice', 2) try: self.assertContains(response, 'text', status_code=999) except AssertionError, e: self.assertIn("Couldn't retrieve content: Response code was 200 (expected 999)", str(e)) try: self.assertContains(response, 'text', status_code=999, msg_prefix='abc') except AssertionError, e: self.assertIn("abc: Couldn't retrieve content: Response code was 200 (expected 999)", str(e)) try: self.assertNotContains(response, 'text', status_code=999) except AssertionError, e: self.assertIn("Couldn't retrieve content: Response code was 200 (expected 999)", str(e)) try: self.assertNotContains(response, 'text', status_code=999, msg_prefix='abc') except AssertionError, e: self.assertIn("abc: Couldn't retrieve content: Response code was 200 (expected 999)", str(e)) try: self.assertNotContains(response, 'once') except AssertionError, e: self.assertIn("Response should not contain 'once'", str(e)) try: self.assertNotContains(response, 'once', msg_prefix='abc') except AssertionError, e: self.assertIn("abc: Response should not contain 'once'", str(e)) try: self.assertContains(response, 'never', 1) except AssertionError, e: self.assertIn("Found 0 instances of 'never' in response (expected 1)", str(e)) try: self.assertContains(response, 'never', 1, msg_prefix='abc') except AssertionError, e: self.assertIn("abc: Found 0 instances of 'never' in response (expected 1)", str(e)) try: self.assertContains(response, 'once', 0) except AssertionError, e: self.assertIn("Found 1 instances of 'once' in response (expected 0)", str(e)) try: self.assertContains(response, 'once', 0, msg_prefix='abc') except AssertionError, e: self.assertIn("abc: Found 1 instances of 'once' in response (expected 0)", str(e)) try: self.assertContains(response, 'once', 2) except AssertionError, e: self.assertIn("Found 1 instances of 'once' in response (expected 2)", str(e)) try: self.assertContains(response, 'once', 2, msg_prefix='abc') except AssertionError, e: self.assertIn("abc: Found 1 instances of 'once' in response (expected 2)", str(e)) try: self.assertContains(response, 'twice', 1) except AssertionError, e: self.assertIn("Found 2 instances of 'twice' in response (expected 1)", str(e)) try: self.assertContains(response, 'twice', 1, msg_prefix='abc') except AssertionError, e: self.assertIn("abc: Found 2 instances of 'twice' in response (expected 1)", str(e)) try: self.assertContains(response, 'thrice') except AssertionError, e: self.assertIn("Couldn't find 'thrice' in response", str(e)) try: self.assertContains(response, 'thrice', msg_prefix='abc') except AssertionError, e: self.assertIn("abc: Couldn't find 'thrice' in response", str(e)) try: self.assertContains(response, 'thrice', 3) except AssertionError, e: self.assertIn("Found 0 instances of 'thrice' in response (expected 3)", str(e)) try: self.assertContains(response, 'thrice', 3, msg_prefix='abc') except AssertionError, e: self.assertIn("abc: Found 0 instances of 'thrice' in response (expected 3)", str(e)) def test_unicode_contains(self): "Unicode characters can be found in template context" #Regression test for #10183 r = self.client.get('/test_client_regress/check_unicode/') self.assertContains(r, u'さかき') self.assertContains(r, '\xe5\xb3\xa0'.decode('utf-8')) def test_unicode_not_contains(self): "Unicode characters can be searched for, and not found in template context" #Regression test for #10183 r = self.client.get('/test_client_regress/check_unicode/') self.assertNotContains(r, u'はたけ') self.assertNotContains(r, '\xe3\x81\xaf\xe3\x81\x9f\xe3\x81\x91'.decode('utf-8')) class AssertTemplateUsedTests(TestCase): fixtures = ['testdata.json'] def test_no_context(self): "Template usage assertions work then templates aren't in use" response = self.client.get('/test_client_regress/no_template_view/') # Check that the no template case doesn't mess with the template assertions self.assertTemplateNotUsed(response, 'GET Template') try: self.assertTemplateUsed(response, 'GET Template') except AssertionError, e: self.assertIn("No templates used to render the response", str(e)) try: self.assertTemplateUsed(response, 'GET Template', msg_prefix='abc') except AssertionError, e: self.assertIn("abc: No templates used to render the response", str(e)) def test_single_context(self): "Template assertions work when there is a single context" response = self.client.get('/test_client/post_view/', {}) try: self.assertTemplateNotUsed(response, 'Empty GET Template') except AssertionError, e: self.assertIn("Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e)) try: self.assertTemplateNotUsed(response, 'Empty GET Template', msg_prefix='abc') except AssertionError, e: self.assertIn("abc: Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e)) try: self.assertTemplateUsed(response, 'Empty POST Template') except AssertionError, e: self.assertIn("Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template", str(e)) try: self.assertTemplateUsed(response, 'Empty POST Template', msg_prefix='abc') except AssertionError, e: self.assertIn("abc: Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template", str(e)) def test_multiple_context(self): "Template assertions work when there are multiple contexts" post_data = { 'text': 'Hello World', 'email': '[email protected]', 'value': 37, 'single': 'b', 'multi': ('b','c','e') } response = self.client.post('/test_client/form_view_with_template/', post_data) self.assertContains(response, 'POST data OK') try: self.assertTemplateNotUsed(response, "form_view.html") except AssertionError, e: self.assertIn("Template 'form_view.html' was used unexpectedly in rendering the response", str(e)) try: self.assertTemplateNotUsed(response, 'base.html') except AssertionError, e: self.assertIn("Template 'base.html' was used unexpectedly in rendering the response", str(e)) try: self.assertTemplateUsed(response, "Valid POST Template") except AssertionError, e: self.assertIn("Template 'Valid POST Template' was not a template used to render the response. Actual template(s) used: form_view.html, base.html", str(e)) class AssertRedirectsTests(TestCase): def test_redirect_page(self): "An assertion is raised if the original page couldn't be retrieved as expected" # This page will redirect with code 301, not 302 response = self.client.get('/test_client/permanent_redirect_view/') try: self.assertRedirects(response, '/test_client/get_view/') except AssertionError, e: self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e)) try: self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc') except AssertionError, e: self.assertIn("abc: Response didn't redirect as expected: Response code was 301 (expected 302)", str(e)) def test_lost_query(self): "An assertion is raised if the redirect location doesn't preserve GET parameters" response = self.client.get('/test_client/redirect_view/', {'var': 'value'}) try: self.assertRedirects(response, '/test_client/get_view/') except AssertionError, e: self.assertIn("Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'", str(e)) try: self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc') except AssertionError, e: self.assertIn("abc: Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'", str(e)) def test_incorrect_target(self): "An assertion is raised if the response redirects to another target" response = self.client.get('/test_client/permanent_redirect_view/') try: # Should redirect to get_view self.assertRedirects(response, '/test_client/some_view/') except AssertionError, e: self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e)) def test_target_page(self): "An assertion is raised if the response redirect target cannot be retrieved as expected" response = self.client.get('/test_client/double_redirect_view/') try: # The redirect target responds with a 301 code, not 200 self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/') except AssertionError, e: self.assertIn("Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)", str(e)) try: # The redirect target responds with a 301 code, not 200 self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/', msg_prefix='abc') except AssertionError, e: self.assertIn("abc: Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)", str(e)) def test_redirect_chain(self): "You can follow a redirect chain of multiple redirects" response = self.client.get('/test_client_regress/redirects/further/more/', {}, follow=True) self.assertRedirects(response, '/test_client_regress/no_template_view/', status_code=301, target_status_code=200) self.assertEqual(len(response.redirect_chain), 1) self.assertEqual(response.redirect_chain[0], ('http://testserver/test_client_regress/no_template_view/', 301)) def test_multiple_redirect_chain(self): "You can follow a redirect chain of multiple redirects" response = self.client.get('/test_client_regress/redirects/', {}, follow=True) self.assertRedirects(response, '/test_client_regress/no_template_view/', status_code=301, target_status_code=200) self.assertEqual(len(response.redirect_chain), 3) self.assertEqual(response.redirect_chain[0], ('http://testserver/test_client_regress/redirects/further/', 301)) self.assertEqual(response.redirect_chain[1], ('http://testserver/test_client_regress/redirects/further/more/', 301)) self.assertEqual(response.redirect_chain[2], ('http://testserver/test_client_regress/no_template_view/', 301)) def test_redirect_chain_to_non_existent(self): "You can follow a chain to a non-existent view" response = self.client.get('/test_client_regress/redirect_to_non_existent_view2/', {}, follow=True) self.assertRedirects(response, '/test_client_regress/non_existent_view/', status_code=301, target_status_code=404) def test_redirect_chain_to_self(self): "Redirections to self are caught and escaped" response = self.client.get('/test_client_regress/redirect_to_self/', {}, follow=True) # The chain of redirects stops once the cycle is detected. self.assertRedirects(response, '/test_client_regress/redirect_to_self/', status_code=301, target_status_code=301) self.assertEqual(len(response.redirect_chain), 2) def test_circular_redirect(self): "Circular redirect chains are caught and escaped" response = self.client.get('/test_client_regress/circular_redirect_1/', {}, follow=True) # The chain of redirects will get back to the starting point, but stop there. self.assertRedirects(response, '/test_client_regress/circular_redirect_2/', status_code=301, target_status_code=301) self.assertEqual(len(response.redirect_chain), 4) def test_redirect_chain_post(self): "A redirect chain will be followed from an initial POST post" response = self.client.post('/test_client_regress/redirects/', {'nothing': 'to_send'}, follow=True) self.assertRedirects(response, '/test_client_regress/no_template_view/', 301, 200) self.assertEqual(len(response.redirect_chain), 3) def test_redirect_chain_head(self): "A redirect chain will be followed from an initial HEAD request" response = self.client.head('/test_client_regress/redirects/', {'nothing': 'to_send'}, follow=True) self.assertRedirects(response, '/test_client_regress/no_template_view/', 301, 200) self.assertEqual(len(response.redirect_chain), 3) def test_redirect_chain_options(self): "A redirect chain will be followed from an initial OPTIONS request" response = self.client.options('/test_client_regress/redirects/', {'nothing': 'to_send'}, follow=True) self.assertRedirects(response, '/test_client_regress/no_template_view/', 301, 200) self.assertEqual(len(response.redirect_chain), 3) def test_redirect_chain_put(self): "A redirect chain will be followed from an initial PUT request" response = self.client.put('/test_client_regress/redirects/', {'nothing': 'to_send'}, follow=True) self.assertRedirects(response, '/test_client_regress/no_template_view/', 301, 200) self.assertEqual(len(response.redirect_chain), 3) def test_redirect_chain_delete(self): "A redirect chain will be followed from an initial DELETE request" response = self.client.delete('/test_client_regress/redirects/', {'nothing': 'to_send'}, follow=True) self.assertRedirects(response, '/test_client_regress/no_template_view/', 301, 200) self.assertEqual(len(response.redirect_chain), 3) def test_redirect_chain_on_non_redirect_page(self): "An assertion is raised if the original page couldn't be retrieved as expected" # This page will redirect with code 301, not 302 response = self.client.get('/test_client/get_view/', follow=True) try: self.assertRedirects(response, '/test_client/get_view/') except AssertionError, e: self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e)) try: self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc') except AssertionError, e: self.assertIn("abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e)) def test_redirect_on_non_redirect_page(self): "An assertion is raised if the original page couldn't be retrieved as expected" # This page will redirect with code 301, not 302 response = self.client.get('/test_client/get_view/') try: self.assertRedirects(response, '/test_client/get_view/') except AssertionError, e: self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e)) try: self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc') except AssertionError, e: self.assertIn("abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e)) class AssertFormErrorTests(TestCase): def test_unknown_form(self): "An assertion is raised if the form name is unknown" post_data = { 'text': 'Hello World', 'email': 'not an email address', 'value': 37, 'single': 'b', 'multi': ('b','c','e') } response = self.client.post('/test_client/form_view/', post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") try: self.assertFormError(response, 'wrong_form', 'some_field', 'Some error.') except AssertionError, e: self.assertIn("The form 'wrong_form' was not used to render the response", str(e)) try: self.assertFormError(response, 'wrong_form', 'some_field', 'Some error.', msg_prefix='abc') except AssertionError, e: self.assertIn("abc: The form 'wrong_form' was not used to render the response", str(e)) def test_unknown_field(self): "An assertion is raised if the field name is unknown" post_data = { 'text': 'Hello World', 'email': 'not an email address', 'value': 37, 'single': 'b', 'multi': ('b','c','e') } response = self.client.post('/test_client/form_view/', post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") try: self.assertFormError(response, 'form', 'some_field', 'Some error.') except AssertionError, e: self.assertIn("The form 'form' in context 0 does not contain the field 'some_field'", str(e)) try: self.assertFormError(response, 'form', 'some_field', 'Some error.', msg_prefix='abc') except AssertionError, e: self.assertIn("abc: The form 'form' in context 0 does not contain the field 'some_field'", str(e)) def test_noerror_field(self): "An assertion is raised if the field doesn't have any errors" post_data = { 'text': 'Hello World', 'email': 'not an email address', 'value': 37, 'single': 'b', 'multi': ('b','c','e') } response = self.client.post('/test_client/form_view/', post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") try: self.assertFormError(response, 'form', 'value', 'Some error.') except AssertionError, e: self.assertIn("The field 'value' on form 'form' in context 0 contains no errors", str(e)) try: self.assertFormError(response, 'form', 'value', 'Some error.', msg_prefix='abc') except AssertionError, e: self.assertIn("abc: The field 'value' on form 'form' in context 0 contains no errors", str(e)) def test_unknown_error(self): "An assertion is raised if the field doesn't contain the provided error" post_data = { 'text': 'Hello World', 'email': 'not an email address', 'value': 37, 'single': 'b', 'multi': ('b','c','e') } response = self.client.post('/test_client/form_view/', post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") try: self.assertFormError(response, 'form', 'email', 'Some error.') except AssertionError, e: self.assertIn("The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [u'Enter a valid e-mail address.'])", str(e)) try: self.assertFormError(response, 'form', 'email', 'Some error.', msg_prefix='abc') except AssertionError, e: self.assertIn("abc: The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [u'Enter a valid e-mail address.'])", str(e)) def test_unknown_nonfield_error(self): """ Checks that an assertion is raised if the form's non field errors doesn't contain the provided error. """ post_data = { 'text': 'Hello World', 'email': 'not an email address', 'value': 37, 'single': 'b', 'multi': ('b','c','e') } response = self.client.post('/test_client/form_view/', post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") try: self.assertFormError(response, 'form', None, 'Some error.') except AssertionError, e: self.assertIn("The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )", str(e)) try: self.assertFormError(response, 'form', None, 'Some error.', msg_prefix='abc') except AssertionError, e: self.assertIn("abc: The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )", str(e)) class LoginTests(TestCase): fixtures = ['testdata'] def test_login_different_client(self): "Check that using a different test client doesn't violate authentication" # Create a second client, and log in. c = Client() login = c.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Get a redirection page with the second client. response = c.get("/test_client_regress/login_protected_redirect_view/") # At this points, the self.client isn't logged in. # Check that assertRedirects uses the original client, not the # default client. self.assertRedirects(response, "http://testserver/test_client_regress/get_view/") class SessionEngineTests(TestCase): fixtures = ['testdata'] def setUp(self): self.old_SESSION_ENGINE = settings.SESSION_ENGINE settings.SESSION_ENGINE = 'regressiontests.test_client_regress.session' def tearDown(self): settings.SESSION_ENGINE = self.old_SESSION_ENGINE def test_login(self): "A session engine that modifies the session key can be used to log in" login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Try to access a login protected page. response = self.client.get("/test_client/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') class URLEscapingTests(TestCase): def test_simple_argument_get(self): "Get a view that has a simple string argument" response = self.client.get(reverse('arg_view', args=['Slartibartfast'])) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'Howdy, Slartibartfast') def test_argument_with_space_get(self): "Get a view that has a string argument that requires escaping" response = self.client.get(reverse('arg_view', args=['Arthur Dent'])) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'Hi, Arthur') def test_simple_argument_post(self): "Post for a view that has a simple string argument" response = self.client.post(reverse('arg_view', args=['Slartibartfast'])) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'Howdy, Slartibartfast') def test_argument_with_space_post(self): "Post for a view that has a string argument that requires escaping" response = self.client.post(reverse('arg_view', args=['Arthur Dent'])) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'Hi, Arthur') class ExceptionTests(TestCase): fixtures = ['testdata.json'] def test_exception_cleared(self): "#5836 - A stale user exception isn't re-raised by the test client." login = self.client.login(username='testclient',password='password') self.assertTrue(login, 'Could not log in') try: response = self.client.get("/test_client_regress/staff_only/") self.fail("General users should not be able to visit this page") except SuspiciousOperation: pass # At this point, an exception has been raised, and should be cleared. # This next operation should be successful; if it isn't we have a problem. login = self.client.login(username='staff', password='password') self.assertTrue(login, 'Could not log in') try: self.client.get("/test_client_regress/staff_only/") except SuspiciousOperation: self.fail("Staff should be able to visit this page") class TemplateExceptionTests(TestCase): def setUp(self): # Reset the loaders so they don't try to render cached templates. if loader.template_source_loaders is not None: for template_loader in loader.template_source_loaders: if hasattr(template_loader, 'reset'): template_loader.reset() self.old_templates = settings.TEMPLATE_DIRS settings.TEMPLATE_DIRS = () def tearDown(self): settings.TEMPLATE_DIRS = self.old_templates def test_no_404_template(self): "Missing templates are correctly reported by test client" try: response = self.client.get("/no_such_view/") self.fail("Should get error about missing template") except TemplateDoesNotExist: pass def test_bad_404_template(self): "Errors found when rendering 404 error templates are re-raised" settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'bad_templates'),) try: response = self.client.get("/no_such_view/") self.fail("Should get error about syntax error in template") except TemplateSyntaxError: pass # We need two different tests to check URLconf substitution - one to check # it was changed, and another one (without self.urls) to check it was reverted on # teardown. This pair of tests relies upon the alphabetical ordering of test execution. class UrlconfSubstitutionTests(TestCase): urls = 'regressiontests.test_client_regress.urls' def test_urlconf_was_changed(self): "TestCase can enforce a custom URLconf on a per-test basis" url = reverse('arg_view', args=['somename']) self.assertEqual(url, '/arg_view/somename/') # This test needs to run *after* UrlconfSubstitutionTests; the zz prefix in the # name is to ensure alphabetical ordering. class zzUrlconfSubstitutionTests(TestCase): def test_urlconf_was_reverted(self): "URLconf is reverted to original value after modification in a TestCase" url = reverse('arg_view', args=['somename']) self.assertEqual(url, '/test_client_regress/arg_view/somename/') class ContextTests(TestCase): fixtures = ['testdata'] def test_single_context(self): "Context variables can be retrieved from a single context" response = self.client.get("/test_client_regress/request_data/", data={'foo':'whiz'}) self.assertEqual(response.context.__class__, Context) self.assertTrue('get-foo' in response.context) self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['request-foo'], 'whiz') self.assertEqual(response.context['data'], 'sausage') try: response.context['does-not-exist'] self.fail('Should not be able to retrieve non-existent key') except KeyError, e: self.assertEqual(e.args[0], 'does-not-exist') def test_inherited_context(self): "Context variables can be retrieved from a list of contexts" response = self.client.get("/test_client_regress/request_data_extended/", data={'foo':'whiz'}) self.assertEqual(response.context.__class__, ContextList) self.assertEqual(len(response.context), 2) self.assertTrue('get-foo' in response.context) self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['request-foo'], 'whiz') self.assertEqual(response.context['data'], 'bacon') try: response.context['does-not-exist'] self.fail('Should not be able to retrieve non-existent key') except KeyError, e: self.assertEqual(e.args[0], 'does-not-exist') def test_15368(self): # Need to insert a context processor that assumes certain things about # the request instance. This triggers a bug caused by some ways of # copying RequestContext. try: django.template.context._standard_context_processors = (lambda request: {'path': request.special_path},) response = self.client.get("/test_client_regress/request_context_view/") self.assertContains(response, 'Path: /test_client_regress/request_context_view/') finally: django.template.context._standard_context_processors = None class SessionTests(TestCase): fixtures = ['testdata.json'] def test_session(self): "The session isn't lost if a user logs in" # The session doesn't exist to start. response = self.client.get('/test_client_regress/check_session/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'NO') # This request sets a session variable. response = self.client.get('/test_client_regress/set_session/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'set_session') # Check that the session has been modified response = self.client.get('/test_client_regress/check_session/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'YES') # Log in login = self.client.login(username='testclient',password='password') self.assertTrue(login, 'Could not log in') # Session should still contain the modified value response = self.client.get('/test_client_regress/check_session/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'YES') def test_logout(self): """Logout should work whether the user is logged in or not (#9978).""" self.client.logout() login = self.client.login(username='testclient',password='password') self.assertTrue(login, 'Could not log in') self.client.logout() self.client.logout() class RequestMethodTests(TestCase): def test_get(self): "Request a view via request method GET" response = self.client.get('/test_client_regress/request_methods/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'request method: GET') def test_post(self): "Request a view via request method POST" response = self.client.post('/test_client_regress/request_methods/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'request method: POST') def test_head(self): "Request a view via request method HEAD" response = self.client.head('/test_client_regress/request_methods/') self.assertEqual(response.status_code, 200) # A HEAD request doesn't return any content. self.assertNotEqual(response.content, 'request method: HEAD') self.assertEqual(response.content, '') def test_options(self): "Request a view via request method OPTIONS" response = self.client.options('/test_client_regress/request_methods/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'request method: OPTIONS') def test_put(self): "Request a view via request method PUT" response = self.client.put('/test_client_regress/request_methods/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'request method: PUT') def test_delete(self): "Request a view via request method DELETE" response = self.client.delete('/test_client_regress/request_methods/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'request method: DELETE') class RequestMethodStringDataTests(TestCase): def test_post(self): "Request a view with string data via request method POST" # Regression test for #11371 data = u'{"test": "json"}' response = self.client.post('/test_client_regress/request_methods/', data=data, content_type='application/json') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'request method: POST') def test_put(self): "Request a view with string data via request method PUT" # Regression test for #11371 data = u'{"test": "json"}' response = self.client.put('/test_client_regress/request_methods/', data=data, content_type='application/json') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'request method: PUT') class QueryStringTests(TestCase): def test_get_like_requests(self): for method_name in ('get','head','options','put','delete'): # A GET-like request can pass a query string as data method = getattr(self.client, method_name) response = method("/test_client_regress/request_data/", data={'foo':'whiz'}) self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['request-foo'], 'whiz') # A GET-like request can pass a query string as part of the URL response = method("/test_client_regress/request_data/?foo=whiz") self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['request-foo'], 'whiz') # Data provided in the URL to a GET-like request is overridden by actual form data response = method("/test_client_regress/request_data/?foo=whiz", data={'foo':'bang'}) self.assertEqual(response.context['get-foo'], 'bang') self.assertEqual(response.context['request-foo'], 'bang') response = method("/test_client_regress/request_data/?foo=whiz", data={'bar':'bang'}) self.assertEqual(response.context['get-foo'], None) self.assertEqual(response.context['get-bar'], 'bang') self.assertEqual(response.context['request-foo'], None) self.assertEqual(response.context['request-bar'], 'bang') def test_post_like_requests(self): # A POST-like request can pass a query string as data response = self.client.post("/test_client_regress/request_data/", data={'foo':'whiz'}) self.assertEqual(response.context['get-foo'], None) self.assertEqual(response.context['post-foo'], 'whiz') # A POST-like request can pass a query string as part of the URL response = self.client.post("/test_client_regress/request_data/?foo=whiz") self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['post-foo'], None) self.assertEqual(response.context['request-foo'], 'whiz') # POST data provided in the URL augments actual form data response = self.client.post("/test_client_regress/request_data/?foo=whiz", data={'foo':'bang'}) self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['post-foo'], 'bang') self.assertEqual(response.context['request-foo'], 'bang') response = self.client.post("/test_client_regress/request_data/?foo=whiz", data={'bar':'bang'}) self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['get-bar'], None) self.assertEqual(response.context['post-foo'], None) self.assertEqual(response.context['post-bar'], 'bang') self.assertEqual(response.context['request-foo'], 'whiz') self.assertEqual(response.context['request-bar'], 'bang') class UnicodePayloadTests(TestCase): def test_simple_unicode_payload(self): "A simple ASCII-only unicode JSON document can be POSTed" # Regression test for #10571 json = u'{"english": "mountain pass"}' response = self.client.post("/test_client_regress/parse_unicode_json/", json, content_type="application/json") self.assertEqual(response.content, json) def test_unicode_payload_utf8(self): "A non-ASCII unicode data encoded as UTF-8 can be POSTed" # Regression test for #10571 json = u'{"dog": "собака"}' response = self.client.post("/test_client_regress/parse_unicode_json/", json, content_type="application/json; charset=utf-8") self.assertEqual(response.content, json.encode('utf-8')) def test_unicode_payload_utf16(self): "A non-ASCII unicode data encoded as UTF-16 can be POSTed" # Regression test for #10571 json = u'{"dog": "собака"}' response = self.client.post("/test_client_regress/parse_unicode_json/", json, content_type="application/json; charset=utf-16") self.assertEqual(response.content, json.encode('utf-16')) def test_unicode_payload_non_utf(self): "A non-ASCII unicode data as a non-UTF based encoding can be POSTed" #Regression test for #10571 json = u'{"dog": "собака"}' response = self.client.post("/test_client_regress/parse_unicode_json/", json, content_type="application/json; charset=koi8-r") self.assertEqual(response.content, json.encode('koi8-r')) class DummyFile(object): def __init__(self, filename): self.name = filename def read(self): return 'TEST_FILE_CONTENT' class UploadedFileEncodingTest(TestCase): def test_file_encoding(self): encoded_file = encode_file('TEST_BOUNDARY', 'TEST_KEY', DummyFile('test_name.bin')) self.assertEqual('--TEST_BOUNDARY', encoded_file[0]) self.assertEqual('Content-Disposition: form-data; name="TEST_KEY"; filename="test_name.bin"', encoded_file[1]) self.assertEqual('TEST_FILE_CONTENT', encoded_file[-1]) def test_guesses_content_type_on_file_encoding(self): self.assertEqual('Content-Type: application/octet-stream', encode_file('IGNORE', 'IGNORE', DummyFile("file.bin"))[2]) self.assertEqual('Content-Type: text/plain', encode_file('IGNORE', 'IGNORE', DummyFile("file.txt"))[2]) self.assertIn(encode_file('IGNORE', 'IGNORE', DummyFile("file.zip"))[2], ( 'Content-Type: application/x-compress', 'Content-Type: application/x-zip', 'Content-Type: application/x-zip-compressed', 'Content-Type: application/zip',)) self.assertEqual('Content-Type: application/octet-stream', encode_file('IGNORE', 'IGNORE', DummyFile("file.unknown"))[2]) class RequestHeadersTest(TestCase): def test_client_headers(self): "A test client can receive custom headers" response = self.client.get("/test_client_regress/check_headers/", HTTP_X_ARG_CHECK='Testing 123') self.assertEqual(response.content, "HTTP_X_ARG_CHECK: Testing 123") self.assertEqual(response.status_code, 200) def test_client_headers_redirect(self): "Test client headers are preserved through redirects" response = self.client.get("/test_client_regress/check_headers_redirect/", follow=True, HTTP_X_ARG_CHECK='Testing 123') self.assertEqual(response.content, "HTTP_X_ARG_CHECK: Testing 123") self.assertRedirects(response, '/test_client_regress/check_headers/', status_code=301, target_status_code=200) class ResponseTemplateDeprecationTests(TestCase): """ Response.template still works backwards-compatibly, but with pending deprecation warning. Refs #12226. """ def test_response_template_data(self): response = self.client.get("/test_client_regress/request_data/", data={'foo':'whiz'}) self.assertEqual(response.template.__class__, Template) self.assertEqual(response.template.name, 'base.html') def test_response_no_template(self): response = self.client.get("/test_client_regress/request_methods/") self.assertEqual(response.template, None) class RawPostDataTest(TestCase): "Access to request.raw_post_data from the test client." def test_raw_post_data(self): # Refs #14753 try: response = self.client.get("/test_client_regress/raw_post_data/") except AssertionError: self.fail("Accessing request.raw_post_data from a view fetched with GET by the test client shouldn't fail.")
43,253
Python
.py
767
46.735332
180
0.657948
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,009
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/test_client_regress/urls.py
from django.conf.urls.defaults import * from django.views.generic.simple import redirect_to import views urlpatterns = patterns('', (r'^no_template_view/$', views.no_template_view), (r'^staff_only/$', views.staff_only_view), (r'^get_view/$', views.get_view), (r'^request_data/$', views.request_data), (r'^request_data_extended/$', views.request_data, {'template':'extended.html', 'data':'bacon'}), url(r'^arg_view/(?P<name>.+)/$', views.view_with_argument, name='arg_view'), (r'^login_protected_redirect_view/$', views.login_protected_redirect_view), (r'^redirects/$', redirect_to, {'url': '/test_client_regress/redirects/further/'}), (r'^redirects/further/$', redirect_to, {'url': '/test_client_regress/redirects/further/more/'}), (r'^redirects/further/more/$', redirect_to, {'url': '/test_client_regress/no_template_view/'}), (r'^redirect_to_non_existent_view/$', redirect_to, {'url': '/test_client_regress/non_existent_view/'}), (r'^redirect_to_non_existent_view2/$', redirect_to, {'url': '/test_client_regress/redirect_to_non_existent_view/'}), (r'^redirect_to_self/$', redirect_to, {'url': '/test_client_regress/redirect_to_self/'}), (r'^circular_redirect_1/$', redirect_to, {'url': '/test_client_regress/circular_redirect_2/'}), (r'^circular_redirect_2/$', redirect_to, {'url': '/test_client_regress/circular_redirect_3/'}), (r'^circular_redirect_3/$', redirect_to, {'url': '/test_client_regress/circular_redirect_1/'}), (r'^set_session/$', views.set_session_view), (r'^check_session/$', views.check_session_view), (r'^request_methods/$', views.request_methods_view), (r'^check_unicode/$', views.return_unicode), (r'^parse_unicode_json/$', views.return_json_file), (r'^check_headers/$', views.check_headers), (r'^check_headers_redirect/$', redirect_to, {'url': '/test_client_regress/check_headers/'}), (r'^raw_post_data/$', views.raw_post_data), (r'^request_context_view/$', views.request_context_view), )
2,013
Python
.py
30
62.733333
120
0.662967
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,010
views.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/test_client_regress/views.py
from django.conf import settings from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect from django.core.exceptions import SuspiciousOperation from django.shortcuts import render_to_response from django.utils import simplejson from django.utils.encoding import smart_str from django.core.serializers.json import DjangoJSONEncoder from django.test.client import CONTENT_TYPE_RE from django.template import RequestContext def no_template_view(request): "A simple view that expects a GET request, and returns a rendered template" return HttpResponse("No template used. Sample content: twice once twice. Content ends.") def staff_only_view(request): "A view that can only be visited by staff. Non staff members get an exception" if request.user.is_staff: return HttpResponse('') else: raise SuspiciousOperation() def get_view(request): "A simple login protected view" return HttpResponse("Hello world") get_view = login_required(get_view) def request_data(request, template='base.html', data='sausage'): "A simple view that returns the request data in the context" return render_to_response(template, { 'get-foo':request.GET.get('foo',None), 'get-bar':request.GET.get('bar',None), 'post-foo':request.POST.get('foo',None), 'post-bar':request.POST.get('bar',None), 'request-foo':request.REQUEST.get('foo',None), 'request-bar':request.REQUEST.get('bar',None), 'data': data, }) def view_with_argument(request, name): """A view that takes a string argument The purpose of this view is to check that if a space is provided in the argument, the test framework unescapes the %20 before passing the value to the view. """ if name == 'Arthur Dent': return HttpResponse('Hi, Arthur') else: return HttpResponse('Howdy, %s' % name) def login_protected_redirect_view(request): "A view that redirects all requests to the GET view" return HttpResponseRedirect('/test_client_regress/get_view/') login_protected_redirect_view = login_required(login_protected_redirect_view) def set_session_view(request): "A view that sets a session variable" request.session['session_var'] = 'YES' return HttpResponse('set_session') def check_session_view(request): "A view that reads a session variable" return HttpResponse(request.session.get('session_var', 'NO')) def request_methods_view(request): "A view that responds with the request method" return HttpResponse('request method: %s' % request.method) def return_unicode(request): return render_to_response('unicode.html') def return_json_file(request): "A view that parses and returns a JSON string as a file." match = CONTENT_TYPE_RE.match(request.META['CONTENT_TYPE']) if match: charset = match.group(1) else: charset = settings.DEFAULT_CHARSET # This just checks that the uploaded data is JSON obj_dict = simplejson.loads(request.raw_post_data.decode(charset)) obj_json = simplejson.dumps(obj_dict, encoding=charset, cls=DjangoJSONEncoder, ensure_ascii=False) response = HttpResponse(smart_str(obj_json, encoding=charset), status=200, mimetype='application/json; charset=' + charset) response['Content-Disposition'] = 'attachment; filename=testfile.json' return response def check_headers(request): "A view that responds with value of the X-ARG-CHECK header" return HttpResponse('HTTP_X_ARG_CHECK: %s' % request.META.get('HTTP_X_ARG_CHECK', 'Undefined')) def raw_post_data(request): "A view that is requested with GET and accesses request.raw_post_data. Refs #14753." return HttpResponse(request.raw_post_data) def request_context_view(request): # Special attribute that won't be present on a plain HttpRequest request.special_path = request.path return render_to_response('request_context.html', context_instance=RequestContext(request, {}))
4,115
Python
.py
86
42.337209
99
0.723897
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,011
session.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/test_client_regress/session.py
from django.contrib.sessions.backends.base import SessionBase class SessionStore(SessionBase): """ A simple cookie-based session storage implemenation. The session key is actually the session data, pickled and encoded. This means that saving the session will change the session key. """ def __init__(self, session_key=None): super(SessionStore, self).__init__(session_key) def exists(self, session_key): return False def create(self): self.session_key = self.encode({}) def save(self, must_create=False): self.session_key = self.encode(self._session) def delete(self, session_key=None): self.session_key = self.encode({}) def load(self): try: return self.decode(self.session_key) except: self.modified = True return {}
861
Python
.py
23
30.26087
70
0.658654
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,012
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/custom_managers_regress/models.py
""" Regression tests for custom manager classes. """ from django.db import models class RestrictedManager(models.Manager): """ A manager that filters out non-public instances. """ def get_query_set(self): return super(RestrictedManager, self).get_query_set().filter(is_public=True) class RelatedModel(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class RestrictedModel(models.Model): name = models.CharField(max_length=50) is_public = models.BooleanField(default=False) related = models.ForeignKey(RelatedModel) objects = RestrictedManager() plain_manager = models.Manager() def __unicode__(self): return self.name class OneToOneRestrictedModel(models.Model): name = models.CharField(max_length=50) is_public = models.BooleanField(default=False) related = models.OneToOneField(RelatedModel) objects = RestrictedManager() plain_manager = models.Manager() def __unicode__(self): return self.name
1,056
Python
.py
30
30.4
84
0.723425
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,013
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/custom_managers_regress/tests.py
from django.test import TestCase from models import RelatedModel, RestrictedModel, OneToOneRestrictedModel class CustomManagersRegressTestCase(TestCase): def test_filtered_default_manager(self): """Even though the default manager filters out some records, we must still be able to save (particularly, save by updating existing records) those filtered instances. This is a regression test for #8990, #9527""" related = RelatedModel.objects.create(name="xyzzy") obj = RestrictedModel.objects.create(name="hidden", related=related) obj.name = "still hidden" obj.save() # If the hidden object wasn't seen during the save process, # there would now be two objects in the database. self.assertEqual(RestrictedModel.plain_manager.count(), 1) def test_delete_related_on_filtered_manager(self): """Deleting related objects should also not be distracted by a restricted manager on the related object. This is a regression test for #2698.""" related = RelatedModel.objects.create(name="xyzzy") for name, public in (('one', True), ('two', False), ('three', False)): RestrictedModel.objects.create(name=name, is_public=public, related=related) obj = RelatedModel.objects.get(name="xyzzy") obj.delete() # All of the RestrictedModel instances should have been # deleted, since they *all* pointed to the RelatedModel. If # the default manager is used, only the public one will be # deleted. self.assertEqual(len(RestrictedModel.plain_manager.all()), 0) def test_delete_one_to_one_manager(self): # The same test case as the last one, but for one-to-one # models, which are implemented slightly different internally, # so it's a different code path. obj = RelatedModel.objects.create(name="xyzzy") OneToOneRestrictedModel.objects.create(name="foo", is_public=False, related=obj) obj = RelatedModel.objects.get(name="xyzzy") obj.delete() self.assertEqual(len(OneToOneRestrictedModel.plain_manager.all()), 0)
2,170
Python
.py
38
48.710526
88
0.693829
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,014
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/get_or_create_regress/models.py
from django.db import models class Publisher(models.Model): name = models.CharField(max_length=100) class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): name = models.CharField(max_length=100) authors = models.ManyToManyField(Author, related_name='books') publisher = models.ForeignKey(Publisher, related_name='books', db_column="publisher_id_column")
417
Python
.py
9
42.666667
99
0.764851
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,015
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/get_or_create_regress/tests.py
from django.test import TestCase from models import Author, Publisher class GetOrCreateTests(TestCase): def test_related(self): p = Publisher.objects.create(name="Acme Publishing") # Create a book through the publisher. book, created = p.books.get_or_create(name="The Book of Ed & Fred") self.assertTrue(created) # The publisher should have one book. self.assertEqual(p.books.count(), 1) # Try get_or_create again, this time nothing should be created. book, created = p.books.get_or_create(name="The Book of Ed & Fred") self.assertFalse(created) # And the publisher should still have one book. self.assertEqual(p.books.count(), 1) # Add an author to the book. ed, created = book.authors.get_or_create(name="Ed") self.assertTrue(created) # The book should have one author. self.assertEqual(book.authors.count(), 1) # Try get_or_create again, this time nothing should be created. ed, created = book.authors.get_or_create(name="Ed") self.assertFalse(created) # And the book should still have one author. self.assertEqual(book.authors.count(), 1) # Add a second author to the book. fred, created = book.authors.get_or_create(name="Fred") self.assertTrue(created) # The book should have two authors now. self.assertEqual(book.authors.count(), 2) # Create an Author not tied to any books. Author.objects.create(name="Ted") # There should be three Authors in total. The book object should have two. self.assertEqual(Author.objects.count(), 3) self.assertEqual(book.authors.count(), 2) # Try creating a book through an author. _, created = ed.books.get_or_create(name="Ed's Recipes", publisher=p) self.assertTrue(created) # Now Ed has two Books, Fred just one. self.assertEqual(ed.books.count(), 2) self.assertEqual(fred.books.count(), 1) # Use the publisher's primary key value instead of a model instance. _, created = ed.books.get_or_create(name='The Great Book of Ed', publisher_id=p.id) self.assertTrue(created) # Try get_or_create again, this time nothing should be created. _, created = ed.books.get_or_create(name='The Great Book of Ed', publisher_id=p.id) self.assertFalse(created) # The publisher should have three books. self.assertEqual(p.books.count(), 3)
2,540
Python
.py
49
43.102041
91
0.659128
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,016
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/datatypes/models.py
""" This is a basic model to test saving and loading boolean and date-related types, which in the past were problematic for some database backends. """ from django.db import models class Donut(models.Model): name = models.CharField(max_length=100) is_frosted = models.BooleanField(default=False) has_sprinkles = models.NullBooleanField() baked_date = models.DateField(null=True) baked_time = models.TimeField(null=True) consumed_at = models.DateTimeField(null=True) review = models.TextField() class Meta: ordering = ('consumed_at',) def __str__(self): return self.name class RumBaba(models.Model): baked_date = models.DateField(auto_now_add=True) baked_timestamp = models.DateTimeField(auto_now_add=True)
771
Python
.py
20
34.3
73
0.733244
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,017
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/datatypes/tests.py
import datetime from django.conf import settings from django.db import DEFAULT_DB_ALIAS from django.test import TestCase, skipIfDBFeature from django.utils import tzinfo from models import Donut, RumBaba class DataTypesTestCase(TestCase): def test_boolean_type(self): d = Donut(name='Apple Fritter') self.assertFalse(d.is_frosted) self.assertTrue(d.has_sprinkles is None) d.has_sprinkles = True self.assertTrue(d.has_sprinkles) d.save() d2 = Donut.objects.get(name='Apple Fritter') self.assertFalse(d2.is_frosted) self.assertTrue(d2.has_sprinkles) def test_date_type(self): d = Donut(name='Apple Fritter') d.baked_date = datetime.date(year=1938, month=6, day=4) d.baked_time = datetime.time(hour=5, minute=30) d.consumed_at = datetime.datetime(year=2007, month=4, day=20, hour=16, minute=19, second=59) d.save() d2 = Donut.objects.get(name='Apple Fritter') self.assertEqual(d2.baked_date, datetime.date(1938, 6, 4)) self.assertEqual(d2.baked_time, datetime.time(5, 30)) self.assertEqual(d2.consumed_at, datetime.datetime(2007, 4, 20, 16, 19, 59)) def test_time_field(self): #Test for ticket #12059: TimeField wrongly handling datetime.datetime object. d = Donut(name='Apple Fritter') d.baked_time = datetime.datetime(year=2007, month=4, day=20, hour=16, minute=19, second=59) d.save() d2 = Donut.objects.get(name='Apple Fritter') self.assertEqual(d2.baked_time, datetime.time(16, 19, 59)) def test_year_boundaries(self): """Year boundary tests (ticket #3689)""" d = Donut.objects.create(name='Date Test 2007', baked_date=datetime.datetime(year=2007, month=12, day=31), consumed_at=datetime.datetime(year=2007, month=12, day=31, hour=23, minute=59, second=59)) d1 = Donut.objects.create(name='Date Test 2006', baked_date=datetime.datetime(year=2006, month=1, day=1), consumed_at=datetime.datetime(year=2006, month=1, day=1)) self.assertEqual("Date Test 2007", Donut.objects.filter(baked_date__year=2007)[0].name) self.assertEqual("Date Test 2006", Donut.objects.filter(baked_date__year=2006)[0].name) d2 = Donut.objects.create(name='Apple Fritter', consumed_at = datetime.datetime(year=2007, month=4, day=20, hour=16, minute=19, second=59)) self.assertEqual([u'Apple Fritter', u'Date Test 2007'], list(Donut.objects.filter(consumed_at__year=2007).order_by('name').values_list('name', flat=True))) self.assertEqual(0, Donut.objects.filter(consumed_at__year=2005).count()) self.assertEqual(0, Donut.objects.filter(consumed_at__year=2008).count()) def test_textfields_unicode(self): """Regression test for #10238: TextField values returned from the database should be unicode.""" d = Donut.objects.create(name=u'Jelly Donut', review=u'Outstanding') newd = Donut.objects.get(id=d.id) self.assertTrue(isinstance(newd.review, unicode)) @skipIfDBFeature('supports_timezones') def test_error_on_timezone(self): """Regression test for #8354: the MySQL and Oracle backends should raise an error if given a timezone-aware datetime object.""" dt = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=tzinfo.FixedOffset(0)) d = Donut(name='Bear claw', consumed_at=dt) self.assertRaises(ValueError, d.save) # ValueError: MySQL backend does not support timezone-aware datetimes. def test_datefield_auto_now_add(self): """Regression test for #10970, auto_now_add for DateField should store a Python datetime.date, not a datetime.datetime""" b = RumBaba.objects.create() # Verify we didn't break DateTimeField behavior self.assertTrue(isinstance(b.baked_timestamp, datetime.datetime)) # We need to test this this way because datetime.datetime inherits # from datetime.date: self.assertTrue(isinstance(b.baked_date, datetime.date) and not isinstance(b.baked_date, datetime.datetime))
4,250
Python
.py
75
47.786667
116
0.6718
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,018
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/defaultfilters/tests.py
# -*- coding: utf-8 -*- import datetime from django.utils import unittest from django.template.defaultfilters import * class DefaultFiltersTests(unittest.TestCase): def test_floatformat(self): self.assertEqual(floatformat(7.7), u'7.7') self.assertEqual(floatformat(7.0), u'7') self.assertEqual(floatformat(0.7), u'0.7') self.assertEqual(floatformat(0.07), u'0.1') self.assertEqual(floatformat(0.007), u'0.0') self.assertEqual(floatformat(0.0), u'0') self.assertEqual(floatformat(7.7, 3), u'7.700') self.assertEqual(floatformat(6.000000, 3), u'6.000') self.assertEqual(floatformat(6.200000, 3), u'6.200') self.assertEqual(floatformat(6.200000, -3), u'6.200') self.assertEqual(floatformat(13.1031, -3), u'13.103') self.assertEqual(floatformat(11.1197, -2), u'11.12') self.assertEqual(floatformat(11.0000, -2), u'11') self.assertEqual(floatformat(11.000001, -2), u'11.00') self.assertEqual(floatformat(8.2798, 3), u'8.280') self.assertEqual(floatformat(u'foo'), u'') self.assertEqual(floatformat(13.1031, u'bar'), u'13.1031') self.assertEqual(floatformat(18.125, 2), u'18.13') self.assertEqual(floatformat(u'foo', u'bar'), u'') self.assertEqual(floatformat(u'¿Cómo esta usted?'), u'') self.assertEqual(floatformat(None), u'') # Check that we're not converting to scientific notation. self.assertEqual(floatformat(0, 6), u'0.000000') self.assertEqual(floatformat(0, 7), u'0.0000000') self.assertEqual(floatformat(0, 10), u'0.0000000000') self.assertEqual(floatformat(0.000000000000000000015, 20), u'0.00000000000000000002') pos_inf = float(1e30000) self.assertEqual(floatformat(pos_inf), unicode(pos_inf)) neg_inf = float(-1e30000) self.assertEqual(floatformat(neg_inf), unicode(neg_inf)) nan = pos_inf / pos_inf self.assertEqual(floatformat(nan), unicode(nan)) class FloatWrapper(object): def __init__(self, value): self.value = value def __float__(self): return self.value self.assertEqual(floatformat(FloatWrapper(11.000001), -2), u'11.00') # This fails because of Python's float handling. Floats with many zeroes # after the decimal point should be passed in as another type such as # unicode or Decimal. @unittest.expectedFailure def test_floatformat_fail(self): self.assertEqual(floatformat(1.00000000000000015, 16), u'1.0000000000000002') def test_addslashes(self): self.assertEqual(addslashes(u'"double quotes" and \'single quotes\''), u'\\"double quotes\\" and \\\'single quotes\\\'') self.assertEqual(addslashes(ur'\ : backslashes, too'), u'\\\\ : backslashes, too') def test_capfirst(self): self.assertEqual(capfirst(u'hello world'), u'Hello world') def test_escapejs(self): self.assertEqual(escapejs(u'"double quotes" and \'single quotes\''), u'\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027') self.assertEqual(escapejs(ur'\ : backslashes, too'), u'\\u005C : backslashes, too') self.assertEqual(escapejs(u'and lots of whitespace: \r\n\t\v\f\b'), u'and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008') self.assertEqual(escapejs(ur'<script>and this</script>'), u'\\u003Cscript\\u003Eand this\\u003C/script\\u003E') self.assertEqual( escapejs(u'paragraph separator:\u2029and line separator:\u2028'), u'paragraph separator:\\u2029and line separator:\\u2028') def test_fix_ampersands(self): self.assertEqual(fix_ampersands(u'Jack & Jill & Jeroboam'), u'Jack &amp; Jill &amp; Jeroboam') def test_linenumbers(self): self.assertEqual(linenumbers(u'line 1\nline 2'), u'1. line 1\n2. line 2') self.assertEqual(linenumbers(u'\n'.join([u'x'] * 10)), u'01. x\n02. x\n03. x\n04. x\n05. x\n06. x\n07. '\ u'x\n08. x\n09. x\n10. x') def test_lower(self): self.assertEqual(lower('TEST'), u'test') # uppercase E umlaut self.assertEqual(lower(u'\xcb'), u'\xeb') def test_make_list(self): self.assertEqual(make_list('abc'), [u'a', u'b', u'c']) self.assertEqual(make_list(1234), [u'1', u'2', u'3', u'4']) def test_slugify(self): self.assertEqual(slugify(' Jack & Jill like numbers 1,2,3 and 4 and'\ ' silly characters ?%.$!/'), u'jack-jill-like-numbers-123-and-4-and-silly-characters') self.assertEqual(slugify(u"Un \xe9l\xe9phant \xe0 l'or\xe9e du bois"), u'un-elephant-a-loree-du-bois') def test_stringformat(self): self.assertEqual(stringformat(1, u'03d'), u'001') self.assertEqual(stringformat(1, u'z'), u'') def test_title(self): self.assertEqual(title('a nice title, isn\'t it?'), u"A Nice Title, Isn't It?") self.assertEqual(title(u'discoth\xe8que'), u'Discoth\xe8que') def test_truncatewords(self): self.assertEqual( truncatewords(u'A sentence with a few words in it', 1), u'A ...') self.assertEqual( truncatewords(u'A sentence with a few words in it', 5), u'A sentence with a few ...') self.assertEqual( truncatewords(u'A sentence with a few words in it', 100), u'A sentence with a few words in it') self.assertEqual( truncatewords(u'A sentence with a few words in it', 'not a number'), u'A sentence with a few words in it') def test_truncatewords_html(self): self.assertEqual(truncatewords_html( u'<p>one <a href="#">two - three <br>four</a> five</p>', 0), u'') self.assertEqual(truncatewords_html(u'<p>one <a href="#">two - '\ u'three <br>four</a> five</p>', 2), u'<p>one <a href="#">two ...</a></p>') self.assertEqual(truncatewords_html( u'<p>one <a href="#">two - three <br>four</a> five</p>', 4), u'<p>one <a href="#">two - three <br>four ...</a></p>') self.assertEqual(truncatewords_html( u'<p>one <a href="#">two - three <br>four</a> five</p>', 5), u'<p>one <a href="#">two - three <br>four</a> five</p>') self.assertEqual(truncatewords_html( u'<p>one <a href="#">two - three <br>four</a> five</p>', 100), u'<p>one <a href="#">two - three <br>four</a> five</p>') self.assertEqual(truncatewords_html( u'\xc5ngstr\xf6m was here', 1), u'\xc5ngstr\xf6m ...') def test_upper(self): self.assertEqual(upper(u'Mixed case input'), u'MIXED CASE INPUT') # lowercase e umlaut self.assertEqual(upper(u'\xeb'), u'\xcb') def test_urlencode(self): self.assertEqual(urlencode(u'fran\xe7ois & jill'), u'fran%C3%A7ois%20%26%20jill') self.assertEqual(urlencode(1), u'1') def test_iriencode(self): self.assertEqual(iriencode(u'S\xf8r-Tr\xf8ndelag'), u'S%C3%B8r-Tr%C3%B8ndelag') self.assertEqual(iriencode(urlencode(u'fran\xe7ois & jill')), u'fran%C3%A7ois%20%26%20jill') def test_urlizetrunc(self): self.assertEqual(urlizetrunc(u'http://short.com/', 20), u'<a href='\ u'"http://short.com/" rel="nofollow">http://short.com/</a>') self.assertEqual(urlizetrunc(u'http://www.google.co.uk/search?hl=en'\ u'&q=some+long+url&btnG=Search&meta=', 20), u'<a href="http://'\ u'www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search&'\ u'meta=" rel="nofollow">http://www.google...</a>') self.assertEqual(urlizetrunc('http://www.google.co.uk/search?hl=en'\ u'&q=some+long+url&btnG=Search&meta=', 20), u'<a href="http://'\ u'www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search'\ u'&meta=" rel="nofollow">http://www.google...</a>') # Check truncating of URIs which are the exact length uri = 'http://31characteruri.com/test/' self.assertEqual(len(uri), 31) self.assertEqual(urlizetrunc(uri, 31), u'<a href="http://31characteruri.com/test/" rel="nofollow">'\ u'http://31characteruri.com/test/</a>') self.assertEqual(urlizetrunc(uri, 30), u'<a href="http://31characteruri.com/test/" rel="nofollow">'\ u'http://31characteruri.com/t...</a>') self.assertEqual(urlizetrunc(uri, 2), u'<a href="http://31characteruri.com/test/"'\ u' rel="nofollow">...</a>') def test_urlize(self): # Check normal urlize self.assertEqual(urlize('http://google.com'), u'<a href="http://google.com" rel="nofollow">http://google.com</a>') self.assertEqual(urlize('http://google.com/'), u'<a href="http://google.com/" rel="nofollow">http://google.com/</a>') self.assertEqual(urlize('www.google.com'), u'<a href="http://www.google.com" rel="nofollow">www.google.com</a>') self.assertEqual(urlize('djangoproject.org'), u'<a href="http://djangoproject.org" rel="nofollow">djangoproject.org</a>') self.assertEqual(urlize('[email protected]'), u'<a href="mailto:[email protected]">[email protected]</a>') # Check urlize with https addresses self.assertEqual(urlize('https://google.com'), u'<a href="https://google.com" rel="nofollow">https://google.com</a>') def test_wordcount(self): self.assertEqual(wordcount(''), 0) self.assertEqual(wordcount(u'oneword'), 1) self.assertEqual(wordcount(u'lots of words'), 3) self.assertEqual(wordwrap(u'this is a long paragraph of text that '\ u'really needs to be wrapped I\'m afraid', 14), u"this is a long\nparagraph of\ntext that\nreally needs\nto be "\ u"wrapped\nI'm afraid") self.assertEqual(wordwrap(u'this is a short paragraph of text.\n '\ u'But this line should be indented', 14), u'this is a\nshort\nparagraph of\ntext.\n But this\nline '\ u'should be\nindented') self.assertEqual(wordwrap(u'this is a short paragraph of text.\n '\ u'But this line should be indented',15), u'this is a short\n'\ u'paragraph of\ntext.\n But this line\nshould be\nindented') def test_rjust(self): self.assertEqual(ljust(u'test', 10), u'test ') self.assertEqual(ljust(u'test', 3), u'test') self.assertEqual(rjust(u'test', 10), u' test') self.assertEqual(rjust(u'test', 3), u'test') def test_center(self): self.assertEqual(center(u'test', 6), u' test ') def test_cut(self): self.assertEqual(cut(u'a string to be mangled', 'a'), u' string to be mngled') self.assertEqual(cut(u'a string to be mangled', 'ng'), u'a stri to be maled') self.assertEqual(cut(u'a string to be mangled', 'strings'), u'a string to be mangled') def test_force_escape(self): self.assertEqual( force_escape(u'<some html & special characters > here'), u'&lt;some html &amp; special characters &gt; here') self.assertEqual( force_escape(u'<some html & special characters > here ĐÅ€£'), u'&lt;some html &amp; special characters &gt; here'\ u' \u0110\xc5\u20ac\xa3') def test_linebreaks(self): self.assertEqual(linebreaks(u'line 1'), u'<p>line 1</p>') self.assertEqual(linebreaks(u'line 1\nline 2'), u'<p>line 1<br />line 2</p>') def test_removetags(self): self.assertEqual(removetags(u'some <b>html</b> with <script>alert'\ u'("You smell")</script> disallowed <img /> tags', 'script img'), u'some <b>html</b> with alert("You smell") disallowed tags') self.assertEqual(striptags(u'some <b>html</b> with <script>alert'\ u'("You smell")</script> disallowed <img /> tags'), u'some html with alert("You smell") disallowed tags') def test_dictsort(self): sorted_dicts = dictsort([{'age': 23, 'name': 'Barbara-Ann'}, {'age': 63, 'name': 'Ra Ra Rasputin'}, {'name': 'Jonny B Goode', 'age': 18}], 'age') self.assertEqual([sorted(dict.items()) for dict in sorted_dicts], [[('age', 18), ('name', 'Jonny B Goode')], [('age', 23), ('name', 'Barbara-Ann')], [('age', 63), ('name', 'Ra Ra Rasputin')]]) def test_dictsortreversed(self): sorted_dicts = dictsortreversed([{'age': 23, 'name': 'Barbara-Ann'}, {'age': 63, 'name': 'Ra Ra Rasputin'}, {'name': 'Jonny B Goode', 'age': 18}], 'age') self.assertEqual([sorted(dict.items()) for dict in sorted_dicts], [[('age', 63), ('name', 'Ra Ra Rasputin')], [('age', 23), ('name', 'Barbara-Ann')], [('age', 18), ('name', 'Jonny B Goode')]]) def test_first(self): self.assertEqual(first([0,1,2]), 0) self.assertEqual(first(u''), u'') self.assertEqual(first(u'test'), u't') def test_join(self): self.assertEqual(join([0,1,2], u'glue'), u'0glue1glue2') def test_length(self): self.assertEqual(length(u'1234'), 4) self.assertEqual(length([1,2,3,4]), 4) self.assertEqual(length_is([], 0), True) self.assertEqual(length_is([], 1), False) self.assertEqual(length_is('a', 1), True) self.assertEqual(length_is(u'a', 10), False) def test_slice(self): self.assertEqual(slice_(u'abcdefg', u'0'), u'') self.assertEqual(slice_(u'abcdefg', u'1'), u'a') self.assertEqual(slice_(u'abcdefg', u'-1'), u'abcdef') self.assertEqual(slice_(u'abcdefg', u'1:2'), u'b') self.assertEqual(slice_(u'abcdefg', u'1:3'), u'bc') self.assertEqual(slice_(u'abcdefg', u'0::2'), u'aceg') def test_unordered_list(self): self.assertEqual(unordered_list([u'item 1', u'item 2']), u'\t<li>item 1</li>\n\t<li>item 2</li>') self.assertEqual(unordered_list([u'item 1', [u'item 1.1']]), u'\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t</ul>\n\t</li>') self.assertEqual( unordered_list([u'item 1', [u'item 1.1', u'item1.2'], u'item 2']), u'\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t\t<li>item1.2'\ u'</li>\n\t</ul>\n\t</li>\n\t<li>item 2</li>') self.assertEqual( unordered_list([u'item 1', [u'item 1.1', [u'item 1.1.1', [u'item 1.1.1.1']]]]), u'\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1\n\t\t<ul>\n\t\t\t<li>'\ u'item 1.1.1\n\t\t\t<ul>\n\t\t\t\t<li>item 1.1.1.1</li>\n\t\t\t'\ u'</ul>\n\t\t\t</li>\n\t\t</ul>\n\t\t</li>\n\t</ul>\n\t</li>') self.assertEqual(unordered_list( ['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]), u'\t<li>States\n\t<ul>\n\t\t<li>Kansas\n\t\t<ul>\n\t\t\t<li>'\ u'Lawrence</li>\n\t\t\t<li>Topeka</li>\n\t\t</ul>\n\t\t</li>'\ u'\n\t\t<li>Illinois</li>\n\t</ul>\n\t</li>') class ULItem(object): def __init__(self, title): self.title = title def __unicode__(self): return u'ulitem-%s' % str(self.title) a = ULItem('a') b = ULItem('b') self.assertEqual(unordered_list([a,b]), u'\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>') # Old format for unordered lists should still work self.assertEqual(unordered_list([u'item 1', []]), u'\t<li>item 1</li>') self.assertEqual(unordered_list([u'item 1', [[u'item 1.1', []]]]), u'\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t</ul>\n\t</li>') self.assertEqual(unordered_list([u'item 1', [[u'item 1.1', []], [u'item 1.2', []]]]), u'\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1'\ u'</li>\n\t\t<li>item 1.2</li>\n\t</ul>\n\t</li>') self.assertEqual(unordered_list(['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]), u'\t<li>States\n\t'\ u'<ul>\n\t\t<li>Kansas\n\t\t<ul>\n\t\t\t<li>Lawrence</li>'\ u'\n\t\t\t<li>Topeka</li>\n\t\t</ul>\n\t\t</li>\n\t\t<li>'\ u'Illinois</li>\n\t</ul>\n\t</li>') def test_add(self): self.assertEqual(add(u'1', u'2'), 3) def test_get_digit(self): self.assertEqual(get_digit(123, 1), 3) self.assertEqual(get_digit(123, 2), 2) self.assertEqual(get_digit(123, 3), 1) self.assertEqual(get_digit(123, 4), 0) self.assertEqual(get_digit(123, 0), 123) self.assertEqual(get_digit(u'xyz', 0), u'xyz') def test_date(self): # real testing of date() is in dateformat.py self.assertEqual(date(datetime.datetime(2005, 12, 29), u"d F Y"), u'29 December 2005') self.assertEqual(date(datetime.datetime(2005, 12, 29), ur'jS o\f F'), u'29th of December') def test_time(self): # real testing of time() is done in dateformat.py self.assertEqual(time(datetime.time(13), u"h"), u'01') self.assertEqual(time(datetime.time(0), u"h"), u'12') def test_timesince(self): # real testing is done in timesince.py, where we can provide our own 'now' self.assertEqual( timesince(datetime.datetime.now() - datetime.timedelta(1)), u'1 day') self.assertEqual( timesince(datetime.datetime(2005, 12, 29), datetime.datetime(2005, 12, 30)), u'1 day') def test_timeuntil(self): self.assertEqual( timeuntil(datetime.datetime.now() + datetime.timedelta(1)), u'1 day') self.assertEqual(timeuntil(datetime.datetime(2005, 12, 30), datetime.datetime(2005, 12, 29)), u'1 day') def test_default(self): self.assertEqual(default(u"val", u"default"), u'val') self.assertEqual(default(None, u"default"), u'default') self.assertEqual(default(u'', u"default"), u'default') def test_if_none(self): self.assertEqual(default_if_none(u"val", u"default"), u'val') self.assertEqual(default_if_none(None, u"default"), u'default') self.assertEqual(default_if_none(u'', u"default"), u'') def test_divisibleby(self): self.assertEqual(divisibleby(4, 2), True) self.assertEqual(divisibleby(4, 3), False) def test_yesno(self): self.assertEqual(yesno(True), u'yes') self.assertEqual(yesno(False), u'no') self.assertEqual(yesno(None), u'maybe') self.assertEqual(yesno(True, u'certainly,get out of town,perhaps'), u'certainly') self.assertEqual(yesno(False, u'certainly,get out of town,perhaps'), u'get out of town') self.assertEqual(yesno(None, u'certainly,get out of town,perhaps'), u'perhaps') self.assertEqual(yesno(None, u'certainly,get out of town'), u'get out of town') def test_filesizeformat(self): self.assertEqual(filesizeformat(1023), u'1023 bytes') self.assertEqual(filesizeformat(1024), u'1.0 KB') self.assertEqual(filesizeformat(10*1024), u'10.0 KB') self.assertEqual(filesizeformat(1024*1024-1), u'1024.0 KB') self.assertEqual(filesizeformat(1024*1024), u'1.0 MB') self.assertEqual(filesizeformat(1024*1024*50), u'50.0 MB') self.assertEqual(filesizeformat(1024*1024*1024-1), u'1024.0 MB') self.assertEqual(filesizeformat(1024*1024*1024), u'1.0 GB') self.assertEqual(filesizeformat(1024*1024*1024*1024), u'1.0 TB') self.assertEqual(filesizeformat(1024*1024*1024*1024*1024), u'1.0 PB') self.assertEqual(filesizeformat(1024*1024*1024*1024*1024*2000), u'2000.0 PB') self.assertEqual(filesizeformat(complex(1,-1)), u'0 bytes') self.assertEqual(filesizeformat(""), u'0 bytes') self.assertEqual(filesizeformat(u"\N{GREEK SMALL LETTER ALPHA}"), u'0 bytes') def test_localized_filesizeformat(self): from django.utils.translation import activate, deactivate old_localize = settings.USE_L10N try: activate('de') settings.USE_L10N = True self.assertEqual(filesizeformat(1023), u'1023 Bytes') self.assertEqual(filesizeformat(1024), u'1,0 KB') self.assertEqual(filesizeformat(10*1024), u'10,0 KB') self.assertEqual(filesizeformat(1024*1024-1), u'1024,0 KB') self.assertEqual(filesizeformat(1024*1024), u'1,0 MB') self.assertEqual(filesizeformat(1024*1024*50), u'50,0 MB') self.assertEqual(filesizeformat(1024*1024*1024-1), u'1024,0 MB') self.assertEqual(filesizeformat(1024*1024*1024), u'1,0 GB') self.assertEqual(filesizeformat(1024*1024*1024*1024), u'1,0 TB') self.assertEqual(filesizeformat(1024*1024*1024*1024*1024), u'1,0 PB') self.assertEqual(filesizeformat(1024*1024*1024*1024*1024*2000), u'2000,0 PB') self.assertEqual(filesizeformat(complex(1,-1)), u'0 Bytes') self.assertEqual(filesizeformat(""), u'0 Bytes') self.assertEqual(filesizeformat(u"\N{GREEK SMALL LETTER ALPHA}"), u'0 Bytes') finally: deactivate() settings.USE_L10N = old_localize def test_pluralize(self): self.assertEqual(pluralize(1), u'') self.assertEqual(pluralize(0), u's') self.assertEqual(pluralize(2), u's') self.assertEqual(pluralize([1]), u'') self.assertEqual(pluralize([]), u's') self.assertEqual(pluralize([1,2,3]), u's') self.assertEqual(pluralize(1,u'es'), u'') self.assertEqual(pluralize(0,u'es'), u'es') self.assertEqual(pluralize(2,u'es'), u'es') self.assertEqual(pluralize(1,u'y,ies'), u'y') self.assertEqual(pluralize(0,u'y,ies'), u'ies') self.assertEqual(pluralize(2,u'y,ies'), u'ies') self.assertEqual(pluralize(0,u'y,ies,error'), u'') def test_phone2numeric(self): self.assertEqual(phone2numeric(u'0800 flowers'), u'0800 3569377') def test_non_string_input(self): # Filters shouldn't break if passed non-strings self.assertEqual(addslashes(123), u'123') self.assertEqual(linenumbers(123), u'1. 123') self.assertEqual(lower(123), u'123') self.assertEqual(make_list(123), [u'1', u'2', u'3']) self.assertEqual(slugify(123), u'123') self.assertEqual(title(123), u'123') self.assertEqual(truncatewords(123, 2), u'123') self.assertEqual(upper(123), u'123') self.assertEqual(urlencode(123), u'123') self.assertEqual(urlize(123), u'123') self.assertEqual(urlizetrunc(123, 1), u'123') self.assertEqual(wordcount(123), 1) self.assertEqual(wordwrap(123, 2), u'123') self.assertEqual(ljust('123', 4), u'123 ') self.assertEqual(rjust('123', 4), u' 123') self.assertEqual(center('123', 5), u' 123 ') self.assertEqual(center('123', 6), u' 123 ') self.assertEqual(cut(123, '2'), u'13') self.assertEqual(escape(123), u'123') self.assertEqual(linebreaks(123), u'<p>123</p>') self.assertEqual(linebreaksbr(123), u'123') self.assertEqual(removetags(123, 'a'), u'123') self.assertEqual(striptags(123), u'123')
24,500
Python
.py
447
43.310962
87
0.579852
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,019
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/model_regress/models.py
# coding: utf-8 from django.db import models CHOICES = ( (1, 'first'), (2, 'second'), ) class Article(models.Model): headline = models.CharField(max_length=100, default='Default headline') pub_date = models.DateTimeField() status = models.IntegerField(blank=True, null=True, choices=CHOICES) misc_data = models.CharField(max_length=100, blank=True) article_text = models.TextField() class Meta: ordering = ('pub_date','headline') # A utf-8 verbose name (Ångström's Articles) to test they are valid. verbose_name = "\xc3\x85ngstr\xc3\xb6m's Articles" def __unicode__(self): return self.headline class Movie(models.Model): #5218: Test models with non-default primary keys / AutoFields movie_id = models.AutoField(primary_key=True) name = models.CharField(max_length=60) class Party(models.Model): when = models.DateField(null=True) class Event(models.Model): when = models.DateTimeField() class Department(models.Model): id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=200) def __unicode__(self): return self.name class Worker(models.Model): department = models.ForeignKey(Department) name = models.CharField(max_length=200) def __unicode__(self): return self.name class BrokenUnicodeMethod(models.Model): name = models.CharField(max_length=7) def __unicode__(self): # Intentionally broken (trying to insert a unicode value into a str # object). return 'Názov: %s' % self.name class NonAutoPK(models.Model): name = models.CharField(max_length=10, primary_key=True)
1,683
Python
.py
44
33.113636
76
0.701419
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,020
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/model_regress/tests.py
import datetime from operator import attrgetter from django.core.exceptions import ValidationError from django.test import TestCase, skipUnlessDBFeature from django.utils import tzinfo from models import (Worker, Article, Party, Event, Department, BrokenUnicodeMethod, NonAutoPK) class ModelTests(TestCase): # The bug is that the following queries would raise: # "TypeError: Related Field has invalid lookup: gte" def test_related_gte_lookup(self): """ Regression test for #10153: foreign key __gte lookups. """ Worker.objects.filter(department__gte=0) def test_related_lte_lookup(self): """ Regression test for #10153: foreign key __lte lookups. """ Worker.objects.filter(department__lte=0) def test_empty_choice(self): # NOTE: Part of the regression test here is merely parsing the model # declaration. The verbose_name, in particular, did not always work. a = Article.objects.create( headline="Look at me!", pub_date=datetime.datetime.now() ) # An empty choice field should return None for the display name. self.assertIs(a.get_status_display(), None) # Empty strings should be returned as Unicode a = Article.objects.get(pk=a.pk) self.assertEqual(a.misc_data, u'') self.assertIs(type(a.misc_data), unicode) def test_long_textfield(self): # TextFields can hold more than 4000 characters (this was broken in # Oracle). a = Article.objects.create( headline="Really, really big", pub_date=datetime.datetime.now(), article_text = "ABCDE" * 1000 ) a = Article.objects.get(pk=a.pk) self.assertEqual (len(a.article_text), 5000) def test_date_lookup(self): # Regression test for #659 Party.objects.create(when=datetime.datetime(1999, 12, 31)) Party.objects.create(when=datetime.datetime(1998, 12, 31)) Party.objects.create(when=datetime.datetime(1999, 1, 1)) self.assertQuerysetEqual( Party.objects.filter(when__month=2), [] ) self.assertQuerysetEqual( Party.objects.filter(when__month=1), [ datetime.date(1999, 1, 1) ], attrgetter("when") ) self.assertQuerysetEqual( Party.objects.filter(when__month=12), [ datetime.date(1999, 12, 31), datetime.date(1998, 12, 31), ], attrgetter("when") ) self.assertQuerysetEqual( Party.objects.filter(when__year=1998), [ datetime.date(1998, 12, 31), ], attrgetter("when") ) # Regression test for #8510 self.assertQuerysetEqual( Party.objects.filter(when__day="31"), [ datetime.date(1999, 12, 31), datetime.date(1998, 12, 31), ], attrgetter("when") ) self.assertQuerysetEqual( Party.objects.filter(when__month="12"), [ datetime.date(1999, 12, 31), datetime.date(1998, 12, 31), ], attrgetter("when") ) self.assertQuerysetEqual( Party.objects.filter(when__year="1998"), [ datetime.date(1998, 12, 31), ], attrgetter("when") ) def test_date_filter_null(self): # Date filtering was failing with NULL date values in SQLite # (regression test for #3501, amongst other things). Party.objects.create(when=datetime.datetime(1999, 1, 1)) Party.objects.create() p = Party.objects.filter(when__month=1)[0] self.assertEqual(p.when, datetime.date(1999, 1, 1)) self.assertQuerysetEqual( Party.objects.filter(pk=p.pk).dates("when", "month"), [ 1 ], attrgetter("month") ) def test_get_next_prev_by_field(self): # Check that get_next_by_FIELD and get_previous_by_FIELD don't crash # when we have usecs values stored on the database # # It crashed after the Field.get_db_prep_* refactor, because on most # backends DateTimeFields supports usecs, but DateTimeField.to_python # didn't recognize them. (Note that # Model._get_next_or_previous_by_FIELD coerces values to strings) Event.objects.create(when=datetime.datetime(2000, 1, 1, 16, 0, 0)) Event.objects.create(when=datetime.datetime(2000, 1, 1, 6, 1, 1)) Event.objects.create(when=datetime.datetime(2000, 1, 1, 13, 1, 1)) e = Event.objects.create(when=datetime.datetime(2000, 1, 1, 12, 0, 20, 24)) self.assertEqual( e.get_next_by_when().when, datetime.datetime(2000, 1, 1, 13, 1, 1) ) self.assertEqual( e.get_previous_by_when().when, datetime.datetime(2000, 1, 1, 6, 1, 1) ) def test_primary_key_foreign_key_types(self): # Check Department and Worker (non-default PK type) d = Department.objects.create(id=10, name="IT") w = Worker.objects.create(department=d, name="Full-time") self.assertEqual(unicode(w), "Full-time") def test_broken_unicode(self): # Models with broken unicode methods should still have a printable repr b = BrokenUnicodeMethod.objects.create(name="Jerry") self.assertEqual(repr(b), "<BrokenUnicodeMethod: [Bad Unicode data]>") @skipUnlessDBFeature("supports_timezones") def test_timezones(self): # Saving an updating with timezone-aware datetime Python objects. # Regression test for #10443. # The idea is that all these creations and saving should work without # crashing. It's not rocket science. dt1 = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=tzinfo.FixedOffset(600)) dt2 = datetime.datetime(2008, 8, 31, 17, 20, tzinfo=tzinfo.FixedOffset(600)) obj = Article.objects.create( headline="A headline", pub_date=dt1, article_text="foo" ) obj.pub_date = dt2 obj.save() self.assertEqual( Article.objects.filter(headline="A headline").update(pub_date=dt1), 1 ) class ModelValidationTest(TestCase): def test_pk_validation(self): one = NonAutoPK.objects.create(name="one") again = NonAutoPK(name="one") self.assertRaises(ValidationError, again.validate_unique)
6,565
Python
.py
153
33.27451
84
0.615637
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,021
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/cache/models.py
from django.db import models from datetime import datetime def expensive_calculation(): expensive_calculation.num_runs += 1 return datetime.now() class Poll(models.Model): question = models.CharField(max_length=200) answer = models.CharField(max_length=200) pub_date = models.DateTimeField('date published', default=expensive_calculation)
361
Python
.py
9
36.666667
84
0.777143
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,022
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/cache/tests.py
# -*- coding: utf-8 -*- # Unit tests for cache framework # Uses whatever cache backend is set in the test settings file. import os import tempfile import time import warnings from django.conf import settings from django.core import management from django.core.cache import get_cache, DEFAULT_CACHE_ALIAS from django.core.cache.backends.base import CacheKeyWarning from django.http import HttpResponse, HttpRequest, QueryDict from django.middleware.cache import FetchFromCacheMiddleware, UpdateCacheMiddleware, CacheMiddleware from django.test import RequestFactory from django.test.utils import get_warnings_state, restore_warnings_state from django.utils import translation from django.utils import unittest from django.utils.cache import patch_vary_headers, get_cache_key, learn_cache_key from django.utils.hashcompat import md5_constructor from django.views.decorators.cache import cache_page from regressiontests.cache.models import Poll, expensive_calculation # functions/classes for complex data type tests def f(): return 42 class C: def m(n): return 24 class DummyCacheTests(unittest.TestCase): # The Dummy cache backend doesn't really behave like a test backend, # so it has different test requirements. def setUp(self): self.cache = get_cache('django.core.cache.backends.dummy.DummyCache') def test_simple(self): "Dummy cache backend ignores cache set calls" self.cache.set("key", "value") self.assertEqual(self.cache.get("key"), None) def test_add(self): "Add doesn't do anything in dummy cache backend" self.cache.add("addkey1", "value") result = self.cache.add("addkey1", "newvalue") self.assertEqual(result, True) self.assertEqual(self.cache.get("addkey1"), None) def test_non_existent(self): "Non-existent keys aren't found in the dummy cache backend" self.assertEqual(self.cache.get("does_not_exist"), None) self.assertEqual(self.cache.get("does_not_exist", "bang!"), "bang!") def test_get_many(self): "get_many returns nothing for the dummy cache backend" self.cache.set('a', 'a') self.cache.set('b', 'b') self.cache.set('c', 'c') self.cache.set('d', 'd') self.assertEqual(self.cache.get_many(['a', 'c', 'd']), {}) self.assertEqual(self.cache.get_many(['a', 'b', 'e']), {}) def test_delete(self): "Cache deletion is transparently ignored on the dummy cache backend" self.cache.set("key1", "spam") self.cache.set("key2", "eggs") self.assertEqual(self.cache.get("key1"), None) self.cache.delete("key1") self.assertEqual(self.cache.get("key1"), None) self.assertEqual(self.cache.get("key2"), None) def test_has_key(self): "The has_key method doesn't ever return True for the dummy cache backend" self.cache.set("hello1", "goodbye1") self.assertEqual(self.cache.has_key("hello1"), False) self.assertEqual(self.cache.has_key("goodbye1"), False) def test_in(self): "The in operator doesn't ever return True for the dummy cache backend" self.cache.set("hello2", "goodbye2") self.assertEqual("hello2" in self.cache, False) self.assertEqual("goodbye2" in self.cache, False) def test_incr(self): "Dummy cache values can't be incremented" self.cache.set('answer', 42) self.assertRaises(ValueError, self.cache.incr, 'answer') self.assertRaises(ValueError, self.cache.incr, 'does_not_exist') def test_decr(self): "Dummy cache values can't be decremented" self.cache.set('answer', 42) self.assertRaises(ValueError, self.cache.decr, 'answer') self.assertRaises(ValueError, self.cache.decr, 'does_not_exist') def test_data_types(self): "All data types are ignored equally by the dummy cache" stuff = { 'string' : 'this is a string', 'int' : 42, 'list' : [1, 2, 3, 4], 'tuple' : (1, 2, 3, 4), 'dict' : {'A': 1, 'B' : 2}, 'function' : f, 'class' : C, } self.cache.set("stuff", stuff) self.assertEqual(self.cache.get("stuff"), None) def test_expiration(self): "Expiration has no effect on the dummy cache" self.cache.set('expire1', 'very quickly', 1) self.cache.set('expire2', 'very quickly', 1) self.cache.set('expire3', 'very quickly', 1) time.sleep(2) self.assertEqual(self.cache.get("expire1"), None) self.cache.add("expire2", "newvalue") self.assertEqual(self.cache.get("expire2"), None) self.assertEqual(self.cache.has_key("expire3"), False) def test_unicode(self): "Unicode values are ignored by the dummy cache" stuff = { u'ascii': u'ascii_value', u'unicode_ascii': u'Iñtërnâtiônàlizætiøn1', u'Iñtërnâtiônàlizætiøn': u'Iñtërnâtiônàlizætiøn2', u'ascii': {u'x' : 1 } } for (key, value) in stuff.items(): self.cache.set(key, value) self.assertEqual(self.cache.get(key), None) def test_set_many(self): "set_many does nothing for the dummy cache backend" self.cache.set_many({'a': 1, 'b': 2}) def test_delete_many(self): "delete_many does nothing for the dummy cache backend" self.cache.delete_many(['a', 'b']) def test_clear(self): "clear does nothing for the dummy cache backend" self.cache.clear() def test_incr_version(self): "Dummy cache versions can't be incremented" self.cache.set('answer', 42) self.assertRaises(ValueError, self.cache.incr_version, 'answer') self.assertRaises(ValueError, self.cache.incr_version, 'does_not_exist') def test_decr_version(self): "Dummy cache versions can't be decremented" self.cache.set('answer', 42) self.assertRaises(ValueError, self.cache.decr_version, 'answer') self.assertRaises(ValueError, self.cache.decr_version, 'does_not_exist') class BaseCacheTests(object): # A common set of tests to apply to all cache backends def test_simple(self): # Simple cache set/get works self.cache.set("key", "value") self.assertEqual(self.cache.get("key"), "value") def test_add(self): # A key can be added to a cache self.cache.add("addkey1", "value") result = self.cache.add("addkey1", "newvalue") self.assertEqual(result, False) self.assertEqual(self.cache.get("addkey1"), "value") def test_prefix(self): # Test for same cache key conflicts between shared backend self.cache.set('somekey', 'value') # should not be set in the prefixed cache self.assertFalse(self.prefix_cache.has_key('somekey')) self.prefix_cache.set('somekey', 'value2') self.assertEqual(self.cache.get('somekey'), 'value') self.assertEqual(self.prefix_cache.get('somekey'), 'value2') def test_non_existent(self): # Non-existent cache keys return as None/default # get with non-existent keys self.assertEqual(self.cache.get("does_not_exist"), None) self.assertEqual(self.cache.get("does_not_exist", "bang!"), "bang!") def test_get_many(self): # Multiple cache keys can be returned using get_many self.cache.set('a', 'a') self.cache.set('b', 'b') self.cache.set('c', 'c') self.cache.set('d', 'd') self.assertEqual(self.cache.get_many(['a', 'c', 'd']), {'a' : 'a', 'c' : 'c', 'd' : 'd'}) self.assertEqual(self.cache.get_many(['a', 'b', 'e']), {'a' : 'a', 'b' : 'b'}) def test_delete(self): # Cache keys can be deleted self.cache.set("key1", "spam") self.cache.set("key2", "eggs") self.assertEqual(self.cache.get("key1"), "spam") self.cache.delete("key1") self.assertEqual(self.cache.get("key1"), None) self.assertEqual(self.cache.get("key2"), "eggs") def test_has_key(self): # The cache can be inspected for cache keys self.cache.set("hello1", "goodbye1") self.assertEqual(self.cache.has_key("hello1"), True) self.assertEqual(self.cache.has_key("goodbye1"), False) def test_in(self): # The in operator can be used to inspet cache contents self.cache.set("hello2", "goodbye2") self.assertEqual("hello2" in self.cache, True) self.assertEqual("goodbye2" in self.cache, False) def test_incr(self): # Cache values can be incremented self.cache.set('answer', 41) self.assertEqual(self.cache.incr('answer'), 42) self.assertEqual(self.cache.get('answer'), 42) self.assertEqual(self.cache.incr('answer', 10), 52) self.assertEqual(self.cache.get('answer'), 52) self.assertRaises(ValueError, self.cache.incr, 'does_not_exist') def test_decr(self): # Cache values can be decremented self.cache.set('answer', 43) self.assertEqual(self.cache.decr('answer'), 42) self.assertEqual(self.cache.get('answer'), 42) self.assertEqual(self.cache.decr('answer', 10), 32) self.assertEqual(self.cache.get('answer'), 32) self.assertRaises(ValueError, self.cache.decr, 'does_not_exist') def test_data_types(self): # Many different data types can be cached stuff = { 'string' : 'this is a string', 'int' : 42, 'list' : [1, 2, 3, 4], 'tuple' : (1, 2, 3, 4), 'dict' : {'A': 1, 'B' : 2}, 'function' : f, 'class' : C, } self.cache.set("stuff", stuff) self.assertEqual(self.cache.get("stuff"), stuff) def test_cache_read_for_model_instance(self): # Don't want fields with callable as default to be called on cache read expensive_calculation.num_runs = 0 Poll.objects.all().delete() my_poll = Poll.objects.create(question="Well?") self.assertEqual(Poll.objects.count(), 1) pub_date = my_poll.pub_date self.cache.set('question', my_poll) cached_poll = self.cache.get('question') self.assertEqual(cached_poll.pub_date, pub_date) # We only want the default expensive calculation run once self.assertEqual(expensive_calculation.num_runs, 1) def test_cache_write_for_model_instance_with_deferred(self): # Don't want fields with callable as default to be called on cache write expensive_calculation.num_runs = 0 Poll.objects.all().delete() my_poll = Poll.objects.create(question="What?") self.assertEqual(expensive_calculation.num_runs, 1) defer_qs = Poll.objects.all().defer('question') self.assertEqual(defer_qs.count(), 1) self.assertEqual(expensive_calculation.num_runs, 1) self.cache.set('deferred_queryset', defer_qs) # cache set should not re-evaluate default functions self.assertEqual(expensive_calculation.num_runs, 1) def test_cache_read_for_model_instance_with_deferred(self): # Don't want fields with callable as default to be called on cache read expensive_calculation.num_runs = 0 Poll.objects.all().delete() my_poll = Poll.objects.create(question="What?") self.assertEqual(expensive_calculation.num_runs, 1) defer_qs = Poll.objects.all().defer('question') self.assertEqual(defer_qs.count(), 1) self.cache.set('deferred_queryset', defer_qs) self.assertEqual(expensive_calculation.num_runs, 1) runs_before_cache_read = expensive_calculation.num_runs cached_polls = self.cache.get('deferred_queryset') # We only want the default expensive calculation run on creation and set self.assertEqual(expensive_calculation.num_runs, runs_before_cache_read) def test_expiration(self): # Cache values can be set to expire self.cache.set('expire1', 'very quickly', 1) self.cache.set('expire2', 'very quickly', 1) self.cache.set('expire3', 'very quickly', 1) time.sleep(2) self.assertEqual(self.cache.get("expire1"), None) self.cache.add("expire2", "newvalue") self.assertEqual(self.cache.get("expire2"), "newvalue") self.assertEqual(self.cache.has_key("expire3"), False) def test_unicode(self): # Unicode values can be cached stuff = { u'ascii': u'ascii_value', u'unicode_ascii': u'Iñtërnâtiônàlizætiøn1', u'Iñtërnâtiônàlizætiøn': u'Iñtërnâtiônàlizætiøn2', u'ascii': {u'x' : 1 } } # Test `set` for (key, value) in stuff.items(): self.cache.set(key, value) self.assertEqual(self.cache.get(key), value) # Test `add` for (key, value) in stuff.items(): self.cache.delete(key) self.cache.add(key, value) self.assertEqual(self.cache.get(key), value) # Test `set_many` for (key, value) in stuff.items(): self.cache.delete(key) self.cache.set_many(stuff) for (key, value) in stuff.items(): self.assertEqual(self.cache.get(key), value) def test_binary_string(self): # Binary strings should be cachable from zlib import compress, decompress value = 'value_to_be_compressed' compressed_value = compress(value) # Test set self.cache.set('binary1', compressed_value) compressed_result = self.cache.get('binary1') self.assertEqual(compressed_value, compressed_result) self.assertEqual(value, decompress(compressed_result)) # Test add self.cache.add('binary1-add', compressed_value) compressed_result = self.cache.get('binary1-add') self.assertEqual(compressed_value, compressed_result) self.assertEqual(value, decompress(compressed_result)) # Test set_many self.cache.set_many({'binary1-set_many': compressed_value}) compressed_result = self.cache.get('binary1-set_many') self.assertEqual(compressed_value, compressed_result) self.assertEqual(value, decompress(compressed_result)) def test_set_many(self): # Multiple keys can be set using set_many self.cache.set_many({"key1": "spam", "key2": "eggs"}) self.assertEqual(self.cache.get("key1"), "spam") self.assertEqual(self.cache.get("key2"), "eggs") def test_set_many_expiration(self): # set_many takes a second ``timeout`` parameter self.cache.set_many({"key1": "spam", "key2": "eggs"}, 1) time.sleep(2) self.assertEqual(self.cache.get("key1"), None) self.assertEqual(self.cache.get("key2"), None) def test_delete_many(self): # Multiple keys can be deleted using delete_many self.cache.set("key1", "spam") self.cache.set("key2", "eggs") self.cache.set("key3", "ham") self.cache.delete_many(["key1", "key2"]) self.assertEqual(self.cache.get("key1"), None) self.assertEqual(self.cache.get("key2"), None) self.assertEqual(self.cache.get("key3"), "ham") def test_clear(self): # The cache can be emptied using clear self.cache.set("key1", "spam") self.cache.set("key2", "eggs") self.cache.clear() self.assertEqual(self.cache.get("key1"), None) self.assertEqual(self.cache.get("key2"), None) def test_long_timeout(self): ''' Using a timeout greater than 30 days makes memcached think it is an absolute expiration timestamp instead of a relative offset. Test that we honour this convention. Refs #12399. ''' self.cache.set('key1', 'eggs', 60*60*24*30 + 1) #30 days + 1 second self.assertEqual(self.cache.get('key1'), 'eggs') self.cache.add('key2', 'ham', 60*60*24*30 + 1) self.assertEqual(self.cache.get('key2'), 'ham') self.cache.set_many({'key3': 'sausage', 'key4': 'lobster bisque'}, 60*60*24*30 + 1) self.assertEqual(self.cache.get('key3'), 'sausage') self.assertEqual(self.cache.get('key4'), 'lobster bisque') def perform_cull_test(self, initial_count, final_count): """This is implemented as a utility method, because only some of the backends implement culling. The culling algorithm also varies slightly, so the final number of entries will vary between backends""" # Create initial cache key entries. This will overflow the cache, causing a cull for i in range(1, initial_count): self.cache.set('cull%d' % i, 'value', 1000) count = 0 # Count how many keys are left in the cache. for i in range(1, initial_count): if self.cache.has_key('cull%d' % i): count = count + 1 self.assertEqual(count, final_count) def test_invalid_keys(self): """ All the builtin backends (except memcached, see below) should warn on keys that would be refused by memcached. This encourages portable caching code without making it too difficult to use production backends with more liberal key rules. Refs #6447. """ # mimic custom ``make_key`` method being defined since the default will # never show the below warnings def func(key, *args): return key old_func = self.cache.key_func self.cache.key_func = func # On Python 2.6+ we could use the catch_warnings context # manager to test this warning nicely. Since we can't do that # yet, the cleanest option is to temporarily ask for # CacheKeyWarning to be raised as an exception. _warnings_state = get_warnings_state() warnings.simplefilter("error", CacheKeyWarning) try: # memcached does not allow whitespace or control characters in keys self.assertRaises(CacheKeyWarning, self.cache.set, 'key with spaces', 'value') # memcached limits key length to 250 self.assertRaises(CacheKeyWarning, self.cache.set, 'a' * 251, 'value') finally: restore_warnings_state(_warnings_state) self.cache.key_func = old_func def test_cache_versioning_get_set(self): # set, using default version = 1 self.cache.set('answer1', 42) self.assertEqual(self.cache.get('answer1'), 42) self.assertEqual(self.cache.get('answer1', version=1), 42) self.assertEqual(self.cache.get('answer1', version=2), None) self.assertEqual(self.v2_cache.get('answer1'), None) self.assertEqual(self.v2_cache.get('answer1', version=1), 42) self.assertEqual(self.v2_cache.get('answer1', version=2), None) # set, default version = 1, but manually override version = 2 self.cache.set('answer2', 42, version=2) self.assertEqual(self.cache.get('answer2'), None) self.assertEqual(self.cache.get('answer2', version=1), None) self.assertEqual(self.cache.get('answer2', version=2), 42) self.assertEqual(self.v2_cache.get('answer2'), 42) self.assertEqual(self.v2_cache.get('answer2', version=1), None) self.assertEqual(self.v2_cache.get('answer2', version=2), 42) # v2 set, using default version = 2 self.v2_cache.set('answer3', 42) self.assertEqual(self.cache.get('answer3'), None) self.assertEqual(self.cache.get('answer3', version=1), None) self.assertEqual(self.cache.get('answer3', version=2), 42) self.assertEqual(self.v2_cache.get('answer3'), 42) self.assertEqual(self.v2_cache.get('answer3', version=1), None) self.assertEqual(self.v2_cache.get('answer3', version=2), 42) # v2 set, default version = 2, but manually override version = 1 self.v2_cache.set('answer4', 42, version=1) self.assertEqual(self.cache.get('answer4'), 42) self.assertEqual(self.cache.get('answer4', version=1), 42) self.assertEqual(self.cache.get('answer4', version=2), None) self.assertEqual(self.v2_cache.get('answer4'), None) self.assertEqual(self.v2_cache.get('answer4', version=1), 42) self.assertEqual(self.v2_cache.get('answer4', version=2), None) def test_cache_versioning_add(self): # add, default version = 1, but manually override version = 2 self.cache.add('answer1', 42, version=2) self.assertEqual(self.cache.get('answer1', version=1), None) self.assertEqual(self.cache.get('answer1', version=2), 42) self.cache.add('answer1', 37, version=2) self.assertEqual(self.cache.get('answer1', version=1), None) self.assertEqual(self.cache.get('answer1', version=2), 42) self.cache.add('answer1', 37, version=1) self.assertEqual(self.cache.get('answer1', version=1), 37) self.assertEqual(self.cache.get('answer1', version=2), 42) # v2 add, using default version = 2 self.v2_cache.add('answer2', 42) self.assertEqual(self.cache.get('answer2', version=1), None) self.assertEqual(self.cache.get('answer2', version=2), 42) self.v2_cache.add('answer2', 37) self.assertEqual(self.cache.get('answer2', version=1), None) self.assertEqual(self.cache.get('answer2', version=2), 42) self.v2_cache.add('answer2', 37, version=1) self.assertEqual(self.cache.get('answer2', version=1), 37) self.assertEqual(self.cache.get('answer2', version=2), 42) # v2 add, default version = 2, but manually override version = 1 self.v2_cache.add('answer3', 42, version=1) self.assertEqual(self.cache.get('answer3', version=1), 42) self.assertEqual(self.cache.get('answer3', version=2), None) self.v2_cache.add('answer3', 37, version=1) self.assertEqual(self.cache.get('answer3', version=1), 42) self.assertEqual(self.cache.get('answer3', version=2), None) self.v2_cache.add('answer3', 37) self.assertEqual(self.cache.get('answer3', version=1), 42) self.assertEqual(self.cache.get('answer3', version=2), 37) def test_cache_versioning_has_key(self): self.cache.set('answer1', 42) # has_key self.assertTrue(self.cache.has_key('answer1')) self.assertTrue(self.cache.has_key('answer1', version=1)) self.assertFalse(self.cache.has_key('answer1', version=2)) self.assertFalse(self.v2_cache.has_key('answer1')) self.assertTrue(self.v2_cache.has_key('answer1', version=1)) self.assertFalse(self.v2_cache.has_key('answer1', version=2)) def test_cache_versioning_delete(self): self.cache.set('answer1', 37, version=1) self.cache.set('answer1', 42, version=2) self.cache.delete('answer1') self.assertEqual(self.cache.get('answer1', version=1), None) self.assertEqual(self.cache.get('answer1', version=2), 42) self.cache.set('answer2', 37, version=1) self.cache.set('answer2', 42, version=2) self.cache.delete('answer2', version=2) self.assertEqual(self.cache.get('answer2', version=1), 37) self.assertEqual(self.cache.get('answer2', version=2), None) self.cache.set('answer3', 37, version=1) self.cache.set('answer3', 42, version=2) self.v2_cache.delete('answer3') self.assertEqual(self.cache.get('answer3', version=1), 37) self.assertEqual(self.cache.get('answer3', version=2), None) self.cache.set('answer4', 37, version=1) self.cache.set('answer4', 42, version=2) self.v2_cache.delete('answer4', version=1) self.assertEqual(self.cache.get('answer4', version=1), None) self.assertEqual(self.cache.get('answer4', version=2), 42) def test_cache_versioning_incr_decr(self): self.cache.set('answer1', 37, version=1) self.cache.set('answer1', 42, version=2) self.cache.incr('answer1') self.assertEqual(self.cache.get('answer1', version=1), 38) self.assertEqual(self.cache.get('answer1', version=2), 42) self.cache.decr('answer1') self.assertEqual(self.cache.get('answer1', version=1), 37) self.assertEqual(self.cache.get('answer1', version=2), 42) self.cache.set('answer2', 37, version=1) self.cache.set('answer2', 42, version=2) self.cache.incr('answer2', version=2) self.assertEqual(self.cache.get('answer2', version=1), 37) self.assertEqual(self.cache.get('answer2', version=2), 43) self.cache.decr('answer2', version=2) self.assertEqual(self.cache.get('answer2', version=1), 37) self.assertEqual(self.cache.get('answer2', version=2), 42) self.cache.set('answer3', 37, version=1) self.cache.set('answer3', 42, version=2) self.v2_cache.incr('answer3') self.assertEqual(self.cache.get('answer3', version=1), 37) self.assertEqual(self.cache.get('answer3', version=2), 43) self.v2_cache.decr('answer3') self.assertEqual(self.cache.get('answer3', version=1), 37) self.assertEqual(self.cache.get('answer3', version=2), 42) self.cache.set('answer4', 37, version=1) self.cache.set('answer4', 42, version=2) self.v2_cache.incr('answer4', version=1) self.assertEqual(self.cache.get('answer4', version=1), 38) self.assertEqual(self.cache.get('answer4', version=2), 42) self.v2_cache.decr('answer4', version=1) self.assertEqual(self.cache.get('answer4', version=1), 37) self.assertEqual(self.cache.get('answer4', version=2), 42) def test_cache_versioning_get_set_many(self): # set, using default version = 1 self.cache.set_many({'ford1': 37, 'arthur1': 42}) self.assertEqual(self.cache.get_many(['ford1','arthur1']), {'ford1': 37, 'arthur1': 42}) self.assertEqual(self.cache.get_many(['ford1','arthur1'], version=1), {'ford1': 37, 'arthur1': 42}) self.assertEqual(self.cache.get_many(['ford1','arthur1'], version=2), {}) self.assertEqual(self.v2_cache.get_many(['ford1','arthur1']), {}) self.assertEqual(self.v2_cache.get_many(['ford1','arthur1'], version=1), {'ford1': 37, 'arthur1': 42}) self.assertEqual(self.v2_cache.get_many(['ford1','arthur1'], version=2), {}) # set, default version = 1, but manually override version = 2 self.cache.set_many({'ford2': 37, 'arthur2': 42}, version=2) self.assertEqual(self.cache.get_many(['ford2','arthur2']), {}) self.assertEqual(self.cache.get_many(['ford2','arthur2'], version=1), {}) self.assertEqual(self.cache.get_many(['ford2','arthur2'], version=2), {'ford2': 37, 'arthur2': 42}) self.assertEqual(self.v2_cache.get_many(['ford2','arthur2']), {'ford2': 37, 'arthur2': 42}) self.assertEqual(self.v2_cache.get_many(['ford2','arthur2'], version=1), {}) self.assertEqual(self.v2_cache.get_many(['ford2','arthur2'], version=2), {'ford2': 37, 'arthur2': 42}) # v2 set, using default version = 2 self.v2_cache.set_many({'ford3': 37, 'arthur3': 42}) self.assertEqual(self.cache.get_many(['ford3','arthur3']), {}) self.assertEqual(self.cache.get_many(['ford3','arthur3'], version=1), {}) self.assertEqual(self.cache.get_many(['ford3','arthur3'], version=2), {'ford3': 37, 'arthur3': 42}) self.assertEqual(self.v2_cache.get_many(['ford3','arthur3']), {'ford3': 37, 'arthur3': 42}) self.assertEqual(self.v2_cache.get_many(['ford3','arthur3'], version=1), {}) self.assertEqual(self.v2_cache.get_many(['ford3','arthur3'], version=2), {'ford3': 37, 'arthur3': 42}) # v2 set, default version = 2, but manually override version = 1 self.v2_cache.set_many({'ford4': 37, 'arthur4': 42}, version=1) self.assertEqual(self.cache.get_many(['ford4','arthur4']), {'ford4': 37, 'arthur4': 42}) self.assertEqual(self.cache.get_many(['ford4','arthur4'], version=1), {'ford4': 37, 'arthur4': 42}) self.assertEqual(self.cache.get_many(['ford4','arthur4'], version=2), {}) self.assertEqual(self.v2_cache.get_many(['ford4','arthur4']), {}) self.assertEqual(self.v2_cache.get_many(['ford4','arthur4'], version=1), {'ford4': 37, 'arthur4': 42}) self.assertEqual(self.v2_cache.get_many(['ford4','arthur4'], version=2), {}) def test_incr_version(self): self.cache.set('answer', 42, version=2) self.assertEqual(self.cache.get('answer'), None) self.assertEqual(self.cache.get('answer', version=1), None) self.assertEqual(self.cache.get('answer', version=2), 42) self.assertEqual(self.cache.get('answer', version=3), None) self.assertEqual(self.cache.incr_version('answer', version=2), 3) self.assertEqual(self.cache.get('answer'), None) self.assertEqual(self.cache.get('answer', version=1), None) self.assertEqual(self.cache.get('answer', version=2), None) self.assertEqual(self.cache.get('answer', version=3), 42) self.v2_cache.set('answer2', 42) self.assertEqual(self.v2_cache.get('answer2'), 42) self.assertEqual(self.v2_cache.get('answer2', version=1), None) self.assertEqual(self.v2_cache.get('answer2', version=2), 42) self.assertEqual(self.v2_cache.get('answer2', version=3), None) self.assertEqual(self.v2_cache.incr_version('answer2'), 3) self.assertEqual(self.v2_cache.get('answer2'), None) self.assertEqual(self.v2_cache.get('answer2', version=1), None) self.assertEqual(self.v2_cache.get('answer2', version=2), None) self.assertEqual(self.v2_cache.get('answer2', version=3), 42) self.assertRaises(ValueError, self.cache.incr_version, 'does_not_exist') def test_decr_version(self): self.cache.set('answer', 42, version=2) self.assertEqual(self.cache.get('answer'), None) self.assertEqual(self.cache.get('answer', version=1), None) self.assertEqual(self.cache.get('answer', version=2), 42) self.assertEqual(self.cache.decr_version('answer', version=2), 1) self.assertEqual(self.cache.get('answer'), 42) self.assertEqual(self.cache.get('answer', version=1), 42) self.assertEqual(self.cache.get('answer', version=2), None) self.v2_cache.set('answer2', 42) self.assertEqual(self.v2_cache.get('answer2'), 42) self.assertEqual(self.v2_cache.get('answer2', version=1), None) self.assertEqual(self.v2_cache.get('answer2', version=2), 42) self.assertEqual(self.v2_cache.decr_version('answer2'), 1) self.assertEqual(self.v2_cache.get('answer2'), None) self.assertEqual(self.v2_cache.get('answer2', version=1), 42) self.assertEqual(self.v2_cache.get('answer2', version=2), None) self.assertRaises(ValueError, self.cache.decr_version, 'does_not_exist', version=2) def test_custom_key_func(self): # Two caches with different key functions aren't visible to each other self.cache.set('answer1', 42) self.assertEqual(self.cache.get('answer1'), 42) self.assertEqual(self.custom_key_cache.get('answer1'), None) self.assertEqual(self.custom_key_cache2.get('answer1'), None) self.custom_key_cache.set('answer2', 42) self.assertEqual(self.cache.get('answer2'), None) self.assertEqual(self.custom_key_cache.get('answer2'), 42) self.assertEqual(self.custom_key_cache2.get('answer2'), 42) def custom_key_func(key, key_prefix, version): "A customized cache key function" return 'CUSTOM-' + '-'.join([key_prefix, str(version), key]) class DBCacheTests(unittest.TestCase, BaseCacheTests): def setUp(self): # Spaces are used in the table name to ensure quoting/escaping is working self._table_name = 'test cache table' management.call_command('createcachetable', self._table_name, verbosity=0, interactive=False) self.cache = get_cache('django.core.cache.backends.db.DatabaseCache', LOCATION=self._table_name, OPTIONS={'MAX_ENTRIES': 30}) self.prefix_cache = get_cache('django.core.cache.backends.db.DatabaseCache', LOCATION=self._table_name, KEY_PREFIX='cacheprefix') self.v2_cache = get_cache('django.core.cache.backends.db.DatabaseCache', LOCATION=self._table_name, VERSION=2) self.custom_key_cache = get_cache('django.core.cache.backends.db.DatabaseCache', LOCATION=self._table_name, KEY_FUNCTION=custom_key_func) self.custom_key_cache2 = get_cache('django.core.cache.backends.db.DatabaseCache', LOCATION=self._table_name, KEY_FUNCTION='regressiontests.cache.tests.custom_key_func') def tearDown(self): from django.db import connection cursor = connection.cursor() cursor.execute('DROP TABLE %s' % connection.ops.quote_name(self._table_name)) def test_cull(self): self.perform_cull_test(50, 29) def test_zero_cull(self): self.cache = get_cache('django.core.cache.backends.db.DatabaseCache', LOCATION=self._table_name, OPTIONS={'MAX_ENTRIES': 30, 'CULL_FREQUENCY': 0}) self.perform_cull_test(50, 18) def test_old_initialization(self): self.cache = get_cache('db://%s?max_entries=30&cull_frequency=0' % self._table_name) self.perform_cull_test(50, 18) class LocMemCacheTests(unittest.TestCase, BaseCacheTests): def setUp(self): self.cache = get_cache('django.core.cache.backends.locmem.LocMemCache', OPTIONS={'MAX_ENTRIES': 30}) self.prefix_cache = get_cache('django.core.cache.backends.locmem.LocMemCache', KEY_PREFIX='cacheprefix') self.v2_cache = get_cache('django.core.cache.backends.locmem.LocMemCache', VERSION=2) self.custom_key_cache = get_cache('django.core.cache.backends.locmem.LocMemCache', OPTIONS={'MAX_ENTRIES': 30}, KEY_FUNCTION=custom_key_func) self.custom_key_cache2 = get_cache('django.core.cache.backends.locmem.LocMemCache', OPTIONS={'MAX_ENTRIES': 30}, KEY_FUNCTION='regressiontests.cache.tests.custom_key_func') # LocMem requires a hack to make the other caches # share a data store with the 'normal' cache. self.prefix_cache._cache = self.cache._cache self.prefix_cache._expire_info = self.cache._expire_info self.v2_cache._cache = self.cache._cache self.v2_cache._expire_info = self.cache._expire_info self.custom_key_cache._cache = self.cache._cache self.custom_key_cache._expire_info = self.cache._expire_info self.custom_key_cache2._cache = self.cache._cache self.custom_key_cache2._expire_info = self.cache._expire_info def tearDown(self): self.cache.clear() def test_cull(self): self.perform_cull_test(50, 29) def test_zero_cull(self): self.cache = get_cache('django.core.cache.backends.locmem.LocMemCache', OPTIONS={'MAX_ENTRIES': 30, 'CULL_FREQUENCY': 0}) self.perform_cull_test(50, 19) def test_old_initialization(self): self.cache = get_cache('locmem://?max_entries=30&cull_frequency=0') self.perform_cull_test(50, 19) def test_multiple_caches(self): "Check that multiple locmem caches are isolated" mirror_cache = get_cache('django.core.cache.backends.locmem.LocMemCache') other_cache = get_cache('django.core.cache.backends.locmem.LocMemCache', LOCATION='other') self.cache.set('value1', 42) self.assertEqual(mirror_cache.get('value1'), 42) self.assertEqual(other_cache.get('value1'), None) # memcached backend isn't guaranteed to be available. # To check the memcached backend, the test settings file will # need to contain a cache backend setting that points at # your memcache server. class MemcachedCacheTests(unittest.TestCase, BaseCacheTests): def setUp(self): name = settings.CACHES[DEFAULT_CACHE_ALIAS]['LOCATION'] self.cache = get_cache('django.core.cache.backends.memcached.MemcachedCache', LOCATION=name) self.prefix_cache = get_cache('django.core.cache.backends.memcached.MemcachedCache', LOCATION=name, KEY_PREFIX='cacheprefix') self.v2_cache = get_cache('django.core.cache.backends.memcached.MemcachedCache', LOCATION=name, VERSION=2) self.custom_key_cache = get_cache('django.core.cache.backends.memcached.MemcachedCache', LOCATION=name, KEY_FUNCTION=custom_key_func) self.custom_key_cache2 = get_cache('django.core.cache.backends.memcached.MemcachedCache', LOCATION=name, KEY_FUNCTION='regressiontests.cache.tests.custom_key_func') def tearDown(self): self.cache.clear() def test_invalid_keys(self): """ On memcached, we don't introduce a duplicate key validation step (for speed reasons), we just let the memcached API library raise its own exception on bad keys. Refs #6447. In order to be memcached-API-library agnostic, we only assert that a generic exception of some kind is raised. """ # memcached does not allow whitespace or control characters in keys self.assertRaises(Exception, self.cache.set, 'key with spaces', 'value') # memcached limits key length to 250 self.assertRaises(Exception, self.cache.set, 'a' * 251, 'value') MemcachedCacheTests = unittest.skipUnless(settings.CACHES[DEFAULT_CACHE_ALIAS]['BACKEND'].startswith('django.core.cache.backends.memcached.'), "memcached not available")(MemcachedCacheTests) class FileBasedCacheTests(unittest.TestCase, BaseCacheTests): """ Specific test cases for the file-based cache. """ def setUp(self): self.dirname = tempfile.mkdtemp() self.cache = get_cache('django.core.cache.backends.filebased.FileBasedCache', LOCATION=self.dirname, OPTIONS={'MAX_ENTRIES': 30}) self.prefix_cache = get_cache('django.core.cache.backends.filebased.FileBasedCache', LOCATION=self.dirname, KEY_PREFIX='cacheprefix') self.v2_cache = get_cache('django.core.cache.backends.filebased.FileBasedCache', LOCATION=self.dirname, VERSION=2) self.custom_key_cache = get_cache('django.core.cache.backends.filebased.FileBasedCache', LOCATION=self.dirname, KEY_FUNCTION=custom_key_func) self.custom_key_cache2 = get_cache('django.core.cache.backends.filebased.FileBasedCache', LOCATION=self.dirname, KEY_FUNCTION='regressiontests.cache.tests.custom_key_func') def tearDown(self): self.cache.clear() def test_hashing(self): """Test that keys are hashed into subdirectories correctly""" self.cache.set("foo", "bar") key = self.cache.make_key("foo") keyhash = md5_constructor(key).hexdigest() keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:]) self.assertTrue(os.path.exists(keypath)) def test_subdirectory_removal(self): """ Make sure that the created subdirectories are correctly removed when empty. """ self.cache.set("foo", "bar") key = self.cache.make_key("foo") keyhash = md5_constructor(key).hexdigest() keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:]) self.assertTrue(os.path.exists(keypath)) self.cache.delete("foo") self.assertTrue(not os.path.exists(keypath)) self.assertTrue(not os.path.exists(os.path.dirname(keypath))) self.assertTrue(not os.path.exists(os.path.dirname(os.path.dirname(keypath)))) def test_cull(self): self.perform_cull_test(50, 29) def test_old_initialization(self): self.cache = get_cache('file://%s?max_entries=30' % self.dirname) self.perform_cull_test(50, 29) class CustomCacheKeyValidationTests(unittest.TestCase): """ Tests for the ability to mixin a custom ``validate_key`` method to a custom cache backend that otherwise inherits from a builtin backend, and override the default key validation. Refs #6447. """ def test_custom_key_validation(self): cache = get_cache('regressiontests.cache.liberal_backend://') # this key is both longer than 250 characters, and has spaces key = 'some key with spaces' * 15 val = 'a value' cache.set(key, val) self.assertEqual(cache.get(key), val) class CacheUtils(unittest.TestCase): """TestCase for django.utils.cache functions.""" def setUp(self): self.path = '/cache/test/' self.old_cache_middleware_key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX self.old_cache_middleware_seconds = settings.CACHE_MIDDLEWARE_SECONDS self.orig_use_i18n = settings.USE_I18N settings.CACHE_MIDDLEWARE_KEY_PREFIX = 'settingsprefix' settings.CACHE_MIDDLEWARE_SECONDS = 1 settings.USE_I18N = False def tearDown(self): settings.CACHE_MIDDLEWARE_KEY_PREFIX = self.old_cache_middleware_key_prefix settings.CACHE_MIDDLEWARE_SECONDS = self.old_cache_middleware_seconds settings.USE_I18N = self.orig_use_i18n def _get_request(self, path, method='GET'): request = HttpRequest() request.META = { 'SERVER_NAME': 'testserver', 'SERVER_PORT': 80, } request.method = method request.path = request.path_info = "/cache/%s" % path return request def test_patch_vary_headers(self): headers = ( # Initial vary, new headers, resulting vary. (None, ('Accept-Encoding',), 'Accept-Encoding'), ('Accept-Encoding', ('accept-encoding',), 'Accept-Encoding'), ('Accept-Encoding', ('ACCEPT-ENCODING',), 'Accept-Encoding'), ('Cookie', ('Accept-Encoding',), 'Cookie, Accept-Encoding'), ('Cookie, Accept-Encoding', ('Accept-Encoding',), 'Cookie, Accept-Encoding'), ('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'), (None, ('Accept-Encoding', 'COOKIE'), 'Accept-Encoding, COOKIE'), ('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'), ('Cookie , Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'), ) for initial_vary, newheaders, resulting_vary in headers: response = HttpResponse() if initial_vary is not None: response['Vary'] = initial_vary patch_vary_headers(response, newheaders) self.assertEqual(response['Vary'], resulting_vary) def test_get_cache_key(self): request = self._get_request(self.path) response = HttpResponse() key_prefix = 'localprefix' # Expect None if no headers have been set yet. self.assertEqual(get_cache_key(request), None) # Set headers to an empty list. learn_cache_key(request, response) self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.GET.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e') # Verify that a specified key_prefix is taken into account. learn_cache_key(request, response, key_prefix=key_prefix) self.assertEqual(get_cache_key(request, key_prefix=key_prefix), 'views.decorators.cache.cache_page.localprefix.GET.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e') def test_get_cache_key_with_query(self): request = self._get_request(self.path + '?test=1') response = HttpResponse() # Expect None if no headers have been set yet. self.assertEqual(get_cache_key(request), None) # Set headers to an empty list. learn_cache_key(request, response) # Verify that the querystring is taken into account. self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.GET.bd889c5a59603af44333ed21504db3cd.d41d8cd98f00b204e9800998ecf8427e') def test_learn_cache_key(self): request = self._get_request(self.path, 'HEAD') response = HttpResponse() response['Vary'] = 'Pony' # Make sure that the Vary header is added to the key hash learn_cache_key(request, response) self.assertEqual(get_cache_key(request), 'views.decorators.cache.cache_page.settingsprefix.HEAD.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e') class PrefixedCacheUtils(CacheUtils): def setUp(self): super(PrefixedCacheUtils, self).setUp() self.old_cache_key_prefix = settings.CACHES['default'].get('KEY_PREFIX', None) settings.CACHES['default']['KEY_PREFIX'] = 'cacheprefix' def tearDown(self): super(PrefixedCacheUtils, self).tearDown() if self.old_cache_key_prefix is None: del settings.CACHES['default']['KEY_PREFIX'] else: settings.CACHES['default']['KEY_PREFIX'] = self.old_cache_key_prefix class CacheHEADTest(unittest.TestCase): def setUp(self): self.orig_cache_middleware_seconds = settings.CACHE_MIDDLEWARE_SECONDS self.orig_cache_middleware_key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX self.orig_caches = settings.CACHES settings.CACHE_MIDDLEWARE_SECONDS = 60 settings.CACHE_MIDDLEWARE_KEY_PREFIX = 'test' settings.CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache' } } self.path = '/cache/test/' def tearDown(self): settings.CACHE_MIDDLEWARE_SECONDS = self.orig_cache_middleware_seconds settings.CACHE_MIDDLEWARE_KEY_PREFIX = self.orig_cache_middleware_key_prefix settings.CACHES = self.orig_caches def _get_request(self, method): request = HttpRequest() request.META = { 'SERVER_NAME': 'testserver', 'SERVER_PORT': 80, } request.method = method request.path = request.path_info = self.path return request def _get_request_cache(self, method): request = self._get_request(method) request._cache_update_cache = True return request def _set_cache(self, request, msg): response = HttpResponse() response.content = msg return UpdateCacheMiddleware().process_response(request, response) def test_head_caches_correctly(self): test_content = 'test content' request = self._get_request_cache('HEAD') self._set_cache(request, test_content) request = self._get_request('HEAD') get_cache_data = FetchFromCacheMiddleware().process_request(request) self.assertNotEqual(get_cache_data, None) self.assertEqual(test_content, get_cache_data.content) def test_head_with_cached_get(self): test_content = 'test content' request = self._get_request_cache('GET') self._set_cache(request, test_content) request = self._get_request('HEAD') get_cache_data = FetchFromCacheMiddleware().process_request(request) self.assertNotEqual(get_cache_data, None) self.assertEqual(test_content, get_cache_data.content) class CacheI18nTest(unittest.TestCase): def setUp(self): self.orig_cache_middleware_seconds = settings.CACHE_MIDDLEWARE_SECONDS self.orig_cache_middleware_key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX self.orig_caches = settings.CACHES self.orig_use_i18n = settings.USE_I18N self.orig_languages = settings.LANGUAGES settings.LANGUAGES = ( ('en', 'English'), ('es', 'Spanish'), ) settings.CACHE_MIDDLEWARE_KEY_PREFIX = 'settingsprefix' self.path = '/cache/test/' def tearDown(self): settings.CACHE_MIDDLEWARE_SECONDS = self.orig_cache_middleware_seconds settings.CACHE_MIDDLEWARE_KEY_PREFIX = self.orig_cache_middleware_key_prefix settings.CACHES = self.orig_caches settings.USE_I18N = self.orig_use_i18n settings.LANGUAGES = self.orig_languages translation.deactivate() def _get_request(self): request = HttpRequest() request.META = { 'SERVER_NAME': 'testserver', 'SERVER_PORT': 80, } request.path = request.path_info = self.path return request def _get_request_cache(self, query_string=None): request = HttpRequest() request.META = { 'SERVER_NAME': 'testserver', 'SERVER_PORT': 80, } if query_string: request.META['QUERY_STRING'] = query_string request.GET = QueryDict(query_string) request.path = request.path_info = self.path request._cache_update_cache = True request.method = 'GET' request.session = {} return request def test_cache_key_i18n(self): settings.USE_I18N = True request = self._get_request() lang = translation.get_language() response = HttpResponse() key = learn_cache_key(request, response) self.assertTrue(key.endswith(lang), "Cache keys should include the language name when i18n is active") key2 = get_cache_key(request) self.assertEqual(key, key2) def test_cache_key_no_i18n (self): settings.USE_I18N = False request = self._get_request() lang = translation.get_language() response = HttpResponse() key = learn_cache_key(request, response) self.assertFalse(key.endswith(lang), "Cache keys shouldn't include the language name when i18n is inactive") def test_middleware(self): def set_cache(request, lang, msg): translation.activate(lang) response = HttpResponse() response.content= msg return UpdateCacheMiddleware().process_response(request, response) settings.CACHE_MIDDLEWARE_SECONDS = 60 settings.CACHE_MIDDLEWARE_KEY_PREFIX = "test" settings.CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache' } } settings.USE_ETAGS = True settings.USE_I18N = True # cache with non empty request.GET request = self._get_request_cache(query_string='foo=bar&other=true') get_cache_data = FetchFromCacheMiddleware().process_request(request) # first access, cache must return None self.assertEqual(get_cache_data, None) response = HttpResponse() content = 'Check for cache with QUERY_STRING' response.content = content UpdateCacheMiddleware().process_response(request, response) get_cache_data = FetchFromCacheMiddleware().process_request(request) # cache must return content self.assertNotEqual(get_cache_data, None) self.assertEqual(get_cache_data.content, content) # different QUERY_STRING, cache must be empty request = self._get_request_cache(query_string='foo=bar&somethingelse=true') get_cache_data = FetchFromCacheMiddleware().process_request(request) self.assertEqual(get_cache_data, None) # i18n tests en_message ="Hello world!" es_message ="Hola mundo!" request = self._get_request_cache() set_cache(request, 'en', en_message) get_cache_data = FetchFromCacheMiddleware().process_request(request) # Check that we can recover the cache self.assertNotEqual(get_cache_data.content, None) self.assertEqual(en_message, get_cache_data.content) # Check that we use etags self.assertTrue(get_cache_data.has_header('ETag')) # Check that we can disable etags settings.USE_ETAGS = False request._cache_update_cache = True set_cache(request, 'en', en_message) get_cache_data = FetchFromCacheMiddleware().process_request(request) self.assertFalse(get_cache_data.has_header('ETag')) # change the session language and set content request = self._get_request_cache() set_cache(request, 'es', es_message) # change again the language translation.activate('en') # retrieve the content from cache get_cache_data = FetchFromCacheMiddleware().process_request(request) self.assertEqual(get_cache_data.content, en_message) # change again the language translation.activate('es') get_cache_data = FetchFromCacheMiddleware().process_request(request) self.assertEqual(get_cache_data.content, es_message) class PrefixedCacheI18nTest(CacheI18nTest): def setUp(self): super(PrefixedCacheI18nTest, self).setUp() self.old_cache_key_prefix = settings.CACHES['default'].get('KEY_PREFIX', None) settings.CACHES['default']['KEY_PREFIX'] = 'cacheprefix' def tearDown(self): super(PrefixedCacheI18nTest, self).tearDown() if self.old_cache_key_prefix is not None: del settings.CACHES['default']['KEY_PREFIX'] else: settings.CACHES['default']['KEY_PREFIX'] = self.old_cache_key_prefix def hello_world_view(request, value): return HttpResponse('Hello World %s' % value) class CacheMiddlewareTest(unittest.TestCase): def setUp(self): self.factory = RequestFactory() self.orig_cache_middleware_alias = settings.CACHE_MIDDLEWARE_ALIAS self.orig_cache_middleware_key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX self.orig_cache_middleware_seconds = settings.CACHE_MIDDLEWARE_SECONDS self.orig_cache_middleware_anonymous_only = getattr(settings, 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY', False) self.orig_caches = settings.CACHES settings.CACHE_MIDDLEWARE_ALIAS = 'other' settings.CACHE_MIDDLEWARE_KEY_PREFIX = 'middlewareprefix' settings.CACHE_MIDDLEWARE_SECONDS = 30 settings.CACHE_MIDDLEWARE_ANONYMOUS_ONLY = False settings.CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache' }, 'other': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'other', 'TIMEOUT': '1' } } def tearDown(self): settings.CACHE_MIDDLEWARE_ALIAS = self.orig_cache_middleware_alias settings.CACHE_MIDDLEWARE_KEY_PREFIX = self.orig_cache_middleware_key_prefix settings.CACHE_MIDDLEWARE_SECONDS = self.orig_cache_middleware_seconds settings.CACHE_MIDDLEWARE_ANONYMOUS_ONLY = self.orig_cache_middleware_anonymous_only settings.CACHES = self.orig_caches def test_constructor(self): """ Ensure the constructor is correctly distinguishing between usage of CacheMiddleware as Middleware vs. usage of CacheMiddleware as view decorator and setting attributes appropriately. """ # If no arguments are passed in construction, it's being used as middleware. middleware = CacheMiddleware() # Now test object attributes against values defined in setUp above self.assertEqual(middleware.cache_timeout, 30) self.assertEqual(middleware.key_prefix, 'middlewareprefix') self.assertEqual(middleware.cache_alias, 'other') self.assertEqual(middleware.cache_anonymous_only, False) # If arguments are being passed in construction, it's being used as a decorator. # First, test with "defaults": as_view_decorator = CacheMiddleware(cache_alias=None, key_prefix=None) self.assertEqual(as_view_decorator.cache_timeout, 300) # Timeout value for 'default' cache, i.e. 300 self.assertEqual(as_view_decorator.key_prefix, '') self.assertEqual(as_view_decorator.cache_alias, 'default') # Value of DEFAULT_CACHE_ALIAS from django.core.cache self.assertEqual(as_view_decorator.cache_anonymous_only, False) # Next, test with custom values: as_view_decorator_with_custom = CacheMiddleware(cache_anonymous_only=True, cache_timeout=60, cache_alias='other', key_prefix='foo') self.assertEqual(as_view_decorator_with_custom.cache_timeout, 60) self.assertEqual(as_view_decorator_with_custom.key_prefix, 'foo') self.assertEqual(as_view_decorator_with_custom.cache_alias, 'other') self.assertEqual(as_view_decorator_with_custom.cache_anonymous_only, True) def test_middleware(self): middleware = CacheMiddleware() prefix_middleware = CacheMiddleware(key_prefix='prefix1') timeout_middleware = CacheMiddleware(cache_timeout=1) request = self.factory.get('/view/') # Put the request through the request middleware result = middleware.process_request(request) self.assertEqual(result, None) response = hello_world_view(request, '1') # Now put the response through the response middleware response = middleware.process_response(request, response) # Repeating the request should result in a cache hit result = middleware.process_request(request) self.assertNotEquals(result, None) self.assertEqual(result.content, 'Hello World 1') # The same request through a different middleware won't hit result = prefix_middleware.process_request(request) self.assertEqual(result, None) # The same request with a timeout _will_ hit result = timeout_middleware.process_request(request) self.assertNotEquals(result, None) self.assertEqual(result.content, 'Hello World 1') def test_cache_middleware_anonymous_only_wont_cause_session_access(self): """ The cache middleware shouldn't cause a session access due to CACHE_MIDDLEWARE_ANONYMOUS_ONLY if nothing else has accessed the session. Refs 13283 """ settings.CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.auth.middleware import AuthenticationMiddleware middleware = CacheMiddleware() session_middleware = SessionMiddleware() auth_middleware = AuthenticationMiddleware() request = self.factory.get('/view_anon/') # Put the request through the request middleware session_middleware.process_request(request) auth_middleware.process_request(request) result = middleware.process_request(request) self.assertEqual(result, None) response = hello_world_view(request, '1') # Now put the response through the response middleware session_middleware.process_response(request, response) response = middleware.process_response(request, response) self.assertEqual(request.session.accessed, False) def test_cache_middleware_anonymous_only_with_cache_page(self): """CACHE_MIDDLEWARE_ANONYMOUS_ONLY should still be effective when used with the cache_page decorator: the response to a request from an authenticated user should not be cached.""" settings.CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True request = self.factory.get('/view_anon/') class MockAuthenticatedUser(object): def is_authenticated(self): return True class MockAccessedSession(object): accessed = True request.user = MockAuthenticatedUser() request.session = MockAccessedSession() response = cache_page(hello_world_view)(request, '1') self.assertFalse("Cache-Control" in response) def test_view_decorator(self): # decorate the same view with different cache decorators default_view = cache_page(hello_world_view) default_with_prefix_view = cache_page(key_prefix='prefix1')(hello_world_view) explicit_default_view = cache_page(cache='default')(hello_world_view) explicit_default_with_prefix_view = cache_page(cache='default', key_prefix='prefix1')(hello_world_view) other_view = cache_page(cache='other')(hello_world_view) other_with_prefix_view = cache_page(cache='other', key_prefix='prefix2')(hello_world_view) other_with_timeout_view = cache_page(4, cache='other', key_prefix='prefix3')(hello_world_view) request = self.factory.get('/view/') # Request the view once response = default_view(request, '1') self.assertEqual(response.content, 'Hello World 1') # Request again -- hit the cache response = default_view(request, '2') self.assertEqual(response.content, 'Hello World 1') # Requesting the same view with the explicit cache should yield the same result response = explicit_default_view(request, '3') self.assertEqual(response.content, 'Hello World 1') # Requesting with a prefix will hit a different cache key response = explicit_default_with_prefix_view(request, '4') self.assertEqual(response.content, 'Hello World 4') # Hitting the same view again gives a cache hit response = explicit_default_with_prefix_view(request, '5') self.assertEqual(response.content, 'Hello World 4') # And going back to the implicit cache will hit the same cache response = default_with_prefix_view(request, '6') self.assertEqual(response.content, 'Hello World 4') # Requesting from an alternate cache won't hit cache response = other_view(request, '7') self.assertEqual(response.content, 'Hello World 7') # But a repeated hit will hit cache response = other_view(request, '8') self.assertEqual(response.content, 'Hello World 7') # And prefixing the alternate cache yields yet another cache entry response = other_with_prefix_view(request, '9') self.assertEqual(response.content, 'Hello World 9') # Request from the alternate cache with a new prefix and a custom timeout response = other_with_timeout_view(request, '10') self.assertEqual(response.content, 'Hello World 10') # But if we wait a couple of seconds... time.sleep(2) # ... the default cache will still hit cache = get_cache('default') response = default_view(request, '11') self.assertEqual(response.content, 'Hello World 1') # ... the default cache with a prefix will still hit response = default_with_prefix_view(request, '12') self.assertEqual(response.content, 'Hello World 4') # ... the explicit default cache will still hit response = explicit_default_view(request, '13') self.assertEqual(response.content, 'Hello World 1') # ... the explicit default cache with a prefix will still hit response = explicit_default_with_prefix_view(request, '14') self.assertEqual(response.content, 'Hello World 4') # .. but a rapidly expiring cache won't hit response = other_view(request, '15') self.assertEqual(response.content, 'Hello World 15') # .. even if it has a prefix response = other_with_prefix_view(request, '16') self.assertEqual(response.content, 'Hello World 16') # ... but a view with a custom timeout will still hit response = other_with_timeout_view(request, '17') self.assertEqual(response.content, 'Hello World 10') # And if we wait a few more seconds time.sleep(2) # the custom timeouot cache will miss response = other_with_timeout_view(request, '18') self.assertEqual(response.content, 'Hello World 18') if __name__ == '__main__': unittest.main()
64,411
Python
.py
1,191
45.025189
190
0.658256
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,023
liberal_backend.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/cache/liberal_backend.py
from django.core.cache.backends.locmem import LocMemCache class LiberalKeyValidationMixin(object): def validate_key(self, key): pass class CacheClass(LiberalKeyValidationMixin, LocMemCache): pass
215
Python
.py
6
31.666667
57
0.805825
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,024
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/requests/tests.py
import time from datetime import datetime, timedelta from StringIO import StringIO from django.core.handlers.modpython import ModPythonRequest from django.core.handlers.wsgi import WSGIRequest, LimitedStream from django.http import HttpRequest, HttpResponse, parse_cookie from django.utils import unittest from django.utils.http import cookie_date class RequestsTests(unittest.TestCase): def test_httprequest(self): request = HttpRequest() self.assertEqual(request.GET.keys(), []) self.assertEqual(request.POST.keys(), []) self.assertEqual(request.COOKIES.keys(), []) self.assertEqual(request.META.keys(), []) def test_wsgirequest(self): request = WSGIRequest({'PATH_INFO': 'bogus', 'REQUEST_METHOD': 'bogus', 'wsgi.input': StringIO('')}) self.assertEqual(request.GET.keys(), []) self.assertEqual(request.POST.keys(), []) self.assertEqual(request.COOKIES.keys(), []) self.assertEqual(set(request.META.keys()), set(['PATH_INFO', 'REQUEST_METHOD', 'SCRIPT_NAME', 'wsgi.input'])) self.assertEqual(request.META['PATH_INFO'], 'bogus') self.assertEqual(request.META['REQUEST_METHOD'], 'bogus') self.assertEqual(request.META['SCRIPT_NAME'], '') def test_modpythonrequest(self): class FakeModPythonRequest(ModPythonRequest): def __init__(self, *args, **kwargs): super(FakeModPythonRequest, self).__init__(*args, **kwargs) self._get = self._post = self._meta = self._cookies = {} class Dummy: def get_options(self): return {} req = Dummy() req.uri = 'bogus' request = FakeModPythonRequest(req) self.assertEqual(request.path, 'bogus') self.assertEqual(request.GET.keys(), []) self.assertEqual(request.POST.keys(), []) self.assertEqual(request.COOKIES.keys(), []) self.assertEqual(request.META.keys(), []) def test_parse_cookie(self): self.assertEqual(parse_cookie('invalid:key=true'), {}) def test_httprequest_location(self): request = HttpRequest() self.assertEqual(request.build_absolute_uri(location="https://www.example.com/asdf"), 'https://www.example.com/asdf') request.get_host = lambda: 'www.example.com' request.path = '' self.assertEqual(request.build_absolute_uri(location="/path/with:colons"), 'http://www.example.com/path/with:colons') def test_near_expiration(self): "Cookie will expire when an near expiration time is provided" response = HttpResponse() # There is a timing weakness in this test; The # expected result for max-age requires that there be # a very slight difference between the evaluated expiration # time, and the time evaluated in set_cookie(). If this # difference doesn't exist, the cookie time will be # 1 second larger. To avoid the problem, put in a quick sleep, # which guarantees that there will be a time difference. expires = datetime.utcnow() + timedelta(seconds=10) time.sleep(0.001) response.set_cookie('datetime', expires=expires) datetime_cookie = response.cookies['datetime'] self.assertEqual(datetime_cookie['max-age'], 10) def test_far_expiration(self): "Cookie will expire when an distant expiration time is provided" response = HttpResponse() response.set_cookie('datetime', expires=datetime(2028, 1, 1, 4, 5, 6)) datetime_cookie = response.cookies['datetime'] self.assertEqual(datetime_cookie['expires'], 'Sat, 01-Jan-2028 04:05:06 GMT') def test_max_age_expiration(self): "Cookie will expire if max_age is provided" response = HttpResponse() response.set_cookie('max_age', max_age=10) max_age_cookie = response.cookies['max_age'] self.assertEqual(max_age_cookie['max-age'], 10) self.assertEqual(max_age_cookie['expires'], cookie_date(time.time()+10)) def test_httponly_cookie(self): response = HttpResponse() response.set_cookie('example', httponly=True) example_cookie = response.cookies['example'] # A compat cookie may be in use -- check that it has worked # both as an output string, and using the cookie attributes self.assertTrue('; httponly' in str(example_cookie)) self.assertTrue(example_cookie['httponly']) def test_limited_stream(self): # Read all of a limited stream stream = LimitedStream(StringIO('test'), 2) self.assertEqual(stream.read(), 'te') # Reading again returns nothing. self.assertEqual(stream.read(), '') # Read a number of characters greater than the stream has to offer stream = LimitedStream(StringIO('test'), 2) self.assertEqual(stream.read(5), 'te') # Reading again returns nothing. self.assertEqual(stream.readline(5), '') # Read sequentially from a stream stream = LimitedStream(StringIO('12345678'), 8) self.assertEqual(stream.read(5), '12345') self.assertEqual(stream.read(5), '678') # Reading again returns nothing. self.assertEqual(stream.readline(5), '') # Read lines from a stream stream = LimitedStream(StringIO('1234\n5678\nabcd\nefgh\nijkl'), 24) # Read a full line, unconditionally self.assertEqual(stream.readline(), '1234\n') # Read a number of characters less than a line self.assertEqual(stream.readline(2), '56') # Read the rest of the partial line self.assertEqual(stream.readline(), '78\n') # Read a full line, with a character limit greater than the line length self.assertEqual(stream.readline(6), 'abcd\n') # Read the next line, deliberately terminated at the line end self.assertEqual(stream.readline(4), 'efgh') # Read the next line... just the line end self.assertEqual(stream.readline(), '\n') # Read everything else. self.assertEqual(stream.readline(), 'ijkl') # Regression for #15018 # If a stream contains a newline, but the provided length # is less than the number of provided characters, the newline # doesn't reset the available character count stream = LimitedStream(StringIO('1234\nabcdef'), 9) self.assertEqual(stream.readline(10), '1234\n') self.assertEqual(stream.readline(3), 'abc') # Now expire the available characters self.assertEqual(stream.readline(3), 'd') # Reading again returns nothing. self.assertEqual(stream.readline(2), '') # Same test, but with read, not readline. stream = LimitedStream(StringIO('1234\nabcdef'), 9) self.assertEqual(stream.read(6), '1234\na') self.assertEqual(stream.read(2), 'bc') self.assertEqual(stream.read(2), 'd') self.assertEqual(stream.read(2), '') self.assertEqual(stream.read(), '') def test_stream(self): request = WSGIRequest({'REQUEST_METHOD': 'POST', 'wsgi.input': StringIO('name=value')}) self.assertEqual(request.read(), 'name=value') def test_read_after_value(self): """ Reading from request is allowed after accessing request contents as POST or raw_post_data. """ request = WSGIRequest({'REQUEST_METHOD': 'POST', 'wsgi.input': StringIO('name=value')}) self.assertEqual(request.POST, {u'name': [u'value']}) self.assertEqual(request.raw_post_data, 'name=value') self.assertEqual(request.read(), 'name=value') def test_value_after_read(self): """ Construction of POST or raw_post_data is not allowed after reading from request. """ request = WSGIRequest({'REQUEST_METHOD': 'POST', 'wsgi.input': StringIO('name=value')}) self.assertEqual(request.read(2), 'na') self.assertRaises(Exception, lambda: request.raw_post_data) self.assertEqual(request.POST, {}) def test_read_by_lines(self): request = WSGIRequest({'REQUEST_METHOD': 'POST', 'wsgi.input': StringIO('name=value')}) self.assertEqual(list(request), ['name=value'])
8,301
Python
.py
161
42.981366
117
0.654552
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,025
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/many_to_one_regress/models.py
""" Regression tests for a few ForeignKey bugs. """ from django.db import models # If ticket #1578 ever slips back in, these models will not be able to be # created (the field names being lower-cased versions of their opposite # classes is important here). class First(models.Model): second = models.IntegerField() class Second(models.Model): first = models.ForeignKey(First, related_name = 'the_first') # Protect against repetition of #1839, #2415 and #2536. class Third(models.Model): name = models.CharField(max_length=20) third = models.ForeignKey('self', null=True, related_name='child_set') class Parent(models.Model): name = models.CharField(max_length=20) bestchild = models.ForeignKey('Child', null=True, related_name='favored_by') class Child(models.Model): name = models.CharField(max_length=20) parent = models.ForeignKey(Parent) # Multiple paths to the same model (#7110, #7125) class Category(models.Model): name = models.CharField(max_length=20) def __unicode__(self): return self.name class Record(models.Model): category = models.ForeignKey(Category) class Relation(models.Model): left = models.ForeignKey(Record, related_name='left_set') right = models.ForeignKey(Record, related_name='right_set') def __unicode__(self): return u"%s - %s" % (self.left.category.name, self.right.category.name)
1,396
Python
.py
33
38.727273
80
0.732593
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,026
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/many_to_one_regress/tests.py
from django.db import models from django.test import TestCase from models import First, Second, Third, Parent, Child, Category, Record, Relation class ManyToOneRegressionTests(TestCase): def test_object_creation(self): Third.objects.create(id='3', name='An example') parent = Parent(name='fred') parent.save() Child.objects.create(name='bam-bam', parent=parent) def test_fk_assignment_and_related_object_cache(self): # Tests of ForeignKey assignment and the related-object cache (see #6886). p = Parent.objects.create(name="Parent") c = Child.objects.create(name="Child", parent=p) # Look up the object again so that we get a "fresh" object. c = Child.objects.get(name="Child") p = c.parent # Accessing the related object again returns the exactly same object. self.assertTrue(c.parent is p) # But if we kill the cache, we get a new object. del c._parent_cache self.assertFalse(c.parent is p) # Assigning a new object results in that object getting cached immediately. p2 = Parent.objects.create(name="Parent 2") c.parent = p2 self.assertTrue(c.parent is p2) # Assigning None succeeds if field is null=True. p.bestchild = None self.assertTrue(p.bestchild is None) # bestchild should still be None after saving. p.save() self.assertTrue(p.bestchild is None) # bestchild should still be None after fetching the object again. p = Parent.objects.get(name="Parent") self.assertTrue(p.bestchild is None) # Assigning None fails: Child.parent is null=False. self.assertRaises(ValueError, setattr, c, "parent", None) # You also can't assign an object of the wrong type here self.assertRaises(ValueError, setattr, c, "parent", First(id=1, second=1)) # Nor can you explicitly assign None to Child.parent during object # creation (regression for #9649). self.assertRaises(ValueError, Child, name='xyzzy', parent=None) self.assertRaises(ValueError, Child.objects.create, name='xyzzy', parent=None) # Creation using keyword argument should cache the related object. p = Parent.objects.get(name="Parent") c = Child(parent=p) self.assertTrue(c.parent is p) # Creation using keyword argument and unsaved related instance (#8070). p = Parent() c = Child(parent=p) self.assertTrue(c.parent is p) # Creation using attname keyword argument and an id will cause the # related object to be fetched. p = Parent.objects.get(name="Parent") c = Child(parent_id=p.id) self.assertFalse(c.parent is p) self.assertEqual(c.parent, p) def test_multiple_foreignkeys(self): # Test of multiple ForeignKeys to the same model (bug #7125). c1 = Category.objects.create(name='First') c2 = Category.objects.create(name='Second') c3 = Category.objects.create(name='Third') r1 = Record.objects.create(category=c1) r2 = Record.objects.create(category=c1) r3 = Record.objects.create(category=c2) r4 = Record.objects.create(category=c2) r5 = Record.objects.create(category=c3) r = Relation.objects.create(left=r1, right=r2) r = Relation.objects.create(left=r3, right=r4) r = Relation.objects.create(left=r1, right=r3) r = Relation.objects.create(left=r5, right=r2) r = Relation.objects.create(left=r3, right=r2) q1 = Relation.objects.filter(left__category__name__in=['First'], right__category__name__in=['Second']) self.assertQuerysetEqual(q1, ["<Relation: First - Second>"]) q2 = Category.objects.filter(record__left_set__right__category__name='Second').order_by('name') self.assertQuerysetEqual(q2, ["<Category: First>", "<Category: Second>"]) p = Parent.objects.create(name="Parent") c = Child.objects.create(name="Child", parent=p) self.assertRaises(ValueError, Child.objects.create, name="Grandchild", parent=c) def test_fk_instantiation_outside_model(self): # Regression for #12190 -- Should be able to instantiate a FK outside # of a model, and interrogate its related field. cat = models.ForeignKey(Category) self.assertEqual('id', cat.rel.get_related_field().name)
4,466
Python
.py
83
45.120482
110
0.665902
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,027
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/text/tests.py
# coding: utf-8 from django.test import TestCase from django.utils.text import * from django.utils.http import urlquote, urlquote_plus, cookie_date, http_date from django.utils.encoding import iri_to_uri from django.utils.translation import activate, deactivate class TextTests(TestCase): """ Tests for stuff in django.utils.text and other text munging util functions. """ def test_get_text_list(self): self.assertEqual(get_text_list(['a', 'b', 'c', 'd']), u'a, b, c or d') self.assertEqual(get_text_list(['a', 'b', 'c'], 'and'), u'a, b and c') self.assertEqual(get_text_list(['a', 'b'], 'and'), u'a and b') self.assertEqual(get_text_list(['a']), u'a') self.assertEqual(get_text_list([]), u'') activate('ar') self.assertEqual(get_text_list(['a', 'b', 'c']), u"a، b أو c") deactivate() def test_smart_split(self): self.assertEqual(list(smart_split(r'''This is "a person" test.''')), [u'This', u'is', u'"a person"', u'test.']) self.assertEqual(list(smart_split(r'''This is "a person's" test.'''))[2], u'"a person\'s"') self.assertEqual(list(smart_split(r'''This is "a person\"s" test.'''))[2], u'"a person\\"s"') self.assertEqual(list(smart_split('''"a 'one''')), [u'"a', u"'one"]) self.assertEqual(list(smart_split(r'''all friends' tests'''))[1], "friends'") self.assertEqual(list(smart_split(u'url search_page words="something else"')), [u'url', u'search_page', u'words="something else"']) self.assertEqual(list(smart_split(u"url search_page words='something else'")), [u'url', u'search_page', u"words='something else'"]) self.assertEqual(list(smart_split(u'url search_page words "something else"')), [u'url', u'search_page', u'words', u'"something else"']) self.assertEqual(list(smart_split(u'url search_page words-"something else"')), [u'url', u'search_page', u'words-"something else"']) self.assertEqual(list(smart_split(u'url search_page words=hello')), [u'url', u'search_page', u'words=hello']) self.assertEqual(list(smart_split(u'url search_page words="something else')), [u'url', u'search_page', u'words="something', u'else']) self.assertEqual(list(smart_split("cut:','|cut:' '")), [u"cut:','|cut:' '"]) def test_urlquote(self): self.assertEqual(urlquote(u'Paris & Orl\xe9ans'), u'Paris%20%26%20Orl%C3%A9ans') self.assertEqual(urlquote(u'Paris & Orl\xe9ans', safe="&"), u'Paris%20&%20Orl%C3%A9ans') self.assertEqual(urlquote_plus(u'Paris & Orl\xe9ans'), u'Paris+%26+Orl%C3%A9ans') self.assertEqual(urlquote_plus(u'Paris & Orl\xe9ans', safe="&"), u'Paris+&+Orl%C3%A9ans') def test_cookie_date(self): t = 1167616461.0 self.assertEqual(cookie_date(t), 'Mon, 01-Jan-2007 01:54:21 GMT') def test_http_date(self): t = 1167616461.0 self.assertEqual(http_date(t), 'Mon, 01 Jan 2007 01:54:21 GMT') def test_iri_to_uri(self): self.assertEqual(iri_to_uri(u'red%09ros\xe9#red'), 'red%09ros%C3%A9#red') self.assertEqual(iri_to_uri(u'/blog/for/J\xfcrgen M\xfcnster/'), '/blog/for/J%C3%BCrgen%20M%C3%BCnster/') self.assertEqual(iri_to_uri(u'locations/%s' % urlquote_plus(u'Paris & Orl\xe9ans')), 'locations/Paris+%26+Orl%C3%A9ans') def test_iri_to_uri_idempotent(self): self.assertEqual(iri_to_uri(iri_to_uri(u'red%09ros\xe9#red')), 'red%09ros%C3%A9#red')
3,699
Python
.py
68
45.294118
92
0.605438
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,028
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/app_loading/tests.py
import copy import os import sys import time from django.conf import Settings from django.db.models.loading import cache, load_app from django.utils.unittest import TestCase class InstalledAppsGlobbingTest(TestCase): def setUp(self): self.OLD_SYS_PATH = sys.path[:] sys.path.append(os.path.dirname(os.path.abspath(__file__))) self.OLD_TZ = os.environ.get("TZ") def test_globbing(self): settings = Settings('test_settings') self.assertEqual(settings.INSTALLED_APPS, ['parent.app', 'parent.app1', 'parent.app_2']) def tearDown(self): sys.path = self.OLD_SYS_PATH if hasattr(time, "tzset") and self.OLD_TZ: os.environ["TZ"] = self.OLD_TZ time.tzset() class EggLoadingTest(TestCase): def setUp(self): self.old_path = sys.path[:] self.egg_dir = '%s/eggs' % os.path.dirname(__file__) # This test adds dummy applications to the app cache. These # need to be removed in order to prevent bad interactions # with the flush operation in other tests. self.old_app_models = copy.deepcopy(cache.app_models) self.old_app_store = copy.deepcopy(cache.app_store) def tearDown(self): sys.path = self.old_path cache.app_models = self.old_app_models cache.app_store = self.old_app_store def test_egg1(self): """Models module can be loaded from an app in an egg""" egg_name = '%s/modelapp.egg' % self.egg_dir sys.path.append(egg_name) models = load_app('app_with_models') self.assertFalse(models is None) def test_egg2(self): """Loading an app from an egg that has no models returns no models (and no error)""" egg_name = '%s/nomodelapp.egg' % self.egg_dir sys.path.append(egg_name) models = load_app('app_no_models') self.assertTrue(models is None) def test_egg3(self): """Models module can be loaded from an app located under an egg's top-level package""" egg_name = '%s/omelet.egg' % self.egg_dir sys.path.append(egg_name) models = load_app('omelet.app_with_models') self.assertFalse(models is None) def test_egg4(self): """Loading an app with no models from under the top-level egg package generates no error""" egg_name = '%s/omelet.egg' % self.egg_dir sys.path.append(egg_name) models = load_app('omelet.app_no_models') self.assertTrue(models is None) def test_egg5(self): """Loading an app from an egg that has an import error in its models module raises that error""" egg_name = '%s/brokenapp.egg' % self.egg_dir sys.path.append(egg_name) self.assertRaises(ImportError, load_app, 'broken_app') try: load_app('broken_app') except ImportError, e: # Make sure the message is indicating the actual # problem in the broken app. self.assertTrue("modelz" in e.args[0])
3,019
Python
.py
68
36.470588
104
0.643733
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,029
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/generic_relations_regress/models.py
from django.db import models from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType __all__ = ('Link', 'Place', 'Restaurant', 'Person', 'Address', 'CharLink', 'TextLink', 'OddRelation1', 'OddRelation2', 'Contact', 'Organization', 'Note') class Link(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey() def __unicode__(self): return "Link to %s id=%s" % (self.content_type, self.object_id) class Place(models.Model): name = models.CharField(max_length=100) links = generic.GenericRelation(Link) def __unicode__(self): return "Place: %s" % self.name class Restaurant(Place): def __unicode__(self): return "Restaurant: %s" % self.name class Address(models.Model): street = models.CharField(max_length=80) city = models.CharField(max_length=50) state = models.CharField(max_length=2) zipcode = models.CharField(max_length=5) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey() def __unicode__(self): return '%s %s, %s %s' % (self.street, self.city, self.state, self.zipcode) class Person(models.Model): account = models.IntegerField(primary_key=True) name = models.CharField(max_length=128) addresses = generic.GenericRelation(Address) def __unicode__(self): return self.name class CharLink(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.CharField(max_length=100) content_object = generic.GenericForeignKey() class TextLink(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.TextField() content_object = generic.GenericForeignKey() class OddRelation1(models.Model): name = models.CharField(max_length=100) clinks = generic.GenericRelation(CharLink) class OddRelation2(models.Model): name = models.CharField(max_length=100) tlinks = generic.GenericRelation(TextLink) # models for test_q_object_or: class Note(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey() note = models.TextField() class Contact(models.Model): notes = generic.GenericRelation(Note) class Organization(models.Model): name = models.CharField(max_length=255) contacts = models.ManyToManyField(Contact, related_name='organizations')
2,612
Python
.py
61
38.04918
82
0.727596
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,030
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/generic_relations_regress/tests.py
from django.test import TestCase from django.contrib.contenttypes.models import ContentType from django.db.models import Q from models import * class GenericRelationTests(TestCase): def test_inherited_models_content_type(self): """ Test that GenericRelations on inherited classes use the correct content type. """ p = Place.objects.create(name="South Park") r = Restaurant.objects.create(name="Chubby's") l1 = Link.objects.create(content_object=p) l2 = Link.objects.create(content_object=r) self.assertEqual(list(p.links.all()), [l1]) self.assertEqual(list(r.links.all()), [l2]) def test_reverse_relation_pk(self): """ Test that the correct column name is used for the primary key on the originating model of a query. See #12664. """ p = Person.objects.create(account=23, name='Chef') a = Address.objects.create(street='123 Anywhere Place', city='Conifer', state='CO', zipcode='80433', content_object=p) qs = Person.objects.filter(addresses__zipcode='80433') self.assertEqual(1, qs.count()) self.assertEqual('Chef', qs[0].name) def test_charlink_delete(self): oddrel = OddRelation1.objects.create(name='clink') cl = CharLink.objects.create(content_object=oddrel) oddrel.delete() def test_textlink_delete(self): oddrel = OddRelation2.objects.create(name='tlink') tl = TextLink.objects.create(content_object=oddrel) oddrel.delete() def test_q_object_or(self): """ Tests that SQL query parameters for generic relations are properly grouped when OR is used. Test for bug http://code.djangoproject.com/ticket/11535 In this bug the first query (below) works while the second, with the query parameters the same but in reverse order, does not. The issue is that the generic relation conditions do not get properly grouped in parentheses. """ note_contact = Contact.objects.create() org_contact = Contact.objects.create() note = Note.objects.create(note='note', content_object=note_contact) org = Organization.objects.create(name='org name') org.contacts.add(org_contact) # search with a non-matching note and a matching org name qs = Contact.objects.filter(Q(notes__note__icontains=r'other note') | Q(organizations__name__icontains=r'org name')) self.assertTrue(org_contact in qs) # search again, with the same query parameters, in reverse order qs = Contact.objects.filter( Q(organizations__name__icontains=r'org name') | Q(notes__note__icontains=r'other note')) self.assertTrue(org_contact in qs)
2,909
Python
.py
60
38.883333
79
0.647972
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,031
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/httpwrappers/tests.py
import copy import pickle from django.http import (QueryDict, HttpResponse, SimpleCookie, BadHeaderError, parse_cookie) from django.utils import unittest class QueryDictTests(unittest.TestCase): def test_missing_key(self): q = QueryDict('') self.assertRaises(KeyError, q.__getitem__, 'foo') def test_immutability(self): q = QueryDict('') self.assertRaises(AttributeError, q.__setitem__, 'something', 'bar') self.assertRaises(AttributeError, q.setlist, 'foo', ['bar']) self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar']) self.assertRaises(AttributeError, q.update, {'foo': 'bar'}) self.assertRaises(AttributeError, q.pop, 'foo') self.assertRaises(AttributeError, q.popitem) self.assertRaises(AttributeError, q.clear) def test_immutable_get_with_default(self): q = QueryDict('') self.assertEqual(q.get('foo', 'default'), 'default') def test_immutable_basic_operations(self): q = QueryDict('') self.assertEqual(q.getlist('foo'), []) self.assertEqual(q.has_key('foo'), False) self.assertEqual('foo' in q, False) self.assertEqual(q.items(), []) self.assertEqual(q.lists(), []) self.assertEqual(q.items(), []) self.assertEqual(q.keys(), []) self.assertEqual(q.values(), []) self.assertEqual(len(q), 0) self.assertEqual(q.urlencode(), '') def test_single_key_value(self): """Test QueryDict with one key/value pair""" q = QueryDict('foo=bar') self.assertEqual(q['foo'], 'bar') self.assertRaises(KeyError, q.__getitem__, 'bar') self.assertRaises(AttributeError, q.__setitem__, 'something', 'bar') self.assertEqual(q.get('foo', 'default'), 'bar') self.assertEqual(q.get('bar', 'default'), 'default') self.assertEqual(q.getlist('foo'), ['bar']) self.assertEqual(q.getlist('bar'), []) self.assertRaises(AttributeError, q.setlist, 'foo', ['bar']) self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar']) self.assertTrue(q.has_key('foo')) self.assertTrue('foo' in q) self.assertFalse(q.has_key('bar')) self.assertFalse('bar' in q) self.assertEqual(q.items(), [(u'foo', u'bar')]) self.assertEqual(q.lists(), [(u'foo', [u'bar'])]) self.assertEqual(q.keys(), ['foo']) self.assertEqual(q.values(), ['bar']) self.assertEqual(len(q), 1) self.assertRaises(AttributeError, q.update, {'foo': 'bar'}) self.assertRaises(AttributeError, q.pop, 'foo') self.assertRaises(AttributeError, q.popitem) self.assertRaises(AttributeError, q.clear) self.assertRaises(AttributeError, q.setdefault, 'foo', 'bar') self.assertEqual(q.urlencode(), 'foo=bar') def test_urlencode(self): q = QueryDict('', mutable=True) q['next'] = '/a&b/' self.assertEqual(q.urlencode(), 'next=%2Fa%26b%2F') self.assertEqual(q.urlencode(safe='/'), 'next=/a%26b/') q = QueryDict('', mutable=True) q['next'] = u'/t\xebst&key/' self.assertEqual(q.urlencode(), 'next=%2Ft%C3%ABst%26key%2F') self.assertEqual(q.urlencode(safe='/'), 'next=/t%C3%ABst%26key/') def test_mutable_copy(self): """A copy of a QueryDict is mutable.""" q = QueryDict('').copy() self.assertRaises(KeyError, q.__getitem__, "foo") q['name'] = 'john' self.assertEqual(q['name'], 'john') def test_mutable_delete(self): q = QueryDict('').copy() q['name'] = 'john' del q['name'] self.assertFalse('name' in q) def test_basic_mutable_operations(self): q = QueryDict('').copy() q['name'] = 'john' self.assertEqual(q.get('foo', 'default'), 'default') self.assertEqual(q.get('name', 'default'), 'john') self.assertEqual(q.getlist('name'), ['john']) self.assertEqual(q.getlist('foo'), []) q.setlist('foo', ['bar', 'baz']) self.assertEqual(q.get('foo', 'default'), 'baz') self.assertEqual(q.getlist('foo'), ['bar', 'baz']) q.appendlist('foo', 'another') self.assertEqual(q.getlist('foo'), ['bar', 'baz', 'another']) self.assertEqual(q['foo'], 'another') self.assertTrue(q.has_key('foo')) self.assertTrue('foo' in q) self.assertEqual(q.items(), [(u'foo', u'another'), (u'name', u'john')]) self.assertEqual(q.lists(), [(u'foo', [u'bar', u'baz', u'another']), (u'name', [u'john'])]) self.assertEqual(q.keys(), [u'foo', u'name']) self.assertEqual(q.values(), [u'another', u'john']) self.assertEqual(len(q), 2) q.update({'foo': 'hello'}) self.assertEqual(q['foo'], 'hello') self.assertEqual(q.get('foo', 'not available'), 'hello') self.assertEqual(q.getlist('foo'), [u'bar', u'baz', u'another', u'hello']) self.assertEqual(q.pop('foo'), [u'bar', u'baz', u'another', u'hello']) self.assertEqual(q.pop('foo', 'not there'), 'not there') self.assertEqual(q.get('foo', 'not there'), 'not there') self.assertEqual(q.setdefault('foo', 'bar'), 'bar') self.assertEqual(q['foo'], 'bar') self.assertEqual(q.getlist('foo'), ['bar']) self.assertEqual(q.urlencode(), 'foo=bar&name=john') q.clear() self.assertEqual(len(q), 0) def test_multiple_keys(self): """Test QueryDict with two key/value pairs with same keys.""" q = QueryDict('vote=yes&vote=no') self.assertEqual(q['vote'], u'no') self.assertRaises(AttributeError, q.__setitem__, 'something', 'bar') self.assertEqual(q.get('vote', 'default'), u'no') self.assertEqual(q.get('foo', 'default'), 'default') self.assertEqual(q.getlist('vote'), [u'yes', u'no']) self.assertEqual(q.getlist('foo'), []) self.assertRaises(AttributeError, q.setlist, 'foo', ['bar', 'baz']) self.assertRaises(AttributeError, q.setlist, 'foo', ['bar', 'baz']) self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar']) self.assertEqual(q.has_key('vote'), True) self.assertEqual('vote' in q, True) self.assertEqual(q.has_key('foo'), False) self.assertEqual('foo' in q, False) self.assertEqual(q.items(), [(u'vote', u'no')]) self.assertEqual(q.lists(), [(u'vote', [u'yes', u'no'])]) self.assertEqual(q.keys(), [u'vote']) self.assertEqual(q.values(), [u'no']) self.assertEqual(len(q), 1) self.assertRaises(AttributeError, q.update, {'foo': 'bar'}) self.assertRaises(AttributeError, q.pop, 'foo') self.assertRaises(AttributeError, q.popitem) self.assertRaises(AttributeError, q.clear) self.assertRaises(AttributeError, q.setdefault, 'foo', 'bar') self.assertRaises(AttributeError, q.__delitem__, 'vote') def test_invalid_input_encoding(self): """ QueryDicts must be able to handle invalid input encoding (in this case, bad UTF-8 encoding). """ q = QueryDict('foo=bar&foo=\xff') self.assertEqual(q['foo'], u'\ufffd') self.assertEqual(q.getlist('foo'), [u'bar', u'\ufffd']) def test_pickle(self): q = QueryDict('') q1 = pickle.loads(pickle.dumps(q, 2)) self.assertEqual(q == q1, True) q = QueryDict('a=b&c=d') q1 = pickle.loads(pickle.dumps(q, 2)) self.assertEqual(q == q1, True) q = QueryDict('a=b&c=d&a=1') q1 = pickle.loads(pickle.dumps(q, 2)) self.assertEqual(q == q1 , True) def test_update_from_querydict(self): """Regression test for #8278: QueryDict.update(QueryDict)""" x = QueryDict("a=1&a=2", mutable=True) y = QueryDict("a=3&a=4") x.update(y) self.assertEqual(x.getlist('a'), [u'1', u'2', u'3', u'4']) def test_non_default_encoding(self): """#13572 - QueryDict with a non-default encoding""" q = QueryDict('sbb=one', encoding='rot_13') self.assertEqual(q.encoding , 'rot_13' ) self.assertEqual(q.items() , [(u'foo', u'bar')] ) self.assertEqual(q.urlencode() , 'sbb=one' ) q = q.copy() self.assertEqual(q.encoding , 'rot_13' ) self.assertEqual(q.items() , [(u'foo', u'bar')] ) self.assertEqual(q.urlencode() , 'sbb=one' ) self.assertEqual(copy.copy(q).encoding , 'rot_13' ) self.assertEqual(copy.deepcopy(q).encoding , 'rot_13') class HttpResponseTests(unittest.TestCase): def test_unicode_headers(self): r = HttpResponse() # If we insert a unicode value it will be converted to an ascii r['value'] = u'test value' self.assertTrue(isinstance(r['value'], str)) # An error is raised ~hen a unicode object with non-ascii is assigned. self.assertRaises(UnicodeEncodeError, r.__setitem__, 'value', u't\xebst value') # An error is raised when a unicode object with non-ASCII format is # passed as initial mimetype or content_type. self.assertRaises(UnicodeEncodeError, HttpResponse, mimetype=u't\xebst value') # HttpResponse headers must be convertible to ASCII. self.assertRaises(UnicodeEncodeError, HttpResponse, content_type=u't\xebst value') # The response also converts unicode keys to strings.) r[u'test'] = 'testing key' l = list(r.items()) l.sort() self.assertEqual(l[1], ('test', 'testing key')) # It will also raise errors for keys with non-ascii data. self.assertRaises(UnicodeEncodeError, r.__setitem__, u't\xebst key', 'value') def test_newlines_in_headers(self): # Bug #10188: Do not allow newlines in headers (CR or LF) r = HttpResponse() self.assertRaises(BadHeaderError, r.__setitem__, 'test\rstr', 'test') self.assertRaises(BadHeaderError, r.__setitem__, 'test\nstr', 'test') class CookieTests(unittest.TestCase): def test_encode(self): """ Test that we don't output tricky characters in encoded value """ # Python 2.4 compatibility note: Python 2.4's cookie implementation # always returns Set-Cookie headers terminating in semi-colons. # That's not the bug this test is looking for, so ignore it. c = SimpleCookie() c['test'] = "An,awkward;value" self.assertTrue(";" not in c.output().rstrip(';')) # IE compat self.assertTrue("," not in c.output().rstrip(';')) # Safari compat def test_decode(self): """ Test that we can still preserve semi-colons and commas """ c = SimpleCookie() c['test'] = "An,awkward;value" c2 = SimpleCookie() c2.load(c.output()) self.assertEqual(c['test'].value, c2['test'].value) def test_decode_2(self): """ Test that we haven't broken normal encoding """ c = SimpleCookie() c['test'] = "\xf0" c2 = SimpleCookie() c2.load(c.output()) self.assertEqual(c['test'].value, c2['test'].value) def test_nonstandard_keys(self): """ Test that a single non-standard cookie name doesn't affect all cookies. Ticket #13007. """ self.assertTrue('good_cookie' in parse_cookie('good_cookie=yes;bad:cookie=yes').keys())
11,505
Python
.py
238
39.655462
99
0.602834
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,032
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/i18n/models.py
from datetime import datetime from django.db import models from django.utils.translation import ugettext_lazy as _ class TestModel(models.Model): text = models.CharField(max_length=10, default=_('Anything')) class Company(models.Model): name = models.CharField(max_length=50) date_added = models.DateTimeField(default=datetime(1799,1,31,23,59,59,0)) cents_payed = models.DecimalField(max_digits=4, decimal_places=2) products_delivered = models.IntegerField()
481
Python
.py
10
44.9
77
0.773987
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,033
test_warnings.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/i18n/test_warnings.py
from os.path import join, normpath, abspath, dirname import warnings import django from django.conf import settings from django.test.utils import get_warnings_state, restore_warnings_state from django.utils.translation import _trans from django.utils.unittest import TestCase class DeprecationWarningTests(TestCase): def setUp(self): self.warning_state = get_warnings_state() self.old_settings_module = settings.SETTINGS_MODULE settings.SETTINGS_MODULE = 'regressiontests' self.old_locale_paths = settings.LOCALE_PATHS def tearDown(self): restore_warnings_state(self.warning_state) settings.SETTINGS_MODULE = self.old_settings_module settings.LOCALE_PATHS = self.old_locale_paths def test_warn_if_project_has_locale_subdir(self): """Test that PendingDeprecationWarning is generated when a deprecated project level locale/ subdir is present.""" project_path = join(dirname(abspath(__file__)), '..') warnings.filterwarnings('error', "Translations in the project directory aren't supported anymore\. Use the LOCALE_PATHS setting instead\.", PendingDeprecationWarning) _trans.__dict__ = {} self.assertRaises(PendingDeprecationWarning, django.utils.translation.ugettext, 'Time') def test_no_warn_if_project_and_locale_paths_overlap(self): """Test that PendingDeprecationWarning isn't generated when a deprecated project level locale/ subdir is also included in LOCALE_PATHS.""" project_path = join(dirname(abspath(__file__)), '..') settings.LOCALE_PATHS += (normpath(join(project_path, 'locale')),) warnings.filterwarnings('error', "Translations in the project directory aren't supported anymore\. Use the LOCALE_PATHS setting instead\.", PendingDeprecationWarning) _trans.__dict__ = {} try: django.utils.translation.ugettext('Time') except PendingDeprecationWarning: self.fail("PendingDeprecationWarning shouldn't be raised when settings/project locale and a LOCALE_PATHS member point to the same file system location.")
2,180
Python
.py
37
50.810811
165
0.713951
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,034
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/i18n/tests.py
# -*- encoding: utf-8 -*- import datetime import decimal import os import sys import pickle from threading import local from django.conf import settings from django.template import Template, Context from django.utils.formats import (get_format, date_format, time_format, localize, localize_input, iter_format_modules, get_format_modules) from django.utils.importlib import import_module from django.utils.numberformat import format as nformat from django.utils.safestring import mark_safe, SafeString, SafeUnicode from django.utils.translation import (ugettext, ugettext_lazy, activate, deactivate, gettext_lazy, pgettext, npgettext, to_locale, get_language_info, get_language) from django.utils.unittest import TestCase from forms import I18nForm, SelectDateForm, SelectDateWidget, CompanyForm from models import Company, TestModel from commands.tests import * from test_warnings import DeprecationWarningTests class TranslationTests(TestCase): def test_lazy_objects(self): """ Format string interpolation should work with *_lazy objects. """ s = ugettext_lazy('Add %(name)s') d = {'name': 'Ringo'} self.assertEqual(u'Add Ringo', s % d) activate('de') try: self.assertEqual(u'Ringo hinzuf\xfcgen', s % d) activate('pl') self.assertEqual(u'Dodaj Ringo', s % d) finally: deactivate() # It should be possible to compare *_lazy objects. s1 = ugettext_lazy('Add %(name)s') self.assertEqual(True, s == s1) s2 = gettext_lazy('Add %(name)s') s3 = gettext_lazy('Add %(name)s') self.assertEqual(True, s2 == s3) self.assertEqual(True, s == s2) s4 = ugettext_lazy('Some other string') self.assertEqual(False, s == s4) def test_lazy_pickle(self): s1 = ugettext_lazy("test") self.assertEqual(unicode(s1), "test") s2 = pickle.loads(pickle.dumps(s1)) self.assertEqual(unicode(s2), "test") def test_pgettext(self): # Reset translation catalog to include other/locale/de self.old_locale_paths = settings.LOCALE_PATHS settings.LOCALE_PATHS += (os.path.join(os.path.dirname(os.path.abspath(__file__)), 'other', 'locale'),) from django.utils.translation import trans_real trans_real._active = local() trans_real._translations = {} activate('de') self.assertEqual(pgettext("unexisting", "May"), u"May") self.assertEqual(pgettext("month name", "May"), u"Mai") self.assertEqual(pgettext("verb", "May"), u"Kann") self.assertEqual(npgettext("search", "%d result", "%d results", 4) % 4, u"4 Resultate") settings.LOCALE_PATHS = self.old_locale_paths def test_string_concat(self): """ unicode(string_concat(...)) should not raise a TypeError - #4796 """ import django.utils.translation self.assertEqual(u'django', unicode(django.utils.translation.string_concat("dja", "ngo"))) def test_safe_status(self): """ Translating a string requiring no auto-escaping shouldn't change the "safe" status. """ s = mark_safe('Password') self.assertEqual(SafeString, type(s)) activate('de') try: self.assertEqual(SafeUnicode, type(ugettext(s))) finally: deactivate() self.assertEqual('aPassword', SafeString('a') + s) self.assertEqual('Passworda', s + SafeString('a')) self.assertEqual('Passworda', s + mark_safe('a')) self.assertEqual('aPassword', mark_safe('a') + s) self.assertEqual('as', mark_safe('a') + mark_safe('s')) def test_maclines(self): """ Translations on files with mac or dos end of lines will be converted to unix eof in .po catalogs, and they have to match when retrieved """ from django.utils.translation.trans_real import translation ca_translation = translation('ca') ca_translation._catalog[u'Mac\nEOF\n'] = u'Catalan Mac\nEOF\n' ca_translation._catalog[u'Win\nEOF\n'] = u'Catalan Win\nEOF\n' activate('ca') try: self.assertEqual(u'Catalan Mac\nEOF\n', ugettext(u'Mac\rEOF\r')) self.assertEqual(u'Catalan Win\nEOF\n', ugettext(u'Win\r\nEOF\r\n')) finally: deactivate() def test_to_locale(self): """ Tests the to_locale function and the special case of Serbian Latin (refs #12230 and r11299) """ self.assertEqual(to_locale('en-us'), 'en_US') self.assertEqual(to_locale('sr-lat'), 'sr_Lat') def test_to_language(self): """ Test the to_language function """ from django.utils.translation.trans_real import to_language self.assertEqual(to_language('en_US'), 'en-us') self.assertEqual(to_language('sr_Lat'), 'sr-lat') class FormattingTests(TestCase): def setUp(self): self.use_i18n = settings.USE_I18N self.use_l10n = settings.USE_L10N self.use_thousand_separator = settings.USE_THOUSAND_SEPARATOR self.thousand_separator = settings.THOUSAND_SEPARATOR self.number_grouping = settings.NUMBER_GROUPING self.n = decimal.Decimal('66666.666') self.f = 99999.999 self.d = datetime.date(2009, 12, 31) self.dt = datetime.datetime(2009, 12, 31, 20, 50) self.t = datetime.time(10, 15, 48) self.l = 10000L self.ctxt = Context({ 'n': self.n, 't': self.t, 'd': self.d, 'dt': self.dt, 'f': self.f, 'l': self.l, }) def tearDown(self): # Restore defaults settings.USE_I18N = self.use_i18n settings.USE_L10N = self.use_l10n settings.USE_THOUSAND_SEPARATOR = self.use_thousand_separator settings.THOUSAND_SEPARATOR = self.thousand_separator settings.NUMBER_GROUPING = self.number_grouping def test_locale_independent(self): """ Localization of numbers """ settings.USE_L10N = True settings.USE_THOUSAND_SEPARATOR = False self.assertEqual(u'66666.66', nformat(self.n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=',')) self.assertEqual(u'66666A6', nformat(self.n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B')) settings.USE_THOUSAND_SEPARATOR = True self.assertEqual(u'66,666.66', nformat(self.n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=',')) self.assertEqual(u'6B6B6B6B6A6', nformat(self.n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B')) self.assertEqual(u'-66666.6', nformat(-66666.666, decimal_sep='.', decimal_pos=1)) self.assertEqual(u'-66666.0', nformat(int('-66666'), decimal_sep='.', decimal_pos=1)) self.assertEqual(u'10000.0', nformat(self.l, decimal_sep='.', decimal_pos=1)) # date filter self.assertEqual(u'31.12.2009 в 20:50', Template('{{ dt|date:"d.m.Y в H:i" }}').render(self.ctxt)) self.assertEqual(u'⌚ 10:15', Template('{{ t|time:"⌚ H:i" }}').render(self.ctxt)) def test_l10n_disabled(self): """ Catalan locale with format i18n disabled translations will be used, but not formats """ settings.USE_L10N = False activate('ca') try: self.assertEqual(u'N j, Y', get_format('DATE_FORMAT')) self.assertEqual(0, get_format('FIRST_DAY_OF_WEEK')) self.assertEqual(u'.', get_format('DECIMAL_SEPARATOR')) self.assertEqual(u'10:15 a.m.', time_format(self.t)) self.assertEqual(u'des. 31, 2009', date_format(self.d)) self.assertEqual(u'desembre 2009', date_format(self.d, 'YEAR_MONTH_FORMAT')) self.assertEqual(u'12/31/2009 8:50 p.m.', date_format(self.dt, 'SHORT_DATETIME_FORMAT')) self.assertEqual(u'No localizable', localize('No localizable')) self.assertEqual(u'66666.666', localize(self.n)) self.assertEqual(u'99999.999', localize(self.f)) self.assertEqual(u'10000', localize(self.l)) self.assertEqual(u'des. 31, 2009', localize(self.d)) self.assertEqual(u'des. 31, 2009, 8:50 p.m.', localize(self.dt)) self.assertEqual(u'66666.666', Template('{{ n }}').render(self.ctxt)) self.assertEqual(u'99999.999', Template('{{ f }}').render(self.ctxt)) self.assertEqual(u'des. 31, 2009', Template('{{ d }}').render(self.ctxt)) self.assertEqual(u'des. 31, 2009, 8:50 p.m.', Template('{{ dt }}').render(self.ctxt)) self.assertEqual(u'66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt)) self.assertEqual(u'100000.0', Template('{{ f|floatformat }}').render(self.ctxt)) self.assertEqual(u'10:15 a.m.', Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt)) self.assertEqual(u'12/31/2009', Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt)) self.assertEqual(u'12/31/2009 8:50 p.m.', Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt)) form = I18nForm({ 'decimal_field': u'66666,666', 'float_field': u'99999,999', 'date_field': u'31/12/2009', 'datetime_field': u'31/12/2009 20:50', 'time_field': u'20:50', 'integer_field': u'1.234', }) self.assertEqual(False, form.is_valid()) self.assertEqual([u'Introdu\xefu un n\xfamero.'], form.errors['float_field']) self.assertEqual([u'Introdu\xefu un n\xfamero.'], form.errors['decimal_field']) self.assertEqual([u'Introdu\xefu una data v\xe0lida.'], form.errors['date_field']) self.assertEqual([u'Introdu\xefu una data/hora v\xe0lides.'], form.errors['datetime_field']) self.assertEqual([u'Introdu\xefu un n\xfamero sencer.'], form.errors['integer_field']) form2 = SelectDateForm({ 'date_field_month': u'12', 'date_field_day': u'31', 'date_field_year': u'2009' }) self.assertEqual(True, form2.is_valid()) self.assertEqual(datetime.date(2009, 12, 31), form2.cleaned_data['date_field']) self.assertEqual( u'<select name="mydate_month" id="id_mydate_month">\n<option value="1">gener</option>\n<option value="2">febrer</option>\n<option value="3">mar\xe7</option>\n<option value="4">abril</option>\n<option value="5">maig</option>\n<option value="6">juny</option>\n<option value="7">juliol</option>\n<option value="8">agost</option>\n<option value="9">setembre</option>\n<option value="10">octubre</option>\n<option value="11">novembre</option>\n<option value="12" selected="selected">desembre</option>\n</select>\n<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>', SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31)) ) # We shouldn't change the behavior of the floatformat filter re: # thousand separator and grouping when USE_L10N is False even # if the USE_THOUSAND_SEPARATOR, NUMBER_GROUPING and # THOUSAND_SEPARATOR settings are specified settings.USE_THOUSAND_SEPARATOR = True settings.NUMBER_GROUPING = 1 settings.THOUSAND_SEPARATOR = '!' self.assertEqual(u'66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt)) self.assertEqual(u'100000.0', Template('{{ f|floatformat }}').render(self.ctxt)) finally: deactivate() def test_l10n_enabled(self): settings.USE_L10N = True # Catalan locale activate('ca') try: self.assertEqual('j \de F \de Y', get_format('DATE_FORMAT')) self.assertEqual(1, get_format('FIRST_DAY_OF_WEEK')) self.assertEqual(',', get_format('DECIMAL_SEPARATOR')) self.assertEqual(u'10:15:48', time_format(self.t)) self.assertEqual(u'31 de desembre de 2009', date_format(self.d)) self.assertEqual(u'desembre del 2009', date_format(self.d, 'YEAR_MONTH_FORMAT')) self.assertEqual(u'31/12/2009 20:50', date_format(self.dt, 'SHORT_DATETIME_FORMAT')) self.assertEqual('No localizable', localize('No localizable')) settings.USE_THOUSAND_SEPARATOR = True self.assertEqual(u'66.666,666', localize(self.n)) self.assertEqual(u'99.999,999', localize(self.f)) self.assertEqual(u'10.000', localize(self.l)) self.assertEqual(u'True', localize(True)) settings.USE_THOUSAND_SEPARATOR = False self.assertEqual(u'66666,666', localize(self.n)) self.assertEqual(u'99999,999', localize(self.f)) self.assertEqual(u'10000', localize(self.l)) self.assertEqual(u'31 de desembre de 2009', localize(self.d)) self.assertEqual(u'31 de desembre de 2009 a les 20:50', localize(self.dt)) settings.USE_THOUSAND_SEPARATOR = True self.assertEqual(u'66.666,666', Template('{{ n }}').render(self.ctxt)) self.assertEqual(u'99.999,999', Template('{{ f }}').render(self.ctxt)) self.assertEqual(u'10.000', Template('{{ l }}').render(self.ctxt)) form3 = I18nForm({ 'decimal_field': u'66.666,666', 'float_field': u'99.999,999', 'date_field': u'31/12/2009', 'datetime_field': u'31/12/2009 20:50', 'time_field': u'20:50', 'integer_field': u'1.234', }) self.assertEqual(True, form3.is_valid()) self.assertEqual(decimal.Decimal('66666.666'), form3.cleaned_data['decimal_field']) self.assertEqual(99999.999, form3.cleaned_data['float_field']) self.assertEqual(datetime.date(2009, 12, 31), form3.cleaned_data['date_field']) self.assertEqual(datetime.datetime(2009, 12, 31, 20, 50), form3.cleaned_data['datetime_field']) self.assertEqual(datetime.time(20, 50), form3.cleaned_data['time_field']) self.assertEqual(1234, form3.cleaned_data['integer_field']) settings.USE_THOUSAND_SEPARATOR = False self.assertEqual(u'66666,666', Template('{{ n }}').render(self.ctxt)) self.assertEqual(u'99999,999', Template('{{ f }}').render(self.ctxt)) self.assertEqual(u'31 de desembre de 2009', Template('{{ d }}').render(self.ctxt)) self.assertEqual(u'31 de desembre de 2009 a les 20:50', Template('{{ dt }}').render(self.ctxt)) self.assertEqual(u'66666,67', Template('{{ n|floatformat:2 }}').render(self.ctxt)) self.assertEqual(u'100000,0', Template('{{ f|floatformat }}').render(self.ctxt)) self.assertEqual(u'10:15:48', Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt)) self.assertEqual(u'31/12/2009', Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt)) self.assertEqual(u'31/12/2009 20:50', Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt)) form4 = I18nForm({ 'decimal_field': u'66666,666', 'float_field': u'99999,999', 'date_field': u'31/12/2009', 'datetime_field': u'31/12/2009 20:50', 'time_field': u'20:50', 'integer_field': u'1234', }) self.assertEqual(True, form4.is_valid()) self.assertEqual(decimal.Decimal('66666.666'), form4.cleaned_data['decimal_field']) self.assertEqual(99999.999, form4.cleaned_data['float_field']) self.assertEqual(datetime.date(2009, 12, 31), form4.cleaned_data['date_field']) self.assertEqual(datetime.datetime(2009, 12, 31, 20, 50), form4.cleaned_data['datetime_field']) self.assertEqual(datetime.time(20, 50), form4.cleaned_data['time_field']) self.assertEqual(1234, form4.cleaned_data['integer_field']) form5 = SelectDateForm({ 'date_field_month': u'12', 'date_field_day': u'31', 'date_field_year': u'2009' }) self.assertEqual(True, form5.is_valid()) self.assertEqual(datetime.date(2009, 12, 31), form5.cleaned_data['date_field']) self.assertEqual( u'<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_month" id="id_mydate_month">\n<option value="1">gener</option>\n<option value="2">febrer</option>\n<option value="3">mar\xe7</option>\n<option value="4">abril</option>\n<option value="5">maig</option>\n<option value="6">juny</option>\n<option value="7">juliol</option>\n<option value="8">agost</option>\n<option value="9">setembre</option>\n<option value="10">octubre</option>\n<option value="11">novembre</option>\n<option value="12" selected="selected">desembre</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>', SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31)) ) finally: deactivate() # Russian locale (with E as month) activate('ru') try: self.assertEqual( u'<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_month" id="id_mydate_month">\n<option value="1">\u042f\u043d\u0432\u0430\u0440\u044c</option>\n<option value="2">\u0424\u0435\u0432\u0440\u0430\u043b\u044c</option>\n<option value="3">\u041c\u0430\u0440\u0442</option>\n<option value="4">\u0410\u043f\u0440\u0435\u043b\u044c</option>\n<option value="5">\u041c\u0430\u0439</option>\n<option value="6">\u0418\u044e\u043d\u044c</option>\n<option value="7">\u0418\u044e\u043b\u044c</option>\n<option value="8">\u0410\u0432\u0433\u0443\u0441\u0442</option>\n<option value="9">\u0421\u0435\u043d\u0442\u044f\u0431\u0440\u044c</option>\n<option value="10">\u041e\u043a\u0442\u044f\u0431\u0440\u044c</option>\n<option value="11">\u041d\u043e\u044f\u0431\u0440\u044c</option>\n<option value="12" selected="selected">\u0414\u0435\u043a\u0430\u0431\u0440\u044c</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>', SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31)) ) finally: deactivate() # English locale activate('en') try: self.assertEqual('N j, Y', get_format('DATE_FORMAT')) self.assertEqual(0, get_format('FIRST_DAY_OF_WEEK')) self.assertEqual('.', get_format('DECIMAL_SEPARATOR')) self.assertEqual(u'Dec. 31, 2009', date_format(self.d)) self.assertEqual(u'December 2009', date_format(self.d, 'YEAR_MONTH_FORMAT')) self.assertEqual(u'12/31/2009 8:50 p.m.', date_format(self.dt, 'SHORT_DATETIME_FORMAT')) self.assertEqual(u'No localizable', localize('No localizable')) settings.USE_THOUSAND_SEPARATOR = True self.assertEqual(u'66,666.666', localize(self.n)) self.assertEqual(u'99,999.999', localize(self.f)) self.assertEqual(u'10,000', localize(self.l)) settings.USE_THOUSAND_SEPARATOR = False self.assertEqual(u'66666.666', localize(self.n)) self.assertEqual(u'99999.999', localize(self.f)) self.assertEqual(u'10000', localize(self.l)) self.assertEqual(u'Dec. 31, 2009', localize(self.d)) self.assertEqual(u'Dec. 31, 2009, 8:50 p.m.', localize(self.dt)) settings.USE_THOUSAND_SEPARATOR = True self.assertEqual(u'66,666.666', Template('{{ n }}').render(self.ctxt)) self.assertEqual(u'99,999.999', Template('{{ f }}').render(self.ctxt)) self.assertEqual(u'10,000', Template('{{ l }}').render(self.ctxt)) settings.USE_THOUSAND_SEPARATOR = False self.assertEqual(u'66666.666', Template('{{ n }}').render(self.ctxt)) self.assertEqual(u'99999.999', Template('{{ f }}').render(self.ctxt)) self.assertEqual(u'Dec. 31, 2009', Template('{{ d }}').render(self.ctxt)) self.assertEqual(u'Dec. 31, 2009, 8:50 p.m.', Template('{{ dt }}').render(self.ctxt)) self.assertEqual(u'66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt)) self.assertEqual(u'100000.0', Template('{{ f|floatformat }}').render(self.ctxt)) self.assertEqual(u'12/31/2009', Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt)) self.assertEqual(u'12/31/2009 8:50 p.m.', Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt)) form5 = I18nForm({ 'decimal_field': u'66666.666', 'float_field': u'99999.999', 'date_field': u'12/31/2009', 'datetime_field': u'12/31/2009 20:50', 'time_field': u'20:50', 'integer_field': u'1234', }) self.assertEqual(True, form5.is_valid()) self.assertEqual(decimal.Decimal('66666.666'), form5.cleaned_data['decimal_field']) self.assertEqual(99999.999, form5.cleaned_data['float_field']) self.assertEqual(datetime.date(2009, 12, 31), form5.cleaned_data['date_field']) self.assertEqual(datetime.datetime(2009, 12, 31, 20, 50), form5.cleaned_data['datetime_field']) self.assertEqual(datetime.time(20, 50), form5.cleaned_data['time_field']) self.assertEqual(1234, form5.cleaned_data['integer_field']) form6 = SelectDateForm({ 'date_field_month': u'12', 'date_field_day': u'31', 'date_field_year': u'2009' }) self.assertEqual(True, form6.is_valid()) self.assertEqual(datetime.date(2009, 12, 31), form6.cleaned_data['date_field']) self.assertEqual( u'<select name="mydate_month" id="id_mydate_month">\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12" selected="selected">December</option>\n</select>\n<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>', SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31)) ) finally: deactivate() def test_sub_locales(self): """ Check if sublocales fall back to the main locale """ settings.USE_L10N = True activate('de-at') settings.USE_THOUSAND_SEPARATOR = True try: self.assertEqual(u'66.666,666', Template('{{ n }}').render(self.ctxt)) finally: deactivate() activate('es-us') try: self.assertEqual(u'31 de diciembre de 2009', date_format(self.d)) finally: deactivate() def test_localized_input(self): """ Tests if form input is correctly localized """ settings.USE_L10N = True activate('de-at') try: form6 = CompanyForm({ 'name': u'acme', 'date_added': datetime.datetime(2009, 12, 31, 6, 0, 0), 'cents_payed': decimal.Decimal('59.47'), 'products_delivered': 12000, }) self.assertEqual(True, form6.is_valid()) self.assertEqual( form6.as_ul(), u'<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" value="acme" maxlength="50" /></li>\n<li><label for="id_date_added">Date added:</label> <input type="text" name="date_added" value="31.12.2009 06:00:00" id="id_date_added" /></li>\n<li><label for="id_cents_payed">Cents payed:</label> <input type="text" name="cents_payed" value="59,47" id="id_cents_payed" /></li>\n<li><label for="id_products_delivered">Products delivered:</label> <input type="text" name="products_delivered" value="12000" id="id_products_delivered" /></li>' ) self.assertEqual(localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), '31.12.2009 06:00:00') self.assertEqual(datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data['date_added']) settings.USE_THOUSAND_SEPARATOR = True # Checking for the localized "products_delivered" field self.assertTrue(u'<input type="text" name="products_delivered" value="12.000" id="id_products_delivered" />' in form6.as_ul()) finally: deactivate() def test_iter_format_modules(self): """ Tests the iter_format_modules function. """ activate('de-at') old_format_module_path = settings.FORMAT_MODULE_PATH try: settings.USE_L10N = True de_format_mod = import_module('django.conf.locale.de.formats') self.assertEqual(list(iter_format_modules('de')), [de_format_mod]) settings.FORMAT_MODULE_PATH = 'regressiontests.i18n.other.locale' test_de_format_mod = import_module('regressiontests.i18n.other.locale.de.formats') self.assertEqual(list(iter_format_modules('de')), [test_de_format_mod, de_format_mod]) finally: settings.FORMAT_MODULE_PATH = old_format_module_path deactivate() def test_iter_format_modules_stability(self): """ Tests the iter_format_modules function always yields format modules in a stable and correct order in presence of both base ll and ll_CC formats. """ settings.USE_L10N = True en_format_mod = import_module('django.conf.locale.en.formats') en_gb_format_mod = import_module('django.conf.locale.en_GB.formats') self.assertEqual(list(iter_format_modules('en-gb')), [en_gb_format_mod, en_format_mod]) def test_get_format_modules_stability(self): activate('de') old_format_module_path = settings.FORMAT_MODULE_PATH settings.FORMAT_MODULE_PATH = 'regressiontests.i18n.other.locale' try: settings.USE_L10N = True old = "%r" % get_format_modules(reverse=True) new = "%r" % get_format_modules(reverse=True) # second try self.assertEqual(new, old, 'Value returned by get_formats_modules() must be preserved between calls.') finally: settings.FORMAT_MODULE_PATH = old_format_module_path deactivate() def test_localize_templatetag_and_filter(self): """ Tests the {% localize %} templatetag """ context = Context({'value': 3.14 }) template1 = Template("{% load l10n %}{% localize %}{{ value }}{% endlocalize %};{% localize on %}{{ value }}{% endlocalize %}") template2 = Template("{% load l10n %}{{ value }};{% localize off %}{{ value }};{% endlocalize %}{{ value }}") template3 = Template('{% load l10n %}{{ value }};{{ value|unlocalize }}') template4 = Template('{% load l10n %}{{ value }};{{ value|localize }}') output1 = '3,14;3,14' output2 = '3,14;3.14;3,14' output3 = '3,14;3.14' output4 = '3.14;3,14' old_localize = settings.USE_L10N try: activate('de') settings.USE_L10N = False self.assertEqual(template1.render(context), output1) self.assertEqual(template4.render(context), output4) settings.USE_L10N = True self.assertEqual(template1.render(context), output1) self.assertEqual(template2.render(context), output2) self.assertEqual(template3.render(context), output3) finally: deactivate() settings.USE_L10N = old_localize class MiscTests(TestCase): def test_parse_spec_http_header(self): """ Testing HTTP header parsing. First, we test that we can parse the values according to the spec (and that we extract all the pieces in the right order). """ from django.utils.translation.trans_real import parse_accept_lang_header p = parse_accept_lang_header # Good headers. self.assertEqual([('de', 1.0)], p('de')) self.assertEqual([('en-AU', 1.0)], p('en-AU')) self.assertEqual([('*', 1.0)], p('*;q=1.00')) self.assertEqual([('en-AU', 0.123)], p('en-AU;q=0.123')) self.assertEqual([('en-au', 0.5)], p('en-au;q=0.5')) self.assertEqual([('en-au', 1.0)], p('en-au;q=1.0')) self.assertEqual([('da', 1.0), ('en', 0.5), ('en-gb', 0.25)], p('da, en-gb;q=0.25, en;q=0.5')) self.assertEqual([('en-au-xx', 1.0)], p('en-au-xx')) self.assertEqual([('de', 1.0), ('en-au', 0.75), ('en-us', 0.5), ('en', 0.25), ('es', 0.125), ('fa', 0.125)], p('de,en-au;q=0.75,en-us;q=0.5,en;q=0.25,es;q=0.125,fa;q=0.125')) self.assertEqual([('*', 1.0)], p('*')) self.assertEqual([('de', 1.0)], p('de;q=0.')) self.assertEqual([], p('')) # Bad headers; should always return []. self.assertEqual([], p('en-gb;q=1.0000')) self.assertEqual([], p('en;q=0.1234')) self.assertEqual([], p('en;q=.2')) self.assertEqual([], p('abcdefghi-au')) self.assertEqual([], p('**')) self.assertEqual([], p('en,,gb')) self.assertEqual([], p('en-au;q=0.1.0')) self.assertEqual([], p('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXZ,en')) self.assertEqual([], p('da, en-gb;q=0.8, en;q=0.7,#')) self.assertEqual([], p('de;q=2.0')) self.assertEqual([], p('de;q=0.a')) self.assertEqual([], p('')) def test_parse_literal_http_header(self): """ Now test that we parse a literal HTTP header correctly. """ from django.utils.translation.trans_real import get_language_from_request g = get_language_from_request from django.http import HttpRequest r = HttpRequest r.COOKIES = {} r.META = {'HTTP_ACCEPT_LANGUAGE': 'pt-br'} self.assertEqual('pt-br', g(r)) r.META = {'HTTP_ACCEPT_LANGUAGE': 'pt'} self.assertEqual('pt', g(r)) r.META = {'HTTP_ACCEPT_LANGUAGE': 'es,de'} self.assertEqual('es', g(r)) r.META = {'HTTP_ACCEPT_LANGUAGE': 'es-ar,de'} self.assertEqual('es-ar', g(r)) # Python 2.3 and 2.4 return slightly different results for completely # bogus locales, so we omit this test for that anything below 2.4. # It's relatively harmless in any cases (GIGO). This also means this # won't be executed on Jython currently, but life's like that # sometimes. (On those platforms, passing in a truly bogus locale # will get you the default locale back.) if sys.version_info >= (2, 5): # This test assumes there won't be a Django translation to a US # variation of the Spanish language, a safe assumption. When the # user sets it as the preferred language, the main 'es' # translation should be selected instead. r.META = {'HTTP_ACCEPT_LANGUAGE': 'es-us'} self.assertEqual(g(r), 'es') # This tests the following scenario: there isn't a main language (zh) # translation of Django but there is a translation to variation (zh_CN) # the user sets zh-cn as the preferred language, it should be selected # by Django without falling back nor ignoring it. r.META = {'HTTP_ACCEPT_LANGUAGE': 'zh-cn,de'} self.assertEqual(g(r), 'zh-cn') def test_parse_language_cookie(self): """ Now test that we parse language preferences stored in a cookie correctly. """ from django.utils.translation.trans_real import get_language_from_request g = get_language_from_request from django.http import HttpRequest r = HttpRequest r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'pt-br'} r.META = {} self.assertEqual('pt-br', g(r)) r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'pt'} r.META = {} self.assertEqual('pt', g(r)) r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'es'} r.META = {'HTTP_ACCEPT_LANGUAGE': 'de'} self.assertEqual('es', g(r)) # Python 2.3 and 2.4 return slightly different results for completely # bogus locales, so we omit this test for that anything below 2.4. # It's relatively harmless in any cases (GIGO). This also means this # won't be executed on Jython currently, but life's like that # sometimes. (On those platforms, passing in a truly bogus locale # will get you the default locale back.) if sys.version_info >= (2, 5): # This test assumes there won't be a Django translation to a US # variation of the Spanish language, a safe assumption. When the # user sets it as the preferred language, the main 'es' # translation should be selected instead. r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'es-us'} r.META = {} self.assertEqual(g(r), 'es') # This tests the following scenario: there isn't a main language (zh) # translation of Django but there is a translation to variation (zh_CN) # the user sets zh-cn as the preferred language, it should be selected # by Django without falling back nor ignoring it. r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'zh-cn'} r.META = {'HTTP_ACCEPT_LANGUAGE': 'de'} self.assertEqual(g(r), 'zh-cn') class ResolutionOrderI18NTests(TestCase): def setUp(self): from django.utils.translation import trans_real # Okay, this is brutal, but we have no other choice to fully reset # the translation framework trans_real._active = local() trans_real._translations = {} activate('de') def tearDown(self): deactivate() def assertUgettext(self, msgid, msgstr): result = ugettext(msgid) self.assertTrue(msgstr in result, ("The string '%s' isn't in the " "translation of '%s'; the actual result is '%s'." % (msgstr, msgid, result))) class AppResolutionOrderI18NTests(ResolutionOrderI18NTests): def setUp(self): self.old_installed_apps = settings.INSTALLED_APPS settings.INSTALLED_APPS = ['regressiontests.i18n.resolution'] + list(settings.INSTALLED_APPS) super(AppResolutionOrderI18NTests, self).setUp() def tearDown(self): settings.INSTALLED_APPS = self.old_installed_apps super(AppResolutionOrderI18NTests, self).tearDown() def test_app_translation(self): self.assertUgettext('Date/time', 'APP') class LocalePathsResolutionOrderI18NTests(ResolutionOrderI18NTests): def setUp(self): self.old_locale_paths = settings.LOCALE_PATHS settings.LOCALE_PATHS += (os.path.join(os.path.dirname(os.path.abspath(__file__)), 'other', 'locale'),) super(LocalePathsResolutionOrderI18NTests, self).setUp() def tearDown(self): settings.LOCALE_PATHS = self.old_locale_paths super(LocalePathsResolutionOrderI18NTests, self).tearDown() def test_locale_paths_translation(self): self.assertUgettext('Time', 'LOCALE_PATHS') def test_locale_paths_override_app_translation(self): old_installed_apps = settings.INSTALLED_APPS settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + ['regressiontests.i18n.resolution'] try: self.assertUgettext('Time', 'LOCALE_PATHS') finally: settings.INSTALLED_APPS = old_installed_apps def test_locale_paths_override_project_translation(self): old_settings_module = settings.SETTINGS_MODULE settings.SETTINGS_MODULE = 'regressiontests' try: self.assertUgettext('Date/time', 'LOCALE_PATHS') finally: settings.SETTINGS_MODULE = old_settings_module class ProjectResolutionOrderI18NTests(ResolutionOrderI18NTests): def setUp(self): self.old_settings_module = settings.SETTINGS_MODULE settings.SETTINGS_MODULE = 'regressiontests' super(ProjectResolutionOrderI18NTests, self).setUp() def tearDown(self): settings.SETTINGS_MODULE = self.old_settings_module super(ProjectResolutionOrderI18NTests, self).tearDown() def test_project_translation(self): self.assertUgettext('Date/time', 'PROJECT') def test_project_override_app_translation(self): old_installed_apps = settings.INSTALLED_APPS settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + ['regressiontests.i18n.resolution'] try: self.assertUgettext('Date/time', 'PROJECT') finally: settings.INSTALLED_APPS = old_installed_apps class DjangoFallbackResolutionOrderI18NTests(ResolutionOrderI18NTests): def test_django_fallback(self): self.assertEqual(ugettext('Date/time'), 'Datum/Zeit') class TestModels(TestCase): def test_lazy(self): tm = TestModel() tm.save() def test_safestr(self): c = Company(cents_payed=12, products_delivered=1) c.name = SafeUnicode(u'Iñtërnâtiônàlizætiøn1') c.save() c.name = SafeString(u'Iñtërnâtiônàlizætiøn1'.encode('utf-8')) c.save() class TestLanguageInfo(TestCase): def test_localized_language_info(self): li = get_language_info('de') self.assertEqual(li['code'], 'de') self.assertEqual(li['name_local'], u'Deutsch') self.assertEqual(li['name'], 'German') self.assertEqual(li['bidi'], False) class MultipleLocaleActivationTests(TestCase): """ Tests for template rendering behavior when multiple locales are activated during the lifetime of the same process. """ def setUp(self): self._old_language = get_language() def tearDown(self): activate(self._old_language) def test_single_locale_activation(self): """ Simple baseline behavior with one locale for all the supported i18n constructs. """ activate('fr') self.assertEqual(Template("{{ _('Yes') }}").render(Context({})), 'Oui') self.assertEqual(Template("{% load i18n %}{% trans 'Yes' %}").render(Context({})), 'Oui') self.assertEqual(Template("{% load i18n %}{% blocktrans %}Yes{% endblocktrans %}").render(Context({})), 'Oui') # Literal marked up with _() in a filter expression def test_multiple_locale_filter(self): activate('de') t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}") activate(self._old_language) activate('nl') self.assertEqual(t.render(Context({})), 'nee') def test_multiple_locale_filter_deactivate(self): activate('de') t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}") deactivate() activate('nl') self.assertEqual(t.render(Context({})), 'nee') def test_multiple_locale_filter_direct_switch(self): activate('de') t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}") activate('nl') self.assertEqual(t.render(Context({})), 'nee') # Literal marked up with _() def test_multiple_locale(self): activate('de') t = Template("{{ _('No') }}") activate(self._old_language) activate('nl') self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_deactivate(self): activate('de') t = Template("{{ _('No') }}") deactivate() activate('nl') self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_direct_switch(self): activate('de') t = Template("{{ _('No') }}") activate('nl') self.assertEqual(t.render(Context({})), 'Nee') # Literal marked up with _(), loading the i18n template tag library def test_multiple_locale_loadi18n(self): activate('de') t = Template("{% load i18n %}{{ _('No') }}") activate(self._old_language) activate('nl') self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_loadi18n_deactivate(self): activate('de') t = Template("{% load i18n %}{{ _('No') }}") deactivate() activate('nl') self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_loadi18n_direct_switch(self): activate('de') t = Template("{% load i18n %}{{ _('No') }}") activate('nl') self.assertEqual(t.render(Context({})), 'Nee') # trans i18n tag def test_multiple_locale_trans(self): activate('de') t = Template("{% load i18n %}{% trans 'No' %}") activate(self._old_language) activate('nl') self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_deactivate_trans(self): activate('de') t = Template("{% load i18n %}{% trans 'No' %}") deactivate() activate('nl') self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_direct_switch_trans(self): activate('de') t = Template("{% load i18n %}{% trans 'No' %}") activate('nl') self.assertEqual(t.render(Context({})), 'Nee') # blocktrans i18n tag def test_multiple_locale_btrans(self): activate('de') t = Template("{% load i18n %}{% blocktrans %}No{% endblocktrans %}") activate(self._old_language) activate('nl') self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_deactivate_btrans(self): activate('de') t = Template("{% load i18n %}{% blocktrans %}No{% endblocktrans %}") deactivate() activate('nl') self.assertEqual(t.render(Context({})), 'Nee') def test_multiple_locale_direct_switch_btrans(self): activate('de') t = Template("{% load i18n %}{% blocktrans %}No{% endblocktrans %}") activate('nl') self.assertEqual(t.render(Context({})), 'Nee')
48,435
Python
.py
782
51.772379
2,355
0.624648
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,035
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/i18n/forms.py
from django import template, forms from django.forms.extras import SelectDateWidget from models import Company class I18nForm(forms.Form): decimal_field = forms.DecimalField(localize=True) float_field = forms.FloatField(localize=True) date_field = forms.DateField(localize=True) datetime_field = forms.DateTimeField(localize=True) time_field = forms.TimeField(localize=True) integer_field = forms.IntegerField(localize=True) class SelectDateForm(forms.Form): date_field = forms.DateField(widget=SelectDateWidget) class CompanyForm(forms.ModelForm): cents_payed = forms.DecimalField(max_digits=4, decimal_places=2, localize=True) products_delivered = forms.IntegerField(localize=True) date_added = forms.DateTimeField(localize=True) class Meta: model = Company
816
Python
.py
18
41.222222
83
0.782116
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,036
compilation.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/i18n/commands/compilation.py
import os try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.core.management import CommandError from django.core.management.commands.compilemessages import compile_messages from django.test import TestCase LOCALE='es_AR' class MessageCompilationTests(TestCase): MO_FILE='locale/%s/LC_MESSAGES/django.mo' % LOCALE def setUp(self): self._cwd = os.getcwd() self.test_dir = os.path.abspath(os.path.dirname(__file__)) def tearDown(self): os.chdir(self._cwd) class PoFileTests(MessageCompilationTests): def test_bom_rejection(self): os.chdir(self.test_dir) # We don't use the django.core.management intrastructure (call_command() # et al) because CommandError's cause exit(1) there. We test the # underlying compile_messages function instead out = StringIO() self.assertRaises(CommandError, compile_messages, out, locale=LOCALE) self.assertFalse(os.path.exists(self.MO_FILE))
1,032
Python
.py
25
35.72
80
0.732197
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,037
extraction.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/i18n/commands/extraction.py
import os import re import shutil from django.test import TestCase from django.core import management LOCALE='de' class ExtractorTests(TestCase): PO_FILE='locale/%s/LC_MESSAGES/django.po' % LOCALE def setUp(self): self._cwd = os.getcwd() self.test_dir = os.path.abspath(os.path.dirname(__file__)) def _rmrf(self, dname): if os.path.commonprefix([self.test_dir, os.path.abspath(dname)]) != self.test_dir: return shutil.rmtree(dname) def tearDown(self): os.chdir(self.test_dir) try: self._rmrf('locale/%s' % LOCALE) except OSError: pass os.chdir(self._cwd) def assertMsgId(self, msgid, s, use_quotes=True): if use_quotes: msgid = '"%s"' % msgid return self.assertTrue(re.search('^msgid %s' % msgid, s, re.MULTILINE)) def assertNotMsgId(self, msgid, s, use_quotes=True): if use_quotes: msgid = '"%s"' % msgid return self.assertTrue(not re.search('^msgid %s' % msgid, s, re.MULTILINE)) class BasicExtractorTests(ExtractorTests): def test_comments_extractor(self): os.chdir(self.test_dir) management.call_command('makemessages', locale=LOCALE, verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) po_contents = open(self.PO_FILE, 'r').read() self.assertTrue('#. Translators: This comment should be extracted' in po_contents) self.assertTrue('This comment should not be extracted' not in po_contents) # Comments in templates self.assertTrue('#. Translators: Django template comment for translators' in po_contents) self.assertTrue("#. Translators: Django comment block for translators\n#. string's meaning unveiled" in po_contents) self.assertTrue('#. Translators: One-line translator comment #1' in po_contents) self.assertTrue('#. Translators: Two-line translator comment #1\n#. continued here.' in po_contents) self.assertTrue('#. Translators: One-line translator comment #2' in po_contents) self.assertTrue('#. Translators: Two-line translator comment #2\n#. continued here.' in po_contents) self.assertTrue('#. Translators: One-line translator comment #3' in po_contents) self.assertTrue('#. Translators: Two-line translator comment #3\n#. continued here.' in po_contents) self.assertTrue('#. Translators: One-line translator comment #4' in po_contents) self.assertTrue('#. Translators: Two-line translator comment #4\n#. continued here.' in po_contents) def test_templatize(self): os.chdir(self.test_dir) management.call_command('makemessages', locale=LOCALE, verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) po_contents = open(self.PO_FILE, 'r').read() self.assertMsgId('I think that 100%% is more that 50%% of anything.', po_contents) self.assertMsgId('I think that 100%% is more that 50%% of %\(obj\)s.', po_contents) def test_extraction_error(self): os.chdir(self.test_dir) shutil.copyfile('./templates/template_with_error.txt', './templates/template_with_error.html') self.assertRaises(SyntaxError, management.call_command, 'makemessages', locale=LOCALE, verbosity=0) try: # TODO: Simplify this try/try block when we drop support for Python 2.4 try: management.call_command('makemessages', locale=LOCALE, verbosity=0) except SyntaxError, e: self.assertEqual(str(e), 'Translation blocks must not include other block tags: blocktrans (file templates/template_with_error.html, line 3)') finally: os.remove('./templates/template_with_error.html') os.remove('./templates/template_with_error.html.py') # Waiting for #8536 to be fixed class JavascriptExtractorTests(ExtractorTests): PO_FILE='locale/%s/LC_MESSAGES/djangojs.po' % LOCALE def test_javascript_literals(self): os.chdir(self.test_dir) management.call_command('makemessages', domain='djangojs', locale=LOCALE, verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) po_contents = open(self.PO_FILE, 'r').read() self.assertMsgId('This literal should be included.', po_contents) self.assertMsgId('This one as well.', po_contents) class IgnoredExtractorTests(ExtractorTests): def test_ignore_option(self): os.chdir(self.test_dir) management.call_command('makemessages', locale=LOCALE, verbosity=0, ignore_patterns=['ignore_dir/*']) self.assertTrue(os.path.exists(self.PO_FILE)) po_contents = open(self.PO_FILE, 'r').read() self.assertMsgId('This literal should be included.', po_contents) self.assertNotMsgId('This should be ignored.', po_contents) class SymlinkExtractorTests(ExtractorTests): def setUp(self): self._cwd = os.getcwd() self.test_dir = os.path.abspath(os.path.dirname(__file__)) self.symlinked_dir = os.path.join(self.test_dir, 'templates_symlinked') def tearDown(self): super(SymlinkExtractorTests, self).tearDown() os.chdir(self.test_dir) try: os.remove(self.symlinked_dir) except OSError: pass os.chdir(self._cwd) def test_symlink(self): if hasattr(os, 'symlink'): if os.path.exists(self.symlinked_dir): self.assertTrue(os.path.islink(self.symlinked_dir)) else: os.symlink(os.path.join(self.test_dir, 'templates'), self.symlinked_dir) os.chdir(self.test_dir) management.call_command('makemessages', locale=LOCALE, verbosity=0, symlinks=True) self.assertTrue(os.path.exists(self.PO_FILE)) po_contents = open(self.PO_FILE, 'r').read() self.assertMsgId('This literal should be included.', po_contents) self.assertTrue('templates_symlinked/test.html' in po_contents) class CopyPluralFormsExtractorTests(ExtractorTests): def test_copy_plural_forms(self): os.chdir(self.test_dir) management.call_command('makemessages', locale=LOCALE, verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) po_contents = open(self.PO_FILE, 'r').read() self.assertTrue('Plural-Forms: nplurals=2; plural=(n != 1)' in po_contents) class NoWrapExtractorTests(ExtractorTests): def test_no_wrap_enabled(self): os.chdir(self.test_dir) management.call_command('makemessages', locale=LOCALE, verbosity=0, no_wrap=True) self.assertTrue(os.path.exists(self.PO_FILE)) po_contents = open(self.PO_FILE, 'r').read() self.assertMsgId('This literal should also be included wrapped or not wrapped depending on the use of the --no-wrap option.', po_contents) def test_no_wrap_disabled(self): os.chdir(self.test_dir) management.call_command('makemessages', locale=LOCALE, verbosity=0, no_wrap=False) self.assertTrue(os.path.exists(self.PO_FILE)) po_contents = open(self.PO_FILE, 'r').read() self.assertMsgId('""\n"This literal should also be included wrapped or not wrapped depending on the "\n"use of the --no-wrap option."', po_contents, use_quotes=False)
7,319
Python
.py
130
47.546154
174
0.671886
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,038
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/i18n/commands/__init__.py
from django.utils.translation import ugettext as _ # Translators: This comment should be extracted dummy1 = _("This is a translatable string.") # This comment should not be extracted dummy2 = _("This is another translatable string.")
237
Python
.py
5
45.8
50
0.786026
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,039
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/i18n/commands/tests.py
import os import re from subprocess import Popen, PIPE def find_command(cmd, path=None, pathext=None): if path is None: path = os.environ.get('PATH', []).split(os.pathsep) if isinstance(path, basestring): path = [path] # check if there are funny path extensions for executables, e.g. Windows if pathext is None: pathext = os.environ.get('PATHEXT', '.COM;.EXE;.BAT;.CMD').split(os.pathsep) # don't use extensions if the command ends with one of them for ext in pathext: if cmd.endswith(ext): pathext = [''] break # check if we find the command on PATH for p in path: f = os.path.join(p, cmd) if os.path.isfile(f): return f for ext in pathext: fext = f + ext if os.path.isfile(fext): return fext return None # checks if it can find xgettext on the PATH and # imports the extraction tests if yes xgettext_cmd = find_command('xgettext') if xgettext_cmd: p = Popen('%s --version' % xgettext_cmd, shell=True, stdout=PIPE, stderr=PIPE, close_fds=os.name != 'nt', universal_newlines=True) output = p.communicate()[0] match = re.search(r'(?P<major>\d+)\.(?P<minor>\d+)', output) if match: xversion = (int(match.group('major')), int(match.group('minor'))) if xversion >= (0, 15): from extraction import * del p if find_command('msgfmt'): from compilation import *
1,477
Python
.py
40
30.35
134
0.622734
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,040
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/model_inheritance_regress/models.py
import datetime from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Meta: ordering = ('name',) def __unicode__(self): return u"%s the place" % self.name class Restaurant(Place): serves_hot_dogs = models.BooleanField() serves_pizza = models.BooleanField() def __unicode__(self): return u"%s the restaurant" % self.name class ItalianRestaurant(Restaurant): serves_gnocchi = models.BooleanField() def __unicode__(self): return u"%s the italian restaurant" % self.name class ParkingLot(Place): # An explicit link to the parent (we can control the attribute name). parent = models.OneToOneField(Place, primary_key=True, parent_link=True) capacity = models.IntegerField() def __unicode__(self): return u"%s the parking lot" % self.name class ParkingLot2(Place): # In lieu of any other connector, an existing OneToOneField will be # promoted to the primary key. parent = models.OneToOneField(Place) class ParkingLot3(Place): # The parent_link connector need not be the pk on the model. primary_key = models.AutoField(primary_key=True) parent = models.OneToOneField(Place, parent_link=True) class Supplier(models.Model): restaurant = models.ForeignKey(Restaurant) class Wholesaler(Supplier): retailer = models.ForeignKey(Supplier,related_name='wholesale_supplier') class Parent(models.Model): created = models.DateTimeField(default=datetime.datetime.now) class Child(Parent): name = models.CharField(max_length=10) class SelfRefParent(models.Model): parent_data = models.IntegerField() self_data = models.ForeignKey('self', null=True) class SelfRefChild(SelfRefParent): child_data = models.IntegerField() 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 class ArticleWithAuthor(Article): author = models.CharField(max_length=100) class M2MBase(models.Model): articles = models.ManyToManyField(Article) class M2MChild(M2MBase): name = models.CharField(max_length=50) class Evaluation(Article): quality = models.IntegerField() class Meta: abstract = True class QualityControl(Evaluation): assignee = models.CharField(max_length=50) class BaseM(models.Model): base_name = models.CharField(max_length=100) def __unicode__(self): return self.base_name class DerivedM(BaseM): customPK = models.IntegerField(primary_key=True) derived_name = models.CharField(max_length=100) def __unicode__(self): return "PK = %d, base_name = %s, derived_name = %s" \ % (self.customPK, self.base_name, self.derived_name) class AuditBase(models.Model): planned_date = models.DateField() class Meta: abstract = True verbose_name_plural = u'Audits' class CertificationAudit(AuditBase): class Meta(AuditBase.Meta): abstract = True class InternalCertificationAudit(CertificationAudit): auditing_dept = models.CharField(max_length=20) # Check that abstract classes don't get m2m tables autocreated. class Person(models.Model): name = models.CharField(max_length=100) class Meta: ordering = ('name',) def __unicode__(self): return self.name class AbstractEvent(models.Model): name = models.CharField(max_length=100) attendees = models.ManyToManyField(Person, related_name="%(class)s_set") class Meta: abstract = True ordering = ('name',) def __unicode__(self): return self.name class BirthdayParty(AbstractEvent): pass class BachelorParty(AbstractEvent): pass class MessyBachelorParty(BachelorParty): pass # Check concrete -> abstract -> concrete inheritance class SearchableLocation(models.Model): keywords = models.CharField(max_length=256) class Station(SearchableLocation): name = models.CharField(max_length=128) class Meta: abstract = True class BusStation(Station): bus_routes = models.CommaSeparatedIntegerField(max_length=128) inbound = models.BooleanField() class TrainStation(Station): zone = models.IntegerField()
4,389
Python
.py
117
32.581197
76
0.722301
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,041
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/model_inheritance_regress/tests.py
""" Regression tests for Model inheritance behaviour. """ import datetime from operator import attrgetter from django.test import TestCase from models import (Place, Restaurant, ItalianRestaurant, ParkingLot, ParkingLot2, ParkingLot3, Supplier, Wholesaler, Child, SelfRefParent, SelfRefChild, ArticleWithAuthor, M2MChild, QualityControl, DerivedM, Person, BirthdayParty, BachelorParty, MessyBachelorParty, InternalCertificationAudit, BusStation, TrainStation) class ModelInheritanceTest(TestCase): def test_model_inheritance(self): # Regression for #7350, #7202 # Check that when you create a Parent object with a specific reference # to an existent child instance, saving the Parent doesn't duplicate # the child. This behaviour is only activated during a raw save - it # is mostly relevant to deserialization, but any sort of CORBA style # 'narrow()' API would require a similar approach. # Create a child-parent-grandparent chain place1 = Place( name="Guido's House of Pasta", address='944 W. Fullerton') place1.save_base(raw=True) restaurant = Restaurant( place_ptr=place1, serves_hot_dogs=True, serves_pizza=False) restaurant.save_base(raw=True) italian_restaurant = ItalianRestaurant( restaurant_ptr=restaurant, serves_gnocchi=True) italian_restaurant.save_base(raw=True) # Create a child-parent chain with an explicit parent link place2 = Place(name='Main St', address='111 Main St') place2.save_base(raw=True) park = ParkingLot(parent=place2, capacity=100) park.save_base(raw=True) # Check that no extra parent objects have been created. places = list(Place.objects.all()) self.assertEqual(places, [place1, place2]) dicts = list(Restaurant.objects.values('name','serves_hot_dogs')) self.assertEqual(dicts, [{ 'name': u"Guido's House of Pasta", 'serves_hot_dogs': True }]) dicts = list(ItalianRestaurant.objects.values( 'name','serves_hot_dogs','serves_gnocchi')) self.assertEqual(dicts, [{ 'name': u"Guido's House of Pasta", 'serves_gnocchi': True, 'serves_hot_dogs': True, }]) dicts = list(ParkingLot.objects.values('name','capacity')) self.assertEqual(dicts, [{ 'capacity': 100, 'name': u'Main St', }]) # You can also update objects when using a raw save. place1.name = "Guido's All New House of Pasta" place1.save_base(raw=True) restaurant.serves_hot_dogs = False restaurant.save_base(raw=True) italian_restaurant.serves_gnocchi = False italian_restaurant.save_base(raw=True) place2.name='Derelict lot' place2.save_base(raw=True) park.capacity = 50 park.save_base(raw=True) # No extra parent objects after an update, either. places = list(Place.objects.all()) self.assertEqual(places, [place2, place1]) self.assertEqual(places[0].name, 'Derelict lot') self.assertEqual(places[1].name, "Guido's All New House of Pasta") dicts = list(Restaurant.objects.values('name','serves_hot_dogs')) self.assertEqual(dicts, [{ 'name': u"Guido's All New House of Pasta", 'serves_hot_dogs': False, }]) dicts = list(ItalianRestaurant.objects.values( 'name', 'serves_hot_dogs', 'serves_gnocchi')) self.assertEqual(dicts, [{ 'name': u"Guido's All New House of Pasta", 'serves_gnocchi': False, 'serves_hot_dogs': False, }]) dicts = list(ParkingLot.objects.values('name','capacity')) self.assertEqual(dicts, [{ 'capacity': 50, 'name': u'Derelict lot', }]) # If you try to raw_save a parent attribute onto a child object, # the attribute will be ignored. italian_restaurant.name = "Lorenzo's Pasta Hut" italian_restaurant.save_base(raw=True) # Note that the name has not changed # - name is an attribute of Place, not ItalianRestaurant dicts = list(ItalianRestaurant.objects.values( 'name','serves_hot_dogs','serves_gnocchi')) self.assertEqual(dicts, [{ 'name': u"Guido's All New House of Pasta", 'serves_gnocchi': False, 'serves_hot_dogs': False, }]) def test_issue_7105(self): # Regressions tests for #7105: dates() queries should be able to use # fields from the parent model as easily as the child. obj = Child.objects.create( name='child', created=datetime.datetime(2008, 6, 26, 17, 0, 0)) dates = list(Child.objects.dates('created', 'month')) self.assertEqual(dates, [datetime.datetime(2008, 6, 1, 0, 0)]) def test_issue_7276(self): # Regression test for #7276: calling delete() on a model with # multi-table inheritance should delete the associated rows from any # ancestor tables, as well as any descendent objects. place1 = Place( name="Guido's House of Pasta", address='944 W. Fullerton') place1.save_base(raw=True) restaurant = Restaurant( place_ptr=place1, serves_hot_dogs=True, serves_pizza=False) restaurant.save_base(raw=True) italian_restaurant = ItalianRestaurant( restaurant_ptr=restaurant, serves_gnocchi=True) italian_restaurant.save_base(raw=True) ident = ItalianRestaurant.objects.all()[0].id self.assertEqual(Place.objects.get(pk=ident), place1) xx = Restaurant.objects.create( name='a', address='xx', serves_hot_dogs=True, serves_pizza=False) # This should delete both Restuarants, plus the related places, plus # the ItalianRestaurant. Restaurant.objects.all().delete() self.assertRaises( Place.DoesNotExist, Place.objects.get, pk=ident) self.assertRaises( ItalianRestaurant.DoesNotExist, ItalianRestaurant.objects.get, pk=ident) def test_issue_6755(self): """ Regression test for #6755 """ r = Restaurant(serves_pizza=False) r.save() self.assertEqual(r.id, r.place_ptr_id) orig_id = r.id r = Restaurant(place_ptr_id=orig_id, serves_pizza=True) r.save() self.assertEqual(r.id, orig_id) self.assertEqual(r.id, r.place_ptr_id) def test_issue_7488(self): # Regression test for #7488. This looks a little crazy, but it's the # equivalent of what the admin interface has to do for the edit-inline # case. suppliers = Supplier.objects.filter( restaurant=Restaurant(name='xx', address='yy')) suppliers = list(suppliers) self.assertEqual(suppliers, []) def test_issue_11764(self): """ Regression test for #11764 """ wholesalers = list(Wholesaler.objects.all().select_related()) self.assertEqual(wholesalers, []) def test_issue_7853(self): """ Regression test for #7853 If the parent class has a self-referential link, make sure that any updates to that link via the child update the right table. """ obj = SelfRefChild.objects.create(child_data=37, parent_data=42) obj.delete() def test_get_next_previous_by_date(self): """ Regression tests for #8076 get_(next/previous)_by_date should work """ c1 = ArticleWithAuthor( headline='ArticleWithAuthor 1', author="Person 1", pub_date=datetime.datetime(2005, 8, 1, 3, 0)) c1.save() c2 = ArticleWithAuthor( headline='ArticleWithAuthor 2', author="Person 2", pub_date=datetime.datetime(2005, 8, 1, 10, 0)) c2.save() c3 = ArticleWithAuthor( headline='ArticleWithAuthor 3', author="Person 3", pub_date=datetime.datetime(2005, 8, 2)) c3.save() self.assertEqual(c1.get_next_by_pub_date(), c2) self.assertEqual(c2.get_next_by_pub_date(), c3) self.assertRaises( ArticleWithAuthor.DoesNotExist, c3.get_next_by_pub_date) self.assertEqual(c3.get_previous_by_pub_date(), c2) self.assertEqual(c2.get_previous_by_pub_date(), c1) self.assertRaises( ArticleWithAuthor.DoesNotExist, c1.get_previous_by_pub_date) def test_inherited_fields(self): """ Regression test for #8825 and #9390 Make sure all inherited fields (esp. m2m fields, in this case) appear on the child class. """ m2mchildren = list(M2MChild.objects.filter(articles__isnull=False)) self.assertEqual(m2mchildren, []) # Ordering should not include any database column more than once (this # is most likely to ocurr naturally with model inheritance, so we # check it here). Regression test for #9390. This necessarily pokes at # the SQL string for the query, since the duplicate problems are only # apparent at that late stage. qs = ArticleWithAuthor.objects.order_by('pub_date', 'pk') sql = qs.query.get_compiler(qs.db).as_sql()[0] fragment = sql[sql.find('ORDER BY'):] pos = fragment.find('pub_date') self.assertEqual(fragment.find('pub_date', pos + 1), -1) def test_queryset_update_on_parent_model(self): """ Regression test for #10362 It is possible to call update() and only change a field in an ancestor model. """ article = ArticleWithAuthor.objects.create( author="fred", headline="Hey there!", pub_date=datetime.datetime(2009, 3, 1, 8, 0, 0)) update = ArticleWithAuthor.objects.filter( author="fred").update(headline="Oh, no!") self.assertEqual(update, 1) update = ArticleWithAuthor.objects.filter( pk=article.pk).update(headline="Oh, no!") self.assertEqual(update, 1) derivedm1 = DerivedM.objects.create( customPK=44, base_name="b1", derived_name="d1") self.assertEqual(derivedm1.customPK, 44) self.assertEqual(derivedm1.base_name, 'b1') self.assertEqual(derivedm1.derived_name, 'd1') derivedms = list(DerivedM.objects.all()) self.assertEqual(derivedms, [derivedm1]) def test_use_explicit_o2o_to_parent_as_pk(self): """ Regression tests for #10406 If there's a one-to-one link between a child model and the parent and no explicit pk declared, we can use the one-to-one link as the pk on the child. """ self.assertEqual(ParkingLot2._meta.pk.name, "parent") # However, the connector from child to parent need not be the pk on # the child at all. self.assertEqual(ParkingLot3._meta.pk.name, "primary_key") # the child->parent link self.assertEqual( ParkingLot3._meta.get_ancestor_link(Place).name, "parent") def test_all_fields_from_abstract_base_class(self): """ Regression tests for #7588 """ # All fields from an ABC, including those inherited non-abstractly # should be available on child classes (#7588). Creating this instance # should work without error. QualityControl.objects.create( headline="Problems in Django", pub_date=datetime.datetime.now(), quality=10, assignee="adrian") def test_abstract_base_class_m2m_relation_inheritance(self): # Check that many-to-many relations defined on an abstract base class # are correctly inherited (and created) on the child class. p1 = Person.objects.create(name='Alice') p2 = Person.objects.create(name='Bob') p3 = Person.objects.create(name='Carol') p4 = Person.objects.create(name='Dave') birthday = BirthdayParty.objects.create( name='Birthday party for Alice') birthday.attendees = [p1, p3] bachelor = BachelorParty.objects.create(name='Bachelor party for Bob') bachelor.attendees = [p2, p4] parties = list(p1.birthdayparty_set.all()) self.assertEqual(parties, [birthday]) parties = list(p1.bachelorparty_set.all()) self.assertEqual(parties, []) parties = list(p2.bachelorparty_set.all()) self.assertEqual(parties, [bachelor]) # Check that a subclass of a subclass of an abstract model doesn't get # it's own accessor. self.assertFalse(hasattr(p2, 'messybachelorparty_set')) # ... but it does inherit the m2m from it's parent messy = MessyBachelorParty.objects.create( name='Bachelor party for Dave') messy.attendees = [p4] messy_parent = messy.bachelorparty_ptr parties = list(p4.bachelorparty_set.all()) self.assertEqual(parties, [bachelor, messy_parent]) def test_abstract_verbose_name_plural_inheritance(self): """ verbose_name_plural correctly inherited from ABC if inheritance chain includes an abstract model. """ # Regression test for #11369: verbose_name_plural should be inherited # from an ABC even when there are one or more intermediate # abstract models in the inheritance chain, for consistency with # verbose_name. self.assertEqual( InternalCertificationAudit._meta.verbose_name_plural, u'Audits' ) def test_inherited_nullable_exclude(self): obj = SelfRefChild.objects.create(child_data=37, parent_data=42) self.assertQuerysetEqual( SelfRefParent.objects.exclude(self_data=72), [ obj.pk ], attrgetter("pk") ) self.assertQuerysetEqual( SelfRefChild.objects.exclude(self_data=72), [ obj.pk ], attrgetter("pk") ) def test_concrete_abstract_concrete_pk(self): """ Primary key set correctly with concrete->abstract->concrete inheritance. """ # Regression test for #13987: Primary key is incorrectly determined # when more than one model has a concrete->abstract->concrete # inheritance hierarchy. self.assertEqual( len([field for field in BusStation._meta.local_fields if field.primary_key]), 1 ) self.assertEqual( len([field for field in TrainStation._meta.local_fields if field.primary_key]), 1 ) self.assertIs(BusStation._meta.pk.model, BusStation) self.assertIs(TrainStation._meta.pk.model, TrainStation)
15,330
Python
.py
355
33.295775
80
0.620828
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,042
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/signals_regress/models.py
from django.db import models class Author(models.Model): name = models.CharField(max_length=20) def __unicode__(self): return self.name class Book(models.Model): name = models.CharField(max_length=20) authors = models.ManyToManyField(Author) def __unicode__(self): return self.name
322
Python
.py
10
27.2
44
0.701299
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,043
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/signals_regress/tests.py
import sys from StringIO import StringIO from django.test import TestCase from django.db import models from regressiontests.signals_regress.models import Author, Book signal_output = [] def pre_save_test(signal, sender, instance, **kwargs): signal_output.append('pre_save signal, %s' % instance) if kwargs.get('raw'): signal_output.append('Is raw') def post_save_test(signal, sender, instance, **kwargs): signal_output.append('post_save signal, %s' % instance) if 'created' in kwargs: if kwargs['created']: signal_output.append('Is created') else: signal_output.append('Is updated') if kwargs.get('raw'): signal_output.append('Is raw') def pre_delete_test(signal, sender, instance, **kwargs): signal_output.append('pre_save signal, %s' % instance) signal_output.append('instance.id is not None: %s' % (instance.id != None)) def post_delete_test(signal, sender, instance, **kwargs): signal_output.append('post_delete signal, %s' % instance) signal_output.append('instance.id is not None: %s' % (instance.id != None)) class SignalsRegressTests(TestCase): """ Testing signals before/after saving and deleting. """ def get_signal_output(self, fn, *args, **kwargs): # Flush any existing signal output global signal_output signal_output = [] fn(*args, **kwargs) return signal_output def setUp(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) self.pre_signals = (len(models.signals.pre_save.receivers), len(models.signals.post_save.receivers), len(models.signals.pre_delete.receivers), len(models.signals.post_delete.receivers)) models.signals.pre_save.connect(pre_save_test) models.signals.post_save.connect(post_save_test) models.signals.pre_delete.connect(pre_delete_test) models.signals.post_delete.connect(post_delete_test) def tearDown(self): models.signals.post_delete.disconnect(post_delete_test) models.signals.pre_delete.disconnect(pre_delete_test) models.signals.post_save.disconnect(post_save_test) models.signals.pre_save.disconnect(pre_save_test) # Check that all our signals got disconnected properly. post_signals = (len(models.signals.pre_save.receivers), len(models.signals.post_save.receivers), len(models.signals.pre_delete.receivers), len(models.signals.post_delete.receivers)) self.assertEqual(self.pre_signals, post_signals) def test_model_signals(self): """ Model saves should throw some signals. """ a1 = Author(name='Neal Stephenson') self.assertEqual(self.get_signal_output(a1.save), [ "pre_save signal, Neal Stephenson", "post_save signal, Neal Stephenson", "Is created" ]) b1 = Book(name='Snow Crash') self.assertEqual(self.get_signal_output(b1.save), [ "pre_save signal, Snow Crash", "post_save signal, Snow Crash", "Is created" ]) def test_m2m_signals(self): """ Assigning and removing to/from m2m shouldn't generate an m2m signal """ b1 = Book(name='Snow Crash') self.get_signal_output(b1.save) a1 = Author(name='Neal Stephenson') self.get_signal_output(a1.save) self.assertEqual(self.get_signal_output(setattr, b1, 'authors', [a1]), []) self.assertEqual(self.get_signal_output(setattr, b1, 'authors', []), [])
3,755
Python
.py
79
38.708861
83
0.649358
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,044
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_scripts/models.py
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 class Meta: ordering = ('-pub_date', 'headline')
300
Python
.py
8
31.125
75
0.690391
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,045
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_scripts/tests.py
""" A series of tests to establish that the command-line managment tools work as advertised - especially with regards to the handling of the DJANGO_SETTINGS_MODULE and default settings.py files. """ import os import shutil import sys import re from django import conf, bin, get_version from django.conf import settings from django.utils import unittest class AdminScriptTestCase(unittest.TestCase): def write_settings(self, filename, apps=None, is_dir=False, sdict=None): test_dir = os.path.dirname(os.path.dirname(__file__)) if is_dir: settings_dir = os.path.join(test_dir,filename) os.mkdir(settings_dir) settings_file = open(os.path.join(settings_dir,'__init__.py'), 'w') else: settings_file = open(os.path.join(test_dir, filename), 'w') settings_file.write('# Settings file automatically generated by regressiontests.admin_scripts test case\n') exports = [ 'DATABASES', 'ROOT_URLCONF' ] for s in exports: if hasattr(settings, s): o = getattr(settings, s) if not isinstance(o, dict): o = "'%s'" % o settings_file.write("%s = %s\n" % (s, o)) if apps is None: apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'admin_scripts'] if apps: settings_file.write("INSTALLED_APPS = %s\n" % apps) if sdict: for k, v in sdict.items(): settings_file.write("%s = %s\n" % (k, v)) settings_file.close() def remove_settings(self, filename, is_dir=False): test_dir = os.path.dirname(os.path.dirname(__file__)) full_name = os.path.join(test_dir, filename) if is_dir: shutil.rmtree(full_name) else: os.remove(full_name) # Also try to remove the compiled file; if it exists, it could # mess up later tests that depend upon the .py file not existing try: if sys.platform.startswith('java'): # Jython produces module$py.class files os.remove(re.sub(r'\.py$', '$py.class', full_name)) else: # CPython produces module.pyc files os.remove(full_name + 'c') except OSError: pass def _ext_backend_paths(self): """ Returns the paths for any external backend packages. """ paths = [] first_package_re = re.compile(r'(^[^\.]+)\.') for backend in settings.DATABASES.values(): result = first_package_re.findall(backend['ENGINE']) if result and result != 'django': backend_pkg = __import__(result[0]) backend_dir = os.path.dirname(backend_pkg.__file__) paths.append(os.path.dirname(backend_dir)) return paths def run_test(self, script, args, settings_file=None, apps=None): test_dir = os.path.dirname(os.path.dirname(__file__)) project_dir = os.path.dirname(test_dir) base_dir = os.path.dirname(project_dir) ext_backend_base_dirs = self._ext_backend_paths() # Remember the old environment old_django_settings_module = os.environ.get('DJANGO_SETTINGS_MODULE', None) if sys.platform.startswith('java'): python_path_var_name = 'JYTHONPATH' else: python_path_var_name = 'PYTHONPATH' old_python_path = os.environ.get(python_path_var_name, None) old_cwd = os.getcwd() # Set the test environment if settings_file: os.environ['DJANGO_SETTINGS_MODULE'] = settings_file elif 'DJANGO_SETTINGS_MODULE' in os.environ: del os.environ['DJANGO_SETTINGS_MODULE'] python_path = [test_dir, base_dir] python_path.extend(ext_backend_base_dirs) os.environ[python_path_var_name] = os.pathsep.join(python_path) # Build the command line executable = sys.executable arg_string = ' '.join(['%s' % arg for arg in args]) if ' ' in executable: cmd = '""%s" "%s" %s"' % (executable, script, arg_string) else: cmd = '%s "%s" %s' % (executable, script, arg_string) # Move to the test directory and run os.chdir(test_dir) try: from subprocess import Popen, PIPE p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) stdin, stdout, stderr = (p.stdin, p.stdout, p.stderr) p.wait() except ImportError: stdin, stdout, stderr = os.popen3(cmd) out, err = stdout.read(), stderr.read() # Restore the old environment if old_django_settings_module: os.environ['DJANGO_SETTINGS_MODULE'] = old_django_settings_module if old_python_path: os.environ[python_path_var_name] = old_python_path # Move back to the old working directory os.chdir(old_cwd) return out, err def run_django_admin(self, args, settings_file=None): bin_dir = os.path.abspath(os.path.dirname(bin.__file__)) return self.run_test(os.path.join(bin_dir,'django-admin.py'), args, settings_file) def run_manage(self, args, settings_file=None): conf_dir = os.path.dirname(conf.__file__) template_manage_py = os.path.join(conf_dir, 'project_template', 'manage.py') test_dir = os.path.dirname(os.path.dirname(__file__)) test_manage_py = os.path.join(test_dir, 'manage.py') shutil.copyfile(template_manage_py, test_manage_py) stdout, stderr = self.run_test('./manage.py', args, settings_file) # Cleanup - remove the generated manage.py script os.remove(test_manage_py) return stdout, stderr def assertNoOutput(self, stream): "Utility assertion: assert that the given stream is empty" self.assertEqual(len(stream), 0, "Stream should be empty: actually contains '%s'" % stream) def assertOutput(self, stream, msg): "Utility assertion: assert that the given message exists in the output" self.assertTrue(msg in stream, "'%s' does not match actual output text '%s'" % (msg, stream)) ########################################################################## # DJANGO ADMIN TESTS # This first series of test classes checks the environment processing # of the django-admin.py script ########################################################################## class DjangoAdminNoSettings(AdminScriptTestCase): "A series of tests for django-admin.py when there is no settings.py file." def test_builtin_command(self): "no settings: django-admin builtin commands fail with an import error when no settings provided" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'environment variable DJANGO_SETTINGS_MODULE is undefined') def test_builtin_with_bad_settings(self): "no settings: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['sqlall','--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Could not import settings 'bad_settings'") def test_builtin_with_bad_environment(self): "no settings: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args,'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "Could not import settings 'bad_settings'") class DjangoAdminDefaultSettings(AdminScriptTestCase): """A series of tests for django-admin.py when using a settings.py file that contains the test application. """ def setUp(self): self.write_settings('settings.py') def tearDown(self): self.remove_settings('settings.py') def test_builtin_command(self): "default: django-admin builtin commands fail with an import error when no settings provided" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'environment variable DJANGO_SETTINGS_MODULE is undefined') def test_builtin_with_settings(self): "default: django-admin builtin commands succeed if settings are provided as argument" args = ['sqlall','--settings=settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, 'CREATE TABLE') def test_builtin_with_environment(self): "default: django-admin builtin commands succeed if settings are provided in the environment" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args,'settings') self.assertNoOutput(err) self.assertOutput(out, 'CREATE TABLE') def test_builtin_with_bad_settings(self): "default: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['sqlall','--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Could not import settings 'bad_settings'") def test_builtin_with_bad_environment(self): "default: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args,'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "Could not import settings 'bad_settings'") def test_custom_command(self): "default: django-admin can't execute user commands if it isn't provided settings" args = ['noargs_command'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "default: django-admin can execute user commands if settings are provided as argument" args = ['noargs_command', '--settings=settings'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:NoArgsCommand") def test_custom_command_with_environment(self): "default: django-admin can execute user commands if settings are provided in environment" args = ['noargs_command'] out, err = self.run_django_admin(args,'settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:NoArgsCommand") class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase): """A series of tests for django-admin.py when using a settings.py file that contains the test application specified using a full path. """ def setUp(self): self.write_settings('settings.py', ['django.contrib.auth', 'django.contrib.contenttypes', 'regressiontests.admin_scripts']) def tearDown(self): self.remove_settings('settings.py') def test_builtin_command(self): "fulldefault: django-admin builtin commands fail with an import error when no settings provided" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'environment variable DJANGO_SETTINGS_MODULE is undefined') def test_builtin_with_settings(self): "fulldefault: django-admin builtin commands succeed if a settings file is provided" args = ['sqlall','--settings=settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, 'CREATE TABLE') def test_builtin_with_environment(self): "fulldefault: django-admin builtin commands succeed if the environment contains settings" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args,'settings') self.assertNoOutput(err) self.assertOutput(out, 'CREATE TABLE') def test_builtin_with_bad_settings(self): "fulldefault: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['sqlall','--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Could not import settings 'bad_settings'") def test_builtin_with_bad_environment(self): "fulldefault: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args,'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "Could not import settings 'bad_settings'") def test_custom_command(self): "fulldefault: django-admin can't execute user commands unless settings are provided" args = ['noargs_command'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "fulldefault: django-admin can execute user commands if settings are provided as argument" args = ['noargs_command', '--settings=settings'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:NoArgsCommand") def test_custom_command_with_environment(self): "fulldefault: django-admin can execute user commands if settings are provided in environment" args = ['noargs_command'] out, err = self.run_django_admin(args,'settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:NoArgsCommand") class DjangoAdminMinimalSettings(AdminScriptTestCase): """A series of tests for django-admin.py when using a settings.py file that doesn't contain the test application. """ def setUp(self): self.write_settings('settings.py', apps=['django.contrib.auth','django.contrib.contenttypes']) def tearDown(self): self.remove_settings('settings.py') def test_builtin_command(self): "minimal: django-admin builtin commands fail with an import error when no settings provided" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'environment variable DJANGO_SETTINGS_MODULE is undefined') def test_builtin_with_settings(self): "minimal: django-admin builtin commands fail if settings are provided as argument" args = ['sqlall','--settings=settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'App with label admin_scripts could not be found') def test_builtin_with_environment(self): "minimal: django-admin builtin commands fail if settings are provided in the environment" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args,'settings') self.assertNoOutput(out) self.assertOutput(err, 'App with label admin_scripts could not be found') def test_builtin_with_bad_settings(self): "minimal: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['sqlall','--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Could not import settings 'bad_settings'") def test_builtin_with_bad_environment(self): "minimal: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args,'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "Could not import settings 'bad_settings'") def test_custom_command(self): "minimal: django-admin can't execute user commands unless settings are provided" args = ['noargs_command'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "minimal: django-admin can't execute user commands, even if settings are provided as argument" args = ['noargs_command', '--settings=settings'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_environment(self): "minimal: django-admin can't execute user commands, even if settings are provided in environment" args = ['noargs_command'] out, err = self.run_django_admin(args,'settings') self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") class DjangoAdminAlternateSettings(AdminScriptTestCase): """A series of tests for django-admin.py when using a settings file with a name other than 'settings.py'. """ def setUp(self): self.write_settings('alternate_settings.py') def tearDown(self): self.remove_settings('alternate_settings.py') def test_builtin_command(self): "alternate: django-admin builtin commands fail with an import error when no settings provided" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'environment variable DJANGO_SETTINGS_MODULE is undefined') def test_builtin_with_settings(self): "alternate: django-admin builtin commands succeed if settings are provided as argument" args = ['sqlall','--settings=alternate_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, 'CREATE TABLE') def test_builtin_with_environment(self): "alternate: django-admin builtin commands succeed if settings are provided in the environment" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args,'alternate_settings') self.assertNoOutput(err) self.assertOutput(out, 'CREATE TABLE') def test_builtin_with_bad_settings(self): "alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['sqlall','--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Could not import settings 'bad_settings'") def test_builtin_with_bad_environment(self): "alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args,'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "Could not import settings 'bad_settings'") def test_custom_command(self): "alternate: django-admin can't execute user commands unless settings are provided" args = ['noargs_command'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "alternate: django-admin can execute user commands if settings are provided as argument" args = ['noargs_command', '--settings=alternate_settings'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:NoArgsCommand") def test_custom_command_with_environment(self): "alternate: django-admin can execute user commands if settings are provided in environment" args = ['noargs_command'] out, err = self.run_django_admin(args,'alternate_settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:NoArgsCommand") class DjangoAdminMultipleSettings(AdminScriptTestCase): """A series of tests for django-admin.py when multiple settings files (including the default 'settings.py') are available. The default settings file is insufficient for performing the operations described, so the alternate settings must be used by the running script. """ def setUp(self): self.write_settings('settings.py', apps=['django.contrib.auth','django.contrib.contenttypes']) self.write_settings('alternate_settings.py') def tearDown(self): self.remove_settings('settings.py') self.remove_settings('alternate_settings.py') def test_builtin_command(self): "alternate: django-admin builtin commands fail with an import error when no settings provided" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'environment variable DJANGO_SETTINGS_MODULE is undefined') def test_builtin_with_settings(self): "alternate: django-admin builtin commands succeed if settings are provided as argument" args = ['sqlall','--settings=alternate_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, 'CREATE TABLE') def test_builtin_with_environment(self): "alternate: django-admin builtin commands succeed if settings are provided in the environment" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args,'alternate_settings') self.assertNoOutput(err) self.assertOutput(out, 'CREATE TABLE') def test_builtin_with_bad_settings(self): "alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['sqlall','--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertOutput(err, "Could not import settings 'bad_settings'") def test_builtin_with_bad_environment(self): "alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args,'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "Could not import settings 'bad_settings'") def test_custom_command(self): "alternate: django-admin can't execute user commands unless settings are provided" args = ['noargs_command'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "alternate: django-admin can't execute user commands, even if settings are provided as argument" args = ['noargs_command', '--settings=alternate_settings'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:NoArgsCommand") def test_custom_command_with_environment(self): "alternate: django-admin can't execute user commands, even if settings are provided in environment" args = ['noargs_command'] out, err = self.run_django_admin(args,'alternate_settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:NoArgsCommand") class DjangoAdminSettingsDirectory(AdminScriptTestCase): """ A series of tests for django-admin.py when the settings file is in a directory. (see #9751). """ def setUp(self): self.write_settings('settings', is_dir=True) def tearDown(self): self.remove_settings('settings', is_dir=True) def test_setup_environ(self): "directory: startapp creates the correct directory" test_dir = os.path.dirname(os.path.dirname(__file__)) args = ['startapp','settings_test'] out, err = self.run_django_admin(args,'settings') self.assertNoOutput(err) self.assertTrue(os.path.exists(os.path.join(test_dir, 'settings_test'))) shutil.rmtree(os.path.join(test_dir, 'settings_test')) def test_builtin_command(self): "directory: django-admin builtin commands fail with an import error when no settings provided" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'environment variable DJANGO_SETTINGS_MODULE is undefined') def test_builtin_with_bad_settings(self): "directory: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['sqlall','--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertOutput(err, "Could not import settings 'bad_settings'") def test_builtin_with_bad_environment(self): "directory: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args,'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "Could not import settings 'bad_settings'") def test_custom_command(self): "directory: django-admin can't execute user commands unless settings are provided" args = ['noargs_command'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_builtin_with_settings(self): "directory: django-admin builtin commands succeed if settings are provided as argument" args = ['sqlall','--settings=settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, 'CREATE TABLE') def test_builtin_with_environment(self): "directory: django-admin builtin commands succeed if settings are provided in the environment" args = ['sqlall','admin_scripts'] out, err = self.run_django_admin(args,'settings') self.assertNoOutput(err) self.assertOutput(out, 'CREATE TABLE') ########################################################################## # MANAGE.PY TESTS # This next series of test classes checks the environment processing # of the generated manage.py script ########################################################################## class ManageNoSettings(AdminScriptTestCase): "A series of tests for manage.py when there is no settings.py file." def test_builtin_command(self): "no settings: manage.py builtin commands fail with an import error when no settings provided" args = ['sqlall','admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") def test_builtin_with_bad_settings(self): "no settings: manage.py builtin commands fail if settings file (from argument) doesn't exist" args = ['sqlall','--settings=bad_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") def test_builtin_with_bad_environment(self): "no settings: manage.py builtin commands fail if settings file (from environment) doesn't exist" args = ['sqlall','admin_scripts'] out, err = self.run_manage(args,'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") class ManageDefaultSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings.py file that contains the test application. """ def setUp(self): self.write_settings('settings.py') def tearDown(self): self.remove_settings('settings.py') def test_builtin_command(self): "default: manage.py builtin commands succeed when default settings are appropriate" args = ['sqlall','admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, 'CREATE TABLE') def test_builtin_with_settings(self): "default: manage.py builtin commands succeed if settings are provided as argument" args = ['sqlall','--settings=settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, 'CREATE TABLE') def test_builtin_with_environment(self): "default: manage.py builtin commands succeed if settings are provided in the environment" args = ['sqlall','admin_scripts'] out, err = self.run_manage(args,'settings') self.assertNoOutput(err) self.assertOutput(out, 'CREATE TABLE') def test_builtin_with_bad_settings(self): "default: manage.py builtin commands succeed if settings file (from argument) doesn't exist" args = ['sqlall','--settings=bad_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Could not import settings 'bad_settings'") def test_builtin_with_bad_environment(self): "default: manage.py builtin commands fail if settings file (from environment) doesn't exist" args = ['sqlall','admin_scripts'] out, err = self.run_manage(args,'bad_settings') self.assertNoOutput(err) self.assertOutput(out, 'CREATE TABLE') def test_custom_command(self): "default: manage.py can execute user commands when default settings are appropriate" args = ['noargs_command'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:NoArgsCommand") def test_custom_command_with_settings(self): "default: manage.py can execute user commands when settings are provided as argument" args = ['noargs_command', '--settings=settings'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:NoArgsCommand") def test_custom_command_with_environment(self): "default: manage.py can execute user commands when settings are provided in environment" args = ['noargs_command'] out, err = self.run_manage(args,'settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:NoArgsCommand") class ManageFullPathDefaultSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings.py file that contains the test application specified using a full path. """ def setUp(self): self.write_settings('settings.py', ['django.contrib.auth', 'django.contrib.contenttypes', 'regressiontests.admin_scripts']) def tearDown(self): self.remove_settings('settings.py') def test_builtin_command(self): "fulldefault: manage.py builtin commands succeed when default settings are appropriate" args = ['sqlall','admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, 'CREATE TABLE') def test_builtin_with_settings(self): "fulldefault: manage.py builtin commands succeed if settings are provided as argument" args = ['sqlall','--settings=settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, 'CREATE TABLE') def test_builtin_with_environment(self): "fulldefault: manage.py builtin commands succeed if settings are provided in the environment" args = ['sqlall','admin_scripts'] out, err = self.run_manage(args,'settings') self.assertNoOutput(err) self.assertOutput(out, 'CREATE TABLE') def test_builtin_with_bad_settings(self): "fulldefault: manage.py builtin commands succeed if settings file (from argument) doesn't exist" args = ['sqlall','--settings=bad_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Could not import settings 'bad_settings'") def test_builtin_with_bad_environment(self): "fulldefault: manage.py builtin commands fail if settings file (from environment) doesn't exist" args = ['sqlall','admin_scripts'] out, err = self.run_manage(args,'bad_settings') self.assertNoOutput(err) self.assertOutput(out, 'CREATE TABLE') def test_custom_command(self): "fulldefault: manage.py can execute user commands when default settings are appropriate" args = ['noargs_command'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:NoArgsCommand") def test_custom_command_with_settings(self): "fulldefault: manage.py can execute user commands when settings are provided as argument" args = ['noargs_command', '--settings=settings'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:NoArgsCommand") def test_custom_command_with_environment(self): "fulldefault: manage.py can execute user commands when settings are provided in environment" args = ['noargs_command'] out, err = self.run_manage(args,'settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:NoArgsCommand") class ManageMinimalSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings.py file that doesn't contain the test application. """ def setUp(self): self.write_settings('settings.py', apps=['django.contrib.auth','django.contrib.contenttypes']) def tearDown(self): self.remove_settings('settings.py') def test_builtin_command(self): "minimal: manage.py builtin commands fail with an import error when no settings provided" args = ['sqlall','admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, 'App with label admin_scripts could not be found') def test_builtin_with_settings(self): "minimal: manage.py builtin commands fail if settings are provided as argument" args = ['sqlall','--settings=settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, 'App with label admin_scripts could not be found') def test_builtin_with_environment(self): "minimal: manage.py builtin commands fail if settings are provided in the environment" args = ['sqlall','admin_scripts'] out, err = self.run_manage(args,'settings') self.assertNoOutput(out) self.assertOutput(err, 'App with label admin_scripts could not be found') def test_builtin_with_bad_settings(self): "minimal: manage.py builtin commands fail if settings file (from argument) doesn't exist" args = ['sqlall','--settings=bad_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Could not import settings 'bad_settings'") def test_builtin_with_bad_environment(self): "minimal: manage.py builtin commands fail if settings file (from environment) doesn't exist" args = ['sqlall','admin_scripts'] out, err = self.run_manage(args,'bad_settings') self.assertNoOutput(out) self.assertOutput(err, 'App with label admin_scripts could not be found') def test_custom_command(self): "minimal: manage.py can't execute user commands without appropriate settings" args = ['noargs_command'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "minimal: manage.py can't execute user commands, even if settings are provided as argument" args = ['noargs_command', '--settings=settings'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_environment(self): "minimal: manage.py can't execute user commands, even if settings are provided in environment" args = ['noargs_command'] out, err = self.run_manage(args,'settings') self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") class ManageAlternateSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings file with a name other than 'settings.py'. """ def setUp(self): self.write_settings('alternate_settings.py') def tearDown(self): self.remove_settings('alternate_settings.py') def test_builtin_command(self): "alternate: manage.py builtin commands fail with an import error when no default settings provided" args = ['sqlall','admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") def test_builtin_with_settings(self): "alternate: manage.py builtin commands fail if settings are provided as argument but no defaults" args = ['sqlall','--settings=alternate_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") def test_builtin_with_environment(self): "alternate: manage.py builtin commands fail if settings are provided in the environment but no defaults" args = ['sqlall','admin_scripts'] out, err = self.run_manage(args,'alternate_settings') self.assertNoOutput(out) self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") def test_builtin_with_bad_settings(self): "alternate: manage.py builtin commands fail if settings file (from argument) doesn't exist" args = ['sqlall','--settings=bad_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") def test_builtin_with_bad_environment(self): "alternate: manage.py builtin commands fail if settings file (from environment) doesn't exist" args = ['sqlall','admin_scripts'] out, err = self.run_manage(args,'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") def test_custom_command(self): "alternate: manage.py can't execute user commands" args = ['noargs_command'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") def test_custom_command_with_settings(self): "alternate: manage.py can't execute user commands, even if settings are provided as argument" args = ['noargs_command', '--settings=alternate_settings'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") def test_custom_command_with_environment(self): "alternate: manage.py can't execute user commands, even if settings are provided in environment" args = ['noargs_command'] out, err = self.run_manage(args,'alternate_settings') self.assertNoOutput(out) self.assertOutput(err, "Can't find the file 'settings.py' in the directory containing './manage.py'") class ManageMultipleSettings(AdminScriptTestCase): """A series of tests for manage.py when multiple settings files (including the default 'settings.py') are available. The default settings file is insufficient for performing the operations described, so the alternate settings must be used by the running script. """ def setUp(self): self.write_settings('settings.py', apps=['django.contrib.auth','django.contrib.contenttypes']) self.write_settings('alternate_settings.py') def tearDown(self): self.remove_settings('settings.py') self.remove_settings('alternate_settings.py') def test_builtin_command(self): "multiple: manage.py builtin commands fail with an import error when no settings provided" args = ['sqlall','admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, 'App with label admin_scripts could not be found.') def test_builtin_with_settings(self): "multiple: manage.py builtin commands succeed if settings are provided as argument" args = ['sqlall','--settings=alternate_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, 'CREATE TABLE') def test_builtin_with_environment(self): "multiple: manage.py builtin commands fail if settings are provided in the environment" # FIXME: This doesn't seem to be the correct output. args = ['sqlall','admin_scripts'] out, err = self.run_manage(args,'alternate_settings') self.assertNoOutput(out) self.assertOutput(err, 'App with label admin_scripts could not be found.') def test_builtin_with_bad_settings(self): "multiple: manage.py builtin commands fail if settings file (from argument) doesn't exist" args = ['sqlall','--settings=bad_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Could not import settings 'bad_settings'") def test_builtin_with_bad_environment(self): "multiple: manage.py builtin commands fail if settings file (from environment) doesn't exist" args = ['sqlall','admin_scripts'] out, err = self.run_manage(args,'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "App with label admin_scripts could not be found") def test_custom_command(self): "multiple: manage.py can't execute user commands using default settings" args = ['noargs_command'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "multiple: manage.py can execute user commands if settings are provided as argument" args = ['noargs_command', '--settings=alternate_settings'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:NoArgsCommand") def test_custom_command_with_environment(self): "multiple: manage.py can execute user commands if settings are provided in environment" args = ['noargs_command'] out, err = self.run_manage(args,'alternate_settings') self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") class ManageSettingsWithImportError(AdminScriptTestCase): """Tests for manage.py when using the default settings.py file with an import error. Ticket #14130. """ def setUp(self): self.write_settings_with_import_error('settings.py') def tearDown(self): self.remove_settings('settings.py') def write_settings_with_import_error(self, filename, apps=None, is_dir=False, sdict=None): test_dir = os.path.dirname(os.path.dirname(__file__)) if is_dir: settings_dir = os.path.join(test_dir,filename) os.mkdir(settings_dir) settings_file = open(os.path.join(settings_dir,'__init__.py'), 'w') else: settings_file = open(os.path.join(test_dir, filename), 'w') settings_file.write('# Settings file automatically generated by regressiontests.admin_scripts test case\n') settings_file.write('# The next line will cause an import error:\nimport foo42bar\n') settings_file.close() def test_builtin_command(self): "import error: manage.py builtin commands shows useful diagnostic info when settings with import errors is provided" args = ['sqlall','admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "ImportError: No module named foo42bar") class ManageValidate(AdminScriptTestCase): def tearDown(self): self.remove_settings('settings.py') def test_nonexistent_app(self): "manage.py validate reports an error on a non-existent app in INSTALLED_APPS" self.write_settings('settings.py', apps=['admin_scriptz.broken_app'], sdict={'USE_I18N': False}) args = ['validate'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, 'No module named admin_scriptz') def test_broken_app(self): "manage.py validate reports an ImportError if an app's models.py raises one on import" self.write_settings('settings.py', apps=['admin_scripts.broken_app']) args = ['validate'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, 'ImportError') def test_complex_app(self): "manage.py validate does not raise an ImportError validating a complex app with nested calls to load_app" self.write_settings('settings.py', apps=['admin_scripts.complex_app', 'admin_scripts.simple_app'], sdict={'DEBUG': True}) args = ['validate'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, '0 errors found') def test_app_with_import(self): "manage.py validate does not raise errors when an app imports a base class that itself has an abstract base" self.write_settings('settings.py', apps=['admin_scripts.app_with_import', 'django.contrib.comments'], sdict={'DEBUG': True}) args = ['validate'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, '0 errors found') class ManageRunserver(AdminScriptTestCase): def setUp(self): from django.core.management.commands.runserver import BaseRunserverCommand def monkey_run(*args, **options): return self.cmd = BaseRunserverCommand() self.cmd.run = monkey_run def assertServerSettings(self, addr, port, ipv6=None, raw_ipv6=False): self.assertEqual(self.cmd.addr, addr) self.assertEqual(self.cmd.port, port) self.assertEqual(self.cmd.use_ipv6, ipv6) self.assertEqual(self.cmd._raw_ipv6, raw_ipv6) def test_runserver_addrport(self): self.cmd.handle() self.assertServerSettings('127.0.0.1', '8000') self.cmd.handle(addrport="1.2.3.4:8000") self.assertServerSettings('1.2.3.4', '8000') self.cmd.handle(addrport="7000") self.assertServerSettings('127.0.0.1', '7000') # IPv6 self.cmd.handle(addrport="", use_ipv6=True) self.assertServerSettings('::1', '8000', ipv6=True, raw_ipv6=True) self.cmd.handle(addrport="7000", use_ipv6=True) self.assertServerSettings('::1', '7000', ipv6=True, raw_ipv6=True) self.cmd.handle(addrport="[2001:0db8:1234:5678::9]:7000") self.assertServerSettings('2001:0db8:1234:5678::9', '7000', ipv6=True, raw_ipv6=True) # Hostname self.cmd.handle(addrport="localhost:8000") self.assertServerSettings('localhost', '8000') self.cmd.handle(addrport="test.domain.local:7000") self.assertServerSettings('test.domain.local', '7000') self.cmd.handle(addrport="test.domain.local:7000", use_ipv6=True) self.assertServerSettings('test.domain.local', '7000', ipv6=True) # Potentially ambiguous # Only 4 characters, all of which could be in an ipv6 address self.cmd.handle(addrport="beef:7654") self.assertServerSettings('beef', '7654') # Uses only characters that could be in an ipv6 address self.cmd.handle(addrport="deadbeef:7654") self.assertServerSettings('deadbeef', '7654') ########################################################################## # COMMAND PROCESSING TESTS # Check that user-space commands are correctly handled - in particular, # that arguments to the commands are correctly parsed and processed. ########################################################################## class CommandTypes(AdminScriptTestCase): "Tests for the various types of base command types that can be defined." def setUp(self): self.write_settings('settings.py') def tearDown(self): self.remove_settings('settings.py') def test_version(self): "--version is handled as a special case" args = ['--version'] out, err = self.run_manage(args) self.assertNoOutput(err) # Only check the first part of the version number self.assertOutput(out, get_version().split('-')[0]) def test_help(self): "--help is handled as a special case" args = ['--help'] out, err = self.run_manage(args) if sys.version_info < (2, 5): self.assertOutput(out, "usage: manage.py subcommand [options] [args]") else: self.assertOutput(out, "Usage: manage.py subcommand [options] [args]") self.assertOutput(err, "Type 'manage.py help <subcommand>' for help on a specific subcommand.") def test_short_help(self): "-h is handled as a short form of --help" args = ['-h'] out, err = self.run_manage(args) if sys.version_info < (2, 5): self.assertOutput(out, "usage: manage.py subcommand [options] [args]") else: self.assertOutput(out, "Usage: manage.py subcommand [options] [args]") self.assertOutput(err, "Type 'manage.py help <subcommand>' for help on a specific subcommand.") def test_specific_help(self): "--help can be used on a specific command" args = ['sqlall','--help'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "Prints the CREATE TABLE, custom SQL and CREATE INDEX SQL statements for the given model module name(s).") def test_base_command(self): "User BaseCommands can execute when a label is provided" args = ['base_command','testlabel'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:BaseCommand labels=('testlabel',), options=[('option_a', '1'), ('option_b', '2'), ('option_c', '3'), ('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]") def test_base_command_no_label(self): "User BaseCommands can execute when no labels are provided" args = ['base_command'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:BaseCommand labels=(), options=[('option_a', '1'), ('option_b', '2'), ('option_c', '3'), ('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]") def test_base_command_multiple_label(self): "User BaseCommands can execute when no labels are provided" args = ['base_command','testlabel','anotherlabel'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:BaseCommand labels=('testlabel', 'anotherlabel'), options=[('option_a', '1'), ('option_b', '2'), ('option_c', '3'), ('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]") def test_base_command_with_option(self): "User BaseCommands can execute with options when a label is provided" args = ['base_command','testlabel','--option_a=x'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:BaseCommand labels=('testlabel',), options=[('option_a', 'x'), ('option_b', '2'), ('option_c', '3'), ('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]") def test_base_command_with_options(self): "User BaseCommands can execute with multiple options when a label is provided" args = ['base_command','testlabel','-a','x','--option_b=y'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:BaseCommand labels=('testlabel',), options=[('option_a', 'x'), ('option_b', 'y'), ('option_c', '3'), ('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]") def test_noargs(self): "NoArg Commands can be executed" args = ['noargs_command'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:NoArgsCommand options=[('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]") def test_noargs_with_args(self): "NoArg Commands raise an error if an argument is provided" args = ['noargs_command','argument'] out, err = self.run_manage(args) self.assertOutput(err, "Error: Command doesn't accept any arguments") def test_app_command(self): "User AppCommands can execute when a single app name is provided" args = ['app_command', 'auth'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:AppCommand app=<module 'django.contrib.auth.models'") self.assertOutput(out, os.sep.join(['django','contrib','auth','models.py'])) self.assertOutput(out, "'>, options=[('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]") def test_app_command_no_apps(self): "User AppCommands raise an error when no app name is provided" args = ['app_command'] out, err = self.run_manage(args) self.assertOutput(err, 'Error: Enter at least one appname.') def test_app_command_multiple_apps(self): "User AppCommands raise an error when multiple app names are provided" args = ['app_command','auth','contenttypes'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:AppCommand app=<module 'django.contrib.auth.models'") self.assertOutput(out, os.sep.join(['django','contrib','auth','models.py'])) self.assertOutput(out, "'>, options=[('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]") self.assertOutput(out, "EXECUTE:AppCommand app=<module 'django.contrib.contenttypes.models'") self.assertOutput(out, os.sep.join(['django','contrib','contenttypes','models.py'])) self.assertOutput(out, "'>, options=[('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]") def test_app_command_invalid_appname(self): "User AppCommands can execute when a single app name is provided" args = ['app_command', 'NOT_AN_APP'] out, err = self.run_manage(args) self.assertOutput(err, "App with label NOT_AN_APP could not be found") def test_app_command_some_invalid_appnames(self): "User AppCommands can execute when some of the provided app names are invalid" args = ['app_command', 'auth', 'NOT_AN_APP'] out, err = self.run_manage(args) self.assertOutput(err, "App with label NOT_AN_APP could not be found") def test_label_command(self): "User LabelCommands can execute when a label is provided" args = ['label_command','testlabel'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:LabelCommand label=testlabel, options=[('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]") def test_label_command_no_label(self): "User LabelCommands raise an error if no label is provided" args = ['label_command'] out, err = self.run_manage(args) self.assertOutput(err, 'Enter at least one label') def test_label_command_multiple_label(self): "User LabelCommands are executed multiple times if multiple labels are provided" args = ['label_command','testlabel','anotherlabel'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:LabelCommand label=testlabel, options=[('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]") self.assertOutput(out, "EXECUTE:LabelCommand label=anotherlabel, options=[('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]") class ArgumentOrder(AdminScriptTestCase): """Tests for 2-stage argument parsing scheme. django-admin command arguments are parsed in 2 parts; the core arguments (--settings, --traceback and --pythonpath) are parsed using a Lax parser. This Lax parser ignores any unknown options. Then the full settings are passed to the command parser, which extracts commands of interest to the individual command. """ def setUp(self): self.write_settings('settings.py', apps=['django.contrib.auth','django.contrib.contenttypes']) self.write_settings('alternate_settings.py') def tearDown(self): self.remove_settings('settings.py') self.remove_settings('alternate_settings.py') def test_setting_then_option(self): "Options passed after settings are correctly handled" args = ['base_command','testlabel','--settings=alternate_settings','--option_a=x'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:BaseCommand labels=('testlabel',), options=[('option_a', 'x'), ('option_b', '2'), ('option_c', '3'), ('pythonpath', None), ('settings', 'alternate_settings'), ('traceback', None), ('verbosity', '1')]") def test_setting_then_short_option(self): "Short options passed after settings are correctly handled" args = ['base_command','testlabel','--settings=alternate_settings','--option_a=x'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:BaseCommand labels=('testlabel',), options=[('option_a', 'x'), ('option_b', '2'), ('option_c', '3'), ('pythonpath', None), ('settings', 'alternate_settings'), ('traceback', None), ('verbosity', '1')]") def test_option_then_setting(self): "Options passed before settings are correctly handled" args = ['base_command','testlabel','--option_a=x','--settings=alternate_settings'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:BaseCommand labels=('testlabel',), options=[('option_a', 'x'), ('option_b', '2'), ('option_c', '3'), ('pythonpath', None), ('settings', 'alternate_settings'), ('traceback', None), ('verbosity', '1')]") def test_short_option_then_setting(self): "Short options passed before settings are correctly handled" args = ['base_command','testlabel','-a','x','--settings=alternate_settings'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:BaseCommand labels=('testlabel',), options=[('option_a', 'x'), ('option_b', '2'), ('option_c', '3'), ('pythonpath', None), ('settings', 'alternate_settings'), ('traceback', None), ('verbosity', '1')]") def test_option_then_setting_then_option(self): "Options are correctly handled when they are passed before and after a setting" args = ['base_command','testlabel','--option_a=x','--settings=alternate_settings','--option_b=y'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:BaseCommand labels=('testlabel',), options=[('option_a', 'x'), ('option_b', 'y'), ('option_c', '3'), ('pythonpath', None), ('settings', 'alternate_settings'), ('traceback', None), ('verbosity', '1')]")
61,095
Python
.py
1,084
48.049815
241
0.667252
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,046
app_command.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_scripts/management/commands/app_command.py
from django.core.management.base import AppCommand class Command(AppCommand): help = 'Test Application-based commands' requires_model_validation = False args = '[appname ...]' def handle_app(self, app, **options): print 'EXECUTE:AppCommand app=%s, options=%s' % (app, sorted(options.items()))
328
Python
.py
7
40.857143
86
0.703226
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,047
noargs_command.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_scripts/management/commands/noargs_command.py
from django.core.management.base import NoArgsCommand class Command(NoArgsCommand): help = "Test No-args commands" requires_model_validation = False def handle_noargs(self, **options): print 'EXECUTE:NoArgsCommand options=%s' % sorted(options.items())
275
Python
.py
6
41
74
0.74812
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,048
label_command.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_scripts/management/commands/label_command.py
from django.core.management.base import LabelCommand class Command(LabelCommand): help = "Test Label-based commands" requires_model_validation = False args = '<label>' def handle_label(self, label, **options): print 'EXECUTE:LabelCommand label=%s, options=%s' % (label, sorted(options.items()))
321
Python
.py
7
41.142857
92
0.717949
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,049
base_command.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_scripts/management/commands/base_command.py
from django.core.management.base import BaseCommand from optparse import make_option class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--option_a','-a', action='store', dest='option_a', default='1'), make_option('--option_b','-b', action='store', dest='option_b', default='2'), make_option('--option_c','-c', action='store', dest='option_c', default='3'), ) help = 'Test basic commands' requires_model_validation = False args = '[labels ...]' def handle(self, *labels, **options): print 'EXECUTE:BaseCommand labels=%s, options=%s' % (labels, sorted(options.items()))
658
Python
.py
13
45.153846
93
0.650078
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,050
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_scripts/app_with_import/models.py
from django.contrib.comments.models import Comment from django.db import models # Regression for #13368. This is an example of a model # that imports a class that has an abstract base class. class CommentScore(models.Model): comment = models.OneToOneField(Comment, primary_key=True)
288
Python
.py
6
46.166667
61
0.807829
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,051
bar.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_scripts/complex_app/models/bar.py
from django.db import models from admin_scripts.complex_app.admin import foo class Bar(models.Model): name = models.CharField(max_length=5) class Meta: app_label = 'complex_app'
195
Python
.py
6
28.666667
47
0.739362
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,052
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_scripts/complex_app/models/__init__.py
from admin_scripts.complex_app.models.bar import Bar from admin_scripts.complex_app.models.foo import Foo __all__ = ['Foo', 'Bar']
132
Python
.py
3
42.666667
52
0.757813
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,053
foo.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_scripts/complex_app/models/foo.py
from django.db import models class Foo(models.Model): name = models.CharField(max_length=5) class Meta: app_label = 'complex_app'
147
Python
.py
5
25
41
0.702128
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,054
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/transactions_regress/tests.py
from django.core.exceptions import ImproperlyConfigured from django.db import connection, transaction from django.db.transaction import commit_on_success, commit_manually, TransactionManagementError from django.test import TransactionTestCase, skipUnlessDBFeature from models import Mod class TestTransactionClosing(TransactionTestCase): """ Tests to make sure that transactions are properly closed when they should be, and aren't left pending after operations have been performed in them. Refs #9964. """ def test_raw_committed_on_success(self): """ Make sure a transaction consisting of raw SQL execution gets committed by the commit_on_success decorator. """ @commit_on_success def raw_sql(): "Write a record using raw sql under a commit_on_success decorator" cursor = connection.cursor() cursor.execute("INSERT into transactions_regress_mod (id,fld) values (17,18)") raw_sql() # Rollback so that if the decorator didn't commit, the record is unwritten transaction.rollback() try: # Check that the record is in the DB obj = Mod.objects.get(pk=17) self.assertEqual(obj.fld, 18) except Mod.DoesNotExist: self.fail("transaction with raw sql not committed") def test_commit_manually_enforced(self): """ Make sure that under commit_manually, even "read-only" transaction require closure (commit or rollback), and a transaction left pending is treated as an error. """ @commit_manually def non_comitter(): "Execute a managed transaction with read-only operations and fail to commit" _ = Mod.objects.count() self.assertRaises(TransactionManagementError, non_comitter) def test_commit_manually_commit_ok(self): """ Test that under commit_manually, a committed transaction is accepted by the transaction management mechanisms """ @commit_manually def committer(): """ Perform a database query, then commit the transaction """ _ = Mod.objects.count() transaction.commit() try: committer() except TransactionManagementError: self.fail("Commit did not clear the transaction state") def test_commit_manually_rollback_ok(self): """ Test that under commit_manually, a rolled-back transaction is accepted by the transaction management mechanisms """ @commit_manually def roller_back(): """ Perform a database query, then rollback the transaction """ _ = Mod.objects.count() transaction.rollback() try: roller_back() except TransactionManagementError: self.fail("Rollback did not clear the transaction state") def test_commit_manually_enforced_after_commit(self): """ Test that under commit_manually, if a transaction is committed and an operation is performed later, we still require the new transaction to be closed """ @commit_manually def fake_committer(): "Query, commit, then query again, leaving with a pending transaction" _ = Mod.objects.count() transaction.commit() _ = Mod.objects.count() self.assertRaises(TransactionManagementError, fake_committer) @skipUnlessDBFeature('supports_transactions') def test_reuse_cursor_reference(self): """ Make sure transaction closure is enforced even when the queries are performed through a single cursor reference retrieved in the beginning (this is to show why it is wrong to set the transaction dirty only when a cursor is fetched from the connection). """ @commit_on_success def reuse_cursor_ref(): """ Fetch a cursor, perform an query, rollback to close the transaction, then write a record (in a new transaction) using the same cursor object (reference). All this under commit_on_success, so the second insert should be committed. """ cursor = connection.cursor() cursor.execute("INSERT into transactions_regress_mod (id,fld) values (1,2)") transaction.rollback() cursor.execute("INSERT into transactions_regress_mod (id,fld) values (1,2)") reuse_cursor_ref() # Rollback so that if the decorator didn't commit, the record is unwritten transaction.rollback() try: # Check that the record is in the DB obj = Mod.objects.get(pk=1) self.assertEqual(obj.fld, 2) except Mod.DoesNotExist: self.fail("After ending a transaction, cursor use no longer sets dirty") def test_failing_query_transaction_closed(self): """ Make sure that under commit_on_success, a transaction is rolled back even if the first database-modifying operation fails. This is prompted by http://code.djangoproject.com/ticket/6669 (and based on sample code posted there to exemplify the problem): Before Django 1.3, transactions were only marked "dirty" by the save() function after it successfully wrote the object to the database. """ from django.contrib.auth.models import User @transaction.commit_on_success def create_system_user(): "Create a user in a transaction" user = User.objects.create_user(username='system', password='iamr00t', email='[email protected]') # Redundant, just makes sure the user id was read back from DB Mod.objects.create(fld=user.id) # Create a user create_system_user() try: # The second call to create_system_user should fail for violating a unique constraint # (it's trying to re-create the same user) create_system_user() except: pass else: raise ImproperlyConfigured('Unique constraint not enforced on django.contrib.auth.models.User') try: # Try to read the database. If the last transaction was indeed closed, # this should cause no problems _ = User.objects.all()[0] except: self.fail("A transaction consisting of a failed operation was not closed.")
6,586
Python
.py
145
35.489655
109
0.645282
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,055
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/max_lengths/models.py
from django.db import models class PersonWithDefaultMaxLengths(models.Model): email = models.EmailField() vcard = models.FileField(upload_to='/tmp') homepage = models.URLField() avatar = models.FilePathField() class PersonWithCustomMaxLengths(models.Model): email = models.EmailField(max_length=250) vcard = models.FileField(upload_to='/tmp', max_length=250) homepage = models.URLField(max_length=250) avatar = models.FilePathField(max_length=250)
482
Python
.py
11
39.727273
62
0.75693
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,056
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/max_lengths/tests.py
from django.db import DatabaseError from django.utils import unittest from regressiontests.max_lengths.models import PersonWithDefaultMaxLengths, PersonWithCustomMaxLengths class MaxLengthArgumentsTests(unittest.TestCase): def verify_max_length(self, model,field,length): self.assertEqual(model._meta.get_field(field).max_length,length) def test_default_max_lengths(self): self.verify_max_length(PersonWithDefaultMaxLengths, 'email', 75) self.verify_max_length(PersonWithDefaultMaxLengths, 'vcard', 100) self.verify_max_length(PersonWithDefaultMaxLengths, 'homepage', 200) self.verify_max_length(PersonWithDefaultMaxLengths, 'avatar', 100) def test_custom_max_lengths(self): self.verify_max_length(PersonWithCustomMaxLengths, 'email', 250) self.verify_max_length(PersonWithCustomMaxLengths, 'vcard', 250) self.verify_max_length(PersonWithCustomMaxLengths, 'homepage', 250) self.verify_max_length(PersonWithCustomMaxLengths, 'avatar', 250) class MaxLengthORMTests(unittest.TestCase): def test_custom_max_lengths(self): args = { "email": "[email protected]", "vcard": "vcard", "homepage": "http://example.com/", "avatar": "me.jpg" } for field in ("email", "vcard", "homepage", "avatar"): new_args = args.copy() new_args[field] = "X" * 250 # a value longer than any of the default fields could hold. p = PersonWithCustomMaxLengths.objects.create(**new_args) self.assertEqual(getattr(p, field), ("X" * 250))
1,620
Python
.py
29
47.482759
102
0.695268
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,057
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/one_to_one_regress/models.py
from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __unicode__(self): return u"%s the place" % self.name class Restaurant(models.Model): place = models.OneToOneField(Place) serves_hot_dogs = models.BooleanField() serves_pizza = models.BooleanField() def __unicode__(self): return u"%s the restaurant" % self.place.name class Bar(models.Model): place = models.OneToOneField(Place) serves_cocktails = models.BooleanField() def __unicode__(self): return u"%s the bar" % self.place.name class UndergroundBar(models.Model): place = models.OneToOneField(Place, null=True) serves_cocktails = models.BooleanField() class Favorites(models.Model): name = models.CharField(max_length = 50) restaurants = models.ManyToManyField(Restaurant) def __unicode__(self): return u"Favorites for %s" % self.name class Target(models.Model): pass class Pointer(models.Model): other = models.OneToOneField(Target, primary_key=True) class Pointer2(models.Model): other = models.OneToOneField(Target)
1,180
Python
.py
31
33.322581
58
0.718558
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,058
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/one_to_one_regress/tests.py
from django.test import TestCase from regressiontests.one_to_one_regress.models import * class OneToOneRegressionTests(TestCase): def setUp(self): self.p1 = Place(name='Demon Dogs', address='944 W. Fullerton') self.p1.save() self.r1 = Restaurant(place=self.p1, serves_hot_dogs=True, serves_pizza=False) self.r1.save() self.b1 = Bar(place=self.p1, serves_cocktails=False) self.b1.save() def test_reverse_relationship_cache_cascade(self): """ Regression test for #9023: accessing the reverse relationship shouldn't result in a cascading delete(). """ bar = UndergroundBar.objects.create(place=self.p1, serves_cocktails=False) # The bug in #9023: if you access the one-to-one relation *before* # setting to None and deleting, the cascade happens anyway. self.p1.undergroundbar bar.place.name='foo' bar.place = None bar.save() self.p1.delete() self.assertEqual(Place.objects.all().count(), 0) self.assertEqual(UndergroundBar.objects.all().count(), 1) def test_create_models_m2m(self): """ Regression test for #1064 and #1506 Check that we create models via the m2m relation if the remote model has a OneToOneField. """ f = Favorites(name = 'Fred') f.save() f.restaurants = [self.r1] self.assertQuerysetEqual( f.restaurants.all(), ['<Restaurant: Demon Dogs the restaurant>'] ) def test_reverse_object_cache(self): """ Regression test for #7173 Check that the name of the cache for the reverse object is correct. """ self.assertEqual(self.p1.restaurant, self.r1) self.assertEqual(self.p1.bar, self.b1) def test_related_object_cache(self): """ Regression test for #6886 (the related-object cache) """ # Look up the objects again so that we get "fresh" objects p = Place.objects.get(name="Demon Dogs") r = p.restaurant # Accessing the related object again returns the exactly same object self.assertTrue(p.restaurant is r) # But if we kill the cache, we get a new object del p._restaurant_cache self.assertFalse(p.restaurant is r) # Reassigning the Restaurant object results in an immediate cache update # We can't use a new Restaurant because that'll violate one-to-one, but # with a new *instance* the is test below will fail if #6886 regresses. r2 = Restaurant.objects.get(pk=r.pk) p.restaurant = r2 self.assertTrue(p.restaurant is r2) # Assigning None succeeds if field is null=True. ug_bar = UndergroundBar.objects.create(place=p, serves_cocktails=False) ug_bar.place = None self.assertTrue(ug_bar.place is None) # Assigning None fails: Place.restaurant is null=False self.assertRaises(ValueError, setattr, p, 'restaurant', None) # You also can't assign an object of the wrong type here self.assertRaises(ValueError, setattr, p, 'restaurant', p) # Creation using keyword argument should cache the related object. p = Place.objects.get(name="Demon Dogs") r = Restaurant(place=p) self.assertTrue(r.place is p) # Creation using keyword argument and unsaved related instance (#8070). p = Place() r = Restaurant(place=p) self.assertTrue(r.place is p) # Creation using attname keyword argument and an id will cause the related # object to be fetched. p = Place.objects.get(name="Demon Dogs") r = Restaurant(place_id=p.id) self.assertFalse(r.place is p) self.assertEqual(r.place, p) def test_filter_one_to_one_relations(self): """ Regression test for #9968 filtering reverse one-to-one relations with primary_key=True was misbehaving. We test both (primary_key=True & False) cases here to prevent any reappearance of the problem. """ t = Target.objects.create() self.assertQuerysetEqual( Target.objects.filter(pointer=None), ['<Target: Target object>'] ) self.assertQuerysetEqual( Target.objects.exclude(pointer=None), [] ) self.assertQuerysetEqual( Target.objects.filter(pointer2=None), ['<Target: Target object>'] ) self.assertQuerysetEqual( Target.objects.exclude(pointer2=None), [] )
4,689
Python
.py
107
34.308411
85
0.631937
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,059
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/csrf_tests/tests.py
# -*- coding: utf-8 -*- import warnings from django.test import TestCase from django.http import HttpRequest, HttpResponse from django.middleware.csrf import CsrfMiddleware, CsrfViewMiddleware from django.views.decorators.csrf import csrf_exempt, csrf_view_exempt, requires_csrf_token from django.core.context_processors import csrf from django.contrib.sessions.middleware import SessionMiddleware from django.utils.importlib import import_module from django.conf import settings from django.template import RequestContext, Template # Response/views used for CsrfResponseMiddleware and CsrfViewMiddleware tests def post_form_response(): resp = HttpResponse(content=u""" <html><body><h1>\u00a1Unicode!<form method="post"><input type="text" /></form></body></html> """, mimetype="text/html") return resp def post_form_response_non_html(): resp = post_form_response() resp["Content-Type"] = "application/xml" return resp def post_form_view(request): """A view that returns a POST form (without a token)""" return post_form_response() # Response/views used for template tag tests def _token_template(): return Template("{% csrf_token %}") def _render_csrf_token_template(req): context = RequestContext(req, processors=[csrf]) template = _token_template() return template.render(context) def token_view(request): """A view that uses {% csrf_token %}""" return HttpResponse(_render_csrf_token_template(request)) def non_token_view_using_request_processor(request): """ A view that doesn't use the token, but does use the csrf view processor. """ context = RequestContext(request, processors=[csrf]) template = Template("") return HttpResponse(template.render(context)) class TestingHttpRequest(HttpRequest): """ A version of HttpRequest that allows us to change some things more easily """ def is_secure(self): return getattr(self, '_is_secure', False) class CsrfMiddlewareTest(TestCase): # The csrf token is potentially from an untrusted source, so could have # characters that need dealing with. _csrf_id_cookie = "<1>\xc2\xa1" _csrf_id = "1" # This is a valid session token for this ID and secret key. This was generated using # the old code that we're to be backwards-compatible with. Don't use the CSRF code # to generate this hash, or we're merely testing the code against itself and not # checking backwards-compatibility. This is also the output of (echo -n test1 | md5sum). _session_token = "5a105e8b9d40e1329780d62ea2265d8a" _session_id = "1" _secret_key_for_session_test= "test" def setUp(self): self.save_warnings_state() warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.middleware.csrf') def tearDown(self): self.restore_warnings_state() def _get_GET_no_csrf_cookie_request(self): return TestingHttpRequest() def _get_GET_csrf_cookie_request(self): req = TestingHttpRequest() req.COOKIES[settings.CSRF_COOKIE_NAME] = self._csrf_id_cookie return req def _get_POST_csrf_cookie_request(self): req = self._get_GET_csrf_cookie_request() req.method = "POST" return req def _get_POST_no_csrf_cookie_request(self): req = self._get_GET_no_csrf_cookie_request() req.method = "POST" return req def _get_POST_request_with_token(self): req = self._get_POST_csrf_cookie_request() req.POST['csrfmiddlewaretoken'] = self._csrf_id return req def _get_POST_session_request_with_token(self): req = self._get_POST_no_csrf_cookie_request() req.COOKIES[settings.SESSION_COOKIE_NAME] = self._session_id req.POST['csrfmiddlewaretoken'] = self._session_token return req def _get_POST_session_request_no_token(self): req = self._get_POST_no_csrf_cookie_request() req.COOKIES[settings.SESSION_COOKIE_NAME] = self._session_id return req def _check_token_present(self, response, csrf_id=None): self.assertContains(response, "name='csrfmiddlewaretoken' value='%s'" % (csrf_id or self._csrf_id)) # Check the post processing and outgoing cookie def test_process_response_no_csrf_cookie(self): """ When no prior CSRF cookie exists, check that the cookie is created and a token is inserted. """ req = self._get_GET_no_csrf_cookie_request() CsrfMiddleware().process_view(req, post_form_view, (), {}) resp = post_form_response() resp_content = resp.content # needed because process_response modifies resp resp2 = CsrfMiddleware().process_response(req, resp) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False) self.assertNotEqual(csrf_cookie, False) self.assertNotEqual(resp_content, resp2.content) self._check_token_present(resp2, csrf_cookie.value) # Check the Vary header got patched correctly self.assertTrue('Cookie' in resp2.get('Vary','')) def test_process_response_for_exempt_view(self): """ Check that a view decorated with 'csrf_view_exempt' is still post-processed to add the CSRF token. """ req = self._get_GET_no_csrf_cookie_request() CsrfMiddleware().process_view(req, csrf_view_exempt(post_form_view), (), {}) resp = post_form_response() resp_content = resp.content # needed because process_response modifies resp resp2 = CsrfMiddleware().process_response(req, resp) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False) self.assertNotEqual(csrf_cookie, False) self.assertNotEqual(resp_content, resp2.content) self._check_token_present(resp2, csrf_cookie.value) def test_process_response_no_csrf_cookie_view_only_get_token_used(self): """ When no prior CSRF cookie exists, check that the cookie is created, even if only CsrfViewMiddleware is used. """ # This is checking that CsrfViewMiddleware has the cookie setting # code. Most of the other tests use CsrfMiddleware. req = self._get_GET_no_csrf_cookie_request() # token_view calls get_token() indirectly CsrfViewMiddleware().process_view(req, token_view, (), {}) resp = token_view(req) resp2 = CsrfViewMiddleware().process_response(req, resp) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False) self.assertNotEqual(csrf_cookie, False) def test_process_response_get_token_not_used(self): """ Check that if get_token() is not called, the view middleware does not add a cookie. """ # This is important to make pages cacheable. Pages which do call # get_token(), assuming they use the token, are not cacheable because # the token is specific to the user req = self._get_GET_no_csrf_cookie_request() # non_token_view_using_request_processor does not call get_token(), but # does use the csrf request processor. By using this, we are testing # that the view processor is properly lazy and doesn't call get_token() # until needed. CsrfViewMiddleware().process_view(req, non_token_view_using_request_processor, (), {}) resp = non_token_view_using_request_processor(req) resp2 = CsrfViewMiddleware().process_response(req, resp) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False) self.assertEqual(csrf_cookie, False) def test_process_response_existing_csrf_cookie(self): """ Check that the token is inserted when a prior CSRF cookie exists """ req = self._get_GET_csrf_cookie_request() CsrfMiddleware().process_view(req, post_form_view, (), {}) resp = post_form_response() resp_content = resp.content # needed because process_response modifies resp resp2 = CsrfMiddleware().process_response(req, resp) self.assertNotEqual(resp_content, resp2.content) self._check_token_present(resp2) def test_process_response_non_html(self): """ Check the the post-processor does nothing for content-types not in _HTML_TYPES. """ req = self._get_GET_no_csrf_cookie_request() CsrfMiddleware().process_view(req, post_form_view, (), {}) resp = post_form_response_non_html() resp_content = resp.content # needed because process_response modifies resp resp2 = CsrfMiddleware().process_response(req, resp) self.assertEqual(resp_content, resp2.content) def test_process_response_exempt_view(self): """ Check that no post processing is done for an exempt view """ req = self._get_GET_csrf_cookie_request() view = csrf_exempt(post_form_view) CsrfMiddleware().process_view(req, view, (), {}) resp = view(req) resp_content = resp.content resp2 = CsrfMiddleware().process_response(req, resp) self.assertEqual(resp_content, resp2.content) # Check the request processing def test_process_request_no_session_no_csrf_cookie(self): """ Check that if neither a CSRF cookie nor a session cookie are present, the middleware rejects the incoming request. This will stop login CSRF. """ req = self._get_POST_no_csrf_cookie_request() req2 = CsrfMiddleware().process_view(req, post_form_view, (), {}) self.assertEqual(403, req2.status_code) def test_process_request_csrf_cookie_no_token(self): """ Check that if a CSRF cookie is present but no token, the middleware rejects the incoming request. """ req = self._get_POST_csrf_cookie_request() req2 = CsrfMiddleware().process_view(req, post_form_view, (), {}) self.assertEqual(403, req2.status_code) def test_process_request_csrf_cookie_and_token(self): """ Check that if both a cookie and a token is present, the middleware lets it through. """ req = self._get_POST_request_with_token() req2 = CsrfMiddleware().process_view(req, post_form_view, (), {}) self.assertEqual(None, req2) def test_process_request_session_cookie_no_csrf_cookie_token(self): """ When no CSRF cookie exists, but the user has a session, check that a token using the session cookie as a legacy CSRF cookie is accepted. """ orig_secret_key = settings.SECRET_KEY settings.SECRET_KEY = self._secret_key_for_session_test try: req = self._get_POST_session_request_with_token() req2 = CsrfMiddleware().process_view(req, post_form_view, (), {}) self.assertEqual(None, req2) finally: settings.SECRET_KEY = orig_secret_key def test_process_request_session_cookie_no_csrf_cookie_no_token(self): """ Check that if a session cookie is present but no token and no CSRF cookie, the request is rejected. """ req = self._get_POST_session_request_no_token() req2 = CsrfMiddleware().process_view(req, post_form_view, (), {}) self.assertEqual(403, req2.status_code) def test_process_request_csrf_cookie_no_token_exempt_view(self): """ Check that if a CSRF cookie is present and no token, but the csrf_exempt decorator has been applied to the view, the middleware lets it through """ req = self._get_POST_csrf_cookie_request() req2 = CsrfMiddleware().process_view(req, csrf_exempt(post_form_view), (), {}) self.assertEqual(None, req2) def test_csrf_token_in_header(self): """ Check that we can pass in the token in a header instead of in the form """ req = self._get_POST_csrf_cookie_request() req.META['HTTP_X_CSRFTOKEN'] = self._csrf_id req2 = CsrfMiddleware().process_view(req, post_form_view, (), {}) self.assertEqual(None, req2) # Tests for the template tag method def test_token_node_no_csrf_cookie(self): """ Check that CsrfTokenNode works when no CSRF cookie is set """ req = self._get_GET_no_csrf_cookie_request() resp = token_view(req) self.assertEqual(u"", resp.content) def test_token_node_empty_csrf_cookie(self): """ Check that we get a new token if the csrf_cookie is the empty string """ req = self._get_GET_no_csrf_cookie_request() req.COOKIES[settings.CSRF_COOKIE_NAME] = "" CsrfViewMiddleware().process_view(req, token_view, (), {}) resp = token_view(req) self.assertNotEqual(u"", resp.content) def test_token_node_with_csrf_cookie(self): """ Check that CsrfTokenNode works when a CSRF cookie is set """ req = self._get_GET_csrf_cookie_request() CsrfViewMiddleware().process_view(req, token_view, (), {}) resp = token_view(req) self._check_token_present(resp) def test_get_token_for_exempt_view(self): """ Check that get_token still works for a view decorated with 'csrf_view_exempt'. """ req = self._get_GET_csrf_cookie_request() CsrfViewMiddleware().process_view(req, csrf_view_exempt(token_view), (), {}) resp = token_view(req) self._check_token_present(resp) def test_get_token_for_requires_csrf_token_view(self): """ Check that get_token works for a view decorated solely with requires_csrf_token """ req = self._get_GET_csrf_cookie_request() resp = requires_csrf_token(token_view)(req) self._check_token_present(resp) def test_token_node_with_new_csrf_cookie(self): """ Check that CsrfTokenNode works when a CSRF cookie is created by the middleware (when one was not already present) """ req = self._get_GET_no_csrf_cookie_request() CsrfViewMiddleware().process_view(req, token_view, (), {}) resp = token_view(req) resp2 = CsrfViewMiddleware().process_response(req, resp) csrf_cookie = resp2.cookies[settings.CSRF_COOKIE_NAME] self._check_token_present(resp, csrf_id=csrf_cookie.value) def test_response_middleware_without_view_middleware(self): """ Check that CsrfResponseMiddleware finishes without error if the view middleware has not been called, as is the case if a request middleware returns a response. """ req = self._get_GET_no_csrf_cookie_request() resp = post_form_view(req) CsrfMiddleware().process_response(req, resp) def test_https_bad_referer(self): """ Test that a POST HTTPS request with a bad referer is rejected """ req = self._get_POST_request_with_token() req._is_secure = True req.META['HTTP_HOST'] = 'www.example.com' req.META['HTTP_REFERER'] = 'https://www.evil.org/somepage' req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {}) self.assertNotEqual(None, req2) self.assertEqual(403, req2.status_code) def test_https_good_referer(self): """ Test that a POST HTTPS request with a good referer is accepted """ req = self._get_POST_request_with_token() req._is_secure = True req.META['HTTP_HOST'] = 'www.example.com' req.META['HTTP_REFERER'] = 'https://www.example.com/somepage' req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {}) self.assertEqual(None, req2) def test_https_good_referer_2(self): """ Test that a POST HTTPS request with a good referer is accepted where the referer contains no trailing slash """ # See ticket #15617 req = self._get_POST_request_with_token() req._is_secure = True req.META['HTTP_HOST'] = 'www.example.com' req.META['HTTP_REFERER'] = 'https://www.example.com' req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {}) self.assertEqual(None, req2)
16,310
Python
.py
343
39.676385
107
0.660089
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,060
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/null_fk/models.py
""" Regression tests for proper working of ForeignKey(null=True). """ from django.db import models class SystemDetails(models.Model): details = models.TextField() class SystemInfo(models.Model): system_details = models.ForeignKey(SystemDetails) system_name = models.CharField(max_length=32) class Forum(models.Model): system_info = models.ForeignKey(SystemInfo) forum_name = models.CharField(max_length=32) class Post(models.Model): forum = models.ForeignKey(Forum, null=True) title = models.CharField(max_length=32) def __unicode__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, null=True) comment_text = models.CharField(max_length=250) class Meta: ordering = ('comment_text',) def __unicode__(self): return self.comment_text
847
Python
.py
24
30.916667
61
0.727273
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,061
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/null_fk/tests.py
from django.test import TestCase from regressiontests.null_fk.models import * class NullFkTests(TestCase): def test_null_fk(self): d = SystemDetails.objects.create(details='First details') s = SystemInfo.objects.create(system_name='First forum', system_details=d) f = Forum.objects.create(system_info=s, forum_name='First forum') p = Post.objects.create(forum=f, title='First Post') c1 = Comment.objects.create(post=p, comment_text='My first comment') c2 = Comment.objects.create(comment_text='My second comment') # Starting from comment, make sure that a .select_related(...) with a specified # set of fields will properly LEFT JOIN multiple levels of NULLs (and the things # that come after the NULLs, or else data that should exist won't). Regression # test for #7369. c = Comment.objects.select_related().get(id=c1.id) self.assertEqual(c.post, p) self.assertEqual(Comment.objects.select_related().get(id=c2.id).post, None) self.assertQuerysetEqual( Comment.objects.select_related('post__forum__system_info').all(), [ (c1.id, u'My first comment', '<Post: First Post>'), (c2.id, u'My second comment', 'None') ], transform = lambda c: (c.id, c.comment_text, repr(c.post)) ) # Regression test for #7530, #7716. self.assertTrue(Comment.objects.select_related('post').filter(post__isnull=True)[0].post is None) self.assertQuerysetEqual( Comment.objects.select_related('post__forum__system_info__system_details'), [ (c1.id, u'My first comment', '<Post: First Post>'), (c2.id, u'My second comment', 'None') ], transform = lambda c: (c.id, c.comment_text, repr(c.post)) )
1,890
Python
.py
35
43.771429
105
0.625
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,062
storage.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/staticfiles_tests/storage.py
from datetime import datetime from django.core.files import storage class DummyStorage(storage.Storage): """ A storage class that does implement modified_time() but raises NotImplementedError when calling """ def _save(self, name, content): return 'dummy' def delete(self, name): pass def exists(self, name): pass def modified_time(self, name): return datetime.date(1970, 1, 1)
447
Python
.py
15
24.2
66
0.682243
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,063
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/staticfiles_tests/tests.py
# -*- encoding: utf-8 -*- import codecs import os import posixpath import shutil import sys import tempfile from StringIO import StringIO from django.conf import settings from django.contrib.staticfiles import finders, storage from django.core.exceptions import ImproperlyConfigured from django.core.files.storage import default_storage from django.core.management import call_command from django.test import TestCase from django.utils.encoding import smart_unicode from django.utils._os import rmtree_errorhandler TEST_ROOT = os.path.normcase(os.path.dirname(__file__)) class StaticFilesTestCase(TestCase): """ Test case with a couple utility assertions. """ def setUp(self): self.old_static_url = settings.STATIC_URL self.old_static_root = settings.STATIC_ROOT self.old_staticfiles_dirs = settings.STATICFILES_DIRS self.old_staticfiles_finders = settings.STATICFILES_FINDERS self.old_media_root = settings.MEDIA_ROOT self.old_media_url = settings.MEDIA_URL self.old_admin_media_prefix = settings.ADMIN_MEDIA_PREFIX self.old_debug = settings.DEBUG self.old_installed_apps = settings.INSTALLED_APPS site_media = os.path.join(TEST_ROOT, 'project', 'site_media') settings.DEBUG = True settings.MEDIA_ROOT = os.path.join(site_media, 'media') settings.MEDIA_URL = '/media/' settings.STATIC_ROOT = os.path.join(site_media, 'static') settings.STATIC_URL = '/static/' settings.ADMIN_MEDIA_PREFIX = '/static/admin/' settings.STATICFILES_DIRS = ( os.path.join(TEST_ROOT, 'project', 'documents'), ) settings.STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) settings.INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.staticfiles', 'regressiontests.staticfiles_tests', 'regressiontests.staticfiles_tests.apps.test', 'regressiontests.staticfiles_tests.apps.no_label', ] # Clear the cached default_storage out, this is because when it first # gets accessed (by some other test), it evaluates settings.MEDIA_ROOT, # since we're planning on changing that we need to clear out the cache. default_storage._wrapped = None # To make sure SVN doesn't hangs itself with the non-ASCII characters # during checkout, we actually create one file dynamically. self._nonascii_filepath = os.path.join( TEST_ROOT, 'apps', 'test', 'static', 'test', u'fi\u015fier.txt') f = codecs.open(self._nonascii_filepath, 'w', 'utf-8') try: f.write(u"fi\u015fier in the app dir") finally: f.close() def tearDown(self): settings.DEBUG = self.old_debug settings.MEDIA_ROOT = self.old_media_root settings.MEDIA_URL = self.old_media_url settings.ADMIN_MEDIA_PREFIX = self.old_admin_media_prefix settings.STATIC_ROOT = self.old_static_root settings.STATIC_URL = self.old_static_url settings.STATICFILES_DIRS = self.old_staticfiles_dirs settings.STATICFILES_FINDERS = self.old_staticfiles_finders settings.INSTALLED_APPS = self.old_installed_apps if os.path.exists(self._nonascii_filepath): os.unlink(self._nonascii_filepath) def assertFileContains(self, filepath, text): self.assertTrue(text in self._get_file(smart_unicode(filepath)), u"'%s' not in '%s'" % (text, filepath)) def assertFileNotFound(self, filepath): self.assertRaises(IOError, self._get_file, filepath) class BuildStaticTestCase(StaticFilesTestCase): """ Tests shared by all file-resolving features (collectstatic, findstatic, and static serve view). This relies on the asserts defined in UtilityAssertsTestCase, but is separated because some test cases need those asserts without all these tests. """ def setUp(self): super(BuildStaticTestCase, self).setUp() self.old_root = settings.STATIC_ROOT settings.STATIC_ROOT = tempfile.mkdtemp() self.run_collectstatic() def tearDown(self): # Use our own error handler that can handle .svn dirs on Windows shutil.rmtree(settings.STATIC_ROOT, ignore_errors=True, onerror=rmtree_errorhandler) settings.STATIC_ROOT = self.old_root super(BuildStaticTestCase, self).tearDown() def run_collectstatic(self, **kwargs): call_command('collectstatic', interactive=False, verbosity='0', ignore_patterns=['*.ignoreme'], **kwargs) def _get_file(self, filepath): assert filepath, 'filepath is empty.' filepath = os.path.join(settings.STATIC_ROOT, filepath) f = codecs.open(filepath, "r", "utf-8") try: return f.read() finally: f.close() class TestDefaults(object): """ A few standard test cases. """ def test_staticfiles_dirs(self): """ Can find a file in a STATICFILES_DIRS directory. """ self.assertFileContains('test.txt', 'Can we find') def test_staticfiles_dirs_subdir(self): """ Can find a file in a subdirectory of a STATICFILES_DIRS directory. """ self.assertFileContains('subdir/test.txt', 'Can we find') def test_staticfiles_dirs_priority(self): """ File in STATICFILES_DIRS has priority over file in app. """ self.assertFileContains('test/file.txt', 'STATICFILES_DIRS') def test_app_files(self): """ Can find a file in an app static/ directory. """ self.assertFileContains('test/file1.txt', 'file1 in the app dir') def test_nonascii_filenames(self): """ Can find a file with non-ASCII character in an app static/ directory. """ self.assertFileContains(u'test/fişier.txt', u'fişier in the app dir') def test_camelcase_filenames(self): """ Can find a file with capital letters. """ self.assertFileContains(u'test/camelCase.txt', u'camelCase') class TestFindStatic(BuildStaticTestCase, TestDefaults): """ Test ``findstatic`` management command. """ def _get_file(self, filepath): _stdout = sys.stdout sys.stdout = StringIO() try: call_command('findstatic', filepath, all=False, verbosity='0') sys.stdout.seek(0) lines = [l.strip() for l in sys.stdout.readlines()] contents = codecs.open( smart_unicode(lines[1].strip()), "r", "utf-8").read() finally: sys.stdout = _stdout return contents def test_all_files(self): """ Test that findstatic returns all candidate files if run without --first. """ _stdout = sys.stdout sys.stdout = StringIO() try: call_command('findstatic', 'test/file.txt', verbosity='0') sys.stdout.seek(0) lines = [l.strip() for l in sys.stdout.readlines()] finally: sys.stdout = _stdout self.assertEqual(len(lines), 3) # three because there is also the "Found <file> here" line self.assertTrue('project' in lines[1]) self.assertTrue('apps' in lines[2]) class TestBuildStatic(BuildStaticTestCase, TestDefaults): """ Test ``collectstatic`` management command. """ def test_ignore(self): """ Test that -i patterns are ignored. """ self.assertFileNotFound('test/test.ignoreme') def test_common_ignore_patterns(self): """ Common ignore patterns (*~, .*, CVS) are ignored. """ self.assertFileNotFound('test/.hidden') self.assertFileNotFound('test/backup~') self.assertFileNotFound('test/CVS') class TestBuildStaticExcludeNoDefaultIgnore(BuildStaticTestCase, TestDefaults): """ Test ``--exclude-dirs`` and ``--no-default-ignore`` options for ``collectstatic`` management command. """ def run_collectstatic(self): super(TestBuildStaticExcludeNoDefaultIgnore, self).run_collectstatic( use_default_ignore_patterns=False) def test_no_common_ignore_patterns(self): """ With --no-default-ignore, common ignore patterns (*~, .*, CVS) are not ignored. """ self.assertFileContains('test/.hidden', 'should be ignored') self.assertFileContains('test/backup~', 'should be ignored') self.assertFileContains('test/CVS', 'should be ignored') class TestNoFilesCreated(object): def test_no_files_created(self): """ Make sure no files were create in the destination directory. """ self.assertEqual(os.listdir(settings.STATIC_ROOT), []) class TestBuildStaticDryRun(BuildStaticTestCase, TestNoFilesCreated): """ Test ``--dry-run`` option for ``collectstatic`` management command. """ def run_collectstatic(self): super(TestBuildStaticDryRun, self).run_collectstatic(dry_run=True) class TestBuildStaticNonLocalStorage(BuildStaticTestCase, TestNoFilesCreated): """ Tests for #15035 """ def setUp(self): self.old_staticfiles_storage = settings.STATICFILES_STORAGE settings.STATICFILES_STORAGE = 'regressiontests.staticfiles_tests.storage.DummyStorage' super(TestBuildStaticNonLocalStorage, self).setUp() def tearDown(self): super(TestBuildStaticNonLocalStorage, self).tearDown() settings.STATICFILES_STORAGE = self.old_staticfiles_storage if sys.platform != 'win32': class TestBuildStaticLinks(BuildStaticTestCase, TestDefaults): """ Test ``--link`` option for ``collectstatic`` management command. Note that by inheriting ``TestDefaults`` we repeat all the standard file resolving tests here, to make sure using ``--link`` does not change the file-selection semantics. """ def run_collectstatic(self): super(TestBuildStaticLinks, self).run_collectstatic(link=True) def test_links_created(self): """ With ``--link``, symbolic links are created. """ self.assertTrue(os.path.islink(os.path.join(settings.STATIC_ROOT, 'test.txt'))) class TestServeStatic(StaticFilesTestCase): """ Test static asset serving view. """ urls = 'regressiontests.staticfiles_tests.urls.default' def _response(self, filepath): return self.client.get( posixpath.join(settings.STATIC_URL, filepath)) def assertFileContains(self, filepath, text): self.assertContains(self._response(filepath), text) def assertFileNotFound(self, filepath): self.assertEqual(self._response(filepath).status_code, 404) class TestServeDisabled(TestServeStatic): """ Test serving static files disabled when DEBUG is False. """ def setUp(self): super(TestServeDisabled, self).setUp() settings.DEBUG = False def test_disabled_serving(self): self.assertRaisesRegexp(ImproperlyConfigured, 'The staticfiles view ' 'can only be used in debug mode ', self._response, 'test.txt') class TestServeStaticWithDefaultURL(TestServeStatic, TestDefaults): """ Test static asset serving view with manually configured URLconf. """ pass class TestServeStaticWithURLHelper(TestServeStatic, TestDefaults): """ Test static asset serving view with staticfiles_urlpatterns helper. """ urls = 'regressiontests.staticfiles_tests.urls.helper' class TestServeAdminMedia(TestServeStatic): """ Test serving media from django.contrib.admin. """ def _response(self, filepath): return self.client.get( posixpath.join(settings.ADMIN_MEDIA_PREFIX, filepath)) def test_serve_admin_media(self): self.assertFileContains('css/base.css', 'body') class FinderTestCase(object): """ Base finder test mixin """ def test_find_first(self): src, dst = self.find_first self.assertEqual(self.finder.find(src), dst) def test_find_all(self): src, dst = self.find_all self.assertEqual(self.finder.find(src, all=True), dst) class TestFileSystemFinder(StaticFilesTestCase, FinderTestCase): """ Test FileSystemFinder. """ def setUp(self): super(TestFileSystemFinder, self).setUp() self.finder = finders.FileSystemFinder() test_file_path = os.path.join(TEST_ROOT, 'project', 'documents', 'test', 'file.txt') self.find_first = (os.path.join('test', 'file.txt'), test_file_path) self.find_all = (os.path.join('test', 'file.txt'), [test_file_path]) class TestAppDirectoriesFinder(StaticFilesTestCase, FinderTestCase): """ Test AppDirectoriesFinder. """ def setUp(self): super(TestAppDirectoriesFinder, self).setUp() self.finder = finders.AppDirectoriesFinder() test_file_path = os.path.join(TEST_ROOT, 'apps', 'test', 'static', 'test', 'file1.txt') self.find_first = (os.path.join('test', 'file1.txt'), test_file_path) self.find_all = (os.path.join('test', 'file1.txt'), [test_file_path]) class TestDefaultStorageFinder(StaticFilesTestCase, FinderTestCase): """ Test DefaultStorageFinder. """ def setUp(self): super(TestDefaultStorageFinder, self).setUp() self.finder = finders.DefaultStorageFinder( storage=storage.StaticFilesStorage(location=settings.MEDIA_ROOT)) test_file_path = os.path.join(settings.MEDIA_ROOT, 'media-file.txt') self.find_first = ('media-file.txt', test_file_path) self.find_all = ('media-file.txt', [test_file_path]) class TestMiscFinder(TestCase): """ A few misc finder tests. """ def test_get_finder(self): self.assertTrue(isinstance(finders.get_finder( 'django.contrib.staticfiles.finders.FileSystemFinder'), finders.FileSystemFinder)) def test_get_finder_bad_classname(self): self.assertRaises(ImproperlyConfigured, finders.get_finder, 'django.contrib.staticfiles.finders.FooBarFinder') def test_get_finder_bad_module(self): self.assertRaises(ImproperlyConfigured, finders.get_finder, 'foo.bar.FooBarFinder') class TestStaticfilesDirsType(TestCase): """ We can't determine if STATICFILES_DIRS is set correctly just by looking at the type, but we can determine if it's definitely wrong. """ def setUp(self): self.old_settings_dir = settings.STATICFILES_DIRS settings.STATICFILES_DIRS = 'a string' def tearDown(self): settings.STATICFILES_DIRS = self.old_settings_dir def test_non_tuple_raises_exception(self): self.assertRaises(ImproperlyConfigured, finders.FileSystemFinder)
15,192
Python
.py
357
34.837535
98
0.668474
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,064
default.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/staticfiles_tests/urls/default.py
from django.conf.urls.defaults import patterns, url urlpatterns = patterns('', url(r'^static/(?P<path>.*)$', 'django.contrib.staticfiles.views.serve'), )
159
Python
.py
4
37.5
76
0.720779
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,065
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/bug639/models.py
import tempfile from django.db import models from django.core.files.storage import FileSystemStorage from django.forms import ModelForm temp_storage_dir = tempfile.mkdtemp() temp_storage = FileSystemStorage(temp_storage_dir) class Photo(models.Model): title = models.CharField(max_length=30) image = models.FileField(storage=temp_storage, upload_to='tests') # Support code for the tests; this keeps track of how many times save() # gets called on each instance. def __init__(self, *args, **kwargs): super(Photo, self).__init__(*args, **kwargs) self._savecount = 0 def save(self, force_insert=False, force_update=False): super(Photo, self).save(force_insert, force_update) self._savecount += 1 class PhotoForm(ModelForm): class Meta: model = Photo
821
Python
.py
20
36.35
75
0.718239
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,066
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/bug639/tests.py
""" Tests for file field behavior, and specifically #639, in which Model.save() gets called *again* for each FileField. This test will fail if calling a ModelForm's save() method causes Model.save() to be called more than once. """ import os import shutil from django.core.files.uploadedfile import SimpleUploadedFile from django.utils import unittest from regressiontests.bug639.models import Photo, PhotoForm, temp_storage_dir class Bug639Test(unittest.TestCase): def testBug639(self): """ Simulate a file upload and check how many times Model.save() gets called. """ # Grab an image for testing. filename = os.path.join(os.path.dirname(__file__), "test.jpg") img = open(filename, "rb").read() # Fake a POST QueryDict and FILES MultiValueDict. data = {'title': 'Testing'} files = {"image": SimpleUploadedFile('test.jpg', img, 'image/jpeg')} form = PhotoForm(data=data, files=files) p = form.save() # Check the savecount stored on the object (see the model). self.assertEqual(p._savecount, 1) def tearDown(self): """ Make sure to delete the "uploaded" file to avoid clogging /tmp. """ p = Photo.objects.get() p.image.delete(save=False) shutil.rmtree(temp_storage_dir)
1,346
Python
.py
33
34.424242
76
0.669479
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,067
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/managers_regress/models.py
""" Various edge-cases for model managers. """ from django.db import models class OnlyFred(models.Manager): def get_query_set(self): return super(OnlyFred, self).get_query_set().filter(name='fred') class OnlyBarney(models.Manager): def get_query_set(self): return super(OnlyBarney, self).get_query_set().filter(name='barney') class Value42(models.Manager): def get_query_set(self): return super(Value42, self).get_query_set().filter(value=42) class AbstractBase1(models.Model): name = models.CharField(max_length=50) class Meta: abstract = True # Custom managers manager1 = OnlyFred() manager2 = OnlyBarney() objects = models.Manager() class AbstractBase2(models.Model): value = models.IntegerField() class Meta: abstract = True # Custom manager restricted = Value42() # No custom manager on this class to make sure the default case doesn't break. class AbstractBase3(models.Model): comment = models.CharField(max_length=50) class Meta: abstract = True class Parent(models.Model): name = models.CharField(max_length=50) manager = OnlyFred() def __unicode__(self): return self.name # Managers from base classes are inherited and, if no manager is specified # *and* the parent has a manager specified, the first one (in the MRO) will # become the default. class Child1(AbstractBase1): data = models.CharField(max_length=25) def __unicode__(self): return self.data class Child2(AbstractBase1, AbstractBase2): data = models.CharField(max_length=25) def __unicode__(self): return self.data class Child3(AbstractBase1, AbstractBase3): data = models.CharField(max_length=25) def __unicode__(self): return self.data class Child4(AbstractBase1): data = models.CharField(max_length=25) # Should be the default manager, although the parent managers are # inherited. default = models.Manager() def __unicode__(self): return self.data class Child5(AbstractBase3): name = models.CharField(max_length=25) default = OnlyFred() objects = models.Manager() def __unicode__(self): return self.name # Will inherit managers from AbstractBase1, but not Child4. class Child6(Child4): value = models.IntegerField() # Will not inherit default manager from parent. class Child7(Parent): pass
2,430
Python
.py
71
29.492958
78
0.71073
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,068
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/managers_regress/tests.py
from django.test import TestCase from models import Child1, Child2, Child3, Child4, Child5, Child6, Child7 class ManagersRegressionTests(TestCase): def test_managers(self): a1 = Child1.objects.create(name='fred', data='a1') a2 = Child1.objects.create(name='barney', data='a2') b1 = Child2.objects.create(name='fred', data='b1', value=1) b2 = Child2.objects.create(name='barney', data='b2', value=42) c1 = Child3.objects.create(name='fred', data='c1', comment='yes') c2 = Child3.objects.create(name='barney', data='c2', comment='no') d1 = Child4.objects.create(name='fred', data='d1') d2 = Child4.objects.create(name='barney', data='d2') e1 = Child5.objects.create(name='fred', comment='yes') e2 = Child5.objects.create(name='barney', comment='no') f1 = Child6.objects.create(name='fred', data='f1', value=42) f2 = Child6.objects.create(name='barney', data='f2', value=42) g1 = Child7.objects.create(name='fred') g2 = Child7.objects.create(name='barney') self.assertQuerysetEqual(Child1.manager1.all(), ["<Child1: a1>"]) self.assertQuerysetEqual(Child1.manager2.all(), ["<Child1: a2>"]) self.assertQuerysetEqual(Child1._default_manager.all(), ["<Child1: a1>"]) self.assertQuerysetEqual(Child2._default_manager.all(), ["<Child2: b1>"]) self.assertQuerysetEqual(Child2.restricted.all(), ["<Child2: b2>"]) self.assertQuerysetEqual(Child3._default_manager.all(), ["<Child3: c1>"]) self.assertQuerysetEqual(Child3.manager1.all(), ["<Child3: c1>"]) self.assertQuerysetEqual(Child3.manager2.all(), ["<Child3: c2>"]) # Since Child6 inherits from Child4, the corresponding rows from f1 and # f2 also appear here. This is the expected result. self.assertQuerysetEqual(Child4._default_manager.order_by('data'), [ "<Child4: d1>", "<Child4: d2>", "<Child4: f1>", "<Child4: f2>" ] ) self.assertQuerysetEqual(Child4.manager1.all(), [ "<Child4: d1>", "<Child4: f1>" ] ) self.assertQuerysetEqual(Child5._default_manager.all(), ["<Child5: fred>"]) self.assertQuerysetEqual(Child6._default_manager.all(), ["<Child6: f1>"]) self.assertQuerysetEqual(Child7._default_manager.order_by('name'), [ "<Child7: barney>", "<Child7: fred>" ] )
2,544
Python
.py
47
43.957447
83
0.608434
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,069
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_registration/models.py
""" Tests for various ways of registering models with the admin site. """ from django.db import models class Person(models.Model): name = models.CharField(max_length=200) class Location(models.Model): class Meta: abstract = True class Place(Location): name = models.CharField(max_length=200)
316
Python
.py
11
25.545455
65
0.747508
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,070
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_registration/tests.py
from django.test import TestCase from django.core.exceptions import ImproperlyConfigured from django.contrib import admin from models import Person, Place, Location class NameAdmin(admin.ModelAdmin): list_display = ['name'] save_on_top = True class TestRegistration(TestCase): def setUp(self): self.site = admin.AdminSite() def test_bare_registration(self): self.site.register(Person) self.assertTrue( isinstance(self.site._registry[Person], admin.options.ModelAdmin) ) def test_registration_with_model_admin(self): self.site.register(Person, NameAdmin) self.assertTrue( isinstance(self.site._registry[Person], NameAdmin) ) def test_prevent_double_registration(self): self.site.register(Person) self.assertRaises(admin.sites.AlreadyRegistered, self.site.register, Person) def test_registration_with_star_star_options(self): self.site.register(Person, search_fields=['name']) self.assertEqual(self.site._registry[Person].search_fields, ['name']) def test_star_star_overrides(self): self.site.register(Person, NameAdmin, search_fields=["name"], list_display=['__str__']) self.assertEqual(self.site._registry[Person].search_fields, ['name']) self.assertEqual(self.site._registry[Person].list_display, ['action_checkbox', '__str__']) self.assertTrue(self.site._registry[Person].save_on_top) def test_iterable_registration(self): self.site.register([Person, Place], search_fields=['name']) self.assertTrue( isinstance(self.site._registry[Person], admin.options.ModelAdmin) ) self.assertEqual(self.site._registry[Person].search_fields, ['name']) self.assertTrue( isinstance(self.site._registry[Place], admin.options.ModelAdmin) ) self.assertEqual(self.site._registry[Place].search_fields, ['name']) def test_abstract_model(self): """ Exception is raised when trying to register an abstract model. Refs #12004. """ self.assertRaises(ImproperlyConfigured, self.site.register, Location)
2,296
Python
.py
51
35.823529
77
0.656823
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,071
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/servers/tests.py
""" Tests for django.core.servers. """ import os import django from django.test import TestCase from django.core.handlers.wsgi import WSGIHandler from django.core.servers.basehttp import AdminMediaHandler from django.conf import settings class AdminMediaHandlerTests(TestCase): def setUp(self): self.admin_media_file_path = os.path.abspath( os.path.join(django.__path__[0], 'contrib', 'admin', 'media') ) self.handler = AdminMediaHandler(WSGIHandler()) def test_media_urls(self): """ Tests that URLs that look like absolute file paths after the settings.ADMIN_MEDIA_PREFIX don't turn into absolute file paths. """ # Cases that should work on all platforms. data = ( ('%scss/base.css' % settings.ADMIN_MEDIA_PREFIX, ('css', 'base.css')), ) # Cases that should raise an exception. bad_data = () # Add platform-specific cases. if os.sep == '/': data += ( # URL, tuple of relative path parts. ('%s\\css/base.css' % settings.ADMIN_MEDIA_PREFIX, ('\\css', 'base.css')), ) bad_data += ( '%s/css/base.css' % settings.ADMIN_MEDIA_PREFIX, '%s///css/base.css' % settings.ADMIN_MEDIA_PREFIX, '%s../css/base.css' % settings.ADMIN_MEDIA_PREFIX, ) elif os.sep == '\\': bad_data += ( '%sC:\css/base.css' % settings.ADMIN_MEDIA_PREFIX, '%s/\\css/base.css' % settings.ADMIN_MEDIA_PREFIX, '%s\\css/base.css' % settings.ADMIN_MEDIA_PREFIX, '%s\\\\css/base.css' % settings.ADMIN_MEDIA_PREFIX ) for url, path_tuple in data: try: output = self.handler.file_path(url) except ValueError: self.fail("Got a ValueError exception, but wasn't expecting" " one. URL was: %s" % url) rel_path = os.path.join(*path_tuple) desired = os.path.normcase( os.path.join(self.admin_media_file_path, rel_path)) self.assertEqual(output, desired, "Got: %s, Expected: %s, URL was: %s" % (output, desired, url)) for url in bad_data: try: output = self.handler.file_path(url) except ValueError: continue self.fail('URL: %s should have caused a ValueError exception.' % url)
2,557
Python
.py
62
30.064516
90
0.552251
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,072
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/bash_completion/tests.py
""" A series of tests to establish that the command-line bash completion works. """ import os import sys import StringIO from django.conf import settings from django.core.management import ManagementUtility from django.utils import unittest class BashCompletionTests(unittest.TestCase): """ Testing the Python level bash completion code. This requires setting up the environment as if we got passed data from bash. """ def setUp(self): self.old_DJANGO_AUTO_COMPLETE = os.environ.get('DJANGO_AUTO_COMPLETE') os.environ['DJANGO_AUTO_COMPLETE'] = '1' self.output = StringIO.StringIO() self.old_stdout = sys.stdout sys.stdout = self.output def tearDown(self): sys.stdout = self.old_stdout if self.old_DJANGO_AUTO_COMPLETE: os.environ['DJANGO_AUTO_COMPLETE'] = self.old_DJANGO_AUTO_COMPLETE else: del os.environ['DJANGO_AUTO_COMPLETE'] def _user_input(self, input_str): os.environ['COMP_WORDS'] = input_str os.environ['COMP_CWORD'] = str(len(input_str.split()) - 1) sys.argv = input_str.split(' ') def _run_autocomplete(self): util = ManagementUtility(argv=sys.argv) try: util.autocomplete() except SystemExit: pass return self.output.getvalue().strip().split('\n') def test_django_admin_py(self): "django_admin.py will autocomplete option flags" self._user_input('django-admin.py sqlall --v') output = self._run_autocomplete() self.assertEqual(output, ['--verbosity=']) def test_manage_py(self): "manage.py will autocomplete option flags" self._user_input('manage.py sqlall --v') output = self._run_autocomplete() self.assertEqual(output, ['--verbosity=']) def test_custom_command(self): "A custom command can autocomplete option flags" self._user_input('django-admin.py test_command --l') output = self._run_autocomplete() self.assertEqual(output, ['--list']) def test_subcommands(self): "Subcommands can be autocompleted" self._user_input('django-admin.py sql') output = self._run_autocomplete() self.assertEqual(output, ['sql sqlall sqlclear sqlcustom sqlflush sqlindexes sqlinitialdata sqlreset sqlsequencereset']) def test_help(self): "No errors, just an empty list if there are no autocomplete options" self._user_input('django-admin.py help --') output = self._run_autocomplete() self.assertEqual(output, ['']) def test_runfcgi(self): "Command arguments will be autocompleted" self._user_input('django-admin.py runfcgi h') output = self._run_autocomplete() self.assertEqual(output, ['host=']) def test_app_completion(self): "Application names will be autocompleted for an AppCommand" self._user_input('django-admin.py sqlall a') output = self._run_autocomplete() app_labels = [name.split('.')[-1] for name in settings.INSTALLED_APPS] self.assertEqual(output, sorted(label for label in app_labels if label.startswith('a')))
3,203
Python
.py
74
35.837838
128
0.66335
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,073
test_command.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/bash_completion/management/commands/test_command.py
import sys, os from optparse import OptionParser, make_option from django.core.management.base import BaseCommand class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option("--list", action="store_true", dest="list", help="Print all options"), ) def handle(self, *args, **options): pass
362
Python
.py
10
30
63
0.672414
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,074
edit.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/generic_views/edit.py
from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import reverse from django import forms from django.test import TestCase from django.utils.unittest import expectedFailure from regressiontests.generic_views.models import Artist, Author from regressiontests.generic_views import views class ModelFormMixinTests(TestCase): def test_get_form(self): form_class = views.AuthorGetQuerySetFormView().get_form_class() self.assertEqual(form_class.Meta.model, Author) class CreateViewTests(TestCase): urls = 'regressiontests.generic_views.urls' def test_create(self): res = self.client.get('/edit/authors/create/') self.assertEqual(res.status_code, 200) self.assertTrue(isinstance(res.context['form'], forms.ModelForm)) self.assertFalse('object' in res.context) self.assertFalse('author' in res.context) self.assertTemplateUsed(res, 'generic_views/author_form.html') res = self.client.post('/edit/authors/create/', {'name': 'Randall Munroe', 'slug': 'randall-munroe'}) self.assertEqual(res.status_code, 302) self.assertRedirects(res, 'http://testserver/list/authors/') self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>']) def test_create_invalid(self): res = self.client.post('/edit/authors/create/', {'name': 'A' * 101, 'slug': 'randall-munroe'}) self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'generic_views/author_form.html') self.assertEqual(len(res.context['form'].errors), 1) self.assertEqual(Author.objects.count(), 0) def test_create_with_object_url(self): res = self.client.post('/edit/artists/create/', {'name': 'Rene Magritte'}) self.assertEqual(res.status_code, 302) artist = Artist.objects.get(name='Rene Magritte') self.assertRedirects(res, 'http://testserver/detail/artist/%d/' % artist.pk) self.assertQuerysetEqual(Artist.objects.all(), ['<Artist: Rene Magritte>']) def test_create_with_redirect(self): res = self.client.post('/edit/authors/create/redirect/', {'name': 'Randall Munroe', 'slug': 'randall-munroe'}) self.assertEqual(res.status_code, 302) self.assertRedirects(res, 'http://testserver/edit/authors/create/') self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>']) def test_create_with_interpolated_redirect(self): res = self.client.post('/edit/authors/create/interpolate_redirect/', {'name': 'Randall Munroe', 'slug': 'randall-munroe'}) self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>']) self.assertEqual(res.status_code, 302) pk = Author.objects.all()[0].pk self.assertRedirects(res, 'http://testserver/edit/author/%d/update/' % pk) def test_create_with_special_properties(self): res = self.client.get('/edit/authors/create/special/') self.assertEqual(res.status_code, 200) self.assertTrue(isinstance(res.context['form'], views.AuthorForm)) self.assertFalse('object' in res.context) self.assertFalse('author' in res.context) self.assertTemplateUsed(res, 'generic_views/form.html') res = self.client.post('/edit/authors/create/special/', {'name': 'Randall Munroe', 'slug': 'randall-munroe'}) self.assertEqual(res.status_code, 302) obj = Author.objects.get(slug='randall-munroe') self.assertRedirects(res, reverse('author_detail', kwargs={'pk': obj.pk})) self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>']) def test_create_without_redirect(self): try: res = self.client.post('/edit/authors/create/naive/', {'name': 'Randall Munroe', 'slug': 'randall-munroe'}) self.fail('Should raise exception -- No redirect URL provided, and no get_absolute_url provided') except ImproperlyConfigured: pass def test_create_restricted(self): res = self.client.post('/edit/authors/create/restricted/', {'name': 'Randall Munroe', 'slug': 'randall-munroe'}) self.assertEqual(res.status_code, 302) self.assertRedirects(res, 'http://testserver/accounts/login/?next=/edit/authors/create/restricted/') class UpdateViewTests(TestCase): urls = 'regressiontests.generic_views.urls' def test_update_post(self): a = Author.objects.create( name='Randall Munroe', slug='randall-munroe', ) res = self.client.get('/edit/author/%d/update/' % a.pk) self.assertEqual(res.status_code, 200) self.assertTrue(isinstance(res.context['form'], forms.ModelForm)) self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk)) self.assertEqual(res.context['author'], Author.objects.get(pk=a.pk)) self.assertTemplateUsed(res, 'generic_views/author_form.html') # Modification with both POST and PUT (browser compatible) res = self.client.post('/edit/author/%d/update/' % a.pk, {'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'}) self.assertEqual(res.status_code, 302) self.assertRedirects(res, 'http://testserver/list/authors/') self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (xkcd)>']) @expectedFailure def test_update_put(self): a = Author.objects.create( name='Randall Munroe', slug='randall-munroe', ) res = self.client.get('/edit/author/%d/update/' % a.pk) self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'generic_views/author_form.html') res = self.client.put('/edit/author/%d/update/' % a.pk, {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'}) self.assertEqual(res.status_code, 302) self.assertRedirects(res, 'http://testserver/list/authors/') self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (author of xkcd)>']) def test_update_invalid(self): a = Author.objects.create( name='Randall Munroe', slug='randall-munroe', ) res = self.client.post('/edit/author/%d/update/' % a.pk, {'name': 'A' * 101, 'slug': 'randall-munroe'}) self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'generic_views/author_form.html') self.assertEqual(len(res.context['form'].errors), 1) self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>']) def test_update_with_object_url(self): a = Artist.objects.create(name='Rene Magritte') res = self.client.post('/edit/artists/%d/update/' % a.pk, {'name': 'Rene Magritte'}) self.assertEqual(res.status_code, 302) self.assertRedirects(res, 'http://testserver/detail/artist/%d/' % a.pk) self.assertQuerysetEqual(Artist.objects.all(), ['<Artist: Rene Magritte>']) def test_update_with_redirect(self): a = Author.objects.create( name='Randall Munroe', slug='randall-munroe', ) res = self.client.post('/edit/author/%d/update/redirect/' % a.pk, {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'}) self.assertEqual(res.status_code, 302) self.assertRedirects(res, 'http://testserver/edit/authors/create/') self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (author of xkcd)>']) def test_update_with_interpolated_redirect(self): a = Author.objects.create( name='Randall Munroe', slug='randall-munroe', ) res = self.client.post('/edit/author/%d/update/interpolate_redirect/' % a.pk, {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'}) self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (author of xkcd)>']) self.assertEqual(res.status_code, 302) pk = Author.objects.all()[0].pk self.assertRedirects(res, 'http://testserver/edit/author/%d/update/' % pk) def test_update_with_special_properties(self): a = Author.objects.create( name='Randall Munroe', slug='randall-munroe', ) res = self.client.get('/edit/author/%d/update/special/' % a.pk) self.assertEqual(res.status_code, 200) self.assertTrue(isinstance(res.context['form'], views.AuthorForm)) self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk)) self.assertEqual(res.context['thingy'], Author.objects.get(pk=a.pk)) self.assertFalse('author' in res.context) self.assertTemplateUsed(res, 'generic_views/form.html') res = self.client.post('/edit/author/%d/update/special/' % a.pk, {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'}) self.assertEqual(res.status_code, 302) self.assertRedirects(res, 'http://testserver/detail/author/%d/' % a.pk) self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (author of xkcd)>']) def test_update_without_redirect(self): try: a = Author.objects.create( name='Randall Munroe', slug='randall-munroe', ) res = self.client.post('/edit/author/%d/update/naive/' % a.pk, {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'}) self.fail('Should raise exception -- No redirect URL provided, and no get_absolute_url provided') except ImproperlyConfigured: pass def test_update_get_object(self): a = Author.objects.create( pk=1, name='Randall Munroe', slug='randall-munroe', ) res = self.client.get('/edit/author/update/') self.assertEqual(res.status_code, 200) self.assertTrue(isinstance(res.context['form'], forms.ModelForm)) self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk)) self.assertEqual(res.context['author'], Author.objects.get(pk=a.pk)) self.assertTemplateUsed(res, 'generic_views/author_form.html') # Modification with both POST and PUT (browser compatible) res = self.client.post('/edit/author/update/', {'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'}) self.assertEqual(res.status_code, 302) self.assertRedirects(res, 'http://testserver/list/authors/') self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (xkcd)>']) class DeleteViewTests(TestCase): urls = 'regressiontests.generic_views.urls' def test_delete_by_post(self): a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'}) res = self.client.get('/edit/author/%d/delete/' % a.pk) self.assertEqual(res.status_code, 200) self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk)) self.assertEqual(res.context['author'], Author.objects.get(pk=a.pk)) self.assertTemplateUsed(res, 'generic_views/author_confirm_delete.html') # Deletion with POST res = self.client.post('/edit/author/%d/delete/' % a.pk) self.assertEqual(res.status_code, 302) self.assertRedirects(res, 'http://testserver/list/authors/') self.assertQuerysetEqual(Author.objects.all(), []) def test_delete_by_delete(self): # Deletion with browser compatible DELETE method a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'}) res = self.client.delete('/edit/author/%d/delete/' % a.pk) self.assertEqual(res.status_code, 302) self.assertRedirects(res, 'http://testserver/list/authors/') self.assertQuerysetEqual(Author.objects.all(), []) def test_delete_with_redirect(self): a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'}) res = self.client.post('/edit/author/%d/delete/redirect/' % a.pk) self.assertEqual(res.status_code, 302) self.assertRedirects(res, 'http://testserver/edit/authors/create/') self.assertQuerysetEqual(Author.objects.all(), []) def test_delete_with_special_properties(self): a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'}) res = self.client.get('/edit/author/%d/delete/special/' % a.pk) self.assertEqual(res.status_code, 200) self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk)) self.assertEqual(res.context['thingy'], Author.objects.get(pk=a.pk)) self.assertFalse('author' in res.context) self.assertTemplateUsed(res, 'generic_views/confirm_delete.html') res = self.client.post('/edit/author/%d/delete/special/' % a.pk) self.assertEqual(res.status_code, 302) self.assertRedirects(res, 'http://testserver/list/authors/') self.assertQuerysetEqual(Author.objects.all(), []) def test_delete_without_redirect(self): try: a = Author.objects.create( name='Randall Munroe', slug='randall-munroe', ) res = self.client.post('/edit/author/%d/delete/naive/' % a.pk) self.fail('Should raise exception -- No redirect URL provided, and no get_absolute_url provided') except ImproperlyConfigured: pass
13,869
Python
.py
244
46.709016
109
0.639267
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,075
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/generic_views/models.py
from django.db import models class Artist(models.Model): name = models.CharField(max_length=100) class Meta: ordering = ['name'] verbose_name = 'professional artist' verbose_name_plural = 'professional artists' def __unicode__(self): return self.name @models.permalink def get_absolute_url(self): return ('artist_detail', (), {'pk': self.id}) class Author(models.Model): name = models.CharField(max_length=100) slug = models.SlugField() class Meta: ordering = ['name'] def __unicode__(self): return self.name class Book(models.Model): name = models.CharField(max_length=300) slug = models.SlugField() pages = models.IntegerField() authors = models.ManyToManyField(Author) pubdate = models.DateField() class Meta: ordering = ['-pubdate'] def __unicode__(self): return self.name class Page(models.Model): content = models.TextField() template = models.CharField(max_length=300)
1,031
Python
.py
32
26.375
53
0.659919
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,076
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/generic_views/urls.py
from django.conf.urls.defaults import * from django.views.generic import TemplateView from django.views.decorators.cache import cache_page import views urlpatterns = patterns('', # base #(r'^about/login-required/$', # views.DecoratedAboutView()), # TemplateView (r'^template/no_template/$', TemplateView.as_view()), (r'^template/simple/(?P<foo>\w+)/$', TemplateView.as_view(template_name='generic_views/about.html')), (r'^template/custom/(?P<foo>\w+)/$', views.CustomTemplateView.as_view(template_name='generic_views/about.html')), (r'^template/cached/(?P<foo>\w+)/$', cache_page(2.0)(TemplateView.as_view(template_name='generic_views/about.html'))), # DetailView (r'^detail/obj/$', views.ObjectDetail.as_view()), url(r'^detail/artist/(?P<pk>\d+)/$', views.ArtistDetail.as_view(), name="artist_detail"), url(r'^detail/author/(?P<pk>\d+)/$', views.AuthorDetail.as_view(), name="author_detail"), (r'^detail/author/byslug/(?P<slug>[\w-]+)/$', views.AuthorDetail.as_view()), (r'^detail/author/(?P<pk>\d+)/template_name_suffix/$', views.AuthorDetail.as_view(template_name_suffix='_view')), (r'^detail/author/(?P<pk>\d+)/template_name/$', views.AuthorDetail.as_view(template_name='generic_views/about.html')), (r'^detail/author/(?P<pk>\d+)/context_object_name/$', views.AuthorDetail.as_view(context_object_name='thingy')), (r'^detail/author/(?P<pk>\d+)/dupe_context_object_name/$', views.AuthorDetail.as_view(context_object_name='object')), (r'^detail/page/(?P<pk>\d+)/field/$', views.PageDetail.as_view()), (r'^detail/author/invalid/url/$', views.AuthorDetail.as_view()), (r'^detail/author/invalid/qs/$', views.AuthorDetail.as_view(queryset=None)), # Create/UpdateView (r'^edit/artists/create/$', views.ArtistCreate.as_view()), (r'^edit/artists/(?P<pk>\d+)/update/$', views.ArtistUpdate.as_view()), (r'^edit/authors/create/naive/$', views.NaiveAuthorCreate.as_view()), (r'^edit/authors/create/redirect/$', views.NaiveAuthorCreate.as_view(success_url='/edit/authors/create/')), (r'^edit/authors/create/interpolate_redirect/$', views.NaiveAuthorCreate.as_view(success_url='/edit/author/%(id)d/update/')), (r'^edit/authors/create/restricted/$', views.AuthorCreateRestricted.as_view()), (r'^edit/authors/create/$', views.AuthorCreate.as_view()), (r'^edit/authors/create/special/$', views.SpecializedAuthorCreate.as_view()), (r'^edit/author/(?P<pk>\d+)/update/naive/$', views.NaiveAuthorUpdate.as_view()), (r'^edit/author/(?P<pk>\d+)/update/redirect/$', views.NaiveAuthorUpdate.as_view(success_url='/edit/authors/create/')), (r'^edit/author/(?P<pk>\d+)/update/interpolate_redirect/$', views.NaiveAuthorUpdate.as_view(success_url='/edit/author/%(id)d/update/')), (r'^edit/author/(?P<pk>\d+)/update/$', views.AuthorUpdate.as_view()), (r'^edit/author/update/$', views.OneAuthorUpdate.as_view()), (r'^edit/author/(?P<pk>\d+)/update/special/$', views.SpecializedAuthorUpdate.as_view()), (r'^edit/author/(?P<pk>\d+)/delete/naive/$', views.NaiveAuthorDelete.as_view()), (r'^edit/author/(?P<pk>\d+)/delete/redirect/$', views.NaiveAuthorDelete.as_view(success_url='/edit/authors/create/')), (r'^edit/author/(?P<pk>\d+)/delete/$', views.AuthorDelete.as_view()), (r'^edit/author/(?P<pk>\d+)/delete/special/$', views.SpecializedAuthorDelete.as_view()), # ArchiveIndexView (r'^dates/books/$', views.BookArchive.as_view()), (r'^dates/books/context_object_name/$', views.BookArchive.as_view(context_object_name='thingies')), (r'^dates/books/allow_empty/$', views.BookArchive.as_view(allow_empty=True)), (r'^dates/books/template_name/$', views.BookArchive.as_view(template_name='generic_views/list.html')), (r'^dates/books/template_name_suffix/$', views.BookArchive.as_view(template_name_suffix='_detail')), (r'^dates/books/invalid/$', views.BookArchive.as_view(queryset=None)), (r'^dates/books/paginated/$', views.BookArchive.as_view(paginate_by=10)), # ListView (r'^list/dict/$', views.DictList.as_view()), (r'^list/dict/paginated/$', views.DictList.as_view(paginate_by=1)), url(r'^list/artists/$', views.ArtistList.as_view(), name="artists_list"), url(r'^list/authors/$', views.AuthorList.as_view(), name="authors_list"), (r'^list/authors/paginated/$', views.AuthorList.as_view(paginate_by=30)), (r'^list/authors/paginated/(?P<page>\d+)/$', views.AuthorList.as_view(paginate_by=30)), (r'^list/authors/notempty/$', views.AuthorList.as_view(allow_empty=False)), (r'^list/authors/template_name/$', views.AuthorList.as_view(template_name='generic_views/list.html')), (r'^list/authors/template_name_suffix/$', views.AuthorList.as_view(template_name_suffix='_objects')), (r'^list/authors/context_object_name/$', views.AuthorList.as_view(context_object_name='author_list')), (r'^list/authors/dupe_context_object_name/$', views.AuthorList.as_view(context_object_name='object_list')), (r'^list/authors/invalid/$', views.AuthorList.as_view(queryset=None)), (r'^list/authors/paginated/custom_class/$', views.AuthorList.as_view(paginate_by=5, paginator_class=views.CustomPaginator)), (r'^list/authors/paginated/custom_constructor/$', views.AuthorListCustomPaginator.as_view()), # YearArchiveView # Mixing keyword and possitional captures below is intentional; the views # ought to be able to accept either. (r'^dates/books/(?P<year>\d{4})/$', views.BookYearArchive.as_view()), (r'^dates/books/(?P<year>\d{4})/make_object_list/$', views.BookYearArchive.as_view(make_object_list=True)), (r'^dates/books/(?P<year>\d{4})/allow_empty/$', views.BookYearArchive.as_view(allow_empty=True)), (r'^dates/books/(?P<year>\d{4})/allow_future/$', views.BookYearArchive.as_view(allow_future=True)), (r'^dates/books/no_year/$', views.BookYearArchive.as_view()), # MonthArchiveView (r'^dates/books/(?P<year>\d{4})/(?P<month>[a-z]{3})/$', views.BookMonthArchive.as_view()), (r'^dates/books/(?P<year>\d{4})/(?P<month>\d{1,2})/$', views.BookMonthArchive.as_view(month_format='%m')), (r'^dates/books/(?P<year>\d{4})/(?P<month>[a-z]{3})/allow_empty/$', views.BookMonthArchive.as_view(allow_empty=True)), (r'^dates/books/(?P<year>\d{4})/(?P<month>[a-z]{3})/allow_future/$', views.BookMonthArchive.as_view(allow_future=True)), (r'^dates/books/(?P<year>\d{4})/no_month/$', views.BookMonthArchive.as_view()), # WeekArchiveView (r'^dates/books/(?P<year>\d{4})/week/(?P<week>\d{1,2})/$', views.BookWeekArchive.as_view()), (r'^dates/books/(?P<year>\d{4})/week/(?P<week>\d{1,2})/allow_empty/$', views.BookWeekArchive.as_view(allow_empty=True)), (r'^dates/books/(?P<year>\d{4})/week/(?P<week>\d{1,2})/allow_future/$', views.BookWeekArchive.as_view(allow_future=True)), (r'^dates/books/(?P<year>\d{4})/week/no_week/$', views.BookWeekArchive.as_view()), (r'^dates/books/(?P<year>\d{4})/week/(?P<week>\d{1,2})/monday/$', views.BookWeekArchive.as_view(week_format='%W')), # DayArchiveView (r'^dates/books/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\d{1,2})/$', views.BookDayArchive.as_view()), (r'^dates/books/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/$', views.BookDayArchive.as_view(month_format='%m')), (r'^dates/books/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\d{1,2})/allow_empty/$', views.BookDayArchive.as_view(allow_empty=True)), (r'^dates/books/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\d{1,2})/allow_future/$', views.BookDayArchive.as_view(allow_future=True)), (r'^dates/books/(?P<year>\d{4})/(?P<month>[a-z]{3})/no_day/$', views.BookDayArchive.as_view()), # TodayArchiveView (r'dates/books/today/$', views.BookTodayArchive.as_view()), (r'dates/books/today/allow_empty/$', views.BookTodayArchive.as_view(allow_empty=True)), # DateDetailView (r'^dates/books/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\d{1,2})/(?P<pk>\d+)/$', views.BookDetail.as_view()), (r'^dates/books/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<pk>\d+)/$', views.BookDetail.as_view(month_format='%m')), (r'^dates/books/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\d{1,2})/(?P<pk>\d+)/allow_future/$', views.BookDetail.as_view(allow_future=True)), (r'^dates/books/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\d{1,2})/nopk/$', views.BookDetail.as_view()), (r'^dates/books/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\d{1,2})/byslug/(?P<slug>[\w-]+)/$', views.BookDetail.as_view()), # Useful for testing redirects (r'^accounts/login/$', 'django.contrib.auth.views.login') )
9,307
Python
.py
190
42.221053
101
0.619037
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,077
dates.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/generic_views/dates.py
import datetime import random from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from regressiontests.generic_views.models import Book class ArchiveIndexViewTests(TestCase): fixtures = ['generic-views-test-data.json'] urls = 'regressiontests.generic_views.urls' def _make_books(self, n, base_date): for i in range(n): b = Book.objects.create( name='Book %d' % i, slug='book-%d' % i, pages=100+i, pubdate=base_date - datetime.timedelta(days=1)) def test_archive_view(self): res = self.client.get('/dates/books/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['date_list'], Book.objects.dates('pubdate', 'year')[::-1]) self.assertEqual(list(res.context['latest']), list(Book.objects.all())) self.assertTemplateUsed(res, 'generic_views/book_archive.html') def test_archive_view_context_object_name(self): res = self.client.get('/dates/books/context_object_name/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['date_list'], Book.objects.dates('pubdate', 'year')[::-1]) self.assertEqual(list(res.context['thingies']), list(Book.objects.all())) self.assertFalse('latest' in res.context) self.assertTemplateUsed(res, 'generic_views/book_archive.html') def test_empty_archive_view(self): Book.objects.all().delete() res = self.client.get('/dates/books/') self.assertEqual(res.status_code, 404) def test_allow_empty_archive_view(self): Book.objects.all().delete() res = self.client.get('/dates/books/allow_empty/') self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context['date_list']), []) self.assertEqual(list(res.context['date_list']), []) self.assertTemplateUsed(res, 'generic_views/book_archive.html') def test_archive_view_template(self): res = self.client.get('/dates/books/template_name/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['date_list'], Book.objects.dates('pubdate', 'year')[::-1]) self.assertEqual(list(res.context['latest']), list(Book.objects.all())) self.assertTemplateUsed(res, 'generic_views/list.html') def test_archive_view_template_suffix(self): res = self.client.get('/dates/books/template_name_suffix/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['date_list'], Book.objects.dates('pubdate', 'year')[::-1]) self.assertEqual(list(res.context['latest']), list(Book.objects.all())) self.assertTemplateUsed(res, 'generic_views/book_detail.html') def test_archive_view_invalid(self): self.assertRaises(ImproperlyConfigured, self.client.get, '/dates/books/invalid/') def test_paginated_archive_view(self): self._make_books(20, base_date=datetime.date.today()) res = self.client.get('/dates/books/paginated/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['date_list'], Book.objects.dates('pubdate', 'year')[::-1]) self.assertEqual(list(res.context['latest']), list(Book.objects.all()[0:10])) self.assertTemplateUsed(res, 'generic_views/book_archive.html') res = self.client.get('/dates/books/paginated/?page=2') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['page_obj'].number, 2) self.assertEqual(list(res.context['latest']), list(Book.objects.all()[10:20])) class YearArchiveViewTests(TestCase): fixtures = ['generic-views-test-data.json'] urls = 'regressiontests.generic_views.urls' def test_year_view(self): res = self.client.get('/dates/books/2008/') self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context['date_list']), [datetime.datetime(2008, 10, 1)]) self.assertEqual(res.context['year'], '2008') self.assertTemplateUsed(res, 'generic_views/book_archive_year.html') def test_year_view_make_object_list(self): res = self.client.get('/dates/books/2006/make_object_list/') self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context['date_list']), [datetime.datetime(2006, 5, 1)]) self.assertEqual(list(res.context['book_list']), list(Book.objects.filter(pubdate__year=2006))) self.assertEqual(list(res.context['object_list']), list(Book.objects.filter(pubdate__year=2006))) self.assertTemplateUsed(res, 'generic_views/book_archive_year.html') def test_year_view_empty(self): res = self.client.get('/dates/books/1999/') self.assertEqual(res.status_code, 404) res = self.client.get('/dates/books/1999/allow_empty/') self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context['date_list']), []) self.assertEqual(list(res.context['book_list']), []) def test_year_view_allow_future(self): # Create a new book in the future year = datetime.date.today().year + 1 b = Book.objects.create(name="The New New Testement", pages=600, pubdate=datetime.date(year, 1, 1)) res = self.client.get('/dates/books/%s/' % year) self.assertEqual(res.status_code, 404) res = self.client.get('/dates/books/%s/allow_empty/' % year) self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context['book_list']), []) res = self.client.get('/dates/books/%s/allow_future/' % year) self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context['date_list']), [datetime.datetime(year, 1, 1)]) def test_year_view_invalid_pattern(self): res = self.client.get('/dates/books/no_year/') self.assertEqual(res.status_code, 404) class MonthArchiveViewTests(TestCase): fixtures = ['generic-views-test-data.json'] urls = 'regressiontests.generic_views.urls' def test_month_view(self): res = self.client.get('/dates/books/2008/oct/') self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'generic_views/book_archive_month.html') self.assertEqual(list(res.context['date_list']), [datetime.datetime(2008, 10, 1)]) self.assertEqual(list(res.context['book_list']), list(Book.objects.filter(pubdate=datetime.date(2008, 10, 1)))) self.assertEqual(res.context['month'], datetime.date(2008, 10, 1)) # Since allow_empty=False, next/prev months must be valid (#7164) self.assertEqual(res.context['next_month'], None) self.assertEqual(res.context['previous_month'], datetime.date(2006, 5, 1)) def test_month_view_allow_empty(self): # allow_empty = False, empty month res = self.client.get('/dates/books/2000/jan/') self.assertEqual(res.status_code, 404) # allow_empty = True, empty month res = self.client.get('/dates/books/2000/jan/allow_empty/') self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context['date_list']), []) self.assertEqual(list(res.context['book_list']), []) self.assertEqual(res.context['month'], datetime.date(2000, 1, 1)) # Since it's allow empty, next/prev are allowed to be empty months (#7164) self.assertEqual(res.context['next_month'], datetime.date(2000, 2, 1)) self.assertEqual(res.context['previous_month'], datetime.date(1999, 12, 1)) # allow_empty but not allow_future: next_month should be empty (#7164) url = datetime.date.today().strftime('/dates/books/%Y/%b/allow_empty/').lower() res = self.client.get(url) self.assertEqual(res.status_code, 200) self.assertEqual(res.context['next_month'], None) def test_month_view_allow_future(self): future = (datetime.date.today() + datetime.timedelta(days=60)).replace(day=1) urlbit = future.strftime('%Y/%b').lower() b = Book.objects.create(name="The New New Testement", pages=600, pubdate=future) # allow_future = False, future month res = self.client.get('/dates/books/%s/' % urlbit) self.assertEqual(res.status_code, 404) # allow_future = True, valid future month res = self.client.get('/dates/books/%s/allow_future/' % urlbit) self.assertEqual(res.status_code, 200) self.assertEqual(res.context['date_list'][0].date(), b.pubdate) self.assertEqual(list(res.context['book_list']), [b]) self.assertEqual(res.context['month'], future) # Since it's allow_future but not allow_empty, next/prev are not # allowed to be empty months (#7164) self.assertEqual(res.context['next_month'], None) self.assertEqual(res.context['previous_month'], datetime.date(2008, 10, 1)) # allow_future, but not allow_empty, with a current month. So next # should be in the future (yup, #7164, again) res = self.client.get('/dates/books/2008/oct/allow_future/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['next_month'], future) self.assertEqual(res.context['previous_month'], datetime.date(2006, 5, 1)) def test_custom_month_format(self): res = self.client.get('/dates/books/2008/10/') self.assertEqual(res.status_code, 200) def test_month_view_invalid_pattern(self): res = self.client.get('/dates/books/2007/no_month/') self.assertEqual(res.status_code, 404) def test_previous_month_without_content(self): "Content can exist on any day of the previous month. Refs #14711" self.pubdate_list = [ datetime.date(2010, month, day) for month,day in ((9,1), (10,2), (11,3)) ] for pubdate in self.pubdate_list: name = str(pubdate) Book.objects.create(name=name, slug=name, pages=100, pubdate=pubdate) res = self.client.get('/dates/books/2010/nov/allow_empty/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['previous_month'], datetime.date(2010,10,1)) # The following test demonstrates the bug res = self.client.get('/dates/books/2010/nov/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['previous_month'], datetime.date(2010,10,1)) # The bug does not occur here because a Book with pubdate of Sep 1 exists res = self.client.get('/dates/books/2010/oct/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['previous_month'], datetime.date(2010,9,1)) class WeekArchiveViewTests(TestCase): fixtures = ['generic-views-test-data.json'] urls = 'regressiontests.generic_views.urls' def test_week_view(self): res = self.client.get('/dates/books/2008/week/39/') self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'generic_views/book_archive_week.html') self.assertEqual(res.context['book_list'][0], Book.objects.get(pubdate=datetime.date(2008, 10, 1))) self.assertEqual(res.context['week'], datetime.date(2008, 9, 28)) def test_week_view_allow_empty(self): res = self.client.get('/dates/books/2008/week/12/') self.assertEqual(res.status_code, 404) res = self.client.get('/dates/books/2008/week/12/allow_empty/') self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context['book_list']), []) def test_week_view_allow_future(self): future = datetime.date(datetime.date.today().year + 1, 1, 1) b = Book.objects.create(name="The New New Testement", pages=600, pubdate=future) res = self.client.get('/dates/books/%s/week/1/' % future.year) self.assertEqual(res.status_code, 404) res = self.client.get('/dates/books/%s/week/1/allow_future/' % future.year) self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context['book_list']), [b]) def test_week_view_invalid_pattern(self): res = self.client.get('/dates/books/2007/week/no_week/') self.assertEqual(res.status_code, 404) def test_week_start_Monday(self): # Regression for #14752 res = self.client.get('/dates/books/2008/week/39/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['week'], datetime.date(2008, 9, 28)) res = self.client.get('/dates/books/2008/week/39/monday/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['week'], datetime.date(2008, 9, 29)) class DayArchiveViewTests(TestCase): fixtures = ['generic-views-test-data.json'] urls = 'regressiontests.generic_views.urls' def test_day_view(self): res = self.client.get('/dates/books/2008/oct/01/') self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'generic_views/book_archive_day.html') self.assertEqual(list(res.context['book_list']), list(Book.objects.filter(pubdate=datetime.date(2008, 10, 1)))) self.assertEqual(res.context['day'], datetime.date(2008, 10, 1)) # Since allow_empty=False, next/prev days must be valid. self.assertEqual(res.context['next_day'], None) self.assertEqual(res.context['previous_day'], datetime.date(2006, 5, 1)) def test_day_view_allow_empty(self): # allow_empty = False, empty month res = self.client.get('/dates/books/2000/jan/1/') self.assertEqual(res.status_code, 404) # allow_empty = True, empty month res = self.client.get('/dates/books/2000/jan/1/allow_empty/') self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context['book_list']), []) self.assertEqual(res.context['day'], datetime.date(2000, 1, 1)) # Since it's allow empty, next/prev are allowed to be empty months (#7164) self.assertEqual(res.context['next_day'], datetime.date(2000, 1, 2)) self.assertEqual(res.context['previous_day'], datetime.date(1999, 12, 31)) # allow_empty but not allow_future: next_month should be empty (#7164) url = datetime.date.today().strftime('/dates/books/%Y/%b/%d/allow_empty/').lower() res = self.client.get(url) self.assertEqual(res.status_code, 200) self.assertEqual(res.context['next_day'], None) def test_day_view_allow_future(self): future = (datetime.date.today() + datetime.timedelta(days=60)) urlbit = future.strftime('%Y/%b/%d').lower() b = Book.objects.create(name="The New New Testement", pages=600, pubdate=future) # allow_future = False, future month res = self.client.get('/dates/books/%s/' % urlbit) self.assertEqual(res.status_code, 404) # allow_future = True, valid future month res = self.client.get('/dates/books/%s/allow_future/' % urlbit) self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context['book_list']), [b]) self.assertEqual(res.context['day'], future) # allow_future but not allow_empty, next/prev amust be valid self.assertEqual(res.context['next_day'], None) self.assertEqual(res.context['previous_day'], datetime.date(2008, 10, 1)) # allow_future, but not allow_empty, with a current month. res = self.client.get('/dates/books/2008/oct/01/allow_future/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['next_day'], future) self.assertEqual(res.context['previous_day'], datetime.date(2006, 5, 1)) def test_next_prev_context(self): res = self.client.get('/dates/books/2008/oct/01/') self.assertEqual(res.content, "Archive for Oct. 1, 2008. Previous day is May 1, 2006") def test_custom_month_format(self): res = self.client.get('/dates/books/2008/10/01/') self.assertEqual(res.status_code, 200) def test_day_view_invalid_pattern(self): res = self.client.get('/dates/books/2007/oct/no_day/') self.assertEqual(res.status_code, 404) def test_today_view(self): res = self.client.get('/dates/books/today/') self.assertEqual(res.status_code, 404) res = self.client.get('/dates/books/today/allow_empty/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['day'], datetime.date.today()) class DateDetailViewTests(TestCase): fixtures = ['generic-views-test-data.json'] urls = 'regressiontests.generic_views.urls' def test_date_detail_by_pk(self): res = self.client.get('/dates/books/2008/oct/01/1/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['object'], Book.objects.get(pk=1)) self.assertEqual(res.context['book'], Book.objects.get(pk=1)) self.assertTemplateUsed(res, 'generic_views/book_detail.html') def test_date_detail_by_slug(self): res = self.client.get('/dates/books/2006/may/01/byslug/dreaming-in-code/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['book'], Book.objects.get(slug='dreaming-in-code')) def test_date_detail_custom_month_format(self): res = self.client.get('/dates/books/2008/10/01/1/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['book'], Book.objects.get(pk=1)) def test_date_detail_allow_future(self): future = (datetime.date.today() + datetime.timedelta(days=60)) urlbit = future.strftime('%Y/%b/%d').lower() b = Book.objects.create(name="The New New Testement", slug="new-new", pages=600, pubdate=future) res = self.client.get('/dates/books/%s/new-new/' % urlbit) self.assertEqual(res.status_code, 404) res = self.client.get('/dates/books/%s/%s/allow_future/' % (urlbit, b.id)) self.assertEqual(res.status_code, 200) self.assertEqual(res.context['book'], b) self.assertTemplateUsed(res, 'generic_views/book_detail.html') def test_invalid_url(self): self.assertRaises(AttributeError, self.client.get, "/dates/books/2008/oct/01/nopk/")
18,304
Python
.py
311
50.254019
107
0.661756
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,078
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/generic_views/tests.py
from regressiontests.generic_views.base import ViewTest, TemplateViewTest, RedirectViewTest from regressiontests.generic_views.dates import ArchiveIndexViewTests, YearArchiveViewTests, MonthArchiveViewTests, WeekArchiveViewTests, DayArchiveViewTests, DateDetailViewTests from regressiontests.generic_views.detail import DetailViewTest from regressiontests.generic_views.edit import ModelFormMixinTests, CreateViewTests, UpdateViewTests, DeleteViewTests from regressiontests.generic_views.list import ListViewTests
514
Python
.py
5
101.8
178
0.901768
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,079
base.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/generic_views/base.py
import time import unittest from django.core.exceptions import ImproperlyConfigured from django.http import HttpResponse from django.test import TestCase, RequestFactory from django.utils import simplejson from django.views.generic import View, TemplateView, RedirectView class SimpleView(View): """ A simple view with a docstring. """ def get(self, request): return HttpResponse('This is a simple view') class SimplePostView(SimpleView): post = SimpleView.get class CustomizableView(SimpleView): parameter = {} def decorator(view): view.is_decorated = True return view class DecoratedDispatchView(SimpleView): @decorator def dispatch(self, request, *args, **kwargs): return super(DecoratedDispatchView, self).dispatch(request, *args, **kwargs) class AboutTemplateView(TemplateView): def get(self, request): return self.render_to_response({}) def get_template_names(self): return ['generic_views/about.html'] class AboutTemplateAttributeView(TemplateView): template_name = 'generic_views/about.html' def get(self, request): return self.render_to_response(context={}) class InstanceView(View): def get(self, request): return self class ViewTest(unittest.TestCase): rf = RequestFactory() def _assert_simple(self, response): self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'This is a simple view') def test_no_init_kwargs(self): """ Test that a view can't be accidentally instantiated before deployment """ try: view = SimpleView(key='value').as_view() self.fail('Should not be able to instantiate a view') except AttributeError: pass def test_no_init_args(self): """ Test that a view can't be accidentally instantiated before deployment """ try: view = SimpleView.as_view('value') self.fail('Should not be able to use non-keyword arguments instantiating a view') except TypeError: pass def test_pathological_http_method(self): """ The edge case of a http request that spoofs an existing method name is caught. """ self.assertEqual(SimpleView.as_view()( self.rf.get('/', REQUEST_METHOD='DISPATCH') ).status_code, 405) def test_get_only(self): """ Test a view which only allows GET doesn't allow other methods. """ self._assert_simple(SimpleView.as_view()(self.rf.get('/'))) self.assertEqual(SimpleView.as_view()(self.rf.post('/')).status_code, 405) self.assertEqual(SimpleView.as_view()( self.rf.get('/', REQUEST_METHOD='FAKE') ).status_code, 405) def test_get_and_post(self): """ Test a view which only allows both GET and POST. """ self._assert_simple(SimplePostView.as_view()(self.rf.get('/'))) self._assert_simple(SimplePostView.as_view()(self.rf.post('/'))) self.assertEqual(SimplePostView.as_view()( self.rf.get('/', REQUEST_METHOD='FAKE') ).status_code, 405) def test_invalid_keyword_argument(self): """ Test that view arguments must be predefined on the class and can't be named like a HTTP method. """ # Check each of the allowed method names for method in SimpleView.http_method_names: kwargs = dict(((method, "value"),)) self.assertRaises(TypeError, SimpleView.as_view, **kwargs) # Check the case view argument is ok if predefined on the class... CustomizableView.as_view(parameter="value") # ...but raises errors otherwise. self.assertRaises(TypeError, CustomizableView.as_view, foobar="value") def test_calling_more_than_once(self): """ Test a view can only be called once. """ request = self.rf.get('/') view = InstanceView.as_view() self.assertNotEqual(view(request), view(request)) def test_class_attributes(self): """ Test that the callable returned from as_view() has proper docstring, name and module. """ self.assertEqual(SimpleView.__doc__, SimpleView.as_view().__doc__) self.assertEqual(SimpleView.__name__, SimpleView.as_view().__name__) self.assertEqual(SimpleView.__module__, SimpleView.as_view().__module__) def test_dispatch_decoration(self): """ Test that attributes set by decorators on the dispatch method are also present on the closure. """ self.assertTrue(DecoratedDispatchView.as_view().is_decorated) class TemplateViewTest(TestCase): urls = 'regressiontests.generic_views.urls' rf = RequestFactory() def _assert_about(self, response): response.render() self.assertEqual(response.status_code, 200) self.assertContains(response, '<h1>About</h1>') def test_get(self): """ Test a view that simply renders a template on GET """ self._assert_about(AboutTemplateView.as_view()(self.rf.get('/about/'))) def test_get_template_attribute(self): """ Test a view that renders a template on GET with the template name as an attribute on the class. """ self._assert_about(AboutTemplateAttributeView.as_view()(self.rf.get('/about/'))) def test_get_generic_template(self): """ Test a completely generic view that renders a template on GET with the template name as an argument at instantiation. """ self._assert_about(TemplateView.as_view(template_name='generic_views/about.html')(self.rf.get('/about/'))) def test_template_name_required(self): """ A template view must provide a template name """ self.assertRaises(ImproperlyConfigured, self.client.get, '/template/no_template/') def test_template_params(self): """ A generic template view passes kwargs as context. """ response = self.client.get('/template/simple/bar/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['params'], {'foo': 'bar'}) def test_extra_template_params(self): """ A template view can be customized to return extra context. """ response = self.client.get('/template/custom/bar/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['params'], {'foo': 'bar'}) self.assertEqual(response.context['key'], 'value') def test_cached_views(self): """ A template view can be cached """ response = self.client.get('/template/cached/bar/') self.assertEqual(response.status_code, 200) time.sleep(1.0) response2 = self.client.get('/template/cached/bar/') self.assertEqual(response2.status_code, 200) self.assertEqual(response.content, response2.content) time.sleep(2.0) # Let the cache expire and test again response2 = self.client.get('/template/cached/bar/') self.assertEqual(response2.status_code, 200) self.assertNotEqual(response.content, response2.content) class RedirectViewTest(unittest.TestCase): rf = RequestFactory() def test_no_url(self): "Without any configuration, returns HTTP 410 GONE" response = RedirectView.as_view()(self.rf.get('/foo/')) self.assertEqual(response.status_code, 410) def test_permanaent_redirect(self): "Default is a permanent redirect" response = RedirectView.as_view(url='/bar/')(self.rf.get('/foo/')) self.assertEqual(response.status_code, 301) self.assertEqual(response['Location'], '/bar/') def test_temporary_redirect(self): "Permanent redirects are an option" response = RedirectView.as_view(url='/bar/', permanent=False)(self.rf.get('/foo/')) self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], '/bar/') def test_include_args(self): "GET arguments can be included in the redirected URL" response = RedirectView.as_view(url='/bar/')(self.rf.get('/foo/')) self.assertEqual(response.status_code, 301) self.assertEqual(response['Location'], '/bar/') response = RedirectView.as_view(url='/bar/', query_string=True)(self.rf.get('/foo/?pork=spam')) self.assertEqual(response.status_code, 301) self.assertEqual(response['Location'], '/bar/?pork=spam') def test_parameter_substitution(self): "Redirection URLs can be parameterized" response = RedirectView.as_view(url='/bar/%(object_id)d/')(self.rf.get('/foo/42/'), object_id=42) self.assertEqual(response.status_code, 301) self.assertEqual(response['Location'], '/bar/42/')
8,991
Python
.py
206
35.669903
114
0.653873
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,080
detail.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/generic_views/detail.py
from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from regressiontests.generic_views.models import Artist, Author, Page class DetailViewTest(TestCase): fixtures = ['generic-views-test-data.json'] urls = 'regressiontests.generic_views.urls' def test_simple_object(self): res = self.client.get('/detail/obj/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['object'], {'foo': 'bar'}) self.assertTemplateUsed(res, 'generic_views/detail.html') def test_detail_by_pk(self): res = self.client.get('/detail/author/1/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['object'], Author.objects.get(pk=1)) self.assertEqual(res.context['author'], Author.objects.get(pk=1)) self.assertTemplateUsed(res, 'generic_views/author_detail.html') def test_detail_by_slug(self): res = self.client.get('/detail/author/byslug/scott-rosenberg/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['object'], Author.objects.get(slug='scott-rosenberg')) self.assertEqual(res.context['author'], Author.objects.get(slug='scott-rosenberg')) self.assertTemplateUsed(res, 'generic_views/author_detail.html') def test_verbose_name(self): res = self.client.get('/detail/artist/1/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['object'], Artist.objects.get(pk=1)) self.assertEqual(res.context['artist'], Artist.objects.get(pk=1)) self.assertTemplateUsed(res, 'generic_views/artist_detail.html') def test_template_name(self): res = self.client.get('/detail/author/1/template_name/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['object'], Author.objects.get(pk=1)) self.assertEqual(res.context['author'], Author.objects.get(pk=1)) self.assertTemplateUsed(res, 'generic_views/about.html') def test_template_name_suffix(self): res = self.client.get('/detail/author/1/template_name_suffix/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['object'], Author.objects.get(pk=1)) self.assertEqual(res.context['author'], Author.objects.get(pk=1)) self.assertTemplateUsed(res, 'generic_views/author_view.html') def test_template_name_field(self): res = self.client.get('/detail/page/1/field/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['object'], Page.objects.get(pk=1)) self.assertEqual(res.context['page'], Page.objects.get(pk=1)) self.assertTemplateUsed(res, 'generic_views/page_template.html') def test_context_object_name(self): res = self.client.get('/detail/author/1/context_object_name/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['object'], Author.objects.get(pk=1)) self.assertEqual(res.context['thingy'], Author.objects.get(pk=1)) self.assertFalse('author' in res.context) self.assertTemplateUsed(res, 'generic_views/author_detail.html') def test_duplicated_context_object_name(self): res = self.client.get('/detail/author/1/dupe_context_object_name/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['object'], Author.objects.get(pk=1)) self.assertFalse('author' in res.context) self.assertTemplateUsed(res, 'generic_views/author_detail.html') def test_invalid_url(self): self.assertRaises(AttributeError, self.client.get, '/detail/author/invalid/url/') def test_invalid_queryset(self): self.assertRaises(ImproperlyConfigured, self.client.get, '/detail/author/invalid/qs/')
3,822
Python
.py
64
51.8125
94
0.697917
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,081
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/generic_views/forms.py
from django import forms from regressiontests.generic_views.models import Author class AuthorForm(forms.ModelForm): name = forms.CharField() slug = forms.SlugField() class Meta: model = Author
217
Python
.py
7
26.571429
55
0.752427
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,082
list.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/generic_views/list.py
from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from regressiontests.generic_views.models import Author, Artist from regressiontests.generic_views.views import CustomPaginator class ListViewTests(TestCase): fixtures = ['generic-views-test-data.json'] urls = 'regressiontests.generic_views.urls' def test_items(self): res = self.client.get('/list/dict/') self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'generic_views/list.html') self.assertEqual(res.context['object_list'][0]['first'], 'John') def test_queryset(self): res = self.client.get('/list/authors/') self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'generic_views/author_list.html') self.assertEqual(list(res.context['object_list']), list(Author.objects.all())) self.assertIs(res.context['author_list'], res.context['object_list']) self.assertIsNone(res.context['paginator']) self.assertIsNone(res.context['page_obj']) self.assertFalse(res.context['is_paginated']) def test_paginated_queryset(self): self._make_authors(100) res = self.client.get('/list/authors/paginated/') self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'generic_views/author_list.html') self.assertEqual(len(res.context['object_list']), 30) self.assertIs(res.context['author_list'], res.context['object_list']) self.assertTrue(res.context['is_paginated']) self.assertEqual(res.context['page_obj'].number, 1) self.assertEqual(res.context['paginator'].num_pages, 4) self.assertEqual(res.context['author_list'][0].name, 'Author 00') self.assertEqual(list(res.context['author_list'])[-1].name, 'Author 29') def test_paginated_queryset_shortdata(self): # Test that short datasets ALSO result in a paginated view. res = self.client.get('/list/authors/paginated/') self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'generic_views/author_list.html') self.assertEqual(list(res.context['object_list']), list(Author.objects.all())) self.assertIs(res.context['author_list'], res.context['object_list']) self.assertEqual(res.context['page_obj'].number, 1) self.assertEqual(res.context['paginator'].num_pages, 1) self.assertFalse(res.context['is_paginated']) def test_paginated_get_page_by_query_string(self): self._make_authors(100) res = self.client.get('/list/authors/paginated/', {'page': '2'}) self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'generic_views/author_list.html') self.assertEqual(len(res.context['object_list']), 30) self.assertIs(res.context['author_list'], res.context['object_list']) self.assertEqual(res.context['author_list'][0].name, 'Author 30') self.assertEqual(res.context['page_obj'].number, 2) def test_paginated_get_last_page_by_query_string(self): self._make_authors(100) res = self.client.get('/list/authors/paginated/', {'page': 'last'}) self.assertEqual(res.status_code, 200) self.assertEqual(len(res.context['object_list']), 10) self.assertIs(res.context['author_list'], res.context['object_list']) self.assertEqual(res.context['author_list'][0].name, 'Author 90') self.assertEqual(res.context['page_obj'].number, 4) def test_paginated_get_page_by_urlvar(self): self._make_authors(100) res = self.client.get('/list/authors/paginated/3/') self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'generic_views/author_list.html') self.assertEqual(len(res.context['object_list']), 30) self.assertIs(res.context['author_list'], res.context['object_list']) self.assertEqual(res.context['author_list'][0].name, 'Author 60') self.assertEqual(res.context['page_obj'].number, 3) def test_paginated_page_out_of_range(self): self._make_authors(100) res = self.client.get('/list/authors/paginated/42/') self.assertEqual(res.status_code, 404) def test_paginated_invalid_page(self): self._make_authors(100) res = self.client.get('/list/authors/paginated/?page=frog') self.assertEqual(res.status_code, 404) def test_paginated_custom_paginator_class(self): self._make_authors(7) res = self.client.get('/list/authors/paginated/custom_class/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['paginator'].num_pages, 1) # Custom pagination allows for 2 orphans on a page size of 5 self.assertEqual(len(res.context['object_list']), 7) def test_paginated_custom_paginator_constructor(self): self._make_authors(7) res = self.client.get('/list/authors/paginated/custom_constructor/') self.assertEqual(res.status_code, 200) # Custom pagination allows for 2 orphans on a page size of 5 self.assertEqual(len(res.context['object_list']), 7) def test_paginated_non_queryset(self): res = self.client.get('/list/dict/paginated/') self.assertEqual(res.status_code, 200) self.assertEqual(len(res.context['object_list']), 1) def test_verbose_name(self): res = self.client.get('/list/artists/') self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'generic_views/list.html') self.assertEqual(list(res.context['object_list']), list(Artist.objects.all())) self.assertIs(res.context['artist_list'], res.context['object_list']) self.assertIsNone(res.context['paginator']) self.assertIsNone(res.context['page_obj']) self.assertFalse(res.context['is_paginated']) def test_allow_empty_false(self): res = self.client.get('/list/authors/notempty/') self.assertEqual(res.status_code, 200) Author.objects.all().delete() res = self.client.get('/list/authors/notempty/') self.assertEqual(res.status_code, 404) def test_template_name(self): res = self.client.get('/list/authors/template_name/') self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context['object_list']), list(Author.objects.all())) self.assertIs(res.context['author_list'], res.context['object_list']) self.assertTemplateUsed(res, 'generic_views/list.html') def test_template_name_suffix(self): res = self.client.get('/list/authors/template_name_suffix/') self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context['object_list']), list(Author.objects.all())) self.assertIs(res.context['author_list'], res.context['object_list']) self.assertTemplateUsed(res, 'generic_views/author_objects.html') def test_context_object_name(self): res = self.client.get('/list/authors/context_object_name/') self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context['object_list']), list(Author.objects.all())) self.assertNotIn('authors', res.context) self.assertIs(res.context['author_list'], res.context['object_list']) self.assertTemplateUsed(res, 'generic_views/author_list.html') def test_duplicate_context_object_name(self): res = self.client.get('/list/authors/dupe_context_object_name/') self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context['object_list']), list(Author.objects.all())) self.assertNotIn('authors', res.context) self.assertNotIn('author_list', res.context) self.assertTemplateUsed(res, 'generic_views/author_list.html') def test_missing_items(self): self.assertRaises(ImproperlyConfigured, self.client.get, '/list/authors/invalid/') def _make_authors(self, n): Author.objects.all().delete() for i in range(n): Author.objects.create(name='Author %02i' % i, slug='a%s' % i)
8,122
Python
.py
141
49.319149
90
0.679065
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,083
views.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/generic_views/views.py
from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.core.urlresolvers import reverse from django.utils.decorators import method_decorator from django.views import generic from regressiontests.generic_views.models import Artist, Author, Book, Page from regressiontests.generic_views.forms import AuthorForm class CustomTemplateView(generic.TemplateView): template_name = 'generic_views/about.html' def get_context_data(self, **kwargs): return { 'params': kwargs, 'key': 'value' } class ObjectDetail(generic.DetailView): template_name = 'generic_views/detail.html' def get_object(self): return {'foo': 'bar'} class ArtistDetail(generic.DetailView): queryset = Artist.objects.all() class AuthorDetail(generic.DetailView): queryset = Author.objects.all() class PageDetail(generic.DetailView): queryset = Page.objects.all() template_name_field = 'template' class DictList(generic.ListView): """A ListView that doesn't use a model.""" queryset = [ {'first': 'John', 'last': 'Lennon'}, {'last': 'Yoko', 'last': 'Ono'} ] template_name = 'generic_views/list.html' class ArtistList(generic.ListView): template_name = 'generic_views/list.html' queryset = Artist.objects.all() class AuthorList(generic.ListView): queryset = Author.objects.all() class CustomPaginator(Paginator): def __init__(self, queryset, page_size, orphans=0, allow_empty_first_page=True): super(CustomPaginator, self).__init__( queryset, page_size, orphans=2, allow_empty_first_page=allow_empty_first_page) class AuthorListCustomPaginator(AuthorList): paginate_by = 5; def get_paginator(self, queryset, page_size, orphans=0, allow_empty_first_page=True): return super(AuthorListCustomPaginator, self).get_paginator( queryset, page_size, orphans=2, allow_empty_first_page=allow_empty_first_page) class ArtistCreate(generic.CreateView): model = Artist class NaiveAuthorCreate(generic.CreateView): queryset = Author.objects.all() class AuthorCreate(generic.CreateView): model = Author success_url = '/list/authors/' class SpecializedAuthorCreate(generic.CreateView): model = Author form_class = AuthorForm template_name = 'generic_views/form.html' context_object_name = 'thingy' def get_success_url(self): return reverse('author_detail', args=[self.object.id,]) class AuthorCreateRestricted(AuthorCreate): post = method_decorator(login_required)(AuthorCreate.post) class ArtistUpdate(generic.UpdateView): model = Artist class NaiveAuthorUpdate(generic.UpdateView): queryset = Author.objects.all() class AuthorUpdate(generic.UpdateView): model = Author success_url = '/list/authors/' class OneAuthorUpdate(generic.UpdateView): success_url = '/list/authors/' def get_object(self): return Author.objects.get(pk=1) class SpecializedAuthorUpdate(generic.UpdateView): model = Author form_class = AuthorForm template_name = 'generic_views/form.html' context_object_name = 'thingy' def get_success_url(self): return reverse('author_detail', args=[self.object.id,]) class NaiveAuthorDelete(generic.DeleteView): queryset = Author.objects.all() class AuthorDelete(generic.DeleteView): model = Author success_url = '/list/authors/' class SpecializedAuthorDelete(generic.DeleteView): queryset = Author.objects.all() template_name = 'generic_views/confirm_delete.html' context_object_name = 'thingy' def get_success_url(self): return reverse('authors_list') class BookConfig(object): queryset = Book.objects.all() date_field = 'pubdate' class BookArchive(BookConfig, generic.ArchiveIndexView): pass class BookYearArchive(BookConfig, generic.YearArchiveView): pass class BookMonthArchive(BookConfig, generic.MonthArchiveView): pass class BookWeekArchive(BookConfig, generic.WeekArchiveView): pass class BookDayArchive(BookConfig, generic.DayArchiveView): pass class BookTodayArchive(BookConfig, generic.TodayArchiveView): pass class BookDetail(BookConfig, generic.DateDetailView): pass class AuthorGetQuerySetFormView(generic.edit.ModelFormMixin): def get_queryset(self): return Author.objects.all()
4,506
Python
.py
117
33.222222
89
0.733534
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,084
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/modeltests/model_inheritance/models.py
""" XX. Model inheritance Model inheritance exists in two varieties: - abstract base classes which are a way of specifying common information inherited by the subclasses. They don't exist as a separate model. - non-abstract base classes (the default), which are models in their own right with their own database tables and everything. Their subclasses have references back to them, created automatically. Both styles are demonstrated here. """ from django.db import models # # Abstract base classes # class CommonInfo(models.Model): name = models.CharField(max_length=50) age = models.PositiveIntegerField() class Meta: abstract = True ordering = ['name'] def __unicode__(self): return u'%s %s' % (self.__class__.__name__, self.name) class Worker(CommonInfo): job = models.CharField(max_length=50) class Student(CommonInfo): school_class = models.CharField(max_length=10) class Meta: pass class StudentWorker(Student, Worker): pass # # Abstract base classes with related models # class Post(models.Model): title = models.CharField(max_length=50) class Attachment(models.Model): post = models.ForeignKey(Post, related_name='attached_%(class)s_set') content = models.TextField() class Meta: abstract = True def __unicode__(self): return self.content class Comment(Attachment): is_spam = models.BooleanField() class Link(Attachment): url = models.URLField() # # Multi-table inheritance # class Chef(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return u"%s the chef" % self.name class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __unicode__(self): return u"%s the place" % self.name class Rating(models.Model): rating = models.IntegerField(null=True, blank=True) class Meta: abstract = True ordering = ['-rating'] class Restaurant(Place, Rating): serves_hot_dogs = models.BooleanField() serves_pizza = models.BooleanField() chef = models.ForeignKey(Chef, null=True, blank=True) class Meta(Rating.Meta): db_table = 'my_restaurant' def __unicode__(self): return u"%s the restaurant" % self.name class ItalianRestaurant(Restaurant): serves_gnocchi = models.BooleanField() def __unicode__(self): return u"%s the italian restaurant" % self.name class Supplier(Place): customers = models.ManyToManyField(Restaurant, related_name='provider') def __unicode__(self): return u"%s the supplier" % self.name class ParkingLot(Place): # An explicit link to the parent (we can control the attribute name). parent = models.OneToOneField(Place, primary_key=True, parent_link=True) main_site = models.ForeignKey(Place, related_name='lot') def __unicode__(self): return u"%s the parking lot" % self.name # # Abstract base classes with related models where the sub-class has the # same name in a different app and inherits from the same abstract base # class. # NOTE: The actual API tests for the following classes are in # model_inheritance_same_model_name/models.py - They are defined # here in order to have the name conflict between apps # class Title(models.Model): title = models.CharField(max_length=50) class NamedURL(models.Model): title = models.ForeignKey(Title, related_name='attached_%(app_label)s_%(class)s_set') url = models.URLField() class Meta: abstract = True class Copy(NamedURL): content = models.TextField() def __unicode__(self): return self.content class Mixin(object): def __init__(self): self.other_attr = 1 super(Mixin, self).__init__() class MixinModel(models.Model, Mixin): pass
3,888
Python
.py
111
30.441441
89
0.702811
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,085
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/modeltests/model_inheritance/tests.py
from operator import attrgetter from django.core.exceptions import FieldError from django.test import TestCase from models import (Chef, CommonInfo, ItalianRestaurant, ParkingLot, Place, Post, Restaurant, Student, StudentWorker, Supplier, Worker, MixinModel) class ModelInheritanceTests(TestCase): def test_abstract(self): # The Student and Worker models both have 'name' and 'age' fields on # them and inherit the __unicode__() method, just as with normal Python # subclassing. This is useful if you want to factor out common # information for programming purposes, but still completely # independent separate models at the database level. w1 = Worker.objects.create(name="Fred", age=35, job="Quarry worker") w2 = Worker.objects.create(name="Barney", age=34, job="Quarry worker") s = Student.objects.create(name="Pebbles", age=5, school_class="1B") self.assertEqual(unicode(w1), "Worker Fred") self.assertEqual(unicode(s), "Student Pebbles") # The children inherit the Meta class of their parents (if they don't # specify their own). self.assertQuerysetEqual( Worker.objects.values("name"), [ {"name": "Barney"}, {"name": "Fred"}, ], lambda o: o ) # Since Student does not subclass CommonInfo's Meta, it has the effect # of completely overriding it. So ordering by name doesn't take place # for Students. self.assertEqual(Student._meta.ordering, []) # However, the CommonInfo class cannot be used as a normal model (it # doesn't exist as a model). self.assertRaises(AttributeError, lambda: CommonInfo.objects.all()) # A StudentWorker which does not exist is both a Student and Worker # which does not exist. self.assertRaises(Student.DoesNotExist, StudentWorker.objects.get, pk=12321321 ) self.assertRaises(Worker.DoesNotExist, StudentWorker.objects.get, pk=12321321 ) # MultipleObjectsReturned is also inherited. # This is written out "long form", rather than using __init__/create() # because of a bug with diamond inheritance (#10808) sw1 = StudentWorker() sw1.name = "Wilma" sw1.age = 35 sw1.save() sw2 = StudentWorker() sw2.name = "Betty" sw2.age = 24 sw2.save() self.assertRaises(Student.MultipleObjectsReturned, StudentWorker.objects.get, pk__lt=sw2.pk + 100 ) self.assertRaises(Worker.MultipleObjectsReturned, StudentWorker.objects.get, pk__lt=sw2.pk + 100 ) def test_multiple_table(self): post = Post.objects.create(title="Lorem Ipsum") # The Post model has distinct accessors for the Comment and Link models. post.attached_comment_set.create(content="Save $ on V1agr@", is_spam=True) post.attached_link_set.create( content="The Web framework for perfections with deadlines.", url="http://www.djangoproject.com/" ) # The Post model doesn't have an attribute called # 'attached_%(class)s_set'. self.assertRaises(AttributeError, getattr, post, "attached_%(class)s_set" ) # The Place/Restaurant/ItalianRestaurant models all exist as # independent models. However, the subclasses also have transparent # access to the fields of their ancestors. # Create a couple of Places. p1 = Place.objects.create(name="Master Shakes", address="666 W. Jersey") p2 = Place.objects.create(name="Ace Harware", address="1013 N. Ashland") # Test constructor for Restaurant. r = Restaurant.objects.create( name="Demon Dogs", address="944 W. Fullerton", serves_hot_dogs=True, serves_pizza=False, rating=2 ) # Test the constructor for ItalianRestaurant. c = Chef.objects.create(name="Albert") ir = ItalianRestaurant.objects.create( name="Ristorante Miron", address="1234 W. Ash", serves_hot_dogs=False, serves_pizza=False, serves_gnocchi=True, rating=4, chef=c ) self.assertQuerysetEqual( ItalianRestaurant.objects.filter(address="1234 W. Ash"), [ "Ristorante Miron", ], attrgetter("name") ) ir.address = "1234 W. Elm" ir.save() self.assertQuerysetEqual( ItalianRestaurant.objects.filter(address="1234 W. Elm"), [ "Ristorante Miron", ], attrgetter("name") ) # Make sure Restaurant and ItalianRestaurant have the right fields in # the right order. self.assertEqual( [f.name for f in Restaurant._meta.fields], ["id", "name", "address", "place_ptr", "rating", "serves_hot_dogs", "serves_pizza", "chef"] ) self.assertEqual( [f.name for f in ItalianRestaurant._meta.fields], ["id", "name", "address", "place_ptr", "rating", "serves_hot_dogs", "serves_pizza", "chef", "restaurant_ptr", "serves_gnocchi"], ) self.assertEqual(Restaurant._meta.ordering, ["-rating"]) # Even though p.supplier for a Place 'p' (a parent of a Supplier), a # Restaurant object cannot access that reverse relation, since it's not # part of the Place-Supplier Hierarchy. self.assertQuerysetEqual(Place.objects.filter(supplier__name="foo"), []) self.assertRaises(FieldError, Restaurant.objects.filter, supplier__name="foo" ) # Parent fields can be used directly in filters on the child model. self.assertQuerysetEqual( Restaurant.objects.filter(name="Demon Dogs"), [ "Demon Dogs", ], attrgetter("name") ) self.assertQuerysetEqual( ItalianRestaurant.objects.filter(address="1234 W. Elm"), [ "Ristorante Miron", ], attrgetter("name") ) # Filters against the parent model return objects of the parent's type. p = Place.objects.get(name="Demon Dogs") self.assertIs(type(p), Place) # Since the parent and child are linked by an automatically created # OneToOneField, you can get from the parent to the child by using the # child's name. self.assertEqual( p.restaurant, Restaurant.objects.get(name="Demon Dogs") ) self.assertEqual( Place.objects.get(name="Ristorante Miron").restaurant.italianrestaurant, ItalianRestaurant.objects.get(name="Ristorante Miron") ) self.assertEqual( Restaurant.objects.get(name="Ristorante Miron").italianrestaurant, ItalianRestaurant.objects.get(name="Ristorante Miron") ) # This won't work because the Demon Dogs restaurant is not an Italian # restaurant. self.assertRaises(ItalianRestaurant.DoesNotExist, lambda: p.restaurant.italianrestaurant ) # An ItalianRestaurant which does not exist is also a Place which does # not exist. self.assertRaises(Place.DoesNotExist, ItalianRestaurant.objects.get, name="The Noodle Void" ) # MultipleObjectsReturned is also inherited. self.assertRaises(Place.MultipleObjectsReturned, Restaurant.objects.get, id__lt=12321 ) # Related objects work just as they normally do. s1 = Supplier.objects.create(name="Joe's Chickens", address="123 Sesame St") s1.customers = [r, ir] s2 = Supplier.objects.create(name="Luigi's Pasta", address="456 Sesame St") s2.customers = [ir] # This won't work because the Place we select is not a Restaurant (it's # a Supplier). p = Place.objects.get(name="Joe's Chickens") self.assertRaises(Restaurant.DoesNotExist, lambda: p.restaurant ) self.assertEqual(p.supplier, s1) self.assertQuerysetEqual( ir.provider.order_by("-name"), [ "Luigi's Pasta", "Joe's Chickens" ], attrgetter("name") ) self.assertQuerysetEqual( Restaurant.objects.filter(provider__name__contains="Chickens"), [ "Ristorante Miron", "Demon Dogs", ], attrgetter("name") ) self.assertQuerysetEqual( ItalianRestaurant.objects.filter(provider__name__contains="Chickens"), [ "Ristorante Miron", ], attrgetter("name"), ) park1 = ParkingLot.objects.create( name="Main St", address="111 Main St", main_site=s1 ) park2 = ParkingLot.objects.create( name="Well Lit", address="124 Sesame St", main_site=ir ) self.assertEqual( Restaurant.objects.get(lot__name="Well Lit").name, "Ristorante Miron" ) # The update() command can update fields in parent and child classes at # once (although it executed multiple SQL queries to do so). rows = Restaurant.objects.filter( serves_hot_dogs=True, name__contains="D" ).update( name="Demon Puppies", serves_hot_dogs=False ) self.assertEqual(rows, 1) r1 = Restaurant.objects.get(pk=r.pk) self.assertFalse(r1.serves_hot_dogs) self.assertEqual(r1.name, "Demon Puppies") # The values() command also works on fields from parent models. self.assertQuerysetEqual( ItalianRestaurant.objects.values("name", "rating"), [ {"rating": 4, "name": "Ristorante Miron"} ], lambda o: o ) # select_related works with fields from the parent object as if they # were a normal part of the model. self.assertNumQueries(2, lambda: ItalianRestaurant.objects.all()[0].chef ) self.assertNumQueries(1, lambda: ItalianRestaurant.objects.select_related("chef")[0].chef ) def test_mixin_init(self): m = MixinModel() self.assertEqual(m.other_attr, 1)
10,540
Python
.py
243
32.958848
140
0.611106
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,086
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/modeltests/user_commands/models.py
""" 38. User-registered management commands The ``manage.py`` utility provides a number of useful commands for managing a Django project. If you want to add a utility command of your own, you can. The user-defined command ``dance`` is defined in the management/commands subdirectory of this test application. It is a simple command that responds with a printed message when invoked. For more details on how to define your own ``manage.py`` commands, look at the ``django.core.management.commands`` directory. This directory contains the definitions for the base Django ``manage.py`` commands. """
600
Python
.py
11
53.272727
78
0.795222
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,087
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/modeltests/user_commands/tests.py
from StringIO import StringIO from django.test import TestCase from django.core import management from django.core.management.base import CommandError class CommandTests(TestCase): def test_command(self): out = StringIO() management.call_command('dance', stdout=out) self.assertEqual(out.getvalue(), "I don't feel like dancing Rock'n'Roll.") def test_command_style(self): out = StringIO() management.call_command('dance', style='Jive', stdout=out) self.assertEqual(out.getvalue(), "I don't feel like dancing Jive.") def test_explode(self): self.assertRaises(CommandError, management.call_command, ('explode',))
706
Python
.py
17
34.941176
78
0.693878
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,088
dance.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/modeltests/user_commands/management/commands/dance.py
from optparse import make_option from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Dance around like a madman." args = '' requires_model_validation = True option_list =[ make_option("-s", "--style", default="Rock'n'Roll") ] def handle(self, *args, **options): self.stdout.write("I don't feel like dancing %s." % options["style"])
411
Python
.py
11
32.454545
77
0.672544
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,089
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/modeltests/files/models.py
""" 42. Storing files according to a custom storage system ``FileField`` and its variations can take a ``storage`` argument to specify how and where files should be stored. """ import random import tempfile from django.db import models from django.core.files.base import ContentFile from django.core.files.storage import FileSystemStorage temp_storage_location = tempfile.mkdtemp() temp_storage = FileSystemStorage(location=temp_storage_location) # Write out a file to be used as default content temp_storage.save('tests/default.txt', ContentFile('default content')) class Storage(models.Model): def custom_upload_to(self, filename): return 'foo' def random_upload_to(self, filename): # This returns a different result each time, # to make sure it only gets called once. return '%s/%s' % (random.randint(100, 999), filename) normal = models.FileField(storage=temp_storage, upload_to='tests') custom = models.FileField(storage=temp_storage, upload_to=custom_upload_to) random = models.FileField(storage=temp_storage, upload_to=random_upload_to) default = models.FileField(storage=temp_storage, upload_to='tests', default='tests/default.txt')
1,206
Python
.py
25
44.64
100
0.760239
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,090
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/modeltests/files/tests.py
import shutil import sys from django.core.cache import cache from django.core.files.base import ContentFile from django.core.files.uploadedfile import SimpleUploadedFile from django.test import TestCase from models import Storage, temp_storage, temp_storage_location if sys.version_info >= (2, 5): from tests_25 import FileObjTests class FileTests(TestCase): def tearDown(self): shutil.rmtree(temp_storage_location) def test_files(self): # Attempting to access a FileField from the class raises a descriptive # error self.assertRaises(AttributeError, lambda: Storage.normal) # An object without a file has limited functionality. obj1 = Storage() self.assertEqual(obj1.normal.name, "") self.assertRaises(ValueError, lambda: obj1.normal.size) # Saving a file enables full functionality. obj1.normal.save("django_test.txt", ContentFile("content")) self.assertEqual(obj1.normal.name, "tests/django_test.txt") self.assertEqual(obj1.normal.size, 7) self.assertEqual(obj1.normal.read(), "content") obj1.normal.close() # File objects can be assigned to FileField attributes, but shouldn't # get committed until the model it's attached to is saved. obj1.normal = SimpleUploadedFile("assignment.txt", "content") dirs, files = temp_storage.listdir("tests") self.assertEqual(dirs, []) self.assertEqual(sorted(files), ["default.txt", "django_test.txt"]) obj1.save() dirs, files = temp_storage.listdir("tests") self.assertEqual( sorted(files), ["assignment.txt", "default.txt", "django_test.txt"] ) # Files can be read in a little at a time, if necessary. obj1.normal.open() self.assertEqual(obj1.normal.read(3), "con") self.assertEqual(obj1.normal.read(), "tent") self.assertEqual(list(obj1.normal.chunks(chunk_size=2)), ["co", "nt", "en", "t"]) obj1.normal.close() # Save another file with the same name. obj2 = Storage() obj2.normal.save("django_test.txt", ContentFile("more content")) self.assertEqual(obj2.normal.name, "tests/django_test_1.txt") self.assertEqual(obj2.normal.size, 12) # Push the objects into the cache to make sure they pickle properly cache.set("obj1", obj1) cache.set("obj2", obj2) self.assertEqual(cache.get("obj2").normal.name, "tests/django_test_1.txt") # Deleting an object does not delete the file it uses. obj2.delete() obj2.normal.save("django_test.txt", ContentFile("more content")) self.assertEqual(obj2.normal.name, "tests/django_test_2.txt") # Multiple files with the same name get _N appended to them. objs = [Storage() for i in range(3)] for o in objs: o.normal.save("multiple_files.txt", ContentFile("Same Content")) self.assertEqual( [o.normal.name for o in objs], ["tests/multiple_files.txt", "tests/multiple_files_1.txt", "tests/multiple_files_2.txt"] ) for o in objs: o.delete() # Default values allow an object to access a single file. obj3 = Storage.objects.create() self.assertEqual(obj3.default.name, "tests/default.txt") self.assertEqual(obj3.default.read(), "default content") obj3.default.close() # But it shouldn't be deleted, even if there are no more objects using # it. obj3.delete() obj3 = Storage() self.assertEqual(obj3.default.read(), "default content") obj3.default.close() # Verify the fix for #5655, making sure the directory is only # determined once. obj4 = Storage() obj4.random.save("random_file", ContentFile("random content")) self.assertTrue(obj4.random.name.endswith("/random_file")) # Clean up the temporary files and dir. obj1.normal.delete() obj2.normal.delete() obj3.default.delete() obj4.random.delete()
4,113
Python
.py
87
38.804598
100
0.654691
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,091
tests_25.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/modeltests/files/tests_25.py
from __future__ import with_statement import tempfile from django.core.files import File from django.utils.unittest import TestCase class FileObjTests(TestCase): def test_context_manager(self): orig_file = tempfile.TemporaryFile() base_file = File(orig_file) with base_file as f: self.assertIs(base_file, f) self.assertFalse(f.closed) self.assertTrue(f.closed) self.assertTrue(orig_file.closed)
467
Python
.py
13
29.384615
44
0.7
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,092
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/modeltests/one_to_one/models.py
""" 10. One-to-one relationships To define a one-to-one relationship, use ``OneToOneField()``. In this example, a ``Place`` optionally can be a ``Restaurant``. """ from django.db import models, transaction, IntegrityError class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __unicode__(self): return u"%s the place" % self.name class Restaurant(models.Model): place = models.OneToOneField(Place, primary_key=True) serves_hot_dogs = models.BooleanField() serves_pizza = models.BooleanField() def __unicode__(self): return u"%s the restaurant" % self.place.name class Waiter(models.Model): restaurant = models.ForeignKey(Restaurant) name = models.CharField(max_length=50) def __unicode__(self): return u"%s the waiter at %s" % (self.name, self.restaurant) class ManualPrimaryKey(models.Model): primary_key = models.CharField(max_length=10, primary_key=True) name = models.CharField(max_length = 50) class RelatedModel(models.Model): link = models.OneToOneField(ManualPrimaryKey) name = models.CharField(max_length = 50) class MultiModel(models.Model): link1 = models.OneToOneField(Place) link2 = models.OneToOneField(ManualPrimaryKey) name = models.CharField(max_length=50) def __unicode__(self): return u"Multimodel %s" % self.name
1,408
Python
.py
34
36.970588
68
0.719324
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,093
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/modeltests/one_to_one/tests.py
from django.test import TestCase from django.db import transaction, IntegrityError from models import Place, Restaurant, Waiter, ManualPrimaryKey, RelatedModel, MultiModel class OneToOneTests(TestCase): def setUp(self): self.p1 = Place(name='Demon Dogs', address='944 W. Fullerton') self.p1.save() self.p2 = Place(name='Ace Hardware', address='1013 N. Ashland') self.p2.save() self.r = Restaurant(place=self.p1, serves_hot_dogs=True, serves_pizza=False) self.r.save() def test_getter(self): # A Restaurant can access its place. self.assertEqual(repr(self.r.place), '<Place: Demon Dogs the place>') # A Place can access its restaurant, if available. self.assertEqual(repr(self.p1.restaurant), '<Restaurant: Demon Dogs the restaurant>') # p2 doesn't have an associated restaurant. self.assertRaises(Restaurant.DoesNotExist, getattr, self.p2, 'restaurant') def test_setter(self): # Set the place using assignment notation. Because place is the primary # key on Restaurant, the save will create a new restaurant self.r.place = self.p2 self.r.save() self.assertEqual(repr(self.p2.restaurant), '<Restaurant: Ace Hardware the restaurant>') self.assertEqual(repr(self.r.place), '<Place: Ace Hardware the place>') self.assertEqual(self.p2.pk, self.r.pk) # Set the place back again, using assignment in the reverse direction. self.p1.restaurant = self.r self.assertEqual(repr(self.p1.restaurant), '<Restaurant: Demon Dogs the restaurant>') r = Restaurant.objects.get(pk=self.p1.id) self.assertEqual(repr(r.place), '<Place: Demon Dogs the place>') def test_manager_all(self): # Restaurant.objects.all() just returns the Restaurants, not the Places. self.assertQuerysetEqual(Restaurant.objects.all(), [ '<Restaurant: Demon Dogs the restaurant>', ]) # Place.objects.all() returns all Places, regardless of whether they # have Restaurants. self.assertQuerysetEqual(Place.objects.order_by('name'), [ '<Place: Ace Hardware the place>', '<Place: Demon Dogs the place>', ]) def test_manager_get(self): def assert_get_restaurant(**params): self.assertEqual(repr(Restaurant.objects.get(**params)), '<Restaurant: Demon Dogs the restaurant>') assert_get_restaurant(place__id__exact=self.p1.pk) assert_get_restaurant(place__id=self.p1.pk) assert_get_restaurant(place__exact=self.p1.pk) assert_get_restaurant(place__exact=self.p1) assert_get_restaurant(place=self.p1.pk) assert_get_restaurant(place=self.p1) assert_get_restaurant(pk=self.p1.pk) assert_get_restaurant(place__pk__exact=self.p1.pk) assert_get_restaurant(place__pk=self.p1.pk) assert_get_restaurant(place__name__startswith="Demon") def assert_get_place(**params): self.assertEqual(repr(Place.objects.get(**params)), '<Place: Demon Dogs the place>') assert_get_place(restaurant__place__exact=self.p1.pk) assert_get_place(restaurant__place__exact=self.p1) assert_get_place(restaurant__place__pk=self.p1.pk) assert_get_place(restaurant__exact=self.p1.pk) assert_get_place(restaurant__exact=self.r) assert_get_place(restaurant__pk=self.p1.pk) assert_get_place(restaurant=self.p1.pk) assert_get_place(restaurant=self.r) assert_get_place(id__exact=self.p1.pk) assert_get_place(pk=self.p1.pk) def test_foreign_key(self): # Add a Waiter to the Restaurant. w = self.r.waiter_set.create(name='Joe') w.save() self.assertEqual(repr(w), '<Waiter: Joe the waiter at Demon Dogs the restaurant>') # Query the waiters def assert_filter_waiters(**params): self.assertQuerysetEqual(Waiter.objects.filter(**params), [ '<Waiter: Joe the waiter at Demon Dogs the restaurant>' ]) assert_filter_waiters(restaurant__place__exact=self.p1.pk) assert_filter_waiters(restaurant__place__exact=self.p1) assert_filter_waiters(restaurant__place__pk=self.p1.pk) assert_filter_waiters(restaurant__exact=self.p1.pk) assert_filter_waiters(restaurant__exact=self.p1) assert_filter_waiters(restaurant__pk=self.p1.pk) assert_filter_waiters(restaurant=self.p1.pk) assert_filter_waiters(restaurant=self.r) assert_filter_waiters(id__exact=self.p1.pk) assert_filter_waiters(pk=self.p1.pk) # Delete the restaurant; the waiter should also be removed r = Restaurant.objects.get(pk=self.p1.pk) r.delete() self.assertEqual(Waiter.objects.count(), 0) def test_multiple_o2o(self): # One-to-one fields still work if you create your own primary key o1 = ManualPrimaryKey(primary_key="abc123", name="primary") o1.save() o2 = RelatedModel(link=o1, name="secondary") o2.save() # You can have multiple one-to-one fields on a model, too. x1 = MultiModel(link1=self.p1, link2=o1, name="x1") x1.save() self.assertEqual(repr(o1.multimodel), '<MultiModel: Multimodel x1>') # This will fail because each one-to-one field must be unique (and # link2=o1 was used for x1, above). sid = transaction.savepoint() mm = MultiModel(link1=self.p2, link2=o1, name="x1") self.assertRaises(IntegrityError, mm.save) transaction.savepoint_rollback(sid)
5,714
Python
.py
109
43.165138
95
0.657909
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,094
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/modeltests/test_client/models.py
# coding: utf-8 """ 39. Testing using the Test Client The test client is a class that can act like a simple browser 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 other browser automation frameworks - it is here to allow testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """ from django.conf import settings from django.core import mail from django.test import Client, TestCase, RequestFactory from views import get_view class ClientTest(TestCase): fixtures = ['testdata.json'] def test_get_view(self): "GET a view" # The data is ignored, but let's check it doesn't crash the system # anyway. data = {'var': u'\xf2'} response = self.client.get('/test_client/get_view/', data) # Check some response details self.assertContains(response, 'This is a test') self.assertEqual(response.context['var'], u'\xf2') self.assertEqual(response.templates[0].name, 'GET Template') def test_get_post_view(self): "GET a view that normally expects POSTs" response = self.client.get('/test_client/post_view/', {}) # Check some response details self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, 'Empty GET Template') self.assertTemplateUsed(response, 'Empty GET Template') self.assertTemplateNotUsed(response, 'Empty POST Template') def test_empty_post(self): "POST an empty dictionary to a view" response = self.client.post('/test_client/post_view/', {}) # Check some response details self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, 'Empty POST Template') self.assertTemplateNotUsed(response, 'Empty GET Template') self.assertTemplateUsed(response, 'Empty POST Template') def test_post(self): "POST some data to a view" post_data = { 'value': 37 } response = self.client.post('/test_client/post_view/', post_data) # Check some response details self.assertEqual(response.status_code, 200) self.assertEqual(response.context['data'], '37') self.assertEqual(response.templates[0].name, 'POST Template') self.assertTrue('Data received' in response.content) def test_response_headers(self): "Check the value of HTTP headers returned in a response" response = self.client.get("/test_client/header_view/") self.assertEqual(response['X-DJANGO-TEST'], 'Slartibartfast') def test_raw_post(self): "POST raw data (with a content type) to a view" test_doc = """<?xml version="1.0" encoding="utf-8"?><library><book><title>Blink</title><author>Malcolm Gladwell</author></book></library>""" response = self.client.post("/test_client/raw_post_view/", test_doc, content_type="text/xml") self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, "Book template") self.assertEqual(response.content, "Blink - Malcolm Gladwell") def test_redirect(self): "GET a URL that redirects elsewhere" response = self.client.get('/test_client/redirect_view/') # Check that the response was a 302 (redirect) and that # assertRedirect() understands to put an implicit http://testserver/ in # front of non-absolute URLs. self.assertRedirects(response, '/test_client/get_view/') host = 'django.testserver' client_providing_host = Client(HTTP_HOST=host) response = client_providing_host.get('/test_client/redirect_view/') # Check that the response was a 302 (redirect) with absolute URI self.assertRedirects(response, '/test_client/get_view/', host=host) def test_redirect_with_query(self): "GET a URL that redirects with given GET parameters" response = self.client.get('/test_client/redirect_view/', {'var': 'value'}) # Check if parameters are intact self.assertRedirects(response, 'http://testserver/test_client/get_view/?var=value') def test_permanent_redirect(self): "GET a URL that redirects permanently elsewhere" response = self.client.get('/test_client/permanent_redirect_view/') # Check that the response was a 301 (permanent redirect) self.assertRedirects(response, 'http://testserver/test_client/get_view/', status_code=301) client_providing_host = Client(HTTP_HOST='django.testserver') response = client_providing_host.get('/test_client/permanent_redirect_view/') # Check that the response was a 301 (permanent redirect) with absolute URI self.assertRedirects(response, 'http://django.testserver/test_client/get_view/', status_code=301) def test_temporary_redirect(self): "GET a URL that does a non-permanent redirect" response = self.client.get('/test_client/temporary_redirect_view/') # Check that the response was a 302 (non-permanent redirect) self.assertRedirects(response, 'http://testserver/test_client/get_view/', status_code=302) def test_redirect_to_strange_location(self): "GET a URL that redirects to a non-200 page" response = self.client.get('/test_client/double_redirect_view/') # Check that the response was a 302, and that # the attempt to get the redirection location returned 301 when retrieved self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/', target_status_code=301) def test_follow_redirect(self): "A URL that redirects can be followed to termination." response = self.client.get('/test_client/double_redirect_view/', follow=True) self.assertRedirects(response, 'http://testserver/test_client/get_view/', status_code=302, target_status_code=200) self.assertEqual(len(response.redirect_chain), 2) def test_redirect_http(self): "GET a URL that redirects to an http URI" response = self.client.get('/test_client/http_redirect_view/',follow=True) self.assertFalse(response.test_was_secure_request) def test_redirect_https(self): "GET a URL that redirects to an https URI" response = self.client.get('/test_client/https_redirect_view/',follow=True) self.assertTrue(response.test_was_secure_request) def test_notfound_response(self): "GET a URL that responds as '404:Not Found'" response = self.client.get('/test_client/bad_view/') # Check that the response was a 404, and that the content contains MAGIC self.assertContains(response, 'MAGIC', status_code=404) def test_valid_form(self): "POST valid data to a form" post_data = { 'text': 'Hello World', 'email': '[email protected]', 'value': 37, 'single': 'b', 'multi': ('b','c','e') } response = self.client.post('/test_client/form_view/', post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Valid POST Template") def test_valid_form_with_hints(self): "GET a form, providing hints in the GET data" hints = { 'text': 'Hello World', 'multi': ('b','c','e') } response = self.client.get('/test_client/form_view/', data=hints) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Form GET Template") # Check that the multi-value data has been rolled out ok self.assertContains(response, 'Select a valid choice.', 0) def test_incomplete_data_form(self): "POST incomplete data to a form" post_data = { 'text': 'Hello World', 'value': 37 } response = self.client.post('/test_client/form_view/', post_data) self.assertContains(response, 'This field is required.', 3) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") self.assertFormError(response, 'form', 'email', 'This field is required.') self.assertFormError(response, 'form', 'single', 'This field is required.') self.assertFormError(response, 'form', 'multi', 'This field is required.') def test_form_error(self): "POST erroneous data to a form" post_data = { 'text': 'Hello World', 'email': 'not an email address', 'value': 37, 'single': 'b', 'multi': ('b','c','e') } response = self.client.post('/test_client/form_view/', post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") self.assertFormError(response, 'form', 'email', 'Enter a valid e-mail address.') def test_valid_form_with_template(self): "POST valid data to a form using multiple templates" post_data = { 'text': 'Hello World', 'email': '[email protected]', 'value': 37, 'single': 'b', 'multi': ('b','c','e') } response = self.client.post('/test_client/form_view_with_template/', post_data) self.assertContains(response, 'POST data OK') self.assertTemplateUsed(response, "form_view.html") self.assertTemplateUsed(response, 'base.html') self.assertTemplateNotUsed(response, "Valid POST Template") def test_incomplete_data_form_with_template(self): "POST incomplete data to a form using multiple templates" post_data = { 'text': 'Hello World', 'value': 37 } response = self.client.post('/test_client/form_view_with_template/', post_data) self.assertContains(response, 'POST data has errors') self.assertTemplateUsed(response, 'form_view.html') self.assertTemplateUsed(response, 'base.html') self.assertTemplateNotUsed(response, "Invalid POST Template") self.assertFormError(response, 'form', 'email', 'This field is required.') self.assertFormError(response, 'form', 'single', 'This field is required.') self.assertFormError(response, 'form', 'multi', 'This field is required.') def test_form_error_with_template(self): "POST erroneous data to a form using multiple templates" post_data = { 'text': 'Hello World', 'email': 'not an email address', 'value': 37, 'single': 'b', 'multi': ('b','c','e') } response = self.client.post('/test_client/form_view_with_template/', post_data) self.assertContains(response, 'POST data has errors') self.assertTemplateUsed(response, "form_view.html") self.assertTemplateUsed(response, 'base.html') self.assertTemplateNotUsed(response, "Invalid POST Template") self.assertFormError(response, 'form', 'email', 'Enter a valid e-mail address.') def test_unknown_page(self): "GET an invalid URL" response = self.client.get('/test_client/unknown_view/') # Check that the response was a 404 self.assertEqual(response.status_code, 404) def test_url_parameters(self): "Make sure that URL ;-parameters are not stripped." response = self.client.get('/test_client/unknown_view/;some-parameter') # Check that the path in the response includes it (ignore that it's a 404) self.assertEqual(response.request['PATH_INFO'], '/test_client/unknown_view/;some-parameter') def test_view_with_login(self): "Request a page that is protected with @login_required" # Get the page without logging in. Should result in 302. response = self.client.get('/test_client/login_protected_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/login_protected_view/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Request a page that requires a login response = self.client.get('/test_client/login_protected_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') def test_view_with_method_login(self): "Request a page that is protected with a @login_required method" # Get the page without logging in. Should result in 302. response = self.client.get('/test_client/login_protected_method_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/login_protected_method_view/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Request a page that requires a login response = self.client.get('/test_client/login_protected_method_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') def test_view_with_login_and_custom_redirect(self): "Request a page that is protected with @login_required(redirect_field_name='redirect_to')" # Get the page without logging in. Should result in 302. response = self.client.get('/test_client/login_protected_view_custom_redirect/') self.assertRedirects(response, 'http://testserver/accounts/login/?redirect_to=/test_client/login_protected_view_custom_redirect/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Request a page that requires a login response = self.client.get('/test_client/login_protected_view_custom_redirect/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') def test_view_with_bad_login(self): "Request a page that is protected with @login, but use bad credentials" login = self.client.login(username='otheruser', password='nopassword') self.assertFalse(login) def test_view_with_inactive_login(self): "Request a page that is protected with @login, but use an inactive login" login = self.client.login(username='inactive', password='password') self.assertFalse(login) def test_logout(self): "Request a logout after logging in" # Log in self.client.login(username='testclient', password='password') # Request a page that requires a login response = self.client.get('/test_client/login_protected_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') # Log out self.client.logout() # Request a page that requires a login response = self.client.get('/test_client/login_protected_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/login_protected_view/') def test_view_with_permissions(self): "Request a page that is protected with @permission_required" # Get the page without logging in. Should result in 302. response = self.client.get('/test_client/permission_protected_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_view/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Log in with wrong permissions. Should result in 302. response = self.client.get('/test_client/permission_protected_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_view/') # TODO: Log in with right permissions and request the page again def test_view_with_method_permissions(self): "Request a page that is protected with a @permission_required method" # Get the page without logging in. Should result in 302. response = self.client.get('/test_client/permission_protected_method_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_method_view/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Log in with wrong permissions. Should result in 302. response = self.client.get('/test_client/permission_protected_method_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_method_view/') # TODO: Log in with right permissions and request the page again def test_session_modifying_view(self): "Request a page that modifies the session" # Session value isn't set initially try: self.client.session['tobacconist'] self.fail("Shouldn't have a session value") except KeyError: pass from django.contrib.sessions.models import Session response = self.client.post('/test_client/session_view/') # Check that the session was modified self.assertEqual(self.client.session['tobacconist'], 'hovercraft') def test_view_with_exception(self): "Request a page that is known to throw an error" self.assertRaises(KeyError, self.client.get, "/test_client/broken_view/") #Try the same assertion, a different way try: self.client.get('/test_client/broken_view/') self.fail('Should raise an error') except KeyError: pass def test_mail_sending(self): "Test that mail is redirected to a dummy outbox during test setup" response = self.client.get('/test_client/mail_sending_view/') self.assertEqual(response.status_code, 200) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Test message') self.assertEqual(mail.outbox[0].body, 'This is a test email') self.assertEqual(mail.outbox[0].from_email, '[email protected]') self.assertEqual(mail.outbox[0].to[0], '[email protected]') self.assertEqual(mail.outbox[0].to[1], '[email protected]') def test_mass_mail_sending(self): "Test that mass mail is redirected to a dummy outbox during test setup" response = self.client.get('/test_client/mass_mail_sending_view/') self.assertEqual(response.status_code, 200) self.assertEqual(len(mail.outbox), 2) self.assertEqual(mail.outbox[0].subject, 'First Test message') self.assertEqual(mail.outbox[0].body, 'This is the first test email') self.assertEqual(mail.outbox[0].from_email, '[email protected]') self.assertEqual(mail.outbox[0].to[0], '[email protected]') self.assertEqual(mail.outbox[0].to[1], '[email protected]') self.assertEqual(mail.outbox[1].subject, 'Second Test message') self.assertEqual(mail.outbox[1].body, 'This is the second test email') self.assertEqual(mail.outbox[1].from_email, '[email protected]') self.assertEqual(mail.outbox[1].to[0], '[email protected]') self.assertEqual(mail.outbox[1].to[1], '[email protected]') class CSRFEnabledClientTests(TestCase): def setUp(self): # Enable the CSRF middleware for this test self.old_MIDDLEWARE_CLASSES = settings.MIDDLEWARE_CLASSES csrf_middleware_class = 'django.middleware.csrf.CsrfViewMiddleware' if csrf_middleware_class not in settings.MIDDLEWARE_CLASSES: settings.MIDDLEWARE_CLASSES += (csrf_middleware_class,) def tearDown(self): settings.MIDDLEWARE_CLASSES = self.old_MIDDLEWARE_CLASSES def test_csrf_enabled_client(self): "A client can be instantiated with CSRF checks enabled" csrf_client = Client(enforce_csrf_checks=True) # The normal client allows the post response = self.client.post('/test_client/post_view/', {}) self.assertEqual(response.status_code, 200) # The CSRF-enabled client rejects it response = csrf_client.post('/test_client/post_view/', {}) self.assertEqual(response.status_code, 403) class CustomTestClient(Client): i_am_customized = "Yes" class CustomTestClientTest(TestCase): client_class = CustomTestClient def test_custom_test_client(self): """A test case can specify a custom class for self.client.""" self.assertEqual(hasattr(self.client, "i_am_customized"), True) class RequestFactoryTest(TestCase): def test_request_factory(self): factory = RequestFactory() request = factory.get('/somewhere/') response = get_view(request) self.assertEqual(response.status_code, 200) self.assertContains(response, 'This is a test')
21,658
Python
.py
388
47.123711
148
0.674745
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,095
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/modeltests/test_client/urls.py
from django.conf.urls.defaults import * from django.views.generic.simple import redirect_to import views urlpatterns = patterns('', (r'^get_view/$', views.get_view), (r'^post_view/$', views.post_view), (r'^header_view/$', views.view_with_header), (r'^raw_post_view/$', views.raw_post_view), (r'^redirect_view/$', views.redirect_view), (r'^secure_view/$', views.view_with_secure), (r'^permanent_redirect_view/$', redirect_to, {'url': '/test_client/get_view/'}), (r'^temporary_redirect_view/$', redirect_to, {'url': '/test_client/get_view/', 'permanent': False}), (r'^http_redirect_view/$', redirect_to, {'url': '/test_client/secure_view/'}), (r'^https_redirect_view/$', redirect_to, {'url': 'https://testserver/test_client/secure_view/'}), (r'^double_redirect_view/$', views.double_redirect_view), (r'^bad_view/$', views.bad_view), (r'^form_view/$', views.form_view), (r'^form_view_with_template/$', views.form_view_with_template), (r'^login_protected_view/$', views.login_protected_view), (r'^login_protected_method_view/$', views.login_protected_method_view), (r'^login_protected_view_custom_redirect/$', views.login_protected_view_changed_redirect), (r'^permission_protected_view/$', views.permission_protected_view), (r'^permission_protected_method_view/$', views.permission_protected_method_view), (r'^session_view/$', views.session_view), (r'^broken_view/$', views.broken_view), (r'^mail_sending_view/$', views.mail_sending_view), (r'^mass_mail_sending_view/$', views.mass_mail_sending_view) )
1,592
Python
.py
28
52.535714
104
0.669866
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,096
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/modeltests/test_client/tests.py
# Validate that you can override the default test suite from django.utils import unittest def suite(): """ Define a suite that deliberately ignores a test defined in this module. """ testSuite = unittest.TestSuite() testSuite.addTest(SampleTests('testGoodStuff')) return testSuite class SampleTests(unittest.TestCase): def testGoodStuff(self): pass def testBadStuff(self): self.fail("This test shouldn't run")
483
Python
.py
15
26.333333
62
0.724832
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,097
views.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/modeltests/test_client/views.py
from xml.dom.minidom import parseString from django.core import mail from django.template import Context, Template from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound from django.contrib.auth.decorators import login_required, permission_required from django.forms.forms import Form from django.forms import fields from django.shortcuts import render_to_response from django.utils.decorators import method_decorator def get_view(request): "A simple view that expects a GET request, and returns a rendered template" t = Template('This is a test. {{ var }} is the value.', name='GET Template') c = Context({'var': request.GET.get('var', 42)}) return HttpResponse(t.render(c)) def post_view(request): """A view that expects a POST, and returns a different template depending on whether any POST data is available """ if request.method == 'POST': if request.POST: t = Template('Data received: {{ data }} is the value.', name='POST Template') c = Context({'data': request.POST['value']}) else: t = Template('Viewing POST page.', name='Empty POST Template') c = Context() else: t = Template('Viewing GET page.', name='Empty GET Template') c = Context() return HttpResponse(t.render(c)) def view_with_header(request): "A view that has a custom header" response = HttpResponse() response['X-DJANGO-TEST'] = 'Slartibartfast' return response def raw_post_view(request): """A view which expects raw XML to be posted and returns content extracted from the XML""" if request.method == 'POST': root = parseString(request.raw_post_data) first_book = root.firstChild.firstChild title, author = [n.firstChild.nodeValue for n in first_book.childNodes] t = Template("{{ title }} - {{ author }}", name="Book template") c = Context({"title": title, "author": author}) else: t = Template("GET request.", name="Book GET template") c = Context() return HttpResponse(t.render(c)) def redirect_view(request): "A view that redirects all requests to the GET view" if request.GET: from urllib import urlencode query = '?' + urlencode(request.GET, True) else: query = '' return HttpResponseRedirect('/test_client/get_view/' + query) def view_with_secure(request): "A view that indicates if the request was secure" response = HttpResponse() response.test_was_secure_request = request.is_secure() return response def double_redirect_view(request): "A view that redirects all requests to a redirection view" return HttpResponseRedirect('/test_client/permanent_redirect_view/') def bad_view(request): "A view that returns a 404 with some error content" return HttpResponseNotFound('Not found!. This page contains some MAGIC content') TestChoices = ( ('a', 'First Choice'), ('b', 'Second Choice'), ('c', 'Third Choice'), ('d', 'Fourth Choice'), ('e', 'Fifth Choice') ) class TestForm(Form): text = fields.CharField() email = fields.EmailField() value = fields.IntegerField() single = fields.ChoiceField(choices=TestChoices) multi = fields.MultipleChoiceField(choices=TestChoices) def form_view(request): "A view that tests a simple form" if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): t = Template('Valid POST data.', name='Valid POST Template') c = Context() else: t = Template('Invalid POST data. {{ form.errors }}', name='Invalid POST Template') c = Context({'form': form}) else: form = TestForm(request.GET) t = Template('Viewing base form. {{ form }}.', name='Form GET Template') c = Context({'form': form}) return HttpResponse(t.render(c)) def form_view_with_template(request): "A view that tests a simple form" if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): message = 'POST data OK' else: message = 'POST data has errors' else: form = TestForm() message = 'GET form page' return render_to_response('form_view.html', { 'form': form, 'message': message } ) def login_protected_view(request): "A simple view that is login protected." t = Template('This is a login protected test. Username is {{ user.username }}.', name='Login Template') c = Context({'user': request.user}) return HttpResponse(t.render(c)) login_protected_view = login_required(login_protected_view) def login_protected_view_changed_redirect(request): "A simple view that is login protected with a custom redirect field set" t = Template('This is a login protected test. Username is {{ user.username }}.', name='Login Template') c = Context({'user': request.user}) return HttpResponse(t.render(c)) login_protected_view_changed_redirect = login_required(redirect_field_name="redirect_to")(login_protected_view_changed_redirect) def permission_protected_view(request): "A simple view that is permission protected." t = Template('This is a permission protected test. ' 'Username is {{ user.username }}. ' 'Permissions are {{ user.get_all_permissions }}.' , name='Permissions Template') c = Context({'user': request.user}) return HttpResponse(t.render(c)) permission_protected_view = permission_required('modeltests.test_perm')(permission_protected_view) class _ViewManager(object): @method_decorator(login_required) def login_protected_view(self, request): t = Template('This is a login protected test using a method. ' 'Username is {{ user.username }}.', name='Login Method Template') c = Context({'user': request.user}) return HttpResponse(t.render(c)) @method_decorator(permission_required('modeltests.test_perm')) def permission_protected_view(self, request): t = Template('This is a permission protected test using a method. ' 'Username is {{ user.username }}. ' 'Permissions are {{ user.get_all_permissions }}.' , name='Permissions Template') c = Context({'user': request.user}) return HttpResponse(t.render(c)) _view_manager = _ViewManager() login_protected_method_view = _view_manager.login_protected_view permission_protected_method_view = _view_manager.permission_protected_view def session_view(request): "A view that modifies the session" request.session['tobacconist'] = 'hovercraft' t = Template('This is a view that modifies the session.', name='Session Modifying View Template') c = Context() return HttpResponse(t.render(c)) def broken_view(request): """A view which just raises an exception, simulating a broken view.""" raise KeyError("Oops! Looks like you wrote some bad code.") def mail_sending_view(request): mail.EmailMessage( "Test message", "This is a test email", "[email protected]", ['[email protected]', '[email protected]']).send() return HttpResponse("Mail sent") def mass_mail_sending_view(request): m1 = mail.EmailMessage( 'First Test message', 'This is the first test email', '[email protected]', ['[email protected]', '[email protected]']) m2 = mail.EmailMessage( 'Second Test message', 'This is the second test email', '[email protected]', ['[email protected]', '[email protected]']) c = mail.get_connection() c.send_messages([m1,m2]) return HttpResponse("Mail sent")
7,858
Python
.py
182
36.521978
128
0.662873
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,098
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/modeltests/transactions/models.py
""" 15. Transactions Django handles transactions in three different ways. The default is to commit each transaction upon a write, but you can decorate a function to get commit-on-success behavior. Alternatively, you can manage the transaction manually. """ from django.db import models, DEFAULT_DB_ALIAS class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() class Meta: ordering = ('first_name', 'last_name') def __unicode__(self): return u"%s %s" % (self.first_name, self.last_name)
617
Python
.py
16
35.0625
77
0.735343
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,099
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/modeltests/transactions/tests.py
import sys from django.db import connection, transaction, IntegrityError, DEFAULT_DB_ALIAS from django.conf import settings from django.test import TransactionTestCase, skipUnlessDBFeature from models import Reporter if sys.version_info >= (2, 5): from tests_25 import TransactionContextManagerTests class TransactionTests(TransactionTestCase): def create_a_reporter_then_fail(self, first, last): a = Reporter(first_name=first, last_name=last) a.save() raise Exception("I meant to do that") def remove_a_reporter(self, first_name): r = Reporter.objects.get(first_name="Alice") r.delete() def manually_managed(self): r = Reporter(first_name="Dirk", last_name="Gently") r.save() transaction.commit() def manually_managed_mistake(self): r = Reporter(first_name="Edward", last_name="Woodward") r.save() # Oops, I forgot to commit/rollback! @skipUnlessDBFeature('supports_transactions') def test_autocommit(self): """ The default behavior is to autocommit after each save() action. """ self.assertRaises(Exception, self.create_a_reporter_then_fail, "Alice", "Smith" ) # The object created before the exception still exists self.assertEqual(Reporter.objects.count(), 1) @skipUnlessDBFeature('supports_transactions') def test_autocommit_decorator(self): """ The autocommit decorator works exactly the same as the default behavior. """ autocomitted_create_then_fail = transaction.autocommit( self.create_a_reporter_then_fail ) self.assertRaises(Exception, autocomitted_create_then_fail, "Alice", "Smith" ) # Again, the object created before the exception still exists self.assertEqual(Reporter.objects.count(), 1) @skipUnlessDBFeature('supports_transactions') def test_autocommit_decorator_with_using(self): """ The autocommit decorator also works with a using argument. """ autocomitted_create_then_fail = transaction.autocommit(using='default')( self.create_a_reporter_then_fail ) self.assertRaises(Exception, autocomitted_create_then_fail, "Alice", "Smith" ) # Again, the object created before the exception still exists self.assertEqual(Reporter.objects.count(), 1) @skipUnlessDBFeature('supports_transactions') def test_commit_on_success(self): """ With the commit_on_success decorator, the transaction is only committed if the function doesn't throw an exception. """ committed_on_success = transaction.commit_on_success( self.create_a_reporter_then_fail) self.assertRaises(Exception, committed_on_success, "Dirk", "Gently") # This time the object never got saved self.assertEqual(Reporter.objects.count(), 0) @skipUnlessDBFeature('supports_transactions') def test_commit_on_success_with_using(self): """ The commit_on_success decorator also works with a using argument. """ using_committed_on_success = transaction.commit_on_success(using='default')( self.create_a_reporter_then_fail ) self.assertRaises(Exception, using_committed_on_success, "Dirk", "Gently" ) # This time the object never got saved self.assertEqual(Reporter.objects.count(), 0) @skipUnlessDBFeature('supports_transactions') def test_commit_on_success_succeed(self): """ If there aren't any exceptions, the data will get saved. """ Reporter.objects.create(first_name="Alice", last_name="Smith") remove_comitted_on_success = transaction.commit_on_success( self.remove_a_reporter ) remove_comitted_on_success("Alice") self.assertEqual(list(Reporter.objects.all()), []) @skipUnlessDBFeature('supports_transactions') def test_commit_on_success_exit(self): @transaction.autocommit() def gen_reporter(): @transaction.commit_on_success def create_reporter(): Reporter.objects.create(first_name="Bobby", last_name="Tables") create_reporter() # Much more formal r = Reporter.objects.get() r.first_name = "Robert" r.save() gen_reporter() r = Reporter.objects.get() self.assertEqual(r.first_name, "Robert") @skipUnlessDBFeature('supports_transactions') def test_manually_managed(self): """ You can manually manage transactions if you really want to, but you have to remember to commit/rollback. """ manually_managed = transaction.commit_manually(self.manually_managed) manually_managed() self.assertEqual(Reporter.objects.count(), 1) @skipUnlessDBFeature('supports_transactions') def test_manually_managed_mistake(self): """ If you forget, you'll get bad errors. """ manually_managed_mistake = transaction.commit_manually( self.manually_managed_mistake ) self.assertRaises(transaction.TransactionManagementError, manually_managed_mistake) @skipUnlessDBFeature('supports_transactions') def test_manually_managed_with_using(self): """ The commit_manually function also works with a using argument. """ using_manually_managed_mistake = transaction.commit_manually(using='default')( self.manually_managed_mistake ) self.assertRaises(transaction.TransactionManagementError, using_manually_managed_mistake ) class TransactionRollbackTests(TransactionTestCase): def execute_bad_sql(self): cursor = connection.cursor() cursor.execute("INSERT INTO transactions_reporter (first_name, last_name) VALUES ('Douglas', 'Adams');") transaction.set_dirty() @skipUnlessDBFeature('requires_rollback_on_dirty_transaction') def test_bad_sql(self): """ Regression for #11900: If a function wrapped by commit_on_success writes a transaction that can't be committed, that transaction should be rolled back. The bug is only visible using the psycopg2 backend, though the fix is generally a good idea. """ execute_bad_sql = transaction.commit_on_success(self.execute_bad_sql) self.assertRaises(IntegrityError, execute_bad_sql) transaction.rollback()
6,706
Python
.py
159
33.465409
112
0.659868
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)