id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
3,200
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,201
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/datatypes/tests.py
import datetime from django.db import DEFAULT_DB_ALIAS from django.test import TestCase from django.utils import tzinfo from models import Donut, RumBaba from django.conf import settings 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.assert_(isinstance(newd.review, unicode)) def test_tz_awareness_mysql(self): """Regression test for #8354: the MySQL backend should raise an error if given a timezone-aware datetime object.""" if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.mysql': 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.assert_(isinstance(b.baked_timestamp, datetime.datetime)) # We need to test this this way because datetime.datetime inherits # from datetime.date: self.assert_(isinstance(b.baked_date, datetime.date) and not isinstance(b.baked_date, datetime.datetime))
4,274
Python
.py
75
47.853333
113
0.665869
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,202
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/defaultfilters/tests.py
# -*- coding: utf-8 -*- import datetime 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'') 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') 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(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(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')
23,204
Python
.py
426
43.046948
87
0.576289
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,203
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,204
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/model_regress/tests.py
import datetime from operator import attrgetter from django.conf import settings from django.core.exceptions import ValidationError from django.db import DEFAULT_DB_ALIAS from django.test import TestCase 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.assertEqual(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.assertEqual(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]>") if settings.DATABASES[DEFAULT_DB_ALIAS]["ENGINE"] not in [ "django.db.backends.mysql", "django.db.backends.oracle" ]: 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,781
Python
.py
158
33.025316
88
0.610808
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,205
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,206
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/cache/urls.py
from django.conf.urls.defaults import patterns urlpatterns = patterns('regressiontests.cache.views', (r'^$', 'home'), )
125
Python
.py
4
29
53
0.741667
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,207
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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 unittest import warnings from django.conf import settings from django.core import management from django.core.cache import get_cache from django.core.cache.backends.base import CacheKeyWarning from django.http import HttpResponse, HttpRequest from django.middleware.cache import FetchFromCacheMiddleware, UpdateCacheMiddleware from django.test import TestCase from django.test.utils import get_warnings_state, restore_warnings_state from django.utils import translation from django.utils.cache import patch_vary_headers, get_cache_key, learn_cache_key from django.utils.hashcompat import md5_constructor 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('dummy://') 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() class BaseCacheTests(object): # A common set of tests to apply to all cache backends def tearDown(self): self.cache.clear() 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_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 } } for (key, value) in stuff.items(): self.cache.set(key, value) 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) self.cache.set('binary1', compressed_value) compressed_result = self.cache.get('binary1') 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. """ # 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) 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('db://%s?max_entries=30' % self._table_name) 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) class LocMemCacheTests(unittest.TestCase, BaseCacheTests): def setUp(self): self.cache = get_cache('locmem://?max_entries=30') def test_cull(self): self.perform_cull_test(50, 29) # 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. if settings.CACHE_BACKEND.startswith('memcached://'): class MemcachedCacheTests(unittest.TestCase, BaseCacheTests): def setUp(self): self.cache = get_cache(settings.CACHE_BACKEND) 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') class FileBasedCacheTests(unittest.TestCase, BaseCacheTests): """ Specific test cases for the file-based cache. """ def setUp(self): self.dirname = tempfile.mkdtemp() self.cache = get_cache('file://%s?max_entries=30' % self.dirname) def test_hashing(self): """Test that keys are hashed into subdirectories correctly""" self.cache.set("foo", "bar") keyhash = md5_constructor("foo").hexdigest() keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:]) self.assert_(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") keyhash = md5_constructor("foo").hexdigest() keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:]) self.assert_(os.path.exists(keypath)) self.cache.delete("foo") self.assert_(not os.path.exists(keypath)) self.assert_(not os.path.exists(os.path.dirname(keypath))) self.assert_(not os.path.exists(os.path.dirname(os.path.dirname(keypath)))) def test_cull(self): self.perform_cull_test(50, 28) 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_settings_key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX self.old_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_settings_key_prefix settings.CACHE_MIDDLEWARE_SECONDS = self.old_middleware_seconds settings.USE_I18N = self.orig_use_i18n def _get_request(self, path): request = HttpRequest() request.META = { 'SERVER_NAME': 'testserver', 'SERVER_PORT': 80, } 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.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e') # Verify that a specified key_prefix is taken in to 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.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e') def test_learn_cache_key(self): request = self._get_request(self.path) 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.a8c87a3d8c44853d7f79474f7ffe4ad5.d41d8cd98f00b204e9800998ecf8427e') 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_cache_backend = settings.CACHE_BACKEND 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.CACHE_BACKEND = self.orig_cache_backend 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): request = HttpRequest() request.META = { 'SERVER_NAME': 'testserver', 'SERVER_PORT': 80, } 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.CACHE_BACKEND='locmem:///' settings.USE_I18N = True 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) # 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 CacheMiddlewareAnonymousOnlyTests(TestCase): urls = 'regressiontests.cache.urls' def setUp(self): self._orig_cache_middleware_anonymous_only = \ getattr(settings, 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY', False) self._orig_middleware_classes = settings.MIDDLEWARE_CLASSES settings.MIDDLEWARE_CLASSES = list(settings.MIDDLEWARE_CLASSES) settings.MIDDLEWARE_CLASSES.insert(0, 'django.middleware.cache.UpdateCacheMiddleware') settings.MIDDLEWARE_CLASSES += ['django.middleware.cache.FetchFromCacheMiddleware'] def tearDown(self): settings.CACHE_MIDDLEWARE_ANONYMOUS_ONLY = self._orig_cache_middleware_anonymous_only settings.MIDDLEWARE_CLASSES = self._orig_middleware_classes def test_cache_middleware_anonymous_only_does_not_cause_vary_cookie(self): settings.CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True response = self.client.get('/') self.failIf('Cookie' in response.get('Vary', '')) if __name__ == '__main__': unittest.main()
28,208
Python
.py
579
40.025907
186
0.647339
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,208
liberal_backend.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/cache/liberal_backend.py
from django.core.cache.backends.locmem import CacheClass as LocMemCacheClass class LiberalKeyValidationMixin(object): def validate_key(self, key): pass class CacheClass(LiberalKeyValidationMixin, LocMemCacheClass): pass
239
Python
.py
6
35.666667
76
0.817391
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,209
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/requests/tests.py
from datetime import datetime, timedelta import time import unittest from django.http import HttpRequest, HttpResponse, parse_cookie from django.core.handlers.wsgi import WSGIRequest from django.core.handlers.modpython import ModPythonRequest 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'}) 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'])) 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')
2,389
Python
.py
49
40.510204
103
0.654506
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,210
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,211
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,212
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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 class TextTests(TestCase): """ Tests for stuff in django.utils.text and other text munging util functions. """ def test_smart_split(self): self.assertEquals(list(smart_split(r'''This is "a person" test.''')), [u'This', u'is', u'"a person"', u'test.']) self.assertEquals(list(smart_split(r'''This is "a person's" test.'''))[2], u'"a person\'s"') self.assertEquals(list(smart_split(r'''This is "a person\"s" test.'''))[2], u'"a person\\"s"') self.assertEquals(list(smart_split('''"a 'one''')), [u'"a', u"'one"]) self.assertEquals(list(smart_split(r'''all friends' tests'''))[1], "friends'") self.assertEquals(list(smart_split(u'url search_page words="something else"')), [u'url', u'search_page', u'words="something else"']) self.assertEquals(list(smart_split(u"url search_page words='something else'")), [u'url', u'search_page', u"words='something else'"]) self.assertEquals(list(smart_split(u'url search_page words "something else"')), [u'url', u'search_page', u'words', u'"something else"']) self.assertEquals(list(smart_split(u'url search_page words-"something else"')), [u'url', u'search_page', u'words-"something else"']) self.assertEquals(list(smart_split(u'url search_page words=hello')), [u'url', u'search_page', u'words=hello']) self.assertEquals(list(smart_split(u'url search_page words="something else')), [u'url', u'search_page', u'words="something', u'else']) self.assertEquals(list(smart_split("cut:','|cut:' '")), [u"cut:','|cut:' '"]) def test_urlquote(self): self.assertEquals(urlquote(u'Paris & Orl\xe9ans'), u'Paris%20%26%20Orl%C3%A9ans') self.assertEquals(urlquote(u'Paris & Orl\xe9ans', safe="&"), u'Paris%20&%20Orl%C3%A9ans') self.assertEquals(urlquote_plus(u'Paris & Orl\xe9ans'), u'Paris+%26+Orl%C3%A9ans') self.assertEquals(urlquote_plus(u'Paris & Orl\xe9ans', safe="&"), u'Paris+&+Orl%C3%A9ans') def test_cookie_date(self): t = 1167616461.0 self.assertEquals(cookie_date(t), 'Mon, 01-Jan-2007 01:54:21 GMT') def test_http_date(self): t = 1167616461.0 self.assertEquals(http_date(t), 'Mon, 01 Jan 2007 01:54:21 GMT') def test_iri_to_uri(self): self.assertEquals(iri_to_uri(u'red%09ros\xe9#red'), 'red%09ros%C3%A9#red') self.assertEquals(iri_to_uri(u'/blog/for/J\xfcrgen M\xfcnster/'), '/blog/for/J%C3%BCrgen%20M%C3%BCnster/') self.assertEquals(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.assertEquals(iri_to_uri(iri_to_uri(u'red%09ros\xe9#red')), 'red%09ros%C3%A9#red')
3,179
Python
.py
58
45.551724
93
0.615881
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,213
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/app_loading/tests.py
import copy import os import sys import time from unittest import TestCase from django.conf import Settings from django.db.models.loading import cache, load_app 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.assertEquals(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,007
Python
.py
68
36.294118
104
0.642955
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,214
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,215
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,216
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/httpwrappers/tests.py
import copy import pickle import unittest from django.http import QueryDict, HttpResponse, CompatCookie, BadHeaderError 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_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 = CompatCookie() c['test'] = "An,awkward;value" self.assert_(";" not in c.output().rstrip(';')) # IE compat self.assert_("," not in c.output().rstrip(';')) # Safari compat def test_decode(self): """ Test that we can still preserve semi-colons and commas """ c = CompatCookie() c['test'] = "An,awkward;value" c2 = CompatCookie() 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 = CompatCookie() c['test'] = "\xf0" c2 = CompatCookie() c2.load(c.output()) self.assertEqual(c['test'].value, c2['test'].value)
10,760
Python
.py
223
39.560538
99
0.602439
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,217
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,218
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/i18n/tests.py
# -*- encoding: utf-8 -*- import datetime import decimal import os import sys import pickle from django.conf import settings from django.template import Template, Context from django.test import TestCase from django.utils.formats import (get_format, date_format, time_format, localize, localize_input, iter_format_modules, get_format_modules) 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, to_locale, get_language) from django.utils.importlib import import_module from forms import I18nForm, SelectDateForm, SelectDateWidget, CompanyForm from models import Company, TestModel 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_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() # 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.assert_(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() 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 = {} trans_real._translations = {} activate('de') def tearDown(self): deactivate() def assertUgettext(self, msgid, msgstr): result = ugettext(msgid) self.assert_(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 = list(settings.INSTALLED_APPS) + ['regressiontests.i18n.resolution'] 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('Date/time', 'LOCALE_PATHS') 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'] self.assertUgettext('Date/time', 'PROJECT') settings.INSTALLED_APPS = old_installed_apps def test_project_override_locale_paths_translation(self): old_locale_paths = settings.LOCALE_PATHS settings.LOCALE_PATHS += (os.path.join(os.path.dirname(os.path.abspath(__file__)), 'other', 'locale'),) self.assertUgettext('Date/time', 'PROJECT') settings.LOCALE_PATHS = old_locale_paths class DjangoFallbackResolutionOrderI18NTests(ResolutionOrderI18NTests): def test_django_fallback(self): self.assertUgettext('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 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')
42,903
Python
.py
712
50.061798
2,017
0.620959
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,219
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,220
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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
3,932
Python
.py
105
32.419048
76
0.71723
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,221
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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) 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_11369(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.assertEquals( 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") )
14,481
Python
.py
336
33.28869
78
0.620663
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,222
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,223
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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.assertEquals(self.pre_signals, post_signals) def test_model_signals(self): """ Model saves should throw some signals. """ a1 = Author(name='Neal Stephenson') self.assertEquals(self.get_signal_output(a1.save), [ "pre_save signal, Neal Stephenson", "post_save signal, Neal Stephenson", "Is created" ]) b1 = Book(name='Snow Crash') self.assertEquals(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.assertEquals(self.get_signal_output(setattr, b1, 'authors', [a1]), []) self.assertEquals(self.get_signal_output(setattr, b1, 'authors', []), [])
3,760
Python
.py
79
38.772152
83
0.649836
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,224
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,225
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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 unittest import shutil import sys import re from django import conf, bin, get_version from django.conf import settings 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.assertEquals(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.assert_(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 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') ########################################################################## # 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_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')]")
57,182
Python
.py
1,011
48.283877
241
0.667363
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,226
app_command.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,227
noargs_command.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,228
label_command.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,229
base_command.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,230
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,231
bar.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,232
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,233
foo.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,234
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,235
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/max_lengths/tests.py
from unittest import TestCase from django.db import DatabaseError from regressiontests.max_lengths.models import PersonWithDefaultMaxLengths, PersonWithCustomMaxLengths class MaxLengthArgumentsTests(TestCase): def verify_max_length(self, model,field,length): self.assertEquals(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(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,615
Python
.py
29
46.758621
102
0.693095
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,236
extraction.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/makemessages/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): return self.assert_(re.search('^msgid "%s"' % msgid, s, re.MULTILINE)) def assertNotMsgId(self, msgid, s): return self.assert_(not re.search('^msgid "%s"' % msgid, s, re.MULTILINE)) class TemplateExtractorTests(ExtractorTests): def test_templatize(self): os.chdir(self.test_dir) management.call_command('makemessages', locale=LOCALE, verbosity=0) self.assert_(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) 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.assert_(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.assert_(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.assert_(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.assert_(os.path.exists(self.PO_FILE)) po_contents = open(self.PO_FILE, 'r').read() self.assertMsgId('This literal should be included.', po_contents) self.assert_('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.assert_(os.path.exists(self.PO_FILE)) po_contents = open(self.PO_FILE, 'r').read() self.assert_('Plural-Forms: nplurals=2; plural=(n != 1)' in po_contents)
3,927
Python
.py
83
39.012048
109
0.654793
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,237
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/makemessages/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
1,419
Python
.py
38
30.605263
134
0.618564
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,238
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,239
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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.assertEquals(self.p1.restaurant, self.r1) self.assertEquals(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,691
Python
.py
107
34.327103
85
0.632098
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,240
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/csrf_tests/tests.py
# -*- coding: utf-8 -*- 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 _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.assert_('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.assertEquals(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.assertEquals(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.assertEquals(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.assertEquals(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.assertEquals(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.assertEquals(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.assertEquals(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.assertEquals(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.assertEquals(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.assertEquals(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.assertEquals(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.assertEquals(None, req2)
15,523
Python
.py
324
40.123457
107
0.662464
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,241
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,242
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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=1) self.assertEquals(c.post, p) self.assertEquals(Comment.objects.select_related().get(id=2).post, None) self.assertQuerysetEqual( Comment.objects.select_related('post__forum__system_info').all(), [ (1, u'My first comment', '<Post: First Post>'), (2, 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'), [ (1, u'My first comment', '<Post: First Post>'), (2, u'My second comment', 'None') ], transform = lambda c: (c.id, c.comment_text, repr(c.post)) )
1,868
Python
.py
35
43.142857
105
0.623768
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,243
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,244
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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 import unittest from django.core.files.uploadedfile import SimpleUploadedFile 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,327
Python
.py
33
33.878788
76
0.667185
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,245
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,246
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,247
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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 Place(models.Model): name = models.CharField(max_length=200)
249
Python
.py
8
28.75
65
0.768908
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,248
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/admin_registration/tests.py
from django.test import TestCase from django.contrib import admin from models import Person, Place 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'])
2,001
Python
.py
44
35.977273
77
0.649718
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,249
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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 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 = ( ('/media/css/base.css', ('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. ('/media/\\css/base.css', ('\\css', 'base.css')), ) bad_data += ( '/media//css/base.css', '/media////css/base.css', '/media/../css/base.css', ) elif os.sep == '\\': bad_data += ( '/media/C:\css/base.css', '/media//\\css/base.css', '/media/\\css/base.css', '/media/\\\\css/base.css' ) 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,299
Python
.py
61
26.344262
78
0.522636
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,250
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/bash_completion/tests.py
""" A series of tests to establish that the command-line bash completion works. """ import os import unittest import sys import StringIO from django.conf import settings from django.core.management import ManagementUtility 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,185
Python
.py
74
35.594595
128
0.662363
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,251
test_command.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,252
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,253
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/model_inheritance/tests.py
from operator import attrgetter from django.conf import settings from django.core.exceptions import FieldError from django.db import connection 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.assertTrue(type(p) is 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. old_DEBUG = settings.DEBUG try: settings.DEBUG = True starting_queries = len(connection.queries) ItalianRestaurant.objects.all()[0].chef self.assertEqual(len(connection.queries) - starting_queries, 2) starting_queries = len(connection.queries) ItalianRestaurant.objects.select_related("chef")[0].chef self.assertEqual(len(connection.queries) - starting_queries, 1) finally: settings.DEBUG = old_DEBUG def test_mixin_init(self): m = MixinModel() self.assertEqual(m.other_attr, 1)
10,909
Python
.py
250
33.224
140
0.613589
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,254
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,255
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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.assertEquals(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.assertEquals(out.getvalue(), "I don't feel like dancing Jive.") def test_explode(self): self.assertRaises(CommandError, management.call_command, ('explode',))
708
Python
.py
17
35.058824
78
0.694767
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,256
dance.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,257
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,258
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/files/tests.py
import shutil 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 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") # 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"]) # 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") # 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") # 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()
3,920
Python
.py
80
40.3125
100
0.655849
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,259
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,260
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,261
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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.test import Client, TestCase from django.conf import settings from django.core import mail 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.template.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.template.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.template.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.template.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.assertEquals(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.template.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.assertEquals(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.assertEquals(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)
20,977
Python
.py
373
47.450402
148
0.673736
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,262
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,263
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/test_client/tests.py
# Validate that you can override the default test suite 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")
465
Python
.py
15
25.133333
62
0.72028
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,264
views.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,265
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/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)
3,266
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/transactions/tests.py
from django.test import TransactionTestCase from django.db import connection, transaction, IntegrityError, DEFAULT_DB_ALIAS from django.conf import settings from models import Reporter PGSQL = 'psycopg2' in settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] MYSQL = 'mysql' in settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] class TransactionTests(TransactionTestCase): if not MYSQL: 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! def execute_bad_sql(self): cursor = connection.cursor() cursor.execute("INSERT INTO transactions_reporter (first_name, last_name) VALUES ('Douglas', 'Adams');") transaction.set_dirty() 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) 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) 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) 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) 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) 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()), []) 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) 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) 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 ) if PGSQL: 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,102
Python
.py
134
33.067164
116
0.597108
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,267
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/model_inheritance_same_model_name/models.py
""" XX. Model inheritance Model inheritance across apps can result in models with the same name resulting in the need for an %(app_label)s format string. This app specifically tests this feature by redefining the Copy model from model_inheritance/models.py """ from django.db import models from modeltests.model_inheritance.models import NamedURL # # Abstract base classes with related models # class Copy(NamedURL): content = models.TextField() def __unicode__(self): return self.content
509
Python
.py
15
31.6
79
0.789796
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,268
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/model_inheritance_same_model_name/tests.py
from django.test import TestCase from modeltests.model_inheritance.models import Title class InheritanceSameModelNameTests(TestCase): def setUp(self): # The Title model has distinct accessors for both # model_inheritance.Copy and model_inheritance_same_model_name.Copy # models. self.title = Title.objects.create(title='Lorem Ipsum') def test_inheritance_related_name(self): from modeltests.model_inheritance.models import Copy self.assertEquals( self.title.attached_model_inheritance_copy_set.create( content='Save $ on V1agr@', url='http://v1agra.com/', title='V1agra is spam', ), Copy.objects.get(content='Save $ on V1agr@')) def test_inheritance_with_same_model_name(self): from modeltests.model_inheritance_same_model_name.models import Copy self.assertEquals( self.title.attached_model_inheritance_same_model_name_copy_set.create( content='The Web framework for perfectionists with deadlines.', url='http://www.djangoproject.com/', title='Django Rocks' ), Copy.objects.get(content='The Web framework for perfectionists with deadlines.')) def test_related_name_attribute_exists(self): # The Post model doesn't have an attribute called 'attached_%(app_label)s_%(class)s_set'. self.assertEqual(hasattr(self.title, 'attached_%(app_label)s_%(class)s_set'), False)
1,510
Python
.py
27
45.851852
97
0.67253
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,269
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/field_defaults/models.py
# coding: utf-8 """ 32. Callable defaults You can pass callable objects as the ``default`` parameter to a field. When the object is created without an explicit value passed in, Django will call the method to determine the default value. This example uses ``datetime.datetime.now`` as the default for the ``pub_date`` field. """ from django.db import models from datetime import datetime class Article(models.Model): headline = models.CharField(max_length=100, default='Default headline') pub_date = models.DateTimeField(default=datetime.now) def __unicode__(self): return self.headline
611
Python
.py
16
35.625
79
0.767797
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,270
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/field_defaults/tests.py
from datetime import datetime from django.test import TestCase from models import Article class DefaultTests(TestCase): def test_field_defaults(self): a = Article() now = datetime.now() a.save() self.assertTrue(isinstance(a.id, (int, long))) self.assertEqual(a.headline, "Default headline") self.assertTrue((now - a.pub_date).seconds < 5)
396
Python
.py
11
29.818182
56
0.681579
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,271
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/properties/models.py
""" 22. Using properties on models Use properties on models just like on any other Python object. """ from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def _get_full_name(self): return "%s %s" % (self.first_name, self.last_name) def _set_full_name(self, combined_name): self.first_name, self.last_name = combined_name.split(' ', 1) full_name = property(_get_full_name) full_name_2 = property(_get_full_name, _set_full_name)
567
Python
.py
14
36.142857
69
0.697802
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,272
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/properties/tests.py
from django.test import TestCase from models import Person class PropertyTests(TestCase): def setUp(self): self.a = Person(first_name='John', last_name='Lennon') self.a.save() def test_getter(self): self.assertEqual(self.a.full_name, 'John Lennon') def test_setter(self): # The "full_name" property hasn't provided a "set" method. self.assertRaises(AttributeError, setattr, self.a, 'full_name', 'Paul McCartney') # But "full_name_2" has, and it can be used to initialise the class. a2 = Person(full_name_2 = 'Paul McCartney') a2.save() self.assertEqual(a2.first_name, 'Paul')
665
Python
.py
15
37.4
89
0.662016
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,273
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/m2m_and_m2o/models.py
""" 29. Many-to-many and many-to-one relationships to the same table Make sure to set ``related_name`` if you use relationships to the same table. """ from django.db import models class User(models.Model): username = models.CharField(max_length=20) class Issue(models.Model): num = models.IntegerField() cc = models.ManyToManyField(User, blank=True, related_name='test_issue_cc') client = models.ForeignKey(User, related_name='test_issue_client') def __unicode__(self): return unicode(self.num) class Meta: ordering = ('num',)
573
Python
.py
15
34.133333
79
0.713768
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,274
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/m2m_and_m2o/tests.py
from django.db.models import Q from django.test import TestCase from models import Issue, User class RelatedObjectTests(TestCase): def test_m2m_and_m2o(self): r = User.objects.create(username="russell") g = User.objects.create(username="gustav") i1 = Issue(num=1) i1.client = r i1.save() i2 = Issue(num=2) i2.client = r i2.save() i2.cc.add(r) i3 = Issue(num=3) i3.client = g i3.save() i3.cc.add(r) self.assertQuerysetEqual( Issue.objects.filter(client=r.id), [ 1, 2, ], lambda i: i.num ) self.assertQuerysetEqual( Issue.objects.filter(client=g.id), [ 3, ], lambda i: i.num ) self.assertQuerysetEqual( Issue.objects.filter(cc__id__exact=g.id), [] ) self.assertQuerysetEqual( Issue.objects.filter(cc__id__exact=r.id), [ 2, 3, ], lambda i: i.num ) # These queries combine results from the m2m and the m2o relationships. # They're three ways of saying the same thing. self.assertQuerysetEqual( Issue.objects.filter(Q(cc__id__exact = r.id) | Q(client=r.id)), [ 1, 2, 3, ], lambda i: i.num ) self.assertQuerysetEqual( Issue.objects.filter(cc__id__exact=r.id) | Issue.objects.filter(client=r.id), [ 1, 2, 3, ], lambda i: i.num ) self.assertQuerysetEqual( Issue.objects.filter(Q(client=r.id) | Q(cc__id__exact=r.id)), [ 1, 2, 3, ], lambda i: i.num )
1,938
Python
.py
67
17.537313
91
0.469673
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,275
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/aggregation/models.py
# coding: utf-8 from django.db import models class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() friends = models.ManyToManyField('self', blank=True) def __unicode__(self): return self.name class Publisher(models.Model): name = models.CharField(max_length=255) num_awards = models.IntegerField() def __unicode__(self): return self.name class Book(models.Model): isbn = models.CharField(max_length=9) name = models.CharField(max_length=255) pages = models.IntegerField() rating = models.FloatField() price = models.DecimalField(decimal_places=2, max_digits=6) authors = models.ManyToManyField(Author) contact = models.ForeignKey(Author, related_name='book_contact_set') publisher = models.ForeignKey(Publisher) pubdate = models.DateField() def __unicode__(self): return self.name class Store(models.Model): name = models.CharField(max_length=255) books = models.ManyToManyField(Book) original_opening = models.DateTimeField() friday_night_closing = models.TimeField() def __unicode__(self): return self.name
1,181
Python
.py
32
31.84375
72
0.710272
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,276
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/aggregation/tests.py
import datetime from decimal import Decimal from django.db.models import Avg, Sum, Count, Max, Min from django.test import TestCase, Approximate from models import Author, Publisher, Book, Store class BaseAggregateTestCase(TestCase): fixtures = ["initial_data.json"] def test_empty_aggregate(self): self.assertEqual(Author.objects.all().aggregate(), {}) def test_single_aggregate(self): vals = Author.objects.aggregate(Avg("age")) self.assertEqual(vals, {"age__avg": Approximate(37.4, places=1)}) def test_multiple_aggregates(self): vals = Author.objects.aggregate(Sum("age"), Avg("age")) self.assertEqual(vals, {"age__sum": 337, "age__avg": Approximate(37.4, places=1)}) def test_filter_aggregate(self): vals = Author.objects.filter(age__gt=29).aggregate(Sum("age")) self.assertEqual(len(vals), 1) self.assertEqual(vals["age__sum"], 254) def test_related_aggregate(self): vals = Author.objects.aggregate(Avg("friends__age")) self.assertEqual(len(vals), 1) self.assertAlmostEqual(vals["friends__age__avg"], 34.07, places=2) vals = Book.objects.filter(rating__lt=4.5).aggregate(Avg("authors__age")) self.assertEqual(len(vals), 1) self.assertAlmostEqual(vals["authors__age__avg"], 38.2857, places=2) vals = Author.objects.all().filter(name__contains="a").aggregate(Avg("book__rating")) self.assertEqual(len(vals), 1) self.assertEqual(vals["book__rating__avg"], 4.0) vals = Book.objects.aggregate(Sum("publisher__num_awards")) self.assertEqual(len(vals), 1) self.assertEquals(vals["publisher__num_awards__sum"], 30) vals = Publisher.objects.aggregate(Sum("book__price")) self.assertEqual(len(vals), 1) self.assertEqual(vals["book__price__sum"], Decimal("270.27")) def test_aggregate_multi_join(self): vals = Store.objects.aggregate(Max("books__authors__age")) self.assertEqual(len(vals), 1) self.assertEqual(vals["books__authors__age__max"], 57) vals = Author.objects.aggregate(Min("book__publisher__num_awards")) self.assertEqual(len(vals), 1) self.assertEqual(vals["book__publisher__num_awards__min"], 1) def test_aggregate_alias(self): vals = Store.objects.filter(name="Amazon.com").aggregate(amazon_mean=Avg("books__rating")) self.assertEqual(len(vals), 1) self.assertAlmostEqual(vals["amazon_mean"], 4.08, places=2) def test_annotate_basic(self): self.assertQuerysetEqual( Book.objects.annotate().order_by('pk'), [ "The Definitive Guide to Django: Web Development Done Right", "Sams Teach Yourself Django in 24 Hours", "Practical Django Projects", "Python Web Development with Django", "Artificial Intelligence: A Modern Approach", "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp" ], lambda b: b.name ) books = Book.objects.annotate(mean_age=Avg("authors__age")) b = books.get(pk=1) self.assertEqual( b.name, u'The Definitive Guide to Django: Web Development Done Right' ) self.assertEqual(b.mean_age, 34.5) def test_annotate_m2m(self): books = Book.objects.filter(rating__lt=4.5).annotate(Avg("authors__age")).order_by("name") self.assertQuerysetEqual( books, [ (u'Artificial Intelligence: A Modern Approach', 51.5), (u'Practical Django Projects', 29.0), (u'Python Web Development with Django', Approximate(30.3, places=1)), (u'Sams Teach Yourself Django in 24 Hours', 45.0) ], lambda b: (b.name, b.authors__age__avg), ) books = Book.objects.annotate(num_authors=Count("authors")).order_by("name") self.assertQuerysetEqual( books, [ (u'Artificial Intelligence: A Modern Approach', 2), (u'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp', 1), (u'Practical Django Projects', 1), (u'Python Web Development with Django', 3), (u'Sams Teach Yourself Django in 24 Hours', 1), (u'The Definitive Guide to Django: Web Development Done Right', 2) ], lambda b: (b.name, b.num_authors) ) def test_backwards_m2m_annotate(self): authors = Author.objects.filter(name__contains="a").annotate(Avg("book__rating")).order_by("name") self.assertQuerysetEqual( authors, [ (u'Adrian Holovaty', 4.5), (u'Brad Dayley', 3.0), (u'Jacob Kaplan-Moss', 4.5), (u'James Bennett', 4.0), (u'Paul Bissex', 4.0), (u'Stuart Russell', 4.0) ], lambda a: (a.name, a.book__rating__avg) ) authors = Author.objects.annotate(num_books=Count("book")).order_by("name") self.assertQuerysetEqual( authors, [ (u'Adrian Holovaty', 1), (u'Brad Dayley', 1), (u'Jacob Kaplan-Moss', 1), (u'James Bennett', 1), (u'Jeffrey Forcier', 1), (u'Paul Bissex', 1), (u'Peter Norvig', 2), (u'Stuart Russell', 1), (u'Wesley J. Chun', 1) ], lambda a: (a.name, a.num_books) ) def test_reverse_fkey_annotate(self): books = Book.objects.annotate(Sum("publisher__num_awards")).order_by("name") self.assertQuerysetEqual( books, [ (u'Artificial Intelligence: A Modern Approach', 7), (u'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp', 9), (u'Practical Django Projects', 3), (u'Python Web Development with Django', 7), (u'Sams Teach Yourself Django in 24 Hours', 1), (u'The Definitive Guide to Django: Web Development Done Right', 3) ], lambda b: (b.name, b.publisher__num_awards__sum) ) publishers = Publisher.objects.annotate(Sum("book__price")).order_by("name") self.assertQuerysetEqual( publishers, [ (u'Apress', Decimal("59.69")), (u"Jonno's House of Books", None), (u'Morgan Kaufmann', Decimal("75.00")), (u'Prentice Hall', Decimal("112.49")), (u'Sams', Decimal("23.09")) ], lambda p: (p.name, p.book__price__sum) ) def test_annotate_values(self): books = list(Book.objects.filter(pk=1).annotate(mean_age=Avg("authors__age")).values()) self.assertEqual( books, [ { "contact_id": 1, "id": 1, "isbn": "159059725", "mean_age": 34.5, "name": "The Definitive Guide to Django: Web Development Done Right", "pages": 447, "price": Approximate(Decimal("30")), "pubdate": datetime.date(2007, 12, 6), "publisher_id": 1, "rating": 4.5, } ] ) books = Book.objects.filter(pk=1).annotate(mean_age=Avg('authors__age')).values('pk', 'isbn', 'mean_age') self.assertEqual( list(books), [ { "pk": 1, "isbn": "159059725", "mean_age": 34.5, } ] ) books = Book.objects.filter(pk=1).annotate(mean_age=Avg("authors__age")).values("name") self.assertEqual( list(books), [ { "name": "The Definitive Guide to Django: Web Development Done Right" } ] ) books = Book.objects.filter(pk=1).values().annotate(mean_age=Avg('authors__age')) self.assertEqual( list(books), [ { "contact_id": 1, "id": 1, "isbn": "159059725", "mean_age": 34.5, "name": "The Definitive Guide to Django: Web Development Done Right", "pages": 447, "price": Approximate(Decimal("30")), "pubdate": datetime.date(2007, 12, 6), "publisher_id": 1, "rating": 4.5, } ] ) books = Book.objects.values("rating").annotate(n_authors=Count("authors__id"), mean_age=Avg("authors__age")).order_by("rating") self.assertEqual( list(books), [ { "rating": 3.0, "n_authors": 1, "mean_age": 45.0, }, { "rating": 4.0, "n_authors": 6, "mean_age": Approximate(37.16, places=1) }, { "rating": 4.5, "n_authors": 2, "mean_age": 34.5, }, { "rating": 5.0, "n_authors": 1, "mean_age": 57.0, } ] ) authors = Author.objects.annotate(Avg("friends__age")).order_by("name") self.assertEqual(len(authors), 9) self.assertQuerysetEqual( authors, [ (u'Adrian Holovaty', 32.0), (u'Brad Dayley', None), (u'Jacob Kaplan-Moss', 29.5), (u'James Bennett', 34.0), (u'Jeffrey Forcier', 27.0), (u'Paul Bissex', 31.0), (u'Peter Norvig', 46.0), (u'Stuart Russell', 57.0), (u'Wesley J. Chun', Approximate(33.66, places=1)) ], lambda a: (a.name, a.friends__age__avg) ) def test_count(self): vals = Book.objects.aggregate(Count("rating")) self.assertEqual(vals, {"rating__count": 6}) vals = Book.objects.aggregate(Count("rating", distinct=True)) self.assertEqual(vals, {"rating__count": 4}) def test_fkey_aggregate(self): explicit = list(Author.objects.annotate(Count('book__id'))) implicit = list(Author.objects.annotate(Count('book'))) self.assertEqual(explicit, implicit) def test_annotate_ordering(self): books = Book.objects.values('rating').annotate(oldest=Max('authors__age')).order_by('oldest', 'rating') self.assertEqual( list(books), [ { "rating": 4.5, "oldest": 35, }, { "rating": 3.0, "oldest": 45 }, { "rating": 4.0, "oldest": 57, }, { "rating": 5.0, "oldest": 57, } ] ) books = Book.objects.values("rating").annotate(oldest=Max("authors__age")).order_by("-oldest", "-rating") self.assertEqual( list(books), [ { "rating": 5.0, "oldest": 57, }, { "rating": 4.0, "oldest": 57, }, { "rating": 3.0, "oldest": 45, }, { "rating": 4.5, "oldest": 35, } ] ) def test_aggregate_annotation(self): vals = Book.objects.annotate(num_authors=Count("authors__id")).aggregate(Avg("num_authors")) self.assertEqual(vals, {"num_authors__avg": Approximate(1.66, places=1)}) def test_filtering(self): p = Publisher.objects.create(name='Expensive Publisher', num_awards=0) Book.objects.create( name='ExpensiveBook1', pages=1, isbn='111', rating=3.5, price=Decimal("1000"), publisher=p, contact_id=1, pubdate=datetime.date(2008,12,1) ) Book.objects.create( name='ExpensiveBook2', pages=1, isbn='222', rating=4.0, price=Decimal("1000"), publisher=p, contact_id=1, pubdate=datetime.date(2008,12,2) ) Book.objects.create( name='ExpensiveBook3', pages=1, isbn='333', rating=4.5, price=Decimal("35"), publisher=p, contact_id=1, pubdate=datetime.date(2008,12,3) ) publishers = Publisher.objects.annotate(num_books=Count("book__id")).filter(num_books__gt=1).order_by("pk") self.assertQuerysetEqual( publishers, [ "Apress", "Prentice Hall", "Expensive Publisher", ], lambda p: p.name, ) publishers = Publisher.objects.filter(book__price__lt=Decimal("40.0")).order_by("pk") self.assertQuerysetEqual( publishers, [ "Apress", "Apress", "Sams", "Prentice Hall", "Expensive Publisher", ], lambda p: p.name ) publishers = Publisher.objects.annotate(num_books=Count("book__id")).filter(num_books__gt=1, book__price__lt=Decimal("40.0")).order_by("pk") self.assertQuerysetEqual( publishers, [ "Apress", "Prentice Hall", "Expensive Publisher", ], lambda p: p.name, ) publishers = Publisher.objects.filter(book__price__lt=Decimal("40.0")).annotate(num_books=Count("book__id")).filter(num_books__gt=1).order_by("pk") self.assertQuerysetEqual( publishers, [ "Apress", ], lambda p: p.name ) publishers = Publisher.objects.annotate(num_books=Count("book")).filter(num_books__range=[1, 3]).order_by("pk") self.assertQuerysetEqual( publishers, [ "Apress", "Sams", "Prentice Hall", "Morgan Kaufmann", "Expensive Publisher", ], lambda p: p.name ) publishers = Publisher.objects.annotate(num_books=Count("book")).filter(num_books__range=[1, 2]).order_by("pk") self.assertQuerysetEqual( publishers, [ "Apress", "Sams", "Prentice Hall", "Morgan Kaufmann", ], lambda p: p.name ) publishers = Publisher.objects.annotate(num_books=Count("book")).filter(num_books__in=[1, 3]).order_by("pk") self.assertQuerysetEqual( publishers, [ "Sams", "Morgan Kaufmann", "Expensive Publisher", ], lambda p: p.name, ) publishers = Publisher.objects.annotate(num_books=Count("book")).filter(num_books__isnull=True) self.assertEqual(len(publishers), 0) def test_annotation(self): vals = Author.objects.filter(pk=1).aggregate(Count("friends__id")) self.assertEqual(vals, {"friends__id__count": 2}) books = Book.objects.annotate(num_authors=Count("authors__name")).filter(num_authors__ge=2).order_by("pk") self.assertQuerysetEqual( books, [ "The Definitive Guide to Django: Web Development Done Right", "Artificial Intelligence: A Modern Approach", ], lambda b: b.name ) authors = Author.objects.annotate(num_friends=Count("friends__id", distinct=True)).filter(num_friends=0).order_by("pk") self.assertQuerysetEqual( authors, [ "Brad Dayley", ], lambda a: a.name ) publishers = Publisher.objects.annotate(num_books=Count("book__id")).filter(num_books__gt=1).order_by("pk") self.assertQuerysetEqual( publishers, [ "Apress", "Prentice Hall", ], lambda p: p.name ) publishers = Publisher.objects.filter(book__price__lt=Decimal("40.0")).annotate(num_books=Count("book__id")).filter(num_books__gt=1) self.assertQuerysetEqual( publishers, [ "Apress", ], lambda p: p.name ) books = Book.objects.annotate(num_authors=Count("authors__id")).filter(authors__name__contains="Norvig", num_authors__gt=1) self.assertQuerysetEqual( books, [ "Artificial Intelligence: A Modern Approach", ], lambda b: b.name ) def test_more_aggregation(self): a = Author.objects.get(name__contains='Norvig') b = Book.objects.get(name__contains='Done Right') b.authors.add(a) b.save() vals = Book.objects.annotate(num_authors=Count("authors__id")).filter(authors__name__contains="Norvig", num_authors__gt=1).aggregate(Avg("rating")) self.assertEqual(vals, {"rating__avg": 4.25}) def test_even_more_aggregate(self): publishers = Publisher.objects.annotate(earliest_book=Min("book__pubdate")).exclude(earliest_book=None).order_by("earliest_book").values() self.assertEqual( list(publishers), [ { 'earliest_book': datetime.date(1991, 10, 15), 'num_awards': 9, 'id': 4, 'name': u'Morgan Kaufmann' }, { 'earliest_book': datetime.date(1995, 1, 15), 'num_awards': 7, 'id': 3, 'name': u'Prentice Hall' }, { 'earliest_book': datetime.date(2007, 12, 6), 'num_awards': 3, 'id': 1, 'name': u'Apress' }, { 'earliest_book': datetime.date(2008, 3, 3), 'num_awards': 1, 'id': 2, 'name': u'Sams' } ] ) vals = Store.objects.aggregate(Max("friday_night_closing"), Min("original_opening")) self.assertEqual( vals, { "friday_night_closing__max": datetime.time(23, 59, 59), "original_opening__min": datetime.datetime(1945, 4, 25, 16, 24, 14), } ) def test_annotate_values_list(self): books = Book.objects.filter(pk=1).annotate(mean_age=Avg("authors__age")).values_list("pk", "isbn", "mean_age") self.assertEqual( list(books), [ (1, "159059725", 34.5), ] ) books = Book.objects.filter(pk=1).annotate(mean_age=Avg("authors__age")).values_list("isbn") self.assertEqual( list(books), [ ('159059725',) ] ) books = Book.objects.filter(pk=1).annotate(mean_age=Avg("authors__age")).values_list("mean_age") self.assertEqual( list(books), [ (34.5,) ] ) books = Book.objects.filter(pk=1).annotate(mean_age=Avg("authors__age")).values_list("mean_age", flat=True) self.assertEqual(list(books), [34.5]) books = Book.objects.values_list("price").annotate(count=Count("price")).order_by("-count", "price") self.assertEqual( list(books), [ (Decimal("29.69"), 2), (Decimal('23.09'), 1), (Decimal('30'), 1), (Decimal('75'), 1), (Decimal('82.8'), 1), ] )
20,519
Python
.py
505
27.180198
155
0.502205
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,277
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/get_latest/models.py
""" 8. get_latest_by Models can have a ``get_latest_by`` attribute, which should be set to the name of a ``DateField`` or ``DateTimeField``. If ``get_latest_by`` exists, the model's manager will get a ``latest()`` method, which will return the latest object in the database according to that field. "Latest" means "having the date farthest into the future." """ from django.db import models class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() expire_date = models.DateField() class Meta: get_latest_by = 'pub_date' def __unicode__(self): return self.headline class Person(models.Model): name = models.CharField(max_length=30) birthday = models.DateField() # Note that this model doesn't have "get_latest_by" set. def __unicode__(self): return self.name
871
Python
.py
23
33.956522
79
0.705113
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,278
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/get_latest/tests.py
from datetime import datetime from django.test import TestCase from models import Article, Person class LatestTests(TestCase): def test_latest(self): # Because no Articles exist yet, latest() raises ArticleDoesNotExist. self.assertRaises(Article.DoesNotExist, Article.objects.latest) a1 = Article.objects.create( headline="Article 1", pub_date=datetime(2005, 7, 26), expire_date=datetime(2005, 9, 1) ) a2 = Article.objects.create( headline="Article 2", pub_date=datetime(2005, 7, 27), expire_date=datetime(2005, 7, 28) ) a3 = Article.objects.create( headline="Article 3", pub_date=datetime(2005, 7, 27), expire_date=datetime(2005, 8, 27) ) a4 = Article.objects.create( headline="Article 4", pub_date=datetime(2005, 7, 28), expire_date=datetime(2005, 7, 30) ) # Get the latest Article. self.assertEqual(Article.objects.latest(), a4) # Get the latest Article that matches certain filters. self.assertEqual( Article.objects.filter(pub_date__lt=datetime(2005, 7, 27)).latest(), a1 ) # Pass a custom field name to latest() to change the field that's used # to determine the latest object. self.assertEqual(Article.objects.latest('expire_date'), a1) self.assertEqual( Article.objects.filter(pub_date__gt=datetime(2005, 7, 26)).latest('expire_date'), a3, ) def test_latest_manual(self): # You can still use latest() with a model that doesn't have # "get_latest_by" set -- just pass in the field name manually. p1 = Person.objects.create(name="Ralph", birthday=datetime(1950, 1, 1)) p2 = Person.objects.create(name="Stephanie", birthday=datetime(1960, 2, 3)) self.assertRaises(AssertionError, Person.objects.latest) self.assertEqual(Person.objects.latest("birthday"), p2)
2,033
Python
.py
44
36.818182
93
0.634343
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,279
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/validators/tests.py
# -*- coding: utf-8 -*- import re import types from unittest import TestCase from datetime import datetime, timedelta from django.core.exceptions import ValidationError from django.core.validators import * NOW = datetime.now() TEST_DATA = ( # (validator, value, expected), (validate_integer, '42', None), (validate_integer, '-42', None), (validate_integer, -42, None), (validate_integer, -42.5, None), (validate_integer, None, ValidationError), (validate_integer, 'a', ValidationError), (validate_email, '[email protected]', None), (validate_email, '[email protected]', None), (validate_email, None, ValidationError), (validate_email, '', ValidationError), (validate_email, 'abc', ValidationError), (validate_email, 'a @x.cz', ValidationError), (validate_email, 'something@@somewhere.com', ValidationError), (validate_slug, 'slug-ok', None), (validate_slug, 'longer-slug-still-ok', None), (validate_slug, '--------', None), (validate_slug, 'nohyphensoranything', None), (validate_slug, '', ValidationError), (validate_slug, ' text ', ValidationError), (validate_slug, ' ', ValidationError), (validate_slug, '[email protected]', ValidationError), (validate_slug, '你好', ValidationError), (validate_slug, '\n', ValidationError), (validate_ipv4_address, '1.1.1.1', None), (validate_ipv4_address, '255.0.0.0', None), (validate_ipv4_address, '0.0.0.0', None), (validate_ipv4_address, '256.1.1.1', ValidationError), (validate_ipv4_address, '25.1.1.', ValidationError), (validate_ipv4_address, '25,1,1,1', ValidationError), (validate_ipv4_address, '25.1 .1.1', ValidationError), (validate_comma_separated_integer_list, '1', None), (validate_comma_separated_integer_list, '1,2,3', None), (validate_comma_separated_integer_list, '1,2,3,', None), (validate_comma_separated_integer_list, '', ValidationError), (validate_comma_separated_integer_list, 'a,b,c', ValidationError), (validate_comma_separated_integer_list, '1, 2, 3', ValidationError), (MaxValueValidator(10), 10, None), (MaxValueValidator(10), -10, None), (MaxValueValidator(10), 0, None), (MaxValueValidator(NOW), NOW, None), (MaxValueValidator(NOW), NOW - timedelta(days=1), None), (MaxValueValidator(0), 1, ValidationError), (MaxValueValidator(NOW), NOW + timedelta(days=1), ValidationError), (MinValueValidator(-10), -10, None), (MinValueValidator(-10), 10, None), (MinValueValidator(-10), 0, None), (MinValueValidator(NOW), NOW, None), (MinValueValidator(NOW), NOW + timedelta(days=1), None), (MinValueValidator(0), -1, ValidationError), (MinValueValidator(NOW), NOW - timedelta(days=1), ValidationError), (MaxLengthValidator(10), '', None), (MaxLengthValidator(10), 10*'x', None), (MaxLengthValidator(10), 15*'x', ValidationError), (MinLengthValidator(10), 15*'x', None), (MinLengthValidator(10), 10*'x', None), (MinLengthValidator(10), '', ValidationError), (URLValidator(), 'http://www.djangoproject.com/', None), (URLValidator(), 'http://localhost/', None), (URLValidator(), 'http://example.com/', None), (URLValidator(), 'http://www.example.com/', None), (URLValidator(), 'http://www.example.com:8000/test', None), (URLValidator(), 'http://valid-with-hyphens.com/', None), (URLValidator(), 'http://subdomain.domain.com/', None), (URLValidator(), 'http://200.8.9.10/', None), (URLValidator(), 'http://200.8.9.10:8000/test', None), (URLValidator(), 'http://valid-----hyphens.com/', None), (URLValidator(), 'http://example.com?something=value', None), (URLValidator(), 'http://example.com/index.php?something=value&another=value2', None), (URLValidator(), 'foo', ValidationError), (URLValidator(), 'http://', ValidationError), (URLValidator(), 'http://example', ValidationError), (URLValidator(), 'http://example.', ValidationError), (URLValidator(), 'http://.com', ValidationError), (URLValidator(), 'http://invalid-.com', ValidationError), (URLValidator(), 'http://-invalid.com', ValidationError), (URLValidator(), 'http://inv-.alid-.com', ValidationError), (URLValidator(), 'http://inv-.-alid.com', ValidationError), (BaseValidator(True), True, None), (BaseValidator(True), False, ValidationError), (RegexValidator('.*'), '', None), (RegexValidator(re.compile('.*')), '', None), (RegexValidator('.*'), 'xxxxx', None), (RegexValidator('x'), 'y', ValidationError), (RegexValidator(re.compile('x')), 'y', ValidationError), ) def create_simple_test_method(validator, expected, value, num): if expected is not None and issubclass(expected, Exception): test_mask = 'test_%s_raises_error_%d' def test_func(self): self.assertRaises(expected, validator, value) else: test_mask = 'test_%s_%d' def test_func(self): self.assertEqual(expected, validator(value)) if isinstance(validator, types.FunctionType): val_name = validator.__name__ else: val_name = validator.__class__.__name__ test_name = test_mask % (val_name, num) return test_name, test_func # Dynamically assemble a test class with the contents of TEST_DATA class TestSimpleValidators(TestCase): def test_single_message(self): v = ValidationError('Not Valid') self.assertEquals(str(v), "[u'Not Valid']") self.assertEquals(repr(v), "ValidationError([u'Not Valid'])") def test_message_list(self): v = ValidationError(['First Problem', 'Second Problem']) self.assertEquals(str(v), "[u'First Problem', u'Second Problem']") self.assertEquals(repr(v), "ValidationError([u'First Problem', u'Second Problem'])") def test_message_dict(self): v = ValidationError({'first': 'First Problem'}) self.assertEquals(str(v), "{'first': 'First Problem'}") self.assertEquals(repr(v), "ValidationError({'first': 'First Problem'})") test_counter = 0 for validator, value, expected in TEST_DATA: name, method = create_simple_test_method(validator, expected, value, test_counter) setattr(TestSimpleValidators, name, method) test_counter += 1
6,299
Python
.py
129
43.44186
92
0.666884
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,280
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/basic/models.py
# coding: utf-8 """ 1. Bare-bones model This is a basic model with only two non-primary-key fields. """ from django.db import models, DEFAULT_DB_ALIAS class Article(models.Model): headline = models.CharField(max_length=100, default='Default headline') pub_date = models.DateTimeField() class Meta: ordering = ('pub_date','headline') def __unicode__(self): return self.headline
413
Python
.py
13
28
75
0.707071
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,281
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/basic/tests.py
from datetime import datetime import re from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.db import models, DEFAULT_DB_ALIAS, connection from django.db.models.fields import FieldDoesNotExist from django.test import TestCase from models import Article class ModelTest(TestCase): def assertRaisesErrorWithMessage(self, error, message, callable, *args, **kwargs): self.assertRaises(error, callable, *args, **kwargs) try: callable(*args, **kwargs) except error, e: self.assertEqual(message, str(e)) def test_lookup(self): # No articles are in the system yet. self.assertQuerysetEqual(Article.objects.all(), []) # Create an Article. a = Article( id=None, headline='Area man programs in Python', pub_date=datetime(2005, 7, 28), ) # Save it into the database. You have to call save() explicitly. a.save() # Now it has an ID. self.assertTrue(a.id != None) # Models have a pk property that is an alias for the primary key # attribute (by default, the 'id' attribute). self.assertEqual(a.pk, a.id) # Access database columns via Python attributes. self.assertEqual(a.headline, 'Area man programs in Python') self.assertEqual(a.pub_date, datetime(2005, 7, 28, 0, 0)) # Change values by changing the attributes, then calling save(). a.headline = 'Area woman programs in Python' a.save() # Article.objects.all() returns all the articles in the database. self.assertQuerysetEqual(Article.objects.all(), ['<Article: Area woman programs in Python>']) # Django provides a rich database lookup API. self.assertEqual(Article.objects.get(id__exact=a.id), a) self.assertEqual(Article.objects.get(headline__startswith='Area woman'), a) self.assertEqual(Article.objects.get(pub_date__year=2005), a) self.assertEqual(Article.objects.get(pub_date__year=2005, pub_date__month=7), a) self.assertEqual(Article.objects.get(pub_date__year=2005, pub_date__month=7, pub_date__day=28), a) self.assertEqual(Article.objects.get(pub_date__week_day=5), a) # The "__exact" lookup type can be omitted, as a shortcut. self.assertEqual(Article.objects.get(id=a.id), a) self.assertEqual(Article.objects.get(headline='Area woman programs in Python'), a) self.assertQuerysetEqual( Article.objects.filter(pub_date__year=2005), ['<Article: Area woman programs in Python>'], ) self.assertQuerysetEqual( Article.objects.filter(pub_date__year=2004), [], ) self.assertQuerysetEqual( Article.objects.filter(pub_date__year=2005, pub_date__month=7), ['<Article: Area woman programs in Python>'], ) self.assertQuerysetEqual( Article.objects.filter(pub_date__week_day=5), ['<Article: Area woman programs in Python>'], ) self.assertQuerysetEqual( Article.objects.filter(pub_date__week_day=6), [], ) # Django raises an Article.DoesNotExist exception for get() if the # parameters don't match any object. self.assertRaisesErrorWithMessage( ObjectDoesNotExist, "Article matching query does not exist.", Article.objects.get, id__exact=2000, ) self.assertRaisesErrorWithMessage( ObjectDoesNotExist, "Article matching query does not exist.", Article.objects.get, pub_date__year=2005, pub_date__month=8, ) self.assertRaisesErrorWithMessage( ObjectDoesNotExist, "Article matching query does not exist.", Article.objects.get, pub_date__week_day=6, ) # Lookup by a primary key is the most common case, so Django # provides a shortcut for primary-key exact lookups. # The following is identical to articles.get(id=a.id). self.assertEqual(Article.objects.get(pk=a.id), a) # pk can be used as a shortcut for the primary key name in any query. self.assertQuerysetEqual(Article.objects.filter(pk__in=[a.id]), ["<Article: Area woman programs in Python>"]) # Model instances of the same type and same ID are considered equal. a = Article.objects.get(pk=a.id) b = Article.objects.get(pk=a.id) self.assertEqual(a, b) def test_object_creation(self): # Create an Article. a = Article( id=None, headline='Area man programs in Python', pub_date=datetime(2005, 7, 28), ) # Save it into the database. You have to call save() explicitly. a.save() # You can initialize a model instance using positional arguments, # which should match the field order as defined in the model. a2 = Article(None, 'Second article', datetime(2005, 7, 29)) a2.save() self.assertNotEqual(a2.id, a.id) self.assertEqual(a2.headline, 'Second article') self.assertEqual(a2.pub_date, datetime(2005, 7, 29, 0, 0)) # ...or, you can use keyword arguments. a3 = Article( id=None, headline='Third article', pub_date=datetime(2005, 7, 30), ) a3.save() self.assertNotEqual(a3.id, a.id) self.assertNotEqual(a3.id, a2.id) self.assertEqual(a3.headline, 'Third article') self.assertEqual(a3.pub_date, datetime(2005, 7, 30, 0, 0)) # You can also mix and match position and keyword arguments, but # be sure not to duplicate field information. a4 = Article(None, 'Fourth article', pub_date=datetime(2005, 7, 31)) a4.save() self.assertEqual(a4.headline, 'Fourth article') # Don't use invalid keyword arguments. self.assertRaisesErrorWithMessage( TypeError, "'foo' is an invalid keyword argument for this function", Article, id=None, headline='Invalid', pub_date=datetime(2005, 7, 31), foo='bar', ) # You can leave off the value for an AutoField when creating an # object, because it'll get filled in automatically when you save(). a5 = Article(headline='Article 6', pub_date=datetime(2005, 7, 31)) a5.save() self.assertEqual(a5.headline, 'Article 6') # If you leave off a field with "default" set, Django will use # the default. a6 = Article(pub_date=datetime(2005, 7, 31)) a6.save() self.assertEqual(a6.headline, u'Default headline') # For DateTimeFields, Django saves as much precision (in seconds) # as you give it. a7 = Article( headline='Article 7', pub_date=datetime(2005, 7, 31, 12, 30), ) a7.save() self.assertEqual(Article.objects.get(id__exact=a7.id).pub_date, datetime(2005, 7, 31, 12, 30)) a8 = Article( headline='Article 8', pub_date=datetime(2005, 7, 31, 12, 30, 45), ) a8.save() self.assertEqual(Article.objects.get(id__exact=a8.id).pub_date, datetime(2005, 7, 31, 12, 30, 45)) # Saving an object again doesn't create a new object -- it just saves # the old one. current_id = a8.id a8.save() self.assertEqual(a8.id, current_id) a8.headline = 'Updated article 8' a8.save() self.assertEqual(a8.id, current_id) # Check that != and == operators behave as expecte on instances self.assertTrue(a7 != a8) self.assertFalse(a7 == a8) self.assertEqual(a8, Article.objects.get(id__exact=a8.id)) self.assertTrue(Article.objects.get(id__exact=a8.id) != Article.objects.get(id__exact=a7.id)) self.assertFalse(Article.objects.get(id__exact=a8.id) == Article.objects.get(id__exact=a7.id)) # You can use 'in' to test for membership... self.assertTrue(a8 in Article.objects.all()) # ... but there will often be more efficient ways if that is all you need: self.assertTrue(Article.objects.filter(id=a8.id).exists()) # dates() returns a list of available dates of the given scope for # the given field. self.assertQuerysetEqual( Article.objects.dates('pub_date', 'year'), ["datetime.datetime(2005, 1, 1, 0, 0)"]) self.assertQuerysetEqual( Article.objects.dates('pub_date', 'month'), ["datetime.datetime(2005, 7, 1, 0, 0)"]) self.assertQuerysetEqual( Article.objects.dates('pub_date', 'day'), ["datetime.datetime(2005, 7, 28, 0, 0)", "datetime.datetime(2005, 7, 29, 0, 0)", "datetime.datetime(2005, 7, 30, 0, 0)", "datetime.datetime(2005, 7, 31, 0, 0)"]) self.assertQuerysetEqual( Article.objects.dates('pub_date', 'day', order='ASC'), ["datetime.datetime(2005, 7, 28, 0, 0)", "datetime.datetime(2005, 7, 29, 0, 0)", "datetime.datetime(2005, 7, 30, 0, 0)", "datetime.datetime(2005, 7, 31, 0, 0)"]) self.assertQuerysetEqual( Article.objects.dates('pub_date', 'day', order='DESC'), ["datetime.datetime(2005, 7, 31, 0, 0)", "datetime.datetime(2005, 7, 30, 0, 0)", "datetime.datetime(2005, 7, 29, 0, 0)", "datetime.datetime(2005, 7, 28, 0, 0)"]) # dates() requires valid arguments. self.assertRaisesErrorWithMessage( TypeError, "dates() takes at least 3 arguments (1 given)", Article.objects.dates, ) self.assertRaisesErrorWithMessage( FieldDoesNotExist, "Article has no field named 'invalid_field'", Article.objects.dates, "invalid_field", "year", ) self.assertRaisesErrorWithMessage( AssertionError, "'kind' must be one of 'year', 'month' or 'day'.", Article.objects.dates, "pub_date", "bad_kind", ) self.assertRaisesErrorWithMessage( AssertionError, "'order' must be either 'ASC' or 'DESC'.", Article.objects.dates, "pub_date", "year", order="bad order", ) # Use iterator() with dates() to return a generator that lazily # requests each result one at a time, to save memory. dates = [] for article in Article.objects.dates('pub_date', 'day', order='DESC').iterator(): dates.append(article) self.assertEqual(dates, [ datetime(2005, 7, 31, 0, 0), datetime(2005, 7, 30, 0, 0), datetime(2005, 7, 29, 0, 0), datetime(2005, 7, 28, 0, 0)]) # You can combine queries with & and |. s1 = Article.objects.filter(id__exact=a.id) s2 = Article.objects.filter(id__exact=a2.id) self.assertQuerysetEqual(s1 | s2, ["<Article: Area man programs in Python>", "<Article: Second article>"]) self.assertQuerysetEqual(s1 & s2, []) # You can get the number of objects like this: self.assertEqual(len(Article.objects.filter(id__exact=a.id)), 1) # You can get items using index and slice notation. self.assertEqual(Article.objects.all()[0], a) self.assertQuerysetEqual(Article.objects.all()[1:3], ["<Article: Second article>", "<Article: Third article>"]) s3 = Article.objects.filter(id__exact=a3.id) self.assertQuerysetEqual((s1 | s2 | s3)[::2], ["<Article: Area man programs in Python>", "<Article: Third article>"]) # Slicing works with longs. self.assertEqual(Article.objects.all()[0L], a) self.assertQuerysetEqual(Article.objects.all()[1L:3L], ["<Article: Second article>", "<Article: Third article>"]) self.assertQuerysetEqual((s1 | s2 | s3)[::2L], ["<Article: Area man programs in Python>", "<Article: Third article>"]) # And can be mixed with ints. self.assertQuerysetEqual(Article.objects.all()[1:3L], ["<Article: Second article>", "<Article: Third article>"]) # Slices (without step) are lazy: self.assertQuerysetEqual(Article.objects.all()[0:5].filter(), ["<Article: Area man programs in Python>", "<Article: Second article>", "<Article: Third article>", "<Article: Article 6>", "<Article: Default headline>"]) # Slicing again works: self.assertQuerysetEqual(Article.objects.all()[0:5][0:2], ["<Article: Area man programs in Python>", "<Article: Second article>"]) self.assertQuerysetEqual(Article.objects.all()[0:5][:2], ["<Article: Area man programs in Python>", "<Article: Second article>"]) self.assertQuerysetEqual(Article.objects.all()[0:5][4:], ["<Article: Default headline>"]) self.assertQuerysetEqual(Article.objects.all()[0:5][5:], []) # Some more tests! self.assertQuerysetEqual(Article.objects.all()[2:][0:2], ["<Article: Third article>", "<Article: Article 6>"]) self.assertQuerysetEqual(Article.objects.all()[2:][:2], ["<Article: Third article>", "<Article: Article 6>"]) self.assertQuerysetEqual(Article.objects.all()[2:][2:3], ["<Article: Default headline>"]) # Using an offset without a limit is also possible. self.assertQuerysetEqual(Article.objects.all()[5:], ["<Article: Fourth article>", "<Article: Article 7>", "<Article: Updated article 8>"]) # Also, once you have sliced you can't filter, re-order or combine self.assertRaisesErrorWithMessage( AssertionError, "Cannot filter a query once a slice has been taken.", Article.objects.all()[0:5].filter, id=a.id, ) self.assertRaisesErrorWithMessage( AssertionError, "Cannot reorder a query once a slice has been taken.", Article.objects.all()[0:5].order_by, 'id', ) try: Article.objects.all()[0:1] & Article.objects.all()[4:5] self.fail('Should raise an AssertionError') except AssertionError, e: self.assertEqual(str(e), "Cannot combine queries once a slice has been taken.") except Exception, e: self.fail('Should raise an AssertionError, not %s' % e) # Negative slices are not supported, due to database constraints. # (hint: inverting your ordering might do what you need). try: Article.objects.all()[-1] self.fail('Should raise an AssertionError') except AssertionError, e: self.assertEqual(str(e), "Negative indexing is not supported.") except Exception, e: self.fail('Should raise an AssertionError, not %s' % e) error = None try: Article.objects.all()[0:-5] except Exception, e: error = e self.assertTrue(isinstance(error, AssertionError)) self.assertEqual(str(error), "Negative indexing is not supported.") # An Article instance doesn't have access to the "objects" attribute. # That's only available on the class. self.assertRaisesErrorWithMessage( AttributeError, "Manager isn't accessible via Article instances", getattr, a7, "objects", ) # Bulk delete test: How many objects before and after the delete? self.assertQuerysetEqual(Article.objects.all(), ["<Article: Area man programs in Python>", "<Article: Second article>", "<Article: Third article>", "<Article: Article 6>", "<Article: Default headline>", "<Article: Fourth article>", "<Article: Article 7>", "<Article: Updated article 8>"]) Article.objects.filter(id__lte=a4.id).delete() self.assertQuerysetEqual(Article.objects.all(), ["<Article: Article 6>", "<Article: Default headline>", "<Article: Article 7>", "<Article: Updated article 8>"]) if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'].startswith('django.db.backends.postgresql'): def test_microsecond_precision(self): # In PostgreSQL, microsecond-level precision is available. a9 = Article( headline='Article 9', pub_date=datetime(2005, 7, 31, 12, 30, 45, 180), ) a9.save() self.assertEqual(Article.objects.get(pk=a9.pk).pub_date, datetime(2005, 7, 31, 12, 30, 45, 180)) if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.mysql': def test_microsecond_precision_not_supported(self): # In MySQL, microsecond-level precision isn't available. You'll lose # microsecond-level precision once the data is saved. a9 = Article( headline='Article 9', pub_date=datetime(2005, 7, 31, 12, 30, 45, 180), ) a9.save() self.assertEqual(Article.objects.get(id__exact=a9.id).pub_date, datetime(2005, 7, 31, 12, 30, 45)) def test_manually_specify_primary_key(self): # You can manually specify the primary key when creating a new object. a101 = Article( id=101, headline='Article 101', pub_date=datetime(2005, 7, 31, 12, 30, 45), ) a101.save() a101 = Article.objects.get(pk=101) self.assertEqual(a101.headline, u'Article 101') def test_create_method(self): # You can create saved objects in a single step a10 = Article.objects.create( headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45), ) self.assertEqual(Article.objects.get(headline="Article 10"), a10) def test_year_lookup_edge_case(self): # Edge-case test: A year lookup should retrieve all objects in # the given year, including Jan. 1 and Dec. 31. a11 = Article.objects.create( headline='Article 11', pub_date=datetime(2008, 1, 1), ) a12 = Article.objects.create( headline='Article 12', pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999), ) self.assertQuerysetEqual(Article.objects.filter(pub_date__year=2008), ["<Article: Article 11>", "<Article: Article 12>"]) def test_unicode_data(self): # Unicode data works, too. a = Article( headline=u'\u6797\u539f \u3081\u3050\u307f', pub_date=datetime(2005, 7, 28), ) a.save() self.assertEqual(Article.objects.get(pk=a.id).headline, u'\u6797\u539f \u3081\u3050\u307f') def test_hash_function(self): # Model instances have a hash function, so they can be used in sets # or as dictionary keys. Two models compare as equal if their primary # keys are equal. a10 = Article.objects.create( headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45), ) a11 = Article.objects.create( headline='Article 11', pub_date=datetime(2008, 1, 1), ) a12 = Article.objects.create( headline='Article 12', pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999), ) s = set([a10, a11, a12]) self.assertTrue(Article.objects.get(headline='Article 11') in s) def test_extra_method_select_argument_with_dashes_and_values(self): # The 'select' argument to extra() supports names with dashes in # them, as long as you use values(). a10 = Article.objects.create( headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45), ) a11 = Article.objects.create( headline='Article 11', pub_date=datetime(2008, 1, 1), ) a12 = Article.objects.create( headline='Article 12', pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999), ) dicts = Article.objects.filter( pub_date__year=2008).extra( select={'dashed-value': '1'} ).values('headline', 'dashed-value') self.assertEqual([sorted(d.items()) for d in dicts], [[('dashed-value', 1), ('headline', u'Article 11')], [('dashed-value', 1), ('headline', u'Article 12')]]) def test_extra_method_select_argument_with_dashes(self): # If you use 'select' with extra() and names containing dashes on a # query that's *not* a values() query, those extra 'select' values # will silently be ignored. a10 = Article.objects.create( headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45), ) a11 = Article.objects.create( headline='Article 11', pub_date=datetime(2008, 1, 1), ) a12 = Article.objects.create( headline='Article 12', pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999), ) articles = Article.objects.filter( pub_date__year=2008).extra( select={'dashed-value': '1', 'undashedvalue': '2'}) self.assertEqual(articles[0].undashedvalue, 2)
22,120
Python
.py
488
34.606557
117
0.590315
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,282
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/many_to_one_null/models.py
""" 16. Many-to-one relationships that can be null To define a many-to-one relationship that can have a null foreign key, use ``ForeignKey()`` with ``null=True`` . """ from django.db import models class Reporter(models.Model): name = models.CharField(max_length=30) def __unicode__(self): return self.name class Article(models.Model): headline = models.CharField(max_length=100) reporter = models.ForeignKey(Reporter, null=True) class Meta: ordering = ('headline',) def __unicode__(self): return self.headline
565
Python
.py
17
29
74
0.700555
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,283
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/many_to_one_null/tests.py
from django.test import TestCase from models import Reporter, Article class ManyToOneNullTests(TestCase): def setUp(self): # Create a Reporter. self.r = Reporter(name='John Smith') self.r.save() # Create an Article. self.a = Article(headline="First", reporter=self.r) self.a.save() # Create an Article via the Reporter object. self.a2 = self.r.article_set.create(headline="Second") # Create an Article with no Reporter by passing "reporter=None". self.a3 = Article(headline="Third", reporter=None) self.a3.save() # Create another article and reporter self.r2 = Reporter(name='Paul Jones') self.r2.save() self.a4 = self.r2.article_set.create(headline='Fourth') def test_get_related(self): self.assertEqual(self.a.reporter.id, self.r.id) # Article objects have access to their related Reporter objects. r = self.a.reporter self.assertEqual(r.id, self.r.id) def test_created_via_related_set(self): self.assertEqual(self.a2.reporter.id, self.r.id) def test_related_set(self): # Reporter objects have access to their related Article objects. self.assertQuerysetEqual(self.r.article_set.all(), ['<Article: First>', '<Article: Second>']) self.assertQuerysetEqual(self.r.article_set.filter(headline__startswith='Fir'), ['<Article: First>']) self.assertEqual(self.r.article_set.count(), 2) def test_created_without_related(self): self.assertEqual(self.a3.reporter, None) # Need to reget a3 to refresh the cache a3 = Article.objects.get(pk=self.a3.pk) self.assertRaises(AttributeError, getattr, a3.reporter, 'id') # Accessing an article's 'reporter' attribute returns None # if the reporter is set to None. self.assertEqual(a3.reporter, None) # To retrieve the articles with no reporters set, use "reporter__isnull=True". self.assertQuerysetEqual(Article.objects.filter(reporter__isnull=True), ['<Article: Third>']) # We can achieve the same thing by filtering for the case where the # reporter is None. self.assertQuerysetEqual(Article.objects.filter(reporter=None), ['<Article: Third>']) # Set the reporter for the Third article self.assertQuerysetEqual(self.r.article_set.all(), ['<Article: First>', '<Article: Second>']) self.r.article_set.add(a3) self.assertQuerysetEqual(self.r.article_set.all(), ['<Article: First>', '<Article: Second>', '<Article: Third>']) # Remove an article from the set, and check that it was removed. self.r.article_set.remove(a3) self.assertQuerysetEqual(self.r.article_set.all(), ['<Article: First>', '<Article: Second>']) self.assertQuerysetEqual(Article.objects.filter(reporter__isnull=True), ['<Article: Third>']) def test_remove_from_wrong_set(self): self.assertQuerysetEqual(self.r2.article_set.all(), ['<Article: Fourth>']) # Try to remove a4 from a set it does not belong to self.assertRaises(Reporter.DoesNotExist, self.r.article_set.remove, self.a4) self.assertQuerysetEqual(self.r2.article_set.all(), ['<Article: Fourth>']) def test_assign_clear_related_set(self): # Use descriptor assignment to allocate ForeignKey. Null is legal, so # existing members of set that are not in the assignment set are set null self.r2.article_set = [self.a2, self.a3] self.assertQuerysetEqual(self.r2.article_set.all(), ['<Article: Second>', '<Article: Third>']) # Clear the rest of the set self.r.article_set.clear() self.assertQuerysetEqual(self.r.article_set.all(), []) self.assertQuerysetEqual(Article.objects.filter(reporter__isnull=True), ['<Article: First>', '<Article: Fourth>'])
4,174
Python
.py
76
43.763158
87
0.627139
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,284
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/custom_methods/models.py
""" 3. Giving models custom methods Any method you add to a model will be available to instances. """ from django.db import models import datetime class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() def __unicode__(self): return self.headline def was_published_today(self): return self.pub_date == datetime.date.today() def articles_from_same_day_1(self): return Article.objects.filter(pub_date=self.pub_date).exclude(id=self.id) def articles_from_same_day_2(self): """ Verbose version of get_articles_from_same_day_1, which does a custom database query for the sake of demonstration. """ from django.db import connection cursor = connection.cursor() cursor.execute(""" SELECT id, headline, pub_date FROM custom_methods_article WHERE pub_date = %s AND id != %s""", [connection.ops.value_to_db_date(self.pub_date), self.id]) return [self.__class__(*row) for row in cursor.fetchall()]
1,139
Python
.py
29
31.206897
81
0.635539
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,285
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/custom_methods/tests.py
from datetime import date from django.test import TestCase from models import Article class MethodsTests(TestCase): def test_custom_methods(self): a = Article.objects.create( headline="Area man programs in Python", pub_date=date(2005, 7, 27) ) b = Article.objects.create( headline="Beatles reunite", pub_date=date(2005, 7, 27) ) self.assertFalse(a.was_published_today()) self.assertQuerysetEqual( a.articles_from_same_day_1(), [ "Beatles reunite", ], lambda a: a.headline, ) self.assertQuerysetEqual( a.articles_from_same_day_2(), [ "Beatles reunite", ], lambda a: a.headline ) self.assertQuerysetEqual( b.articles_from_same_day_1(), [ "Area man programs in Python", ], lambda a: a.headline, ) self.assertQuerysetEqual( b.articles_from_same_day_2(), [ "Area man programs in Python", ], lambda a: a.headline )
1,155
Python
.py
36
21.472222
78
0.539084
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,286
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/field_subclassing/models.py
""" Tests for field subclassing. """ from django.db import models from django.utils.encoding import force_unicode from fields import Small, SmallField, SmallerField, JSONField class MyModel(models.Model): name = models.CharField(max_length=10) data = SmallField('small field') def __unicode__(self): return force_unicode(self.name) class OtherModel(models.Model): data = SmallerField() class DataModel(models.Model): data = JSONField()
471
Python
.py
15
28.066667
61
0.752784
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,287
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/field_subclassing/tests.py
from django.core import serializers from django.test import TestCase from fields import Small from models import DataModel, MyModel, OtherModel class CustomField(TestCase): def test_defer(self): d = DataModel.objects.create(data=[1, 2, 3]) self.assertTrue(isinstance(d.data, list)) d = DataModel.objects.get(pk=d.pk) self.assertTrue(isinstance(d.data, list)) self.assertEqual(d.data, [1, 2, 3]) d = DataModel.objects.defer("data").get(pk=d.pk) d.save() d = DataModel.objects.get(pk=d.pk) self.assertTrue(isinstance(d.data, list)) self.assertEqual(d.data, [1, 2, 3]) def test_custom_field(self): # Creating a model with custom fields is done as per normal. s = Small(1, 2) self.assertEqual(str(s), "12") m = MyModel.objects.create(name="m", data=s) # Custom fields still have normal field's attributes. self.assertEqual(m._meta.get_field("data").verbose_name, "small field") # The m.data attribute has been initialised correctly. It's a Small # object. self.assertEqual((m.data.first, m.data.second), (1, 2)) # The data loads back from the database correctly and 'data' has the # right type. m1 = MyModel.objects.get(pk=m.pk) self.assertTrue(isinstance(m1.data, Small)) self.assertEqual(str(m1.data), "12") # We can do normal filtering on the custom field (and will get an error # when we use a lookup type that does not make sense). s1 = Small(1, 3) s2 = Small("a", "b") self.assertQuerysetEqual( MyModel.objects.filter(data__in=[s, s1, s2]), [ "m", ], lambda m: m.name, ) self.assertRaises(TypeError, lambda: MyModel.objects.filter(data__lt=s)) # Serialization works, too. stream = serializers.serialize("json", MyModel.objects.all()) self.assertEqual(stream, '[{"pk": 1, "model": "field_subclassing.mymodel", "fields": {"data": "12", "name": "m"}}]') obj = list(serializers.deserialize("json", stream))[0] self.assertEqual(obj.object, m) # Test retrieving custom field data m.delete() m1 = MyModel.objects.create(name="1", data=Small(1, 2)) m2 = MyModel.objects.create(name="2", data=Small(2, 3)) self.assertQuerysetEqual( MyModel.objects.all(), [ "12", "23", ], lambda m: str(m.data) ) def test_field_subclassing(self): o = OtherModel.objects.create(data=Small("a", "b")) o = OtherModel.objects.get() self.assertEqual(o.data.first, "a") self.assertEqual(o.data.second, "b")
2,795
Python
.py
63
35.142857
124
0.605011
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,288
fields.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/field_subclassing/fields.py
from django.core.exceptions import FieldError from django.db import models from django.utils import simplejson as json from django.utils.encoding import force_unicode class Small(object): """ A simple class to show that non-trivial Python objects can be used as attributes. """ def __init__(self, first, second): self.first, self.second = first, second def __unicode__(self): return u'%s%s' % (force_unicode(self.first), force_unicode(self.second)) def __str__(self): return unicode(self).encode('utf-8') class SmallField(models.Field): """ Turns the "Small" class into a Django field. Because of the similarities with normal character fields and the fact that Small.__unicode__ does something sensible, we don't need to implement a lot here. """ __metaclass__ = models.SubfieldBase def __init__(self, *args, **kwargs): kwargs['max_length'] = 2 super(SmallField, self).__init__(*args, **kwargs) def get_internal_type(self): return 'CharField' def to_python(self, value): if isinstance(value, Small): return value return Small(value[0], value[1]) def get_db_prep_save(self, value): return unicode(value) def get_prep_lookup(self, lookup_type, value): if lookup_type == 'exact': return force_unicode(value) if lookup_type == 'in': return [force_unicode(v) for v in value] if lookup_type == 'isnull': return [] raise TypeError('Invalid lookup type: %r' % lookup_type) class SmallerField(SmallField): pass class JSONField(models.TextField): __metaclass__ = models.SubfieldBase description = ("JSONField automatically serializes and desializes values to " "and from JSON.") def to_python(self, value): if not value: return None if isinstance(value, basestring): value = json.loads(value) return value def get_db_prep_save(self, value): if value is None: return None return json.dumps(value)
2,131
Python
.py
57
30.333333
81
0.646087
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,289
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/raw_query/models.py
from django.db import models class Author(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) dob = models.DateField() def __init__(self, *args, **kwargs): super(Author, self).__init__(*args, **kwargs) # Protect against annotations being passed to __init__ -- # this'll make the test suite get angry if annotations aren't # treated differently than fields. for k in kwargs: assert k in [f.attname for f in self._meta.fields], \ "Author.__init__ got an unexpected paramater: %s" % k class Book(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(Author) paperback = models.BooleanField() opening_line = models.TextField() class Coffee(models.Model): brand = models.CharField(max_length=255, db_column="name") class Reviewer(models.Model): reviewed = models.ManyToManyField(Book) class FriendlyAuthor(Author): pass
1,016
Python
.py
24
36.416667
69
0.682556
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,290
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/raw_query/tests.py
from datetime import date from django.conf import settings from django.db import connection from django.db.models.sql.query import InvalidQuery from django.test import TestCase from models import Author, Book, Coffee, Reviewer, FriendlyAuthor class RawQueryTests(TestCase): fixtures = ['raw_query_books.json'] def assertSuccessfulRawQuery(self, model, query, expected_results, expected_annotations=(), params=[], translations=None): """ Execute the passed query against the passed model and check the output """ results = list(model.objects.raw(query, params=params, translations=translations)) self.assertProcessed(model, results, expected_results, expected_annotations) self.assertAnnotations(results, expected_annotations) def assertProcessed(self, model, results, orig, expected_annotations=()): """ Compare the results of a raw query against expected results """ self.assertEqual(len(results), len(orig)) for index, item in enumerate(results): orig_item = orig[index] for annotation in expected_annotations: setattr(orig_item, *annotation) for field in model._meta.fields: # Check that all values on the model are equal self.assertEquals(getattr(item,field.attname), getattr(orig_item,field.attname)) # This includes checking that they are the same type self.assertEquals(type(getattr(item,field.attname)), type(getattr(orig_item,field.attname))) def assertNoAnnotations(self, results): """ Check that the results of a raw query contain no annotations """ self.assertAnnotations(results, ()) def assertAnnotations(self, results, expected_annotations): """ Check that the passed raw query results contain the expected annotations """ if expected_annotations: for index, result in enumerate(results): annotation, value = expected_annotations[index] self.assertTrue(hasattr(result, annotation)) self.assertEqual(getattr(result, annotation), value) def assert_num_queries(self, n, func, *args, **kwargs): old_DEBUG = settings.DEBUG settings.DEBUG = True starting_queries = len(connection.queries) try: func(*args, **kwargs) finally: settings.DEBUG = old_DEBUG self.assertEqual(starting_queries + n, len(connection.queries)) def testSimpleRawQuery(self): """ Basic test of raw query with a simple database query """ query = "SELECT * FROM raw_query_author" authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors) def testRawQueryLazy(self): """ Raw queries are lazy: they aren't actually executed until they're iterated over. """ q = Author.objects.raw('SELECT * FROM raw_query_author') self.assert_(q.query.cursor is None) list(q) self.assert_(q.query.cursor is not None) def testFkeyRawQuery(self): """ Test of a simple raw query against a model containing a foreign key """ query = "SELECT * FROM raw_query_book" books = Book.objects.all() self.assertSuccessfulRawQuery(Book, query, books) def testDBColumnHandler(self): """ Test of a simple raw query against a model containing a field with db_column defined. """ query = "SELECT * FROM raw_query_coffee" coffees = Coffee.objects.all() self.assertSuccessfulRawQuery(Coffee, query, coffees) def testOrderHandler(self): """ Test of raw raw query's tolerance for columns being returned in any order """ selects = ( ('dob, last_name, first_name, id'), ('last_name, dob, first_name, id'), ('first_name, last_name, dob, id'), ) for select in selects: query = "SELECT %s FROM raw_query_author" % select authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors) def testTranslations(self): """ Test of raw query's optional ability to translate unexpected result column names to specific model fields """ query = "SELECT first_name AS first, last_name AS last, dob, id FROM raw_query_author" translations = {'first': 'first_name', 'last': 'last_name'} authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors, translations=translations) def testParams(self): """ Test passing optional query parameters """ query = "SELECT * FROM raw_query_author WHERE first_name = %s" author = Author.objects.all()[2] params = [author.first_name] results = list(Author.objects.raw(query, params=params)) self.assertProcessed(Author, results, [author]) self.assertNoAnnotations(results) self.assertEqual(len(results), 1) def testManyToMany(self): """ Test of a simple raw query against a model containing a m2m field """ query = "SELECT * FROM raw_query_reviewer" reviewers = Reviewer.objects.all() self.assertSuccessfulRawQuery(Reviewer, query, reviewers) def testExtraConversions(self): """ Test to insure that extra translations are ignored. """ query = "SELECT * FROM raw_query_author" translations = {'something': 'else'} authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors, translations=translations) def testMissingFields(self): query = "SELECT id, first_name, dob FROM raw_query_author" for author in Author.objects.raw(query): self.assertNotEqual(author.first_name, None) # last_name isn't given, but it will be retrieved on demand self.assertNotEqual(author.last_name, None) def testMissingFieldsWithoutPK(self): query = "SELECT first_name, dob FROM raw_query_author" try: list(Author.objects.raw(query)) self.fail('Query without primary key should fail') except InvalidQuery: pass def testAnnotations(self): query = "SELECT a.*, count(b.id) as book_count FROM raw_query_author a LEFT JOIN raw_query_book b ON a.id = b.author_id GROUP BY a.id, a.first_name, a.last_name, a.dob ORDER BY a.id" expected_annotations = ( ('book_count', 3), ('book_count', 0), ('book_count', 1), ('book_count', 0), ) authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors, expected_annotations) def testInvalidQuery(self): query = "UPDATE raw_query_author SET first_name='thing' WHERE first_name='Joe'" self.assertRaises(InvalidQuery, Author.objects.raw, query) def testWhiteSpaceQuery(self): query = " SELECT * FROM raw_query_author" authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors) def testMultipleIterations(self): query = "SELECT * FROM raw_query_author" normal_authors = Author.objects.all() raw_authors = Author.objects.raw(query) # First Iteration first_iterations = 0 for index, raw_author in enumerate(raw_authors): self.assertEqual(normal_authors[index], raw_author) first_iterations += 1 # Second Iteration second_iterations = 0 for index, raw_author in enumerate(raw_authors): self.assertEqual(normal_authors[index], raw_author) second_iterations += 1 self.assertEqual(first_iterations, second_iterations) def testGetItem(self): # Indexing on RawQuerySets query = "SELECT * FROM raw_query_author ORDER BY id ASC" third_author = Author.objects.raw(query)[2] self.assertEqual(third_author.first_name, 'Bob') first_two = Author.objects.raw(query)[0:2] self.assertEquals(len(first_two), 2) self.assertRaises(TypeError, lambda: Author.objects.raw(query)['test']) def test_inheritance(self): # date is the end of the Cuban Missile Crisis, I have no idea when # Wesley was bron f = FriendlyAuthor.objects.create(first_name="Wesley", last_name="Chun", dob=date(1962, 10, 28)) query = "SELECT * FROM raw_query_friendlyauthor" self.assertEqual( [o.pk for o in FriendlyAuthor.objects.raw(query)], [f.pk] ) def test_query_count(self): self.assert_num_queries(1, list, Author.objects.raw("SELECT * FROM raw_query_author") )
9,056
Python
.py
202
35.247525
190
0.636395
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,291
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/str/models.py
# -*- coding: utf-8 -*- """ 2. Adding __str__() or __unicode__() to models Although it's not a strict requirement, each model should have a ``_str__()`` or ``__unicode__()`` method to return a "human-readable" representation of the object. Do this not only for your own sanity when dealing with the interactive prompt, but also because objects' representations are used throughout Django's automatically-generated admin. Normally, you should write ``__unicode__()`` method, since this will work for all field types (and Django will automatically provide an appropriate ``__str__()`` method). However, you can write a ``__str__()`` method directly, if you prefer. You must be careful to encode the results correctly, though. """ from django.db import models class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateTimeField() def __str__(self): # Caution: this is only safe if you are certain that headline will be # in ASCII. return self.headline class InternationalArticle(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateTimeField() def __unicode__(self): return self.headline
1,213
Python
.py
26
43.269231
79
0.719729
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,292
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/str/tests.py
# -*- coding: utf-8 -*- import datetime from django.test import TestCase from models import Article, InternationalArticle class SimpleTests(TestCase): def test_basic(self): a = Article.objects.create( headline='Area man programs in Python', pub_date=datetime.datetime(2005, 7, 28) ) self.assertEqual(str(a), 'Area man programs in Python') self.assertEqual(repr(a), '<Article: Area man programs in Python>') def test_international(self): a = InternationalArticle.objects.create( headline=u'Girl wins €12.500 in lottery', pub_date=datetime.datetime(2005, 7, 28) ) # The default str() output will be the UTF-8 encoded output of __unicode__(). self.assertEqual(str(a), 'Girl wins \xe2\x82\xac12.500 in lottery')
834
Python
.py
19
36.368421
85
0.656404
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,293
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/force_insert_update/models.py
""" Tests for forcing insert and update queries (instead of Django's normal automatic behaviour). """ from django.db import models, transaction, IntegrityError class Counter(models.Model): name = models.CharField(max_length = 10) value = models.IntegerField() class WithCustomPK(models.Model): name = models.IntegerField(primary_key=True) value = models.IntegerField()
387
Python
.py
11
32.545455
71
0.772727
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,294
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/force_insert_update/tests.py
from django.db import transaction, IntegrityError, DatabaseError from django.test import TestCase from models import Counter, WithCustomPK class ForceTests(TestCase): def test_force_update(self): c = Counter.objects.create(name="one", value=1) # The normal case c.value = 2 c.save() # Same thing, via an update c.value = 3 c.save(force_update=True) # Won't work because force_update and force_insert are mutually # exclusive c.value = 4 self.assertRaises(ValueError, c.save, force_insert=True, force_update=True) # Try to update something that doesn't have a primary key in the first # place. c1 = Counter(name="two", value=2) self.assertRaises(ValueError, c1.save, force_update=True) c1.save(force_insert=True) # Won't work because we can't insert a pk of the same value. sid = transaction.savepoint() c.value = 5 self.assertRaises(IntegrityError, c.save, force_insert=True) transaction.savepoint_rollback(sid) # Trying to update should still fail, even with manual primary keys, if # the data isn't in the database already. obj = WithCustomPK(name=1, value=1) self.assertRaises(DatabaseError, obj.save, force_update=True)
1,336
Python
.py
30
36.466667
83
0.667951
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,295
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/choices/models.py
""" 21. Specifying 'choices' for a field Most fields take a ``choices`` parameter, which should be a tuple of tuples specifying which are the valid values for that field. For each field that has ``choices``, a model instance gets a ``get_fieldname_display()`` method, where ``fieldname`` is the name of the field. This method returns the "human-readable" value of the field. """ from django.db import models GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) class Person(models.Model): name = models.CharField(max_length=20) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) def __unicode__(self): return self.name
666
Python
.py
18
34.111111
75
0.718069
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,296
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/choices/tests.py
from django.test import TestCase from models import Person class ChoicesTests(TestCase): def test_display(self): a = Person.objects.create(name='Adrian', gender='M') s = Person.objects.create(name='Sara', gender='F') self.assertEqual(a.gender, 'M') self.assertEqual(s.gender, 'F') self.assertEqual(a.get_gender_display(), 'Male') self.assertEqual(s.get_gender_display(), 'Female') # If the value for the field doesn't correspond to a valid choice, # the value itself is provided as a display value. a.gender = '' self.assertEqual(a.get_gender_display(), '') a.gender = 'U' self.assertEqual(a.get_gender_display(), 'U')
742
Python
.py
16
37.6875
74
0.647226
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,297
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/order_with_respect_to/models.py
""" Tests for the order_with_respect_to Meta attribute. """ from django.db import models class Question(models.Model): text = models.CharField(max_length=200) class Answer(models.Model): text = models.CharField(max_length=200) question = models.ForeignKey(Question) class Meta: order_with_respect_to = 'question' def __unicode__(self): return unicode(self.text) class Post(models.Model): title = models.CharField(max_length=200) parent = models.ForeignKey("self", related_name="children", null=True) class Meta: order_with_respect_to = "parent" def __unicode__(self): return self.title
663
Python
.py
20
28.3
74
0.698738
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,298
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/order_with_respect_to/tests.py
from operator import attrgetter from django.test import TestCase from models import Post, Question, Answer class OrderWithRespectToTests(TestCase): def test_basic(self): q1 = Question.objects.create(text="Which Beatle starts with the letter 'R'?") q2 = Question.objects.create(text="What is your name?") Answer.objects.create(text="John", question=q1) Answer.objects.create(text="Jonno", question=q2) Answer.objects.create(text="Paul", question=q1) Answer.objects.create(text="Paulo", question=q2) Answer.objects.create(text="George", question=q1) Answer.objects.create(text="Ringo", question=q1) # The answers will always be ordered in the order they were inserted. self.assertQuerysetEqual( q1.answer_set.all(), [ "John", "Paul", "George", "Ringo", ], attrgetter("text"), ) # We can retrieve the answers related to a particular object, in the # order they were created, once we have a particular object. a1 = Answer.objects.filter(question=q1)[0] self.assertEqual(a1.text, "John") a2 = a1.get_next_in_order() self.assertEqual(a2.text, "Paul") a4 = list(Answer.objects.filter(question=q1))[-1] self.assertEqual(a4.text, "Ringo") self.assertEqual(a4.get_previous_in_order().text, "George") # Determining (and setting) the ordering for a particular item is also # possible. id_list = [o.pk for o in q1.answer_set.all()] self.assertEqual(a2.question.get_answer_order(), id_list) a5 = Answer.objects.create(text="Number five", question=q1) # It doesn't matter which answer we use to check the order, it will # always be the same. self.assertEqual( a2.question.get_answer_order(), a5.question.get_answer_order() ) # The ordering can be altered: id_list = [o.pk for o in q1.answer_set.all()] x = id_list.pop() id_list.insert(-1, x) self.assertNotEqual(a5.question.get_answer_order(), id_list) a5.question.set_answer_order(id_list) self.assertQuerysetEqual( q1.answer_set.all(), [ "John", "Paul", "George", "Number five", "Ringo" ], attrgetter("text") ) def test_recursive_ordering(self): p1 = Post.objects.create(title='1') p2 = Post.objects.create(title='2') p1_1 = Post.objects.create(title="1.1", parent=p1) p1_2 = Post.objects.create(title="1.2", parent=p1) p2_1 = Post.objects.create(title="2.1", parent=p2) p1_3 = Post.objects.create(title="1.3", parent=p1) self.assertEqual(p1.get_post_order(), [p1_1.pk, p1_2.pk, p1_3.pk])
2,870
Python
.py
59
38.423729
85
0.62304
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
3,299
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/modeltests/proxy_model_inheritance/tests.py
""" XX. Proxy model inheritance Proxy model inheritance across apps can result in syncdb not creating the table for the proxied model (as described in #12286). This test creates two dummy apps and calls syncdb, then verifies that the table has been created. """ import os import sys from django.conf import settings, Settings from django.core.management import call_command from django.db.models.loading import load_app from django.test import TransactionTestCase class ProxyModelInheritanceTests(TransactionTestCase): def setUp(self): self.old_sys_path = sys.path[:] sys.path.append(os.path.dirname(os.path.abspath(__file__))) self.old_installed_apps = settings.INSTALLED_APPS settings.INSTALLED_APPS = ('app1', 'app2') map(load_app, settings.INSTALLED_APPS) call_command('syncdb', verbosity=0) global ProxyModel, NiceModel from app1.models import ProxyModel from app2.models import NiceModel def tearDown(self): settings.INSTALLED_APPS = self.old_installed_apps sys.path = self.old_sys_path def test_table_exists(self): self.assertEquals(NiceModel.objects.all().count(), 0) self.assertEquals(ProxyModel.objects.all().count(), 0)
1,255
Python
.py
29
38.034483
79
0.735029
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)