id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
2,900
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/it/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'd F Y' # 25 Ottobre 2006 TIME_FORMAT = 'H:i:s' # 14:30:59 DATETIME_FORMAT = 'l d F Y H:i:s' # Mercoledì 25 Ottobre 2006 14:30:59 YEAR_MONTH_FORMAT = 'F Y' # Ottobre 2006 MONTH_DAY_FORMAT = 'j/F' # 10/2006 SHORT_DATE_FORMAT = 'd/M/Y' # 25/12/2009 SHORT_DATETIME_FORMAT = 'd/M/Y H:i:s' # 25/10/2009 14:30:59 FIRST_DAY_OF_WEEK = 1 # Lunedì # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%Y/%m/%d', # '2008-10-25', '2008/10/25' '%d-%m-%Y', '%d/%m/%Y', # '25-10-2006', '25/10/2006' '%d-%m-%y', '%d/%m/%y', # '25-10-06', '25/10/06' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%d-%m-%Y %H:%M:%S', # '25-10-2006 14:30:59' '%d-%m-%Y %H:%M', # '25-10-2006 14:30' '%d-%m-%Y', # '25-10-2006' '%d-%m-%y %H:%M:%S', # '25-10-06 14:30:59' '%d-%m-%y %H:%M', # '25-10-06 14:30' '%d-%m-%y', # '25-10-06' '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%Y', # '25/10/2006' '%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59' '%d/%m/%y %H:%M', # '25/10/06 14:30' '%d/%m/%y', # '25/10/06' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
1,838
Python
.py
44
38.863636
77
0.515084
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,901
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/zh_TW/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date # DATE_FORMAT = # TIME_FORMAT = # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = # MONTH_DAY_FORMAT = # SHORT_DATE_FORMAT = # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = # DECIMAL_SEPARATOR = # THOUSAND_SEPARATOR = # NUMBER_GROUPING =
697
Python
.py
21
31.428571
77
0.737389
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,902
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/fa/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F Y' TIME_FORMAT = 'G:i:s' DATETIME_FORMAT = 'j F Y، ساعت G:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'Y/n/j' SHORT_DATETIME_FORMAT = 'Y/n/j،‏ G:i:s' # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
758
Python
.py
21
34.380952
77
0.723521
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,903
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/lv/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = r'Y. \g\a\d\a j. F' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = r'Y. \g\a\d\a j. F, H:i:s' YEAR_MONTH_FORMAT = r'Y. \g. F' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = r'j.m.Y' SHORT_DATETIME_FORMAT = 'j.m.Y H:i:s' FIRST_DAY_OF_WEEK = 1 #Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' '%H.%M.%S', # '14.30.59' '%H.%M', # '14.30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%d.%m.%y %H:%M', # '25.10.06 14:30' '%d.%m.%y %H.%M.%S', # '25.10.06 14.30.59' '%d.%m.%y %H.%M', # '25.10.06 14.30' '%d.%m.%y', # '25.10.06' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = u' ' # Non-breaking space NUMBER_GROUPING = 3
1,490
Python
.py
39
35.615385
80
0.539683
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,904
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/nb/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06' '%Y-%m-%d', # '2006-10-25', # '%d. %b %Y', '%d %b %Y', # '25. okt 2006', '25 okt 2006' # '%d. %b. %Y', '%d %b. %Y', # '25. okt. 2006', '25 okt. 2006' # '%d. %B %Y', '%d %B %Y', # '25. oktober 2006', '25 oktober 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%Y-%m-%d', # '2006-10-25' '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%d.%m.%y %H:%M', # '25.10.06 14:30' '%d.%m.%y', # '25.10.06' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' NUMBER_GROUPING = 3
1,657
Python
.py
41
37.707317
81
0.503717
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,905
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/mn/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'd F Y' TIME_FORMAT = 'g:i:s A' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = # MONTH_DAY_FORMAT = SHORT_DATE_FORMAT = 'j M Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = # DECIMAL_SEPARATOR = # THOUSAND_SEPARATOR = # NUMBER_GROUPING =
703
Python
.py
21
32.380952
77
0.745588
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,906
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/ar/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F، Y' TIME_FORMAT = 'g:i:s A' # DATETIME_FORMAT = YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd‏/m‏/Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
730
Python
.py
21
33.095238
77
0.72792
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,907
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/pt/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = r'j \de F \de Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = r'j \de F \de Y à\s H:i' YEAR_MONTH_FORMAT = r'F \de Y' MONTH_DAY_FORMAT = r'j \de F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y H:i' FIRST_DAY_OF_WEEK = 0 # Sunday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%d/%m/%Y', '%d/%m/%y', # '2006-10-25', '25/10/2006', '25/10/06' # '%d de %b de %Y', '%d de %b, %Y', # '25 de Out de 2006', '25 Out, 2006' # '%d de %B de %Y', '%d de %B, %Y', # '25 de Outubro de 2006', '25 de Outubro, 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%Y', # '25/10/2006' '%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59' '%d/%m/%y %H:%M', # '25/10/06 14:30' '%d/%m/%y', # '25/10/06' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
1,532
Python
.py
38
37.789474
90
0.541555
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,908
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/he/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j בF Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = 'j בF Y H:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j בF' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y H:i:s' # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' # NUMBER_GROUPING =
748
Python
.py
21
34.142857
77
0.727147
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,909
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/mk/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'd F Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = 'j. F Y. H:i' YEAR_MONTH_FORMAT = 'F Y.' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'j.m.Y.' SHORT_DATETIME_FORMAT = 'j.m.Y. H:i' FIRST_DAY_OF_WEEK = 1 # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%d.%m.%Y.', '%d.%m.%y.', # '25.10.2006.', '25.10.06.' '%d. %m. %Y.', '%d. %m. %y.', # '25. 10. 2006.', '25. 10. 06.' '%Y-%m-%d', # '2006-10-25' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y. %H:%M:%S', # '25.10.2006. 14:30:59' '%d.%m.%Y. %H:%M', # '25.10.2006. 14:30' '%d.%m.%Y.', # '25.10.2006.' '%d.%m.%y. %H:%M:%S', # '25.10.06. 14:30:59' '%d.%m.%y. %H:%M', # '25.10.06. 14:30' '%d.%m.%y.', # '25.10.06.' '%d. %m. %Y. %H:%M:%S', # '25. 10. 2006. 14:30:59' '%d. %m. %Y. %H:%M', # '25. 10. 2006. 14:30' '%d. %m. %Y.', # '25. 10. 2006.' '%d. %m. %y. %H:%M:%S', # '25. 10. 06. 14:30:59' '%d. %m. %y. %H:%M', # '25. 10. 06. 14:30' '%d. %m. %y.', # '25. 10. 06.' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
1,758
Python
.py
44
37.022727
77
0.477472
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,910
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/nn/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06' '%Y-%m-%d', # '2006-10-25', # '%d. %b %Y', '%d %b %Y', # '25. okt 2006', '25 okt 2006' # '%d. %b. %Y', '%d %b. %Y', # '25. okt. 2006', '25 okt. 2006' # '%d. %B %Y', '%d %B %Y', # '25. oktober 2006', '25 oktober 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%Y-%m-%d', # '2006-10-25' '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%d.%m.%y %H:%M', # '25.10.06 14:30' '%d.%m.%y', # '25.10.06' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' NUMBER_GROUPING = 3
1,657
Python
.py
41
37.707317
81
0.503717
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,911
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/bn/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F, Y' TIME_FORMAT = 'g:i:s A' # DATETIME_FORMAT = YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M, Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' # NUMBER_GROUPING =
724
Python
.py
21
33.047619
77
0.728959
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,912
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/sq/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'd F Y' TIME_FORMAT = 'g.i.s.A' # DATETIME_FORMAT = YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'Y-m-d' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
722
Python
.py
21
32.952381
77
0.731044
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,913
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/vi/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = r'\N\gà\y d \t\há\n\g n \nă\m Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = r'H:i:s \N\gà\y d \t\há\n\g n \nă\m Y' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd-m-Y' SHORT_DATETIME_FORMAT = 'H:i:s d-m-Y' # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
798
Python
.py
21
36.380952
77
0.712614
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,914
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/es_AR/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = r'j N Y' TIME_FORMAT = r'H:i:s' DATETIME_FORMAT = r'j N Y H:i:s' YEAR_MONTH_FORMAT = r'F Y' MONTH_DAY_FORMAT = r'j \de F' SHORT_DATE_FORMAT = r'd/m/Y' SHORT_DATETIME_FORMAT = r'd/m/Y H:i' FIRST_DAY_OF_WEEK = 0 # 0: Sunday, 1: Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%d/%m/%Y', # '31/12/2009' '%d/%m/%y', # '31/12/09' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d/%m/%Y %H:%M:%S', '%d/%m/%Y %H:%M', '%d/%m/%y %H:%M:%S', '%d/%m/%y %H:%M', ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
984
Python
.py
32
28.6875
77
0.634737
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,915
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/kn/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F Y' TIME_FORMAT = 'h:i:s A' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = # DECIMAL_SEPARATOR = # THOUSAND_SEPARATOR = # NUMBER_GROUPING =
717
Python
.py
21
32.571429
77
0.733429
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,916
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/cy/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'd F Y' TIME_FORMAT = 'g:i:s A' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = # MONTH_DAY_FORMAT = SHORT_DATE_FORMAT = 'j M Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = # DECIMAL_SEPARATOR = # THOUSAND_SEPARATOR = # NUMBER_GROUPING =
714
Python
.py
21
32.380952
77
0.733719
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,917
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/da/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i' FIRST_DAY_OF_WEEK = 1 # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%d.%m.%Y', # '25.10.2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
1,023
Python
.py
29
33.517241
77
0.58871
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,918
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/id/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j N Y' DATETIME_FORMAT = "j N Y, G.i.s" TIME_FORMAT = 'G.i.s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd-m-Y' SHORT_DATETIME_FORMAT = 'd-m-Y G.i.s' FIRST_DAY_OF_WEEK = 1 #Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%d-%m-%y', '%d/%m/%y', # '25-10-09', 25/10/09' '%d-%m-%Y', '%d/%m/%Y', # '25-10-2009', 25/10/2009' '%d %b %Y', # '25 Oct 2006', '%d %B %Y', # '25 October 2006' ) TIME_INPUT_FORMATS = ( '%H.%M.%S', # '14.30.59' '%H.%M', # '14.30' ) DATETIME_INPUT_FORMATS = ( '%d-%m-%Y %H.%M.%S', # '25-10-2009 14.30.59' '%d-%m-%Y %H.%M', # '25-10-2009 14.30' '%d-%m-%Y', # '25-10-2009' '%d-%m-%y %H.%M.%S', # '25-10-09' 14.30.59' '%d-%m-%y %H.%M', # '25-10-09' 14.30' '%d-%m-%y', # '25-10-09'' '%m/%d/%y %H.%M.%S', # '10/25/06 14.30.59' '%m/%d/%y %H.%M', # '10/25/06 14.30' '%m/%d/%y', # '10/25/06' '%m/%d/%Y %H.%M.%S', # '25/10/2009 14.30.59' '%m/%d/%Y %H.%M', # '25/10/2009 14.30' '%m/%d/%Y', # '10/25/2009' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
1,818
Python
.py
42
40.452381
77
0.44777
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,919
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/uk/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j E Y р.' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = 'j E Y р. H:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = u' ' # NUMBER_GROUPING =
741
Python
.py
21
33.761905
77
0.725874
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,920
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/ga/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F Y' TIME_FORMAT = 'H:i:s' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' # NUMBER_GROUPING =
717
Python
.py
21
32.666667
77
0.731988
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,921
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/en_GB/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'N j, Y' # 'Oct. 25, 2006' TIME_FORMAT = 'P' # '2:30 pm' DATETIME_FORMAT = 'N j, Y, P' # 'Oct. 25, 2006, 2:30 pm' YEAR_MONTH_FORMAT = 'F Y' # 'October 2006' MONTH_DAY_FORMAT = 'F j' # 'October 25' SHORT_DATE_FORMAT = 'd/m/Y' # '25/10/2006' SHORT_DATETIME_FORMAT = 'd/m/Y P' # '25/10/2006 2:30 pm' FIRST_DAY_OF_WEEK = 0 # Sunday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06' '%Y-%m-%d', # '2006-10-25' # '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' # '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' # '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' # '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%Y', # '25/10/2006' '%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59' '%d/%m/%y %H:%M', # '25/10/06 14:30' '%d/%m/%y', # '25/10/06' ) DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
2,048
Python
.py
41
47.219512
79
0.443613
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,922
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/sk/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'G:i:s' DATETIME_FORMAT = 'j. F Y G:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y G:i:s' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%d.%m.%Y', '%d.%m.%y', # '25.10.2006', '25.10.06' '%Y-%m-%d', '%y-%m-%d', # '2006-10-25', '06-10-25' # '%d. %B %Y', '%d. %b. %Y', # '25. October 2006', '25. Oct. 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' NUMBER_GROUPING = 3
1,288
Python
.py
35
34.485714
77
0.566747
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,923
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/ml/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'N j, Y' TIME_FORMAT = 'P' DATETIME_FORMAT = 'N j, Y, P' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'F j' SHORT_DATE_FORMAT = 'm/d/Y' SHORT_DATETIME_FORMAT = 'm/d/Y P' FIRST_DAY_OF_WEEK = 0 # Sunday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' # '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' # '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' # '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' # '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' ) DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
1,635
Python
.py
40
38.2
81
0.515075
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,924
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/sv/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'Y-m-d' SHORT_DATETIME_FORMAT = 'Y-m-d H:i' FIRST_DAY_OF_WEEK = 1 # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y', # '10/25/06' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' NUMBER_GROUPING = 3
1,365
Python
.py
38
33.394737
77
0.532075
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,925
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/bs/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. N Y.' TIME_FORMAT = 'G:i' DATETIME_FORMAT = 'j. N. Y. G:i T' YEAR_MONTH_FORMAT = 'F Y.' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'Y M j' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
736
Python
.py
21
33.666667
77
0.7223
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,926
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/hi/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F Y' TIME_FORMAT = 'g:i:s A' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd-m-Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' # NUMBER_GROUPING =
719
Python
.py
21
32.761905
77
0.731322
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,927
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/fr/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = 'j F Y H:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j N Y' SHORT_DATETIME_FORMAT = 'j N Y H:i:s' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06' '%d.%m.%Y', '%d.%m.%y', # Swiss (fr_CH), '25.10.2006', '25.10.06' '%Y-%m-%d', '%y-%m-%d', # '2006-10-25', '06-10-25' # '%d %B %Y', '%d %b %Y', # '25 octobre 2006', '25 oct. 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%Y', # '25/10/2006' '%d.%m.%Y %H:%M:%S', # Swiss (fr_CH), '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # Swiss (fr_CH), '25.10.2006 14:30' '%d.%m.%Y', # Swiss (fr_CH), '25.10.2006' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' NUMBER_GROUPING = 3
1,530
Python
.py
39
36.641026
77
0.546004
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,928
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/tr/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'd F Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = 'd F Y H:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'd F' SHORT_DATE_FORMAT = 'd M Y' SHORT_DATETIME_FORMAT = 'd M Y H:i:s' FIRST_DAY_OF_WEEK = 1 # Pazartesi # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06' '%Y-%m-%d', '%y-%m-%d', # '2006-10-25', '06-10-25' # '%d %B %Y', '%d %b. %Y', # '25 Ekim 2006', '25 Eki. 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%Y', # '25/10/2006' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
1,281
Python
.py
35
34.285714
77
0.569936
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,929
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/pt_BR/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = r'j \de N \de Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = r'j \de N \de Y à\s H:i' YEAR_MONTH_FORMAT = r'F \de Y' MONTH_DAY_FORMAT = r'j \de F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y H:i' FIRST_DAY_OF_WEEK = 0 # Sunday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%d/%m/%Y', '%d/%m/%y', # '2006-10-25', '25/10/2006', '25/10/06' # '%d de %b de %Y', '%d de %b, %Y', # '25 de Out de 2006', '25 Out, 2006' # '%d de %B de %Y', '%d de %B, %Y', # '25 de Outubro de 2006', '25 de Outubro, 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%Y', # '25/10/2006' '%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59' '%d/%m/%y %H:%M', # '25/10/06 14:30' '%d/%m/%y', # '25/10/06' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
1,530
Python
.py
38
37.736842
90
0.541611
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,930
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/app_template/tests.py
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2)
383
Python
.py
12
27.583333
79
0.705722
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,931
settings.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/project_template/settings.py
# Django settings for {{ project_name }} project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '[email protected]'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale USE_L10N = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # URL prefix for admin static files -- CSS, JavaScript and images. # Make sure to use a trailing slash. # Examples: "http://foo.com/static/admin/", "/static/admin/". ADMIN_MEDIA_PREFIX = '/static/admin/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = '' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = '{{ project_name }}.urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: # 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } }
5,005
Python
.py
122
37.57377
115
0.702469
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,932
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/project_template/urls.py
from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', '{{ project_name }}.views.home', name='home'), # url(r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), )
601
Python
.py
13
42.769231
75
0.683219
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,933
manage.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/project_template/manage.py
#!/usr/bin/env python from django.core.management import execute_manager import imp try: imp.find_module('settings') # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__) sys.exit(1) import settings if __name__ == "__main__": execute_manager(settings)
503
Python
.py
12
39.083333
216
0.736196
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,934
shortcut.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/urls/shortcut.py
from django.conf.urls.defaults import * urlpatterns = patterns('django.views', (r'^(?P<content_type_id>\d+)/(?P<object_id>.*)/$', 'defaults.shortcut'), )
159
Python
.py
4
37.5
76
0.668831
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,935
i18n.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/urls/i18n.py
from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^setlang/$', 'django.views.i18n.set_language'), )
125
Python
.py
4
29
54
0.708333
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,936
defaults.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/urls/defaults.py
from django.core.urlresolvers import RegexURLPattern, RegexURLResolver from django.core.exceptions import ImproperlyConfigured __all__ = ['handler404', 'handler500', 'include', 'patterns', 'url'] handler404 = 'django.views.defaults.page_not_found' handler500 = 'django.views.defaults.server_error' def include(arg, namespace=None, app_name=None): if isinstance(arg, tuple): # callable returning a namespace hint if namespace: raise ImproperlyConfigured('Cannot override the namespace for a dynamic module that provides a namespace') urlconf_module, app_name, namespace = arg else: # No namespace hint - use manually provided namespace urlconf_module = arg return (urlconf_module, app_name, namespace) def patterns(prefix, *args): pattern_list = [] for t in args: if isinstance(t, (list, tuple)): t = url(prefix=prefix, *t) elif isinstance(t, RegexURLPattern): t.add_prefix(prefix) pattern_list.append(t) return pattern_list def url(regex, view, kwargs=None, name=None, prefix=''): if isinstance(view, (list,tuple)): # For include(...) processing. urlconf_module, app_name, namespace = view return RegexURLResolver(regex, urlconf_module, kwargs, app_name=app_name, namespace=namespace) else: if isinstance(view, basestring): if not view: raise ImproperlyConfigured('Empty URL pattern view name not permitted (for pattern %r)' % regex) if prefix: view = prefix + '.' + view return RegexURLPattern(regex, view, kwargs, name)
1,656
Python
.py
36
38.5
118
0.674102
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,937
static.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/urls/static.py
import re from django.conf import settings from django.conf.urls.defaults import patterns, url from django.core.exceptions import ImproperlyConfigured def static(prefix, view='django.views.static.serve', **kwargs): """ Helper function to return a URL pattern for serving files in debug mode. from django.conf import settings from django.conf.urls.static import static urlpatterns = patterns('', # ... the rest of your URLconf goes here ... ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) """ # No-op if not in debug mode or an non-local prefix if not settings.DEBUG or (prefix and '://' in prefix): return [] elif not prefix: raise ImproperlyConfigured("Empty static prefix not permitted") return patterns('', url(r'^%s(?P<path>.*)$' % re.escape(prefix.lstrip('/')), view, kwargs=kwargs), )
893
Python
.py
21
37.52381
86
0.697005
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,938
setup.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/setup.py
from distutils.core import setup from distutils.command.install_data import install_data from distutils.command.install import INSTALL_SCHEMES import os import sys class osx_install_data(install_data): # On MacOS, the platform-specific lib dir is /System/Library/Framework/Python/.../ # which is wrong. Python 2.5 supplied with MacOS 10.5 has an Apple-specific fix # for this in distutils.command.install_data#306. It fixes install_lib but not # install_data, which is why we roll our own install_data class. def finalize_options(self): # By the time finalize_options is called, install.install_lib is set to the # fixed directory, so we set the installdir to install_lib. The # install_data class uses ('install_data', 'install_dir') instead. self.set_undefined_options('install', ('install_lib', 'install_dir')) install_data.finalize_options(self) if sys.platform == "darwin": cmdclasses = {'install_data': osx_install_data} else: cmdclasses = {'install_data': install_data} def fullsplit(path, result=None): """ Split a pathname into components (the opposite of os.path.join) in a platform-neutral way. """ if result is None: result = [] head, tail = os.path.split(path) if head == '': return [tail] + result if head == path: return result return fullsplit(head, [tail] + result) # Tell distutils to put the data_files in platform-specific installation # locations. See here for an explanation: # http://groups.google.com/group/comp.lang.python/browse_thread/thread/35ec7b2fed36eaec/2105ee4d9e8042cb for scheme in INSTALL_SCHEMES.values(): scheme['data'] = scheme['purelib'] # Compile the list of packages available, because distutils doesn't have # an easy way to do this. packages, data_files = [], [] root_dir = os.path.dirname(__file__) if root_dir != '': os.chdir(root_dir) django_dir = 'django' for dirpath, dirnames, filenames in os.walk(django_dir): # Ignore dirnames that start with '.' for i, dirname in enumerate(dirnames): if dirname.startswith('.'): del dirnames[i] if '__init__.py' in filenames: packages.append('.'.join(fullsplit(dirpath))) elif filenames: data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames]]) # Small hack for working with bdist_wininst. # See http://mail.python.org/pipermail/distutils-sig/2004-August/004134.html if len(sys.argv) > 1 and sys.argv[1] == 'bdist_wininst': for file_info in data_files: file_info[0] = '\\PURELIB\\%s' % file_info[0] # Dynamically calculate the version based on django.VERSION. version = __import__('django').get_version() if u'SVN' in version: version = ' '.join(version.split(' ')[:-1]) setup( name = "Django", version = version.replace(' ', '-'), url = 'http://www.djangoproject.com/', author = 'Django Software Foundation', author_email = '[email protected]', description = 'A high-level Python Web framework that encourages rapid development and clean, pragmatic design.', download_url = 'http://media.djangoproject.com/releases/1.2/Django-1.2.5.tar.gz', packages = packages, cmdclass = cmdclasses, data_files = data_files, scripts = ['django/bin/django-admin.py'], classifiers = ['Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Internet :: WWW/HTTP :: WSGI', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
4,087
Python
.py
88
39.965909
117
0.661319
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,939
csrf_migration_helper.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/extras/csrf_migration_helper.py
#!/usr/bin/env python # This script aims to help developers locate forms and view code that needs to # use the new CSRF protection in Django 1.2. It tries to find all the code that # may need the steps described in the CSRF documentation. It does not modify # any code directly, it merely attempts to locate it. Developers should be # aware of its limitations, described below. # # For each template that contains at least one POST form, the following info is printed: # # <Absolute path to template> # AKA: <Aliases (relative to template directory/directories that contain it)> # POST forms: <Number of POST forms> # With token: <Number of POST forms with the CSRF token already added> # Without token: # <File name and line number of form without token> # # Searching for: # <Template names that need to be searched for in view code # (includes templates that 'include' current template)> # # Found: # <File name and line number of any view code found> # # The format used allows this script to be used in Emacs grep mode: # M-x grep # Run grep (like this): /path/to/my/virtualenv/python /path/to/django/src/extras/csrf_migration_helper.py --settings=mysettings /path/to/my/srcs # Limitations # =========== # # - All templates must be stored on disk in '.html' or '.htm' files. # (extensions configurable below) # # - All Python code must be stored on disk in '.py' files. (extensions # configurable below) # # - All templates must be accessible from TEMPLATE_DIRS or from the 'templates/' # directory in apps specified in INSTALLED_APPS. Non-file based template # loaders are out of the picture, because there is no way to ask them to # return all templates. # # - If you put the {% csrf_token %} tag on the same line as the <form> tag it # will be detected, otherwise it will be assumed that the form does not have # the token. # # - It's impossible to programmatically determine which forms should and should # not have the token added. The developer must decide when to do this, # ensuring that the token is only added to internally targetted forms. # # - It's impossible to programmatically work out when a template is used. The # attempts to trace back to view functions are guesses, and could easily fail # in the following ways: # # * If the 'include' template tag is used with a variable # i.e. {% include tname %} where tname is a variable containing the actual # template name, rather than {% include "my_template.html" %}. # # * If the template name has been built up by view code instead of as a simple # string. For example, generic views and the admin both do this. (These # apps are both contrib and both use RequestContext already, as it happens). # # * If the 'ssl' tag (or any template tag other than 'include') is used to # include the template in another template. # # - All templates belonging to apps referenced in INSTALLED_APPS will be # searched, which may include third party apps or Django contrib. In some # cases, this will be a good thing, because even if the templates of these # apps have been fixed by someone else, your own view code may reference the # same template and may need to be updated. # # You may, however, wish to comment out some entries in INSTALLED_APPS or # TEMPLATE_DIRS before running this script. # Improvements to this script are welcome! # Configuration # ============= TEMPLATE_EXTENSIONS = [ ".html", ".htm", ] PYTHON_SOURCE_EXTENSIONS = [ ".py", ] TEMPLATE_ENCODING = "UTF-8" PYTHON_ENCODING = "UTF-8" # Method # ====== # Find templates: # - template dirs # - installed apps # # Search for POST forms # - Work out what the name of the template is, as it would appear in an # 'include' or get_template() call. This can be done by comparing template # filename to all template dirs. Some templates can have more than one # 'name' e.g. if a directory and one of its child directories are both in # TEMPLATE_DIRS. This is actually a common hack used for # overriding-and-extending admin templates. # # For each POST form, # - see if it already contains '{% csrf_token %}' immediately after <form> # - work back to the view function(s): # - First, see if the form is included in any other templates, then # recursively compile a list of affected templates. # - Find any code function that references that template. This is just a # brute force text search that can easily return false positives # and fail to find real instances. import os import sys import re from optparse import OptionParser USAGE = """ This tool helps to locate forms that need CSRF tokens added and the corresponding view code. This processing is NOT fool proof, and you should read the help contained in the script itself. Also, this script may need configuring (by editing the script) before use. Usage: python csrf_migration_helper.py [--settings=path.to.your.settings] /path/to/python/code [more paths...] Paths can be specified as relative paths. With no arguments, this help is printed. """ _POST_FORM_RE = \ re.compile(r'(<form\W[^>]*\bmethod\s*=\s*(\'|"|)POST(\'|"|)\b[^>]*>)', re.IGNORECASE) _TOKEN_RE = re.compile('\{% csrf_token') def get_template_dirs(): """ Returns a set of all directories that contain project templates. """ from django.conf import settings dirs = set() if ('django.template.loaders.filesystem.load_template_source' in settings.TEMPLATE_LOADERS or 'django.template.loaders.filesystem.Loader' in settings.TEMPLATE_LOADERS): dirs.update(map(unicode, settings.TEMPLATE_DIRS)) if ('django.template.loaders.app_directories.load_template_source' in settings.TEMPLATE_LOADERS or 'django.template.loaders.app_directories.Loader' in settings.TEMPLATE_LOADERS): from django.template.loaders.app_directories import app_template_dirs dirs.update(app_template_dirs) return dirs def make_template_info(filename, root_dirs): """ Creates a Template object for a filename, calculating the possible relative_filenames from the supplied filename and root template directories """ return Template(filename, [filename[len(d)+1:] for d in root_dirs if filename.startswith(d)]) class Template(object): def __init__(self, absolute_filename, relative_filenames): self.absolute_filename, self.relative_filenames = absolute_filename, relative_filenames def content(self): try: return self._content except AttributeError: fd = open(self.absolute_filename) try: content = fd.read().decode(TEMPLATE_ENCODING) except UnicodeDecodeError, e: message = '%s in %s' % ( e[4], self.absolute_filename.encode('UTF-8', 'ignore')) raise UnicodeDecodeError(*(e.args[:4] + (message,))) fd.close() self._content = content return content content = property(content) def post_form_info(self): """ Get information about any POST forms in the template. Returns [(linenumber, csrf_token added)] """ matches = [] for ln, line in enumerate(self.content.split("\n")): m = _POST_FORM_RE.search(line) if m is not None: matches.append((ln + 1, _TOKEN_RE.search(line) is not None)) return matches def includes_template(self, t): """ Returns true if this template includes template 't' (via {% include %}) """ for r in t.relative_filenames: if re.search(r'\{%\s*include\s+(\'|")' + re.escape(r) + r'(\1)\s*%\}', self.content): return True return False def related_templates(self): """ Returns all templates that include this one, recursively. (starting with this one) """ try: return self._related_templates except AttributeError: pass retval = set([self]) for t in self.all_templates: if t.includes_template(self): # If two templates mutually include each other, directly or # indirectly, we have a problem here... retval = retval.union(t.related_templates()) self._related_templates = retval return retval def __repr__(self): return repr(self.absolute_filename) def __eq__(self, other): return self.absolute_filename == other.absolute_filename def __hash__(self): return hash(self.absolute_filename) def get_templates(dirs): """ Returns all files in dirs that have template extensions, as Template objects. """ templates = set() for root in dirs: for (dirpath, dirnames, filenames) in os.walk(root): for f in filenames: if len([True for e in TEMPLATE_EXTENSIONS if f.endswith(e)]) > 0: t = make_template_info(os.path.join(dirpath, f), dirs) # templates need to be able to search others: t.all_templates = templates templates.add(t) return templates def get_python_code(paths): """ Returns all Python code, as a list of tuples, each one being: (filename, list of lines) """ retval = [] for p in paths: if not os.path.isdir(p): raise Exception("'%s' is not a directory." % p) for (dirpath, dirnames, filenames) in os.walk(p): for f in filenames: if len([True for e in PYTHON_SOURCE_EXTENSIONS if f.endswith(e)]) > 0: fn = os.path.join(dirpath, f) fd = open(fn) content = [l.decode(PYTHON_ENCODING) for l in fd.readlines()] fd.close() retval.append((fn, content)) return retval def search_python_list(python_code, template_names): """ Searches python code for a list of template names. Returns a list of tuples, each one being: (filename, line number) """ retval = [] for tn in template_names: retval.extend(search_python(python_code, tn)) retval = list(set(retval)) retval.sort() return retval def search_python(python_code, template_name): """ Searches Python code for a template name. Returns a list of tuples, each one being: (filename, line number) """ retval = [] for fn, content in python_code: for ln, line in enumerate(content): if ((u'"%s"' % template_name) in line) or \ ((u"'%s'" % template_name) in line): retval.append((fn, ln + 1)) return retval def main(pythonpaths): template_dirs = get_template_dirs() templates = get_templates(template_dirs) python_code = get_python_code(pythonpaths) for t in templates: # Logic form_matches = t.post_form_info() num_post_forms = len(form_matches) form_lines_without_token = [ln for (ln, has_token) in form_matches if not has_token] if num_post_forms == 0: continue to_search = [rf for rt in t.related_templates() for rf in rt.relative_filenames] found = search_python_list(python_code, to_search) # Display: print t.absolute_filename for r in t.relative_filenames: print u" AKA %s" % r print u" POST forms: %s" % num_post_forms print u" With token: %s" % (num_post_forms - len(form_lines_without_token)) if form_lines_without_token: print u" Without token:" for ln in form_lines_without_token: print "%s:%d:" % (t.absolute_filename, ln) print print u" Searching for:" for r in to_search: print u" " + r print print u" Found:" if len(found) == 0: print " Nothing" else: for fn, ln in found: print "%s:%d:" % (fn, ln) print print "----" parser = OptionParser(usage=USAGE) parser.add_option("", "--settings", action="store", dest="settings", help="Dotted path to settings file") if __name__ == '__main__': options, args = parser.parse_args() if len(args) == 0: parser.print_help() sys.exit(1) settings = getattr(options, 'settings', None) if settings is None: if os.environ.get("DJANGO_SETTINGS_MODULE", None) is None: print "You need to set DJANGO_SETTINGS_MODULE or use the '--settings' parameter" sys.exit(1) else: os.environ["DJANGO_SETTINGS_MODULE"] = settings main(args)
12,787
Python
.py
312
34.855769
146
0.651327
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,940
conf.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/docs/conf.py
# -*- coding: utf-8 -*- # # Django documentation build configuration file, created by # sphinx-quickstart on Thu Mar 27 09:06:53 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed automatically). # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "_ext"))) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ["djangodocs"] # Add any paths that contain templates here, relative to this directory. # templates_path = [] # The suffix of source filenames. source_suffix = '.txt' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'contents' # General substitutions. project = 'Django' copyright = 'Django Software Foundation and contributors' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.2' # The full version, including alpha/beta/rc tags. release = version # The next version to be released django_next_version = '1.3' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = False # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'trac' # Sphinx will recurse into subversion configuration folders and try to read # any document file within. These should be ignored. # Note: exclude_dirnames is new in Sphinx 0.5 exclude_dirnames = ['.svn'] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "djangodocs" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ["_theme"] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. html_use_smartypants = True # HTML translator class for the builder html_translator_class = "djangodocs.DjangoHTMLTranslator" # Content template for the index page. #html_index = '' # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Djangodoc' modindex_common_prefix = ["django."] # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). #latex_documents = [] latex_documents = [ ('contents', 'django.tex', u'Django Documentation', u'Django Software Foundation', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('contents', 'django', 'Django Documentation', ['Django Software Foundation'], 1) ] # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. epub_title = u'Django' epub_author = u'Django Software Foundation' epub_publisher = u'Django Software Foundation' epub_copyright = u'2010, Django Software Foundation' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. #epub_exclude_files = [] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True
8,709
Python
.py
196
43.015306
85
0.734716
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,941
djangodocs.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/docs/_ext/djangodocs.py
""" Sphinx plugins for Django documentation. """ import os import re from docutils import nodes, transforms try: import json except ImportError: try: import simplejson as json except ImportError: try: from django.utils import simplejson as json except ImportError: json = None from sphinx import addnodes, roles from sphinx.builders.html import StandaloneHTMLBuilder from sphinx.writers.html import SmartyPantsHTMLTranslator from sphinx.util.console import bold from sphinx.util.compat import Directive # RE for option descriptions without a '--' prefix simple_option_desc_re = re.compile( r'([-_a-zA-Z0-9]+)(\s*.*?)(?=,\s+(?:/|-|--)|$)') def setup(app): app.add_crossref_type( directivename = "setting", rolename = "setting", indextemplate = "pair: %s; setting", ) app.add_crossref_type( directivename = "templatetag", rolename = "ttag", indextemplate = "pair: %s; template tag" ) app.add_crossref_type( directivename = "templatefilter", rolename = "tfilter", indextemplate = "pair: %s; template filter" ) app.add_crossref_type( directivename = "fieldlookup", rolename = "lookup", indextemplate = "pair: %s; field lookup type", ) app.add_description_unit( directivename = "django-admin", rolename = "djadmin", indextemplate = "pair: %s; django-admin command", parse_node = parse_django_admin_node, ) app.add_description_unit( directivename = "django-admin-option", rolename = "djadminopt", indextemplate = "pair: %s; django-admin command-line option", parse_node = parse_django_adminopt_node, ) app.add_config_value('django_next_version', '0.0', True) app.add_directive('versionadded', VersionDirective) app.add_directive('versionchanged', VersionDirective) app.add_transform(SuppressBlockquotes) app.add_builder(DjangoStandaloneHTMLBuilder) class VersionDirective(Directive): has_content = True required_arguments = 1 optional_arguments = 1 final_argument_whitespace = True option_spec = {} def run(self): env = self.state.document.settings.env arg0 = self.arguments[0] is_nextversion = env.config.django_next_version == arg0 ret = [] node = addnodes.versionmodified() ret.append(node) if not is_nextversion: if len(self.arguments) == 1: linktext = 'Please, see the release notes </releases/%s>' % (arg0) try: xrefs = roles.XRefRole()('doc', linktext, linktext, self.lineno, self.state) # Sphinx >= 1.0 except AttributeError: xrefs = roles.xfileref_role('doc', linktext, linktext, self.lineno, self.state) # Sphinx < 1.0 node.extend(xrefs[0]) node['version'] = arg0 else: node['version'] = "Development version" node['type'] = self.name if len(self.arguments) == 2: inodes, messages = self.state.inline_text(self.arguments[1], self.lineno+1) node.extend(inodes) if self.content: self.state.nested_parse(self.content, self.content_offset, node) ret = ret + messages env.note_versionchange(node['type'], node['version'], node, self.lineno) return ret class SuppressBlockquotes(transforms.Transform): """ Remove the default blockquotes that encase indented list, tables, etc. """ default_priority = 300 suppress_blockquote_child_nodes = ( nodes.bullet_list, nodes.enumerated_list, nodes.definition_list, nodes.literal_block, nodes.doctest_block, nodes.line_block, nodes.table ) def apply(self): for node in self.document.traverse(nodes.block_quote): if len(node.children) == 1 and isinstance(node.children[0], self.suppress_blockquote_child_nodes): node.replace_self(node.children[0]) class DjangoHTMLTranslator(SmartyPantsHTMLTranslator): """ Django-specific reST to HTML tweaks. """ # Don't use border=1, which docutils does by default. def visit_table(self, node): self.body.append(self.starttag(node, 'table', CLASS='docutils')) # <big>? Really? def visit_desc_parameterlist(self, node): self.body.append('(') self.first_param = 1 def depart_desc_parameterlist(self, node): self.body.append(')') # # Don't apply smartypants to literal blocks # def visit_literal_block(self, node): self.no_smarty += 1 SmartyPantsHTMLTranslator.visit_literal_block(self, node) def depart_literal_block(self, node): SmartyPantsHTMLTranslator.depart_literal_block(self, node) self.no_smarty -= 1 # # Turn the "new in version" stuff (versionadded/versionchanged) into a # better callout -- the Sphinx default is just a little span, # which is a bit less obvious that I'd like. # # FIXME: these messages are all hardcoded in English. We need to change # that to accomodate other language docs, but I can't work out how to make # that work. # version_text = { 'deprecated': 'Deprecated in Django %s', 'versionchanged': 'Changed in Django %s', 'versionadded': 'New in Django %s', } def visit_versionmodified(self, node): self.body.append( self.starttag(node, 'div', CLASS=node['type']) ) title = "%s%s" % ( self.version_text[node['type']] % node['version'], len(node) and ":" or "." ) self.body.append('<span class="title">%s</span> ' % title) def depart_versionmodified(self, node): self.body.append("</div>\n") # Give each section a unique ID -- nice for custom CSS hooks def visit_section(self, node): old_ids = node.get('ids', []) node['ids'] = ['s-' + i for i in old_ids] node['ids'].extend(old_ids) SmartyPantsHTMLTranslator.visit_section(self, node) node['ids'] = old_ids def parse_django_admin_node(env, sig, signode): command = sig.split(' ')[0] env._django_curr_admin_command = command title = "django-admin.py %s" % sig signode += addnodes.desc_name(title, title) return sig def parse_django_adminopt_node(env, sig, signode): """A copy of sphinx.directives.CmdoptionDesc.parse_signature()""" try: from sphinx.domains.std import option_desc_re # Sphinx >= 1.0 except ImportError: from sphinx.directives.desc import option_desc_re # Sphinx < 1.0 count = 0 firstname = '' for m in option_desc_re.finditer(sig): optname, args = m.groups() if count: signode += addnodes.desc_addname(', ', ', ') signode += addnodes.desc_name(optname, optname) signode += addnodes.desc_addname(args, args) if not count: firstname = optname count += 1 if not count: for m in simple_option_desc_re.finditer(sig): optname, args = m.groups() if count: signode += addnodes.desc_addname(', ', ', ') signode += addnodes.desc_name(optname, optname) signode += addnodes.desc_addname(args, args) if not count: firstname = optname count += 1 if not firstname: raise ValueError return firstname class DjangoStandaloneHTMLBuilder(StandaloneHTMLBuilder): """ Subclass to add some extra things we need. """ name = 'djangohtml' def finish(self): super(DjangoStandaloneHTMLBuilder, self).finish() if json is None: self.warn("cannot create templatebuiltins.js due to missing simplejson dependency") return self.info(bold("writing templatebuiltins.js...")) try: # Sphinx < 1.0 xrefs = self.env.reftargets.items() templatebuiltins = dict([('ttags', [n for ((t,n),(l,a)) in xrefs if t == 'ttag' and l == 'ref/templates/builtins']), ('tfilters', [n for ((t,n),(l,a)) in xrefs if t == 'tfilter' and l == 'ref/templates/builtins'])]) except AttributeError: # Sphinx >= 1.0 xrefs = self.env.domaindata["std"]["objects"] templatebuiltins = dict([('ttags', [n for ((t,n), (l,a)) in xrefs.items() if t == 'templatetag' and l == 'ref/templates/builtins' ]), ('tfilters', [n for ((t,n), (l,a)) in xrefs.items() if t == 'templatefilter' and t == 'ref/templates/builtins'])]) outfilename = os.path.join(self.outdir, "templatebuiltins.js") f = open(outfilename, 'wb') f.write('var django_template_builtins = ') json.dump(templatebuiltins, f) f.write(';\n') f.close();
9,475
Python
.py
238
30.302521
114
0.587622
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,942
literals_to_xrefs.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/docs/_ext/literals_to_xrefs.py
""" Runs through a reST file looking for old-style literals, and helps replace them with new-style references. """ import re import sys import shelve refre = re.compile(r'``([^`\s]+?)``') ROLES = ( 'attr', 'class', "djadmin", 'data', 'exc', 'file', 'func', 'lookup', 'meth', 'mod' , "djadminopt", "ref", "setting", "term", "tfilter", "ttag", # special "skip" ) ALWAYS_SKIP = [ "NULL", "True", "False", ] def fixliterals(fname): data = open(fname).read() last = 0 new = [] storage = shelve.open("/tmp/literals_to_xref.shelve") lastvalues = storage.get("lastvalues", {}) for m in refre.finditer(data): new.append(data[last:m.start()]) last = m.end() line_start = data.rfind("\n", 0, m.start()) line_end = data.find("\n", m.end()) prev_start = data.rfind("\n", 0, line_start) next_end = data.find("\n", line_end + 1) # Skip always-skip stuff if m.group(1) in ALWAYS_SKIP: new.append(m.group(0)) continue # skip when the next line is a title next_line = data[m.end():next_end].strip() if next_line[0] in "!-/:-@[-`{-~" and all(c == next_line[0] for c in next_line): new.append(m.group(0)) continue sys.stdout.write("\n"+"-"*80+"\n") sys.stdout.write(data[prev_start+1:m.start()]) sys.stdout.write(colorize(m.group(0), fg="red")) sys.stdout.write(data[m.end():next_end]) sys.stdout.write("\n\n") replace_type = None while replace_type is None: replace_type = raw_input( colorize("Replace role: ", fg="yellow") ).strip().lower() if replace_type and replace_type not in ROLES: replace_type = None if replace_type == "": new.append(m.group(0)) continue if replace_type == "skip": new.append(m.group(0)) ALWAYS_SKIP.append(m.group(1)) continue default = lastvalues.get(m.group(1), m.group(1)) if default.endswith("()") and replace_type in ("class", "func", "meth"): default = default[:-2] replace_value = raw_input( colorize("Text <target> [", fg="yellow") + default + colorize("]: ", fg="yellow") ).strip() if not replace_value: replace_value = default new.append(":%s:`%s`" % (replace_type, replace_value)) lastvalues[m.group(1)] = replace_value new.append(data[last:]) open(fname, "w").write("".join(new)) storage["lastvalues"] = lastvalues storage.close() # # The following is taken from django.utils.termcolors and is copied here to # avoid the dependancy. # def colorize(text='', opts=(), **kwargs): """ Returns your text, enclosed in ANSI graphics codes. Depends on the keyword arguments 'fg' and 'bg', and the contents of the opts tuple/list. Returns the RESET code if no parameters are given. Valid colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white' Valid options: 'bold' 'underscore' 'blink' 'reverse' 'conceal' 'noreset' - string will not be auto-terminated with the RESET code Examples: colorize('hello', fg='red', bg='blue', opts=('blink',)) colorize() colorize('goodbye', opts=('underscore',)) print colorize('first line', fg='red', opts=('noreset',)) print 'this should be red too' print colorize('and so should this') print 'this should not be red' """ color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white') foreground = dict([(color_names[x], '3%s' % x) for x in range(8)]) background = dict([(color_names[x], '4%s' % x) for x in range(8)]) RESET = '0' opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'} text = str(text) code_list = [] if text == '' and len(opts) == 1 and opts[0] == 'reset': return '\x1b[%sm' % RESET for k, v in kwargs.iteritems(): if k == 'fg': code_list.append(foreground[v]) elif k == 'bg': code_list.append(background[v]) for o in opts: if o in opt_dict: code_list.append(opt_dict[o]) if 'noreset' not in opts: text = text + '\x1b[%sm' % RESET return ('\x1b[%sm' % ';'.join(code_list)) + text if __name__ == '__main__': try: fixliterals(sys.argv[1]) except (KeyboardInterrupt, SystemExit): print
4,814
Python
.py
141
26.120567
93
0.555727
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,943
applyxrefs.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/docs/_ext/applyxrefs.py
"""Adds xref targets to the top of files.""" import sys import os testing = False DONT_TOUCH = ( './index.txt', ) def target_name(fn): if fn.endswith('.txt'): fn = fn[:-4] return '_' + fn.lstrip('./').replace('/', '-') def process_file(fn, lines): lines.insert(0, '\n') lines.insert(0, '.. %s:\n' % target_name(fn)) try: f = open(fn, 'w') except IOError: print("Can't open %s for writing. Not touching it." % fn) return try: f.writelines(lines) except IOError: print("Can't write to %s. Not touching it." % fn) finally: f.close() def has_target(fn): try: f = open(fn, 'r') except IOError: print("Can't open %s. Not touching it." % fn) return (True, None) readok = True try: lines = f.readlines() except IOError: print("Can't read %s. Not touching it." % fn) readok = False finally: f.close() if not readok: return (True, None) #print fn, len(lines) if len(lines) < 1: print("Not touching empty file %s." % fn) return (True, None) if lines[0].startswith('.. _'): return (True, None) return (False, lines) def main(argv=None): if argv is None: argv = sys.argv if len(argv) == 1: argv.extend('.') files = [] for root in argv[1:]: for (dirpath, dirnames, filenames) in os.walk(root): files.extend([(dirpath, f) for f in filenames]) files.sort() files = [os.path.join(p, fn) for p, fn in files if fn.endswith('.txt')] #print files for fn in files: if fn in DONT_TOUCH: print("Skipping blacklisted file %s." % fn) continue target_found, lines = has_target(fn) if not target_found: if testing: print '%s: %s' % (fn, lines[0]), else: print "Adding xref to %s" % fn process_file(fn, lines) else: print "Skipping %s: already has a xref" % fn if __name__ == '__main__': sys.exit(main())
2,148
Python
.py
75
21.346667
75
0.533721
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,944
modpython.txt
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/docs/howto/deployment/modpython.txt
.. _howto-deployment-modpython: ============================================ How to use Django with Apache and mod_python ============================================ .. warning:: Support for mod_python will be deprecated in a future release of Django. If you are configuring a new deployment, you are strongly encouraged to consider using :doc:`mod_wsgi </howto/deployment/modwsgi>` or any of the other :doc:`supported backends </howto/deployment/index>`. .. highlight:: apache The `mod_python`_ module for Apache_ can be used to deploy Django to a production server, although it has been mostly superseded by the simpler :doc:`mod_wsgi deployment option </howto/deployment/modwsgi>`. mod_python is similar to (and inspired by) `mod_perl`_ : It embeds Python within Apache and loads Python code into memory when the server starts. Code stays in memory throughout the life of an Apache process, which leads to significant performance gains over other server arrangements. Django requires Apache 2.x and mod_python 3.x, and you should use Apache's `prefork MPM`_, as opposed to the `worker MPM`_. .. seealso:: * Apache is a big, complex animal, and this document only scratches the surface of what Apache can do. If you need more advanced information about Apache, there's no better source than `Apache's own official documentation`_ * You may also be interested in :doc:`How to use Django with FastCGI, SCGI, or AJP </howto/deployment/fastcgi>`. .. _Apache: http://httpd.apache.org/ .. _mod_python: http://www.modpython.org/ .. _mod_perl: http://perl.apache.org/ .. _prefork MPM: http://httpd.apache.org/docs/2.2/mod/prefork.html .. _worker MPM: http://httpd.apache.org/docs/2.2/mod/worker.html .. _apache's own official documentation: http://httpd.apache.org/docs/ Basic configuration =================== To configure Django with mod_python, first make sure you have Apache installed, with the mod_python module activated. Then edit your ``httpd.conf`` file and add the following:: <Location "/mysite/"> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonOption django.root /mysite PythonDebug On </Location> ...and replace ``mysite.settings`` with the Python import path to your Django project's settings file. This tells Apache: "Use mod_python for any URL at or under '/mysite/', using the Django mod_python handler." It passes the value of :ref:`DJANGO_SETTINGS_MODULE <django-settings-module>` so mod_python knows which settings to use. Because mod_python does not know we are serving this site from underneath the ``/mysite/`` prefix, this value needs to be passed through to the mod_python handler in Django, via the ``PythonOption django.root ...`` line. The value set on that line (the last item) should match the string given in the ``<Location ...>`` directive. The effect of this is that Django will automatically strip the ``/mysite`` string from the front of any URLs before matching them against your URLconf patterns. If you later move your site to live under ``/mysite2``, you will not have to change anything except the ``django.root`` option in the config file. When using ``django.root`` you should make sure that what's left, after the prefix has been removed, begins with a slash. Your URLconf patterns that are expecting an initial slash will then work correctly. In the above example, since we want to send things like ``/mysite/admin/`` to ``/admin/``, we need to remove the string ``/mysite`` from the beginning, so that is the ``django.root`` value. It would be an error to use ``/mysite/`` (with a trailing slash) in this case. Note that we're using the ``<Location>`` directive, not the ``<Directory>`` directive. The latter is used for pointing at places on your filesystem, whereas ``<Location>`` points at places in the URL structure of a Web site. ``<Directory>`` would be meaningless here. Also, if your Django project is not on the default ``PYTHONPATH`` for your computer, you'll have to tell mod_python where your project can be found: .. parsed-literal:: <Location "/mysite/"> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonOption django.root /mysite PythonDebug On **PythonPath "['/path/to/project'] + sys.path"** </Location> The value you use for ``PythonPath`` should include the parent directories of all the modules you are going to import in your application. It should also include the parent directory of the :ref:`DJANGO_SETTINGS_MODULE <django-settings-module>` location. This is exactly the same situation as setting the Python path for interactive usage. Whenever you try to import something, Python will run through all the directories in ``sys.path`` in turn, from first to last, and try to import from each directory until one succeeds. Make sure that your Python source files' permissions are set such that the Apache user (usually named ``apache`` or ``httpd`` on most systems) will have read access to the files. An example might make this clearer. Suppose you have some applications under ``/usr/local/django-apps/`` (for example, ``/usr/local/django-apps/weblog/`` and so forth), your settings file is at ``/var/www/mysite/settings.py`` and you have specified :ref:`DJANGO_SETTINGS_MODULE <django-settings-module>` as in the above example. In this case, you would need to write your ``PythonPath`` directive as:: PythonPath "['/usr/local/django-apps/', '/var/www'] + sys.path" With this path, ``import weblog`` and ``import mysite.settings`` will both work. If you had ``import blogroll`` in your code somewhere and ``blogroll`` lived under the ``weblog/`` directory, you would *also* need to add ``/usr/local/django-apps/weblog/`` to your ``PythonPath``. Remember: the **parent directories** of anything you import directly must be on the Python path. .. note:: If you're using Windows, we still recommended that you use forward slashes in the pathnames, even though Windows normally uses the backslash character as its native separator. Apache knows how to convert from the forward slash format to the native format, so this approach is portable and easier to read. (It avoids tricky problems with having to double-escape backslashes.) This is valid even on a Windows system:: PythonPath "['c:/path/to/project'] + sys.path" You can also add directives such as ``PythonAutoReload Off`` for performance. See the `mod_python documentation`_ for a full list of options. Note that you should set ``PythonDebug Off`` on a production server. If you leave ``PythonDebug On``, your users would see ugly (and revealing) Python tracebacks if something goes wrong within mod_python. Restart Apache, and any request to ``/mysite/`` or below will be served by Django. Note that Django's URLconfs won't trim the "/mysite/" -- they get passed the full URL. When deploying Django sites on mod_python, you'll need to restart Apache each time you make changes to your Python code. .. _mod_python documentation: http://modpython.org/live/current/doc-html/directives.html Multiple Django installations on the same Apache ================================================ It's entirely possible to run multiple Django installations on the same Apache instance. Just use ``VirtualHost`` for that, like so:: NameVirtualHost * <VirtualHost *> ServerName www.example.com # ... SetEnv DJANGO_SETTINGS_MODULE mysite.settings </VirtualHost> <VirtualHost *> ServerName www2.example.com # ... SetEnv DJANGO_SETTINGS_MODULE mysite.other_settings </VirtualHost> If you need to put two Django installations within the same ``VirtualHost`` (or in different ``VirtualHost`` blocks that share the same server name), you'll need to take a special precaution to ensure mod_python's cache doesn't mess things up. Use the ``PythonInterpreter`` directive to give different ``<Location>`` directives separate interpreters:: <VirtualHost *> ServerName www.example.com # ... <Location "/something"> SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonInterpreter mysite </Location> <Location "/otherthing"> SetEnv DJANGO_SETTINGS_MODULE mysite.other_settings PythonInterpreter othersite </Location> </VirtualHost> The values of ``PythonInterpreter`` don't really matter, as long as they're different between the two ``Location`` blocks. Running a development server with mod_python ============================================ If you use mod_python for your development server, you can avoid the hassle of having to restart the server each time you make code changes. Just set ``MaxRequestsPerChild 1`` in your ``httpd.conf`` file to force Apache to reload everything for each request. But don't do that on a production server, or we'll revoke your Django privileges. If you're the type of programmer who debugs using scattered ``print`` statements, note that output to ``stdout`` will not appear in the Apache log and can even `cause response errors`_. .. _cause response errors: http://blog.dscpl.com.au/2009/04/wsgi-and-printing-to-standard-output.html If you have the need to print debugging information in a mod_python setup, you have a few options. You can print to ``stderr`` explicitly, like so:: print >> sys.stderr, 'debug text' sys.stderr.flush() (note that ``stderr`` is buffered, so calling ``flush`` is necessary if you wish debugging information to be displayed promptly.) A more compact approach is to use an assertion:: assert False, 'debug text' Another alternative is to add debugging information to the template of your page. .. _serving-media-files: Serving media files =================== Django doesn't serve media files itself; it leaves that job to whichever Web server you choose. We recommend using a separate Web server -- i.e., one that's not also running Django -- for serving media. Here are some good choices: * lighttpd_ * Nginx_ * TUX_ * A stripped-down version of Apache_ * Cherokee_ If, however, you have no option but to serve media files on the same Apache ``VirtualHost`` as Django, here's how you can turn off mod_python for a particular part of the site:: <Location "/media"> SetHandler None </Location> Just change ``Location`` to the root URL of your media files. You can also use ``<LocationMatch>`` to match a regular expression. This example sets up Django at the site root but explicitly disables Django for the ``media`` subdirectory and any URL that ends with ``.jpg``, ``.gif`` or ``.png``:: <Location "/"> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settings </Location> <Location "/media"> SetHandler None </Location> <LocationMatch "\.(jpg|gif|png)$"> SetHandler None </LocationMatch> .. _lighttpd: http://www.lighttpd.net/ .. _Nginx: http://wiki.nginx.org/Main .. _TUX: http://en.wikipedia.org/wiki/TUX_web_server .. _Apache: http://httpd.apache.org/ .. _Cherokee: http://www.cherokee-project.com/ .. _serving-the-admin-files: Serving the admin files ======================= Note that the Django development server automagically serves admin media files, but this is not the case when you use any other server arrangement. You're responsible for setting up Apache, or whichever media server you're using, to serve the admin files. The admin files live in (:file:`django/contrib/admin/media`) of the Django distribution. Here are two recommended approaches: 1. Create a symbolic link to the admin media files from within your document root. This way, all of your Django-related files -- code **and** templates -- stay in one place, and you'll still be able to ``svn update`` your code to get the latest admin templates, if they change. 2. Or, copy the admin media files so that they live within your Apache document root. Using "eggs" with mod_python ============================ If you installed Django from a Python egg_ or are using eggs in your Django project, some extra configuration is required. Create an extra file in your project (or somewhere else) that contains something like the following: .. code-block:: python import os os.environ['PYTHON_EGG_CACHE'] = '/some/directory' Here, ``/some/directory`` is a directory that the Apache Web server process can write to. It will be used as the location for any unpacking of code the eggs need to do. Then you have to tell mod_python to import this file before doing anything else. This is done using the PythonImport_ directive to mod_python. You need to ensure that you have specified the ``PythonInterpreter`` directive to mod_python as described above__ (you need to do this even if you aren't serving multiple installations in this case). Then add the ``PythonImport`` line in the main server configuration (i.e., outside the ``Location`` or ``VirtualHost`` sections). For example:: PythonInterpreter my_django PythonImport /path/to/my/project/file.py my_django Note that you can use an absolute path here (or a normal dotted import path), as described in the `mod_python manual`_. We use an absolute path in the above example because if any Python path modifications are required to access your project, they will not have been done at the time the ``PythonImport`` line is processed. .. _Egg: http://peak.telecommunity.com/DevCenter/PythonEggs .. _PythonImport: http://www.modpython.org/live/current/doc-html/dir-other-pimp.html .. _mod_python manual: PythonImport_ __ `Multiple Django installations on the same Apache`_ Error handling ============== When you use Apache/mod_python, errors will be caught by Django -- in other words, they won't propagate to the Apache level and won't appear in the Apache ``error_log``. The exception for this is if something is really wonky in your Django setup. In that case, you'll see an "Internal Server Error" page in your browser and the full Python traceback in your Apache ``error_log`` file. The ``error_log`` traceback is spread over multiple lines. (Yes, this is ugly and rather hard to read, but it's how mod_python does things.) If you get a segmentation fault =============================== If Apache causes a segmentation fault, there are two probable causes, neither of which has to do with Django itself. 1. It may be because your Python code is importing the "pyexpat" module, which may conflict with the version embedded in Apache. For full information, see `Expat Causing Apache Crash`_. 2. It may be because you're running mod_python and mod_php in the same Apache instance, with MySQL as your database backend. In some cases, this causes a known mod_python issue due to version conflicts in PHP and the Python MySQL backend. There's full information in the `mod_python FAQ entry`_. If you continue to have problems setting up mod_python, a good thing to do is get a barebones mod_python site working, without the Django framework. This is an easy way to isolate mod_python-specific problems. `Getting mod_python Working`_ details this procedure. The next step should be to edit your test code and add an import of any Django-specific code you're using -- your views, your models, your URLconf, your RSS configuration, etc. Put these imports in your test handler function and access your test URL in a browser. If this causes a crash, you've confirmed it's the importing of Django code that causes the problem. Gradually reduce the set of imports until it stops crashing, so as to find the specific module that causes the problem. Drop down further into modules and look into their imports, as necessary. .. _Expat Causing Apache Crash: http://www.dscpl.com.au/wiki/ModPython/Articles/ExpatCausingApacheCrash .. _mod_python FAQ entry: http://modpython.org/FAQ/faqw.py?req=show&file=faq02.013.htp .. _Getting mod_python Working: http://www.dscpl.com.au/wiki/ModPython/Articles/GettingModPythonWorking If you get a UnicodeEncodeError =============================== If you're taking advantage of the internationalization features of Django (see :doc:`/topics/i18n/index`) and you intend to allow users to upload files, you must ensure that the environment used to start Apache is configured to accept non-ASCII file names. If your environment is not correctly configured, you will trigger ``UnicodeEncodeError`` exceptions when calling functions like ``os.path()`` on filenames that contain non-ASCII characters. To avoid these problems, the environment used to start Apache should contain settings analogous to the following:: export LANG='en_US.UTF-8' export LC_ALL='en_US.UTF-8' Consult the documentation for your operating system for the appropriate syntax and location to put these configuration items; ``/etc/apache2/envvars`` is a common location on Unix platforms. Once you have added these statements to your environment, restart Apache.
17,332
Python
.py
314
52.009554
103
0.743631
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,945
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/urls.py
from django.conf.urls.defaults import * urlpatterns = patterns('', # test_client modeltest urls (r'^test_client/', include('modeltests.test_client.urls')), (r'^test_client_regress/', include('regressiontests.test_client_regress.urls')), # File upload test views (r'^file_uploads/', include('regressiontests.file_uploads.urls')), # Always provide the auth system login and logout views (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}), (r'^accounts/logout/$', 'django.contrib.auth.views.logout'), # test urlconf for {% url %} template tag (r'^url_tag/', include('regressiontests.templates.urls')), # django built-in views (r'^views/', include('regressiontests.views.urls')), # test urlconf for middleware tests (r'^middleware/', include('regressiontests.middleware.urls')), # admin view tests (r'^test_admin/', include('regressiontests.admin_views.urls')), (r'^generic_inline_admin/', include('regressiontests.generic_inline_admin.urls')), # admin widget tests (r'widget_admin/', include('regressiontests.admin_widgets.urls')), (r'^utils/', include('regressiontests.utils.urls')), # test urlconf for syndication tests (r'^syndication/', include('regressiontests.syndication.urls')), # conditional get views (r'condition/', include('regressiontests.conditional_processing.urls')), # middleware exceptions tests (r'middleware_exceptions/', include('regressiontests.middleware_exceptions.urls')), # special headers views (r'special_headers/', include('regressiontests.special_headers.urls')), )
1,658
Python
.py
31
48.451613
95
0.708178
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,946
test_sqlite.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/test_sqlite.py
# This is an example test settings file for use with the Django test suite. # # The 'sqlite3' backend requires only the ENGINE setting (an in- # memory database will be used). All other backends will require a # NAME and potentially authentication information. See the # following section in the docs for more information: # # http://docs.djangoproject.com/en/dev/internals/contributing/#unit-tests # # The different databases that Django supports behave differently in certain # situations, so it is recommended to run the test suite against as many # database backends as possible. You may want to create a separate settings # file for each of the backends you test against. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3' }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', } }
835
Python
.py
21
37.190476
76
0.751538
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,947
runtests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/runtests.py
#!/usr/bin/env python import os, subprocess, sys, traceback import unittest import django.contrib as contrib CONTRIB_DIR_NAME = 'django.contrib' MODEL_TESTS_DIR_NAME = 'modeltests' REGRESSION_TESTS_DIR_NAME = 'regressiontests' TEST_TEMPLATE_DIR = 'templates' CONTRIB_DIR = os.path.dirname(contrib.__file__) MODEL_TEST_DIR = os.path.join(os.path.dirname(__file__), MODEL_TESTS_DIR_NAME) REGRESSION_TEST_DIR = os.path.join(os.path.dirname(__file__), REGRESSION_TESTS_DIR_NAME) REGRESSION_SUBDIRS_TO_SKIP = ['locale'] ALWAYS_INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.flatpages', 'django.contrib.redirects', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.comments', 'django.contrib.admin', 'django.contrib.admindocs', ] def geodjango(settings): # All databases must have spatial backends to run GeoDjango tests. spatial_dbs = [name for name, db_dict in settings.DATABASES.items() if db_dict['ENGINE'].startswith('django.contrib.gis')] return len(spatial_dbs) == len(settings.DATABASES) def get_test_models(): models = [] for loc, dirpath in (MODEL_TESTS_DIR_NAME, MODEL_TEST_DIR), (REGRESSION_TESTS_DIR_NAME, REGRESSION_TEST_DIR), (CONTRIB_DIR_NAME, CONTRIB_DIR): for f in os.listdir(dirpath): if f.startswith('__init__') or f.startswith('.') or \ f.startswith('sql') or f.startswith('invalid') or \ os.path.basename(f) in REGRESSION_SUBDIRS_TO_SKIP: continue models.append((loc, f)) return models def get_invalid_models(): models = [] for loc, dirpath in (MODEL_TESTS_DIR_NAME, MODEL_TEST_DIR), (REGRESSION_TESTS_DIR_NAME, REGRESSION_TEST_DIR), (CONTRIB_DIR_NAME, CONTRIB_DIR): for f in os.listdir(dirpath): if f.startswith('__init__') or f.startswith('.') or f.startswith('sql'): continue if f.startswith('invalid'): models.append((loc, f)) return models class InvalidModelTestCase(unittest.TestCase): def __init__(self, model_label): unittest.TestCase.__init__(self) self.model_label = model_label def runTest(self): from django.core.management.validation import get_validation_errors from django.db.models.loading import load_app from cStringIO import StringIO try: module = load_app(self.model_label) except Exception, e: self.fail('Unable to load invalid model module') # Make sure sys.stdout is not a tty so that we get errors without # coloring attached (makes matching the results easier). We restore # sys.stderr afterwards. orig_stdout = sys.stdout s = StringIO() sys.stdout = s count = get_validation_errors(s, module) sys.stdout = orig_stdout s.seek(0) error_log = s.read() actual = error_log.split('\n') expected = module.model_errors.split('\n') unexpected = [err for err in actual if err not in expected] missing = [err for err in expected if err not in actual] self.assert_(not unexpected, "Unexpected Errors: " + '\n'.join(unexpected)) self.assert_(not missing, "Missing Errors: " + '\n'.join(missing)) def setup(verbosity, test_labels): from django.conf import settings state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), 'TEMPLATE_DIRS': settings.TEMPLATE_DIRS, 'USE_I18N': settings.USE_I18N, 'LOGIN_URL': settings.LOGIN_URL, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'MIDDLEWARE_CLASSES': settings.MIDDLEWARE_CLASSES, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'urls' settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), TEST_TEMPLATE_DIR),) settings.USE_I18N = True settings.LANGUAGE_CODE = 'en' settings.LOGIN_URL = '/accounts/login/' settings.MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.common.CommonMiddleware', ) settings.SITE_ID = 1 # For testing comment-utils, we require the MANAGERS attribute # to be set, so that a test email is sent out which we catch # in our tests. settings.MANAGERS = ("[email protected]",) # Load all the ALWAYS_INSTALLED_APPS. # (This import statement is intentionally delayed until after we # access settings because of the USE_I18N dependency.) from django.db.models.loading import get_apps, load_app get_apps() # Load all the test model apps. test_labels_set = set([label.split('.')[0] for label in test_labels]) test_models = get_test_models() # If GeoDjango, then we'll want to add in the test applications # that are a part of its test suite. if geodjango(settings): from django.contrib.gis.tests import geo_apps test_models.extend(geo_apps(runtests=True)) for model_dir, model_name in test_models: model_label = '.'.join([model_dir, model_name]) # if the model was named on the command line, or # no models were named (i.e., run all), import # this model and add it to the list to test. if not test_labels or model_name in test_labels_set: if verbosity >= 1: print "Importing model %s" % model_name mod = load_app(model_label) if mod: if model_label not in settings.INSTALLED_APPS: settings.INSTALLED_APPS.append(model_label) return state def teardown(state): from django.conf import settings # Restore the old settings. for key, value in state.items(): setattr(settings, key, value) def django_tests(verbosity, interactive, failfast, test_labels): from django.conf import settings state = setup(verbosity, test_labels) # Add tests for invalid models. extra_tests = [] for model_dir, model_name in get_invalid_models(): model_label = '.'.join([model_dir, model_name]) if not test_labels or model_name in test_labels: extra_tests.append(InvalidModelTestCase(model_label)) try: # Invalid models are not working apps, so we cannot pass them into # the test runner with the other test_labels test_labels.remove(model_name) except ValueError: pass # If GeoDjango is used, add it's tests that aren't a part of # an application (e.g., GEOS, GDAL, Distance objects). if geodjango(settings): from django.contrib.gis.tests import geodjango_suite extra_tests.append(geodjango_suite(apps=False)) # Run the test suite, including the extra validation tests. from django.test.utils import get_runner if not hasattr(settings, 'TEST_RUNNER'): settings.TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner' TestRunner = get_runner(settings) if hasattr(TestRunner, 'func_name'): # Pre 1.2 test runners were just functions, # and did not support the 'failfast' option. import warnings warnings.warn( 'Function-based test runners are deprecated. Test runners should be classes with a run_tests() method.', PendingDeprecationWarning ) failures = TestRunner(test_labels, verbosity=verbosity, interactive=interactive, extra_tests=extra_tests) else: test_runner = TestRunner(verbosity=verbosity, interactive=interactive, failfast=failfast) failures = test_runner.run_tests(test_labels, extra_tests=extra_tests) teardown(state) return failures def bisect_tests(bisection_label, options, test_labels): state = setup(int(options.verbosity), test_labels) if not test_labels: # Get the full list of test labels to use for bisection from django.db.models.loading import get_apps test_labels = [app.__name__.split('.')[-2] for app in get_apps()] print '***** Bisecting test suite:',' '.join(test_labels) # Make sure the bisection point isn't in the test list # Also remove tests that need to be run in specific combinations for label in [bisection_label, 'model_inheritance_same_model_name']: try: test_labels.remove(label) except ValueError: pass subprocess_args = ['python','runtests.py', '--settings=%s' % options.settings] if options.failfast: subprocess_args.append('--failfast') if options.verbosity: subprocess_args.append('--verbosity=%s' % options.verbosity) if not options.interactive: subprocess_args.append('--noinput') iteration = 1 while len(test_labels) > 1: midpoint = len(test_labels)/2 test_labels_a = test_labels[:midpoint] + [bisection_label] test_labels_b = test_labels[midpoint:] + [bisection_label] print '***** Pass %da: Running the first half of the test suite' % iteration print '***** Test labels:',' '.join(test_labels_a) failures_a = subprocess.call(subprocess_args + test_labels_a) print '***** Pass %db: Running the second half of the test suite' % iteration print '***** Test labels:',' '.join(test_labels_b) print failures_b = subprocess.call(subprocess_args + test_labels_b) if failures_a and not failures_b: print "***** Problem found in first half. Bisecting again..." iteration = iteration + 1 test_labels = test_labels_a[:-1] elif failures_b and not failures_a: print "***** Problem found in second half. Bisecting again..." iteration = iteration + 1 test_labels = test_labels_b[:-1] elif failures_a and failures_b: print "***** Multiple sources of failure found" break else: print "***** No source of failure found... try pair execution (--pair)" break if len(test_labels) == 1: print "***** Source of error:",test_labels[0] teardown(state) def paired_tests(paired_test, options, test_labels): state = setup(int(options.verbosity), test_labels) if not test_labels: print "" # Get the full list of test labels to use for bisection from django.db.models.loading import get_apps test_labels = [app.__name__.split('.')[-2] for app in get_apps()] print '***** Trying paired execution' # Make sure the bisection point isn't in the test list # Also remove tests that need to be run in specific combinations for label in [paired_test, 'model_inheritance_same_model_name']: try: test_labels.remove(label) except ValueError: pass subprocess_args = ['python','runtests.py', '--settings=%s' % options.settings] if options.failfast: subprocess_args.append('--failfast') if options.verbosity: subprocess_args.append('--verbosity=%s' % options.verbosity) if not options.interactive: subprocess_args.append('--noinput') for i, label in enumerate(test_labels): print '***** %d of %d: Check test pairing with %s' % (i+1, len(test_labels), label) failures = subprocess.call(subprocess_args + [label, paired_test]) if failures: print '***** Found problem pair with',label return print '***** No problem pair found' teardown(state) if __name__ == "__main__": from optparse import OptionParser usage = "%prog [options] [model model model ...]" parser = OptionParser(usage=usage) parser.add_option('-v','--verbosity', action='store', dest='verbosity', default='0', type='choice', choices=['0', '1', '2'], help='Verbosity level; 0=minimal output, 1=normal output, 2=all output') parser.add_option('--noinput', action='store_false', dest='interactive', default=True, help='Tells Django to NOT prompt the user for input of any kind.') parser.add_option('--failfast', action='store_true', dest='failfast', default=False, help='Tells Django to stop running the test suite after first failed test.') parser.add_option('--settings', help='Python path to settings module, e.g. "myproject.settings". If this isn\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be used.') parser.add_option('--bisect', action='store', dest='bisect', default=None, help="Bisect the test suite to discover a test that causes a test failure when combined with the named test.") parser.add_option('--pair', action='store', dest='pair', default=None, help="Run the test suite in pairs with the named test to find problem pairs.") options, args = parser.parse_args() if options.settings: os.environ['DJANGO_SETTINGS_MODULE'] = options.settings elif "DJANGO_SETTINGS_MODULE" not in os.environ: parser.error("DJANGO_SETTINGS_MODULE is not set in the environment. " "Set it or use --settings.") if options.bisect: bisect_tests(options.bisect, options, args) elif options.pair: paired_tests(options.pair, options, args) else: failures = django_tests(int(options.verbosity), options.interactive, options.failfast, args) if failures: sys.exit(bool(failures))
13,764
Python
.py
287
40.142857
161
0.657581
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,948
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/test_utils/tests.py
r""" # Some checks of the doctest output normalizer. # Standard doctests do fairly >>> from django.utils import simplejson >>> from django.utils.xmlutils import SimplerXMLGenerator >>> from StringIO import StringIO >>> def produce_long(): ... return 42L >>> def produce_int(): ... return 42 >>> def produce_json(): ... return simplejson.dumps(['foo', {'bar': ('baz', None, 1.0, 2), 'whiz': 42}]) >>> def produce_xml(): ... stream = StringIO() ... xml = SimplerXMLGenerator(stream, encoding='utf-8') ... xml.startDocument() ... xml.startElement("foo", {"aaa" : "1.0", "bbb": "2.0"}) ... xml.startElement("bar", {"ccc" : "3.0"}) ... xml.characters("Hello") ... xml.endElement("bar") ... xml.startElement("whiz", {}) ... xml.characters("Goodbye") ... xml.endElement("whiz") ... xml.endElement("foo") ... xml.endDocument() ... return stream.getvalue() >>> def produce_xml_fragment(): ... stream = StringIO() ... xml = SimplerXMLGenerator(stream, encoding='utf-8') ... xml.startElement("foo", {"aaa": "1.0", "bbb": "2.0"}) ... xml.characters("Hello") ... xml.endElement("foo") ... xml.startElement("bar", {"ccc": "3.0", "ddd": "4.0"}) ... xml.endElement("bar") ... return stream.getvalue() # Long values are normalized and are comparable to normal integers ... >>> produce_long() 42 # ... and vice versa >>> produce_int() 42L # JSON output is normalized for field order, so it doesn't matter # which order json dictionary attributes are listed in output >>> produce_json() '["foo", {"bar": ["baz", null, 1.0, 2], "whiz": 42}]' >>> produce_json() '["foo", {"whiz": 42, "bar": ["baz", null, 1.0, 2]}]' # XML output is normalized for attribute order, so it doesn't matter # which order XML element attributes are listed in output >>> produce_xml() '<?xml version="1.0" encoding="UTF-8"?>\n<foo aaa="1.0" bbb="2.0"><bar ccc="3.0">Hello</bar><whiz>Goodbye</whiz></foo>' >>> produce_xml() '<?xml version="1.0" encoding="UTF-8"?>\n<foo bbb="2.0" aaa="1.0"><bar ccc="3.0">Hello</bar><whiz>Goodbye</whiz></foo>' >>> produce_xml_fragment() '<foo aaa="1.0" bbb="2.0">Hello</foo><bar ccc="3.0" ddd="4.0"></bar>' >>> produce_xml_fragment() '<foo bbb="2.0" aaa="1.0">Hello</foo><bar ddd="4.0" ccc="3.0"></bar>' """
2,307
Python
.py
58
38.517241
119
0.617174
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,949
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/syndication/models.py
from django.db import models class Entry(models.Model): title = models.CharField(max_length=200) date = models.DateTimeField() class Meta: ordering = ('date',) def __unicode__(self): return self.title def get_absolute_url(self): return "/blog/%s/" % self.pk class Article(models.Model): title = models.CharField(max_length=200) entry = models.ForeignKey(Entry) def __unicode__(self): return self.title
474
Python
.py
15
25.8
44
0.660754
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,950
feeds.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/syndication/feeds.py
from django.contrib.syndication import feeds, views from django.core.exceptions import ObjectDoesNotExist from django.utils import feedgenerator, tzinfo from models import Article, Entry class ComplexFeed(views.Feed): def get_object(self, request, foo=None): if foo is not None: raise ObjectDoesNotExist return None class TestRss2Feed(views.Feed): title = 'My blog' description = 'A more thorough description of my blog.' link = '/blog/' feed_guid = '/foo/bar/1234' author_name = 'Sally Smith' author_email = '[email protected]' author_link = 'http://www.example.com/' categories = ('python', 'django') feed_copyright = 'Copyright (c) 2007, Sally Smith' ttl = 600 def items(self): return Entry.objects.all() def item_description(self, item): return "Overridden description: %s" % item def item_pubdate(self, item): return item.date item_author_name = 'Sally Smith' item_author_email = '[email protected]' item_author_link = 'http://www.example.com/' item_categories = ('python', 'testing') item_copyright = 'Copyright (c) 2007, Sally Smith' class TestRss091Feed(TestRss2Feed): feed_type = feedgenerator.RssUserland091Feed class TestAtomFeed(TestRss2Feed): feed_type = feedgenerator.Atom1Feed subtitle = TestRss2Feed.description class ArticlesFeed(TestRss2Feed): """ A feed to test no link being defined. Articles have no get_absolute_url() method, and item_link() is not defined. """ def items(self): return Article.objects.all() class TestEnclosureFeed(TestRss2Feed): pass class TemplateFeed(TestRss2Feed): """ A feed to test defining item titles and descriptions with templates. """ title_template = 'syndication/title.html' description_template = 'syndication/description.html' # Defining a template overrides any item_title definition def item_title(self): return "Not in a template" class NaiveDatesFeed(TestAtomFeed): """ A feed with naive (non-timezone-aware) dates. """ def item_pubdate(self, item): return item.date class TZAwareDatesFeed(TestAtomFeed): """ A feed with timezone-aware dates. """ def item_pubdate(self, item): # Provide a weird offset so that the test can know it's getting this # specific offset and not accidentally getting on from # settings.TIME_ZONE. return item.date.replace(tzinfo=tzinfo.FixedOffset(42)) class TestFeedUrlFeed(TestAtomFeed): feed_url = 'http://example.com/customfeedurl/' class MyCustomAtom1Feed(feedgenerator.Atom1Feed): """ Test of a custom feed generator class. """ def root_attributes(self): attrs = super(MyCustomAtom1Feed, self).root_attributes() attrs[u'django'] = u'rocks' return attrs def add_root_elements(self, handler): super(MyCustomAtom1Feed, self).add_root_elements(handler) handler.addQuickElement(u'spam', u'eggs') def item_attributes(self, item): attrs = super(MyCustomAtom1Feed, self).item_attributes(item) attrs[u'bacon'] = u'yum' return attrs def add_item_elements(self, handler, item): super(MyCustomAtom1Feed, self).add_item_elements(handler, item) handler.addQuickElement(u'ministry', u'silly walks') class TestCustomFeed(TestAtomFeed): feed_type = MyCustomAtom1Feed class DeprecatedComplexFeed(feeds.Feed): def get_object(self, bits): if len(bits) != 1: raise ObjectDoesNotExist return None class DeprecatedRssFeed(feeds.Feed): link = "/blog/" title = 'My blog' def items(self): return Entry.objects.all() def item_link(self, item): return "/blog/%s/" % item.pk
3,833
Python
.py
103
31.368932
77
0.694934
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,951
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/syndication/urls.py
from django.conf.urls.defaults import * import feeds feed_dict = { 'complex': feeds.DeprecatedComplexFeed, 'rss': feeds.DeprecatedRssFeed, } urlpatterns = patterns('django.contrib.syndication.views', (r'^complex/(?P<foo>.*)/$', feeds.ComplexFeed()), (r'^rss2/$', feeds.TestRss2Feed()), (r'^rss091/$', feeds.TestRss091Feed()), (r'^atom/$', feeds.TestAtomFeed()), (r'^custom/$', feeds.TestCustomFeed()), (r'^naive-dates/$', feeds.NaiveDatesFeed()), (r'^aware-dates/$', feeds.TZAwareDatesFeed()), (r'^feedurl/$', feeds.TestFeedUrlFeed()), (r'^articles/$', feeds.ArticlesFeed()), (r'^template/$', feeds.TemplateFeed()), (r'^depr-feeds/(?P<url>.*)/$', 'feed', {'feed_dict': feed_dict}), (r'^depr-feeds-empty/(?P<url>.*)/$', 'feed', {'feed_dict': None}), )
811
Python
.py
20
36.55
70
0.625159
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,952
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/syndication/tests.py
import datetime from django.contrib.syndication import feeds, views from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from django.utils import tzinfo from django.utils.feedgenerator import rfc2822_date, rfc3339_date from models import Entry from xml.dom import minidom try: set except NameError: from sets import Set as set class FeedTestCase(TestCase): fixtures = ['feeddata.json'] def assertChildNodes(self, elem, expected): actual = set([n.nodeName for n in elem.childNodes]) expected = set(expected) self.assertEqual(actual, expected) def assertChildNodeContent(self, elem, expected): for k, v in expected.items(): self.assertEqual( elem.getElementsByTagName(k)[0].firstChild.wholeText, v) def assertCategories(self, elem, expected): self.assertEqual(set(i.firstChild.wholeText for i in elem.childNodes if i.nodeName == 'category'), set(expected)); ###################################### # Feed view ###################################### class SyndicationFeedTest(FeedTestCase): """ Tests for the high-level syndication feed framework. """ def test_rss2_feed(self): """ Test the structure and content of feeds generated by Rss201rev2Feed. """ response = self.client.get('/syndication/rss2/') doc = minidom.parseString(response.content) # Making sure there's only 1 `rss` element and that the correct # RSS version was specified. feed_elem = doc.getElementsByTagName('rss') self.assertEqual(len(feed_elem), 1) feed = feed_elem[0] self.assertEqual(feed.getAttribute('version'), '2.0') # Making sure there's only one `channel` element w/in the # `rss` element. chan_elem = feed.getElementsByTagName('channel') self.assertEqual(len(chan_elem), 1) chan = chan_elem[0] # Find the last build date d = Entry.objects.latest('date').date ltz = tzinfo.LocalTimezone(d) last_build_date = rfc2822_date(d.replace(tzinfo=ltz)) self.assertChildNodes(chan, ['title', 'link', 'description', 'language', 'lastBuildDate', 'item', 'atom:link', 'ttl', 'copyright', 'category']) self.assertChildNodeContent(chan, { 'title': 'My blog', 'description': 'A more thorough description of my blog.', 'link': 'http://example.com/blog/', 'language': 'en', 'lastBuildDate': last_build_date, #'atom:link': '', 'ttl': '600', 'copyright': 'Copyright (c) 2007, Sally Smith', }) self.assertCategories(chan, ['python', 'django']); # Ensure the content of the channel is correct self.assertChildNodeContent(chan, { 'title': 'My blog', 'link': 'http://example.com/blog/', }) # Check feed_url is passed self.assertEqual( chan.getElementsByTagName('atom:link')[0].getAttribute('href'), 'http://example.com/syndication/rss2/' ) # Find the pubdate of the first feed item d = Entry.objects.get(pk=1).date ltz = tzinfo.LocalTimezone(d) pub_date = rfc2822_date(d.replace(tzinfo=ltz)) items = chan.getElementsByTagName('item') self.assertEqual(len(items), Entry.objects.count()) self.assertChildNodeContent(items[0], { 'title': 'My first entry', 'description': 'Overridden description: My first entry', 'link': 'http://example.com/blog/1/', 'guid': 'http://example.com/blog/1/', 'pubDate': pub_date, 'author': '[email protected] (Sally Smith)', }) self.assertCategories(items[0], ['python', 'testing']); for item in items: self.assertChildNodes(item, ['title', 'link', 'description', 'guid', 'category', 'pubDate', 'author']) def test_rss091_feed(self): """ Test the structure and content of feeds generated by RssUserland091Feed. """ response = self.client.get('/syndication/rss091/') doc = minidom.parseString(response.content) # Making sure there's only 1 `rss` element and that the correct # RSS version was specified. feed_elem = doc.getElementsByTagName('rss') self.assertEqual(len(feed_elem), 1) feed = feed_elem[0] self.assertEqual(feed.getAttribute('version'), '0.91') # Making sure there's only one `channel` element w/in the # `rss` element. chan_elem = feed.getElementsByTagName('channel') self.assertEqual(len(chan_elem), 1) chan = chan_elem[0] self.assertChildNodes(chan, ['title', 'link', 'description', 'language', 'lastBuildDate', 'item', 'atom:link', 'ttl', 'copyright', 'category']) # Ensure the content of the channel is correct self.assertChildNodeContent(chan, { 'title': 'My blog', 'link': 'http://example.com/blog/', }) self.assertCategories(chan, ['python', 'django']) # Check feed_url is passed self.assertEqual( chan.getElementsByTagName('atom:link')[0].getAttribute('href'), 'http://example.com/syndication/rss091/' ) items = chan.getElementsByTagName('item') self.assertEqual(len(items), Entry.objects.count()) self.assertChildNodeContent(items[0], { 'title': 'My first entry', 'description': 'Overridden description: My first entry', 'link': 'http://example.com/blog/1/', }) for item in items: self.assertChildNodes(item, ['title', 'link', 'description']) self.assertCategories(item, []) def test_atom_feed(self): """ Test the structure and content of feeds generated by Atom1Feed. """ response = self.client.get('/syndication/atom/') feed = minidom.parseString(response.content).firstChild self.assertEqual(feed.nodeName, 'feed') self.assertEqual(feed.getAttribute('xmlns'), 'http://www.w3.org/2005/Atom') self.assertChildNodes(feed, ['title', 'subtitle', 'link', 'id', 'updated', 'entry', 'rights', 'category', 'author']) for link in feed.getElementsByTagName('link'): if link.getAttribute('rel') == 'self': self.assertEqual(link.getAttribute('href'), 'http://example.com/syndication/atom/') entries = feed.getElementsByTagName('entry') self.assertEqual(len(entries), Entry.objects.count()) for entry in entries: self.assertChildNodes(entry, ['title', 'link', 'id', 'summary', 'category', 'updated', 'rights', 'author']) summary = entry.getElementsByTagName('summary')[0] self.assertEqual(summary.getAttribute('type'), 'html') def test_custom_feed_generator(self): response = self.client.get('/syndication/custom/') feed = minidom.parseString(response.content).firstChild self.assertEqual(feed.nodeName, 'feed') self.assertEqual(feed.getAttribute('django'), 'rocks') self.assertChildNodes(feed, ['title', 'subtitle', 'link', 'id', 'updated', 'entry', 'spam', 'rights', 'category', 'author']) entries = feed.getElementsByTagName('entry') self.assertEqual(len(entries), Entry.objects.count()) for entry in entries: self.assertEqual(entry.getAttribute('bacon'), 'yum') self.assertChildNodes(entry, ['title', 'link', 'id', 'summary', 'ministry', 'rights', 'author', 'updated', 'category']) summary = entry.getElementsByTagName('summary')[0] self.assertEqual(summary.getAttribute('type'), 'html') def test_title_escaping(self): """ Tests that titles are escaped correctly in RSS feeds. """ response = self.client.get('/syndication/rss2/') doc = minidom.parseString(response.content) for item in doc.getElementsByTagName('item'): link = item.getElementsByTagName('link')[0] if link.firstChild.wholeText == 'http://example.com/blog/4/': title = item.getElementsByTagName('title')[0] self.assertEquals(title.firstChild.wholeText, u'A &amp; B &lt; C &gt; D') def test_naive_datetime_conversion(self): """ Test that datetimes are correctly converted to the local time zone. """ # Naive date times passed in get converted to the local time zone, so # check the recived zone offset against the local offset. response = self.client.get('/syndication/naive-dates/') doc = minidom.parseString(response.content) updated = doc.getElementsByTagName('updated')[0].firstChild.wholeText d = Entry.objects.latest('date').date ltz = tzinfo.LocalTimezone(d) latest = rfc3339_date(d.replace(tzinfo=ltz)) self.assertEqual(updated, latest) def test_aware_datetime_conversion(self): """ Test that datetimes with timezones don't get trodden on. """ response = self.client.get('/syndication/aware-dates/') doc = minidom.parseString(response.content) updated = doc.getElementsByTagName('updated')[0].firstChild.wholeText self.assertEqual(updated[-6:], '+00:42') def test_feed_url(self): """ Test that the feed_url can be overridden. """ response = self.client.get('/syndication/feedurl/') doc = minidom.parseString(response.content) for link in doc.getElementsByTagName('link'): if link.getAttribute('rel') == 'self': self.assertEqual(link.getAttribute('href'), 'http://example.com/customfeedurl/') def test_secure_urls(self): """ Test URLs are prefixed with https:// when feed is requested over HTTPS. """ response = self.client.get('/syndication/rss2/', **{ 'wsgi.url_scheme': 'https', }) doc = minidom.parseString(response.content) chan = doc.getElementsByTagName('channel')[0] self.assertEqual( chan.getElementsByTagName('link')[0].firstChild.wholeText[0:5], 'https' ) atom_link = chan.getElementsByTagName('atom:link')[0] self.assertEqual(atom_link.getAttribute('href')[0:5], 'https') for link in doc.getElementsByTagName('link'): if link.getAttribute('rel') == 'self': self.assertEqual(link.getAttribute('href')[0:5], 'https') def test_item_link_error(self): """ Test that a ImproperlyConfigured is raised if no link could be found for the item(s). """ self.assertRaises(ImproperlyConfigured, self.client.get, '/syndication/articles/') def test_template_feed(self): """ Test that the item title and description can be overridden with templates. """ response = self.client.get('/syndication/template/') doc = minidom.parseString(response.content) feed = doc.getElementsByTagName('rss')[0] chan = feed.getElementsByTagName('channel')[0] items = chan.getElementsByTagName('item') self.assertChildNodeContent(items[0], { 'title': 'Title in your templates: My first entry', 'description': 'Description in your templates: My first entry', 'link': 'http://example.com/blog/1/', }) def test_add_domain(self): """ Test add_domain() prefixes domains onto the correct URLs. """ self.assertEqual( views.add_domain('example.com', '/foo/?arg=value'), 'http://example.com/foo/?arg=value' ) self.assertEqual( views.add_domain('example.com', '/foo/?arg=value', True), 'https://example.com/foo/?arg=value' ) self.assertEqual( views.add_domain('example.com', 'http://djangoproject.com/doc/'), 'http://djangoproject.com/doc/' ) self.assertEqual( views.add_domain('example.com', 'https://djangoproject.com/doc/'), 'https://djangoproject.com/doc/' ) self.assertEqual( views.add_domain('example.com', 'mailto:[email protected]'), 'mailto:[email protected]' ) ###################################### # Deprecated feeds ###################################### class DeprecatedSyndicationFeedTest(FeedTestCase): """ Tests for the deprecated API (feed() view and the feed_dict etc). """ def test_empty_feed_dict(self): """ Test that an empty feed_dict raises a 404. """ response = self.client.get('/syndication/depr-feeds-empty/aware-dates/') self.assertEquals(response.status_code, 404) def test_nonexistent_slug(self): """ Test that a non-existent slug raises a 404. """ response = self.client.get('/syndication/depr-feeds/foobar/') self.assertEquals(response.status_code, 404) def test_rss_feed(self): """ A simple test for Rss201rev2Feed feeds generated by the deprecated system. """ response = self.client.get('/syndication/depr-feeds/rss/') doc = minidom.parseString(response.content) feed = doc.getElementsByTagName('rss')[0] self.assertEqual(feed.getAttribute('version'), '2.0') chan = feed.getElementsByTagName('channel')[0] self.assertChildNodes(chan, ['title', 'link', 'description', 'language', 'lastBuildDate', 'item', 'atom:link']) items = chan.getElementsByTagName('item') self.assertEqual(len(items), Entry.objects.count()) def test_complex_base_url(self): """ Tests that the base url for a complex feed doesn't raise a 500 exception. """ response = self.client.get('/syndication/depr-feeds/complex/') self.assertEquals(response.status_code, 404)
14,191
Python
.py
306
37.055556
151
0.615685
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,953
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/select_related_regress/models.py
from django.db import models class Building(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return u"Building: %s" % self.name class Device(models.Model): building = models.ForeignKey('Building') name = models.CharField(max_length=10) def __unicode__(self): return u"device '%s' in building %s" % (self.name, self.building) class Port(models.Model): device = models.ForeignKey('Device') port_number = models.CharField(max_length=10) def __unicode__(self): return u"%s/%s" % (self.device.name, self.port_number) class Connection(models.Model): start = models.ForeignKey(Port, related_name='connection_start', unique=True) end = models.ForeignKey(Port, related_name='connection_end', unique=True) def __unicode__(self): return u"%s to %s" % (self.start, self.end) # Another non-tree hierarchy that exercises code paths similar to the above # example, but in a slightly different configuration. class TUser(models.Model): name = models.CharField(max_length=200) class Person(models.Model): user = models.ForeignKey(TUser, unique=True) class Organizer(models.Model): person = models.ForeignKey(Person) class Student(models.Model): person = models.ForeignKey(Person) class Class(models.Model): org = models.ForeignKey(Organizer) class Enrollment(models.Model): std = models.ForeignKey(Student) cls = models.ForeignKey(Class) # Models for testing bug #8036. class Country(models.Model): name = models.CharField(max_length=50) class State(models.Model): name = models.CharField(max_length=50) country = models.ForeignKey(Country) class ClientStatus(models.Model): name = models.CharField(max_length=50) class Client(models.Model): name = models.CharField(max_length=50) state = models.ForeignKey(State, null=True) status = models.ForeignKey(ClientStatus) class SpecialClient(Client): value = models.IntegerField() # Some model inheritance exercises class Parent(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return self.name class Child(Parent): value = models.IntegerField() class Item(models.Model): name = models.CharField(max_length=10) child = models.ForeignKey(Child, null=True) def __unicode__(self): return self.name
2,390
Python
.py
62
34.129032
77
0.722222
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,954
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/select_related_regress/tests.py
from django.test import TestCase from regressiontests.select_related_regress.models import * class SelectRelatedRegressTests(TestCase): def test_regression_7110(self): """ Regression test for bug #7110. When using select_related(), we must query the Device and Building tables using two different aliases (each) in order to differentiate the start and end Connection fields. The net result is that both the "connections = ..." queries here should give the same results without pulling in more than the absolute minimum number of tables (history has shown that it's easy to make a mistake in the implementation and include some unnecessary bonus joins). """ b=Building.objects.create(name='101') dev1=Device.objects.create(name="router", building=b) dev2=Device.objects.create(name="switch", building=b) dev3=Device.objects.create(name="server", building=b) port1=Port.objects.create(port_number='4',device=dev1) port2=Port.objects.create(port_number='7',device=dev2) port3=Port.objects.create(port_number='1',device=dev3) c1=Connection.objects.create(start=port1, end=port2) c2=Connection.objects.create(start=port2, end=port3) connections=Connection.objects.filter(start__device__building=b, end__device__building=b).order_by('id') self.assertEquals([(c.id, unicode(c.start), unicode(c.end)) for c in connections], [(1, u'router/4', u'switch/7'), (2, u'switch/7', u'server/1')]) connections=Connection.objects.filter(start__device__building=b, end__device__building=b).select_related().order_by('id') self.assertEquals([(c.id, unicode(c.start), unicode(c.end)) for c in connections], [(1, u'router/4', u'switch/7'), (2, u'switch/7', u'server/1')]) # This final query should only join seven tables (port, device and building # twice each, plus connection once). self.assertEquals(connections.query.count_active_tables(), 7) def test_regression_8106(self): """ Regression test for bug #8106. Same sort of problem as the previous test, but this time there are more extra tables to pull in as part of the select_related() and some of them could potentially clash (so need to be kept separate). """ us = TUser.objects.create(name="std") usp = Person.objects.create(user=us) uo = TUser.objects.create(name="org") uop = Person.objects.create(user=uo) s = Student.objects.create(person = usp) o = Organizer.objects.create(person = uop) c = Class.objects.create(org=o) e = Enrollment.objects.create(std=s, cls=c) e_related = Enrollment.objects.all().select_related()[0] self.assertEquals(e_related.std.person.user.name, u"std") self.assertEquals(e_related.cls.org.person.user.name, u"org") def test_regression_8036(self): """ Regression test for bug #8036 the first related model in the tests below ("state") is empty and we try to select the more remotely related state__country. The regression here was not skipping the empty column results for country before getting status. """ australia = Country.objects.create(name='Australia') active = ClientStatus.objects.create(name='active') client = Client.objects.create(name='client', status=active) self.assertEquals(client.status, active) self.assertEquals(Client.objects.select_related()[0].status, active) self.assertEquals(Client.objects.select_related('state')[0].status, active) self.assertEquals(Client.objects.select_related('state', 'status')[0].status, active) self.assertEquals(Client.objects.select_related('state__country')[0].status, active) self.assertEquals(Client.objects.select_related('state__country', 'status')[0].status, active) self.assertEquals(Client.objects.select_related('status')[0].status, active) def test_multi_table_inheritance(self): """ Exercising select_related() with multi-table model inheritance. """ c1 = Child.objects.create(name="child1", value=42) i1 = Item.objects.create(name="item1", child=c1) i2 = Item.objects.create(name="item2") self.assertQuerysetEqual( Item.objects.select_related("child").order_by("name"), ["<Item: item1>", "<Item: item2>"] ) def test_regression_12851(self): """ Regression for #12851 Deferred fields are used correctly if you select_related a subset of fields. """ australia = Country.objects.create(name='Australia') active = ClientStatus.objects.create(name='active') wa = State.objects.create(name="Western Australia", country=australia) c1 = Client.objects.create(name='Brian Burke', state=wa, status=active) burke = Client.objects.select_related('state').defer('state__name').get(name='Brian Burke') self.assertEquals(burke.name, u'Brian Burke') self.assertEquals(burke.state.name, u'Western Australia') # Still works if we're dealing with an inherited class sc1 = SpecialClient.objects.create(name='Troy Buswell', state=wa, status=active, value=42) troy = SpecialClient.objects.select_related('state').defer('state__name').get(name='Troy Buswell') self.assertEquals(troy.name, u'Troy Buswell') self.assertEquals(troy.value, 42) self.assertEquals(troy.state.name, u'Western Australia') # Still works if we defer an attribute on the inherited class troy = SpecialClient.objects.select_related('state').defer('value', 'state__name').get(name='Troy Buswell') self.assertEquals(troy.name, u'Troy Buswell') self.assertEquals(troy.value, 42) self.assertEquals(troy.state.name, u'Western Australia') # Also works if you use only, rather than defer troy = SpecialClient.objects.select_related('state').only('name').get(name='Troy Buswell') self.assertEquals(troy.name, u'Troy Buswell') self.assertEquals(troy.value, 42) self.assertEquals(troy.state.name, u'Western Australia')
6,343
Python
.py
106
50.764151
129
0.676115
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,955
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/context_processors/urls.py
from django.conf.urls.defaults import * import views urlpatterns = patterns('', (r'^request_attrs/$', views.request_processor), (r'^auth_processor_no_attr_access/$', views.auth_processor_no_attr_access), (r'^auth_processor_attr_access/$', views.auth_processor_attr_access), (r'^auth_processor_user/$', views.auth_processor_user), (r'^auth_processor_perms/$', views.auth_processor_perms), (r'^auth_processor_messages/$', views.auth_processor_messages), url(r'^userpage/(.+)/$', views.userpage, name="userpage"), )
544
Python
.py
11
45.636364
79
0.7
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,956
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/context_processors/tests.py
""" Tests for Django's bundled context processors. """ from django.conf import settings from django.contrib.auth import authenticate from django.db.models import Q from django.test import TestCase from django.template import Template class RequestContextProcessorTests(TestCase): """ Tests for the ``django.core.context_processors.request`` processor. """ urls = 'regressiontests.context_processors.urls' def test_request_attributes(self): """ Test that the request object is available in the template and that its attributes can't be overridden by GET and POST parameters (#3828). """ url = '/request_attrs/' # We should have the request object in the template. response = self.client.get(url) self.assertContains(response, 'Have request') # Test is_secure. response = self.client.get(url) self.assertContains(response, 'Not secure') response = self.client.get(url, {'is_secure': 'blah'}) self.assertContains(response, 'Not secure') response = self.client.post(url, {'is_secure': 'blah'}) self.assertContains(response, 'Not secure') # Test path. response = self.client.get(url) self.assertContains(response, url) response = self.client.get(url, {'path': '/blah/'}) self.assertContains(response, url) response = self.client.post(url, {'path': '/blah/'}) self.assertContains(response, url) class AuthContextProcessorTests(TestCase): """ Tests for the ``django.contrib.auth.context_processors.auth`` processor """ urls = 'regressiontests.context_processors.urls' fixtures = ['context-processors-users.xml'] def test_session_not_accessed(self): """ Tests that the session is not accessed simply by including the auth context processor """ response = self.client.get('/auth_processor_no_attr_access/') self.assertContains(response, "Session not accessed") def test_session_is_accessed(self): """ Tests that the session is accessed if the auth context processor is used and relevant attributes accessed. """ response = self.client.get('/auth_processor_attr_access/') self.assertContains(response, "Session accessed") def test_perms_attrs(self): self.client.login(username='super', password='secret') response = self.client.get('/auth_processor_perms/') self.assertContains(response, "Has auth permissions") def test_message_attrs(self): self.client.login(username='super', password='secret') response = self.client.get('/auth_processor_messages/') self.assertContains(response, "Message 1") def test_user_attrs(self): """ Test that the lazy objects returned behave just like the wrapped objects. """ # These are 'functional' level tests for common use cases. Direct # testing of the implementation (SimpleLazyObject) is in the 'utils' # tests. self.client.login(username='super', password='secret') user = authenticate(username='super', password='secret') response = self.client.get('/auth_processor_user/') self.assertContains(response, "unicode: super") self.assertContains(response, "id: 100") self.assertContains(response, "username: super") # bug #12037 is tested by the {% url %} in the template: self.assertContains(response, "url: /userpage/super/") # See if this object can be used for queries where a Q() comparing # a user can be used with another Q() (in an AND or OR fashion). # This simulates what a template tag might do with the user from the # context. Note that we don't need to execute a query, just build it. # # The failure case (bug #12049) on Python 2.4 with a LazyObject-wrapped # User is a fatal TypeError: "function() takes at least 2 arguments # (0 given)" deep inside deepcopy(). # # Python 2.5 and 2.6 succeeded, but logged internally caught exception # spew: # # Exception RuntimeError: 'maximum recursion depth exceeded while # calling a Python object' in <type 'exceptions.AttributeError'> # ignored" query = Q(user=response.context['user']) & Q(someflag=True) # Tests for user equality. This is hard because User defines # equality in a non-duck-typing way # See bug #12060 self.assertEqual(response.context['user'], user) self.assertEqual(user, response.context['user'])
4,683
Python
.py
100
39.11
81
0.663531
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,957
views.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/context_processors/views.py
from django.core import context_processors from django.shortcuts import render_to_response from django.template.context import RequestContext def request_processor(request): return render_to_response('context_processors/request_attrs.html', RequestContext(request, {}, processors=[context_processors.request])) def auth_processor_no_attr_access(request): r1 = render_to_response('context_processors/auth_attrs_no_access.html', RequestContext(request, {}, processors=[context_processors.auth])) # *After* rendering, we check whether the session was accessed return render_to_response('context_processors/auth_attrs_test_access.html', {'session_accessed':request.session.accessed}) def auth_processor_attr_access(request): r1 = render_to_response('context_processors/auth_attrs_access.html', RequestContext(request, {}, processors=[context_processors.auth])) return render_to_response('context_processors/auth_attrs_test_access.html', {'session_accessed':request.session.accessed}) def auth_processor_user(request): return render_to_response('context_processors/auth_attrs_user.html', RequestContext(request, {}, processors=[context_processors.auth])) def auth_processor_perms(request): return render_to_response('context_processors/auth_attrs_perms.html', RequestContext(request, {}, processors=[context_processors.auth])) def auth_processor_messages(request): request.user.message_set.create(message="Message 1") return render_to_response('context_processors/auth_attrs_messages.html', RequestContext(request, {}, processors=[context_processors.auth])) def userpage(request): pass
1,698
Python
.py
29
53.517241
79
0.762793
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,958
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/admin_ordering/models.py
# coding: utf-8 from django.db import models class Band(models.Model): name = models.CharField(max_length=100) bio = models.TextField() rank = models.IntegerField() class Meta: ordering = ('name',)
224
Python
.py
8
23.75
43
0.682243
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,959
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/admin_ordering/tests.py
from django.test import TestCase from django.contrib.admin.options import ModelAdmin from models import Band class TestAdminOrdering(TestCase): """ Let's make sure that ModelAdmin.queryset uses the ordering we define in ModelAdmin rather that ordering defined in the model's inner Meta class. """ def setUp(self): b1 = Band(name='Aerosmith', bio='', rank=3) b1.save() b2 = Band(name='Radiohead', bio='', rank=1) b2.save() b3 = Band(name='Van Halen', bio='', rank=2) b3.save() def test_default_ordering(self): """ The default ordering should be by name, as specified in the inner Meta class. """ ma = ModelAdmin(Band, None) names = [b.name for b in ma.queryset(None)] self.assertEqual([u'Aerosmith', u'Radiohead', u'Van Halen'], names) def test_specified_ordering(self): """ Let's use a custom ModelAdmin that changes the ordering, and make sure it actually changes. """ class BandAdmin(ModelAdmin): ordering = ('rank',) # default ordering is ('name',) ma = BandAdmin(Band, None) names = [b.name for b in ma.queryset(None)] self.assertEqual([u'Radiohead', u'Van Halen', u'Aerosmith'], names)
1,308
Python
.py
34
31.088235
78
0.627266
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,960
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/m2m_regress/models.py
from django.db import models from django.contrib.auth import models as auth # No related name is needed here, since symmetrical relations are not # explicitly reversible. class SelfRefer(models.Model): name = models.CharField(max_length=10) references = models.ManyToManyField('self') related = models.ManyToManyField('self') def __unicode__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return self.name # Regression for #11956 -- a many to many to the base class class TagCollection(Tag): tags = models.ManyToManyField(Tag, related_name='tag_collections') def __unicode__(self): return self.name # A related_name is required on one of the ManyToManyField entries here because # they are both addressable as reverse relations from Tag. class Entry(models.Model): name = models.CharField(max_length=10) topics = models.ManyToManyField(Tag) related = models.ManyToManyField(Tag, related_name="similar") def __unicode__(self): return self.name # Two models both inheriting from a base model with a self-referential m2m field class SelfReferChild(SelfRefer): pass class SelfReferChildSibling(SelfRefer): pass # Many-to-Many relation between models, where one of the PK's isn't an Autofield class Line(models.Model): name = models.CharField(max_length=100) class Worksheet(models.Model): id = models.CharField(primary_key=True, max_length=100) lines = models.ManyToManyField(Line, blank=True, null=True) # Regression for #11226 -- A model with the same name that another one to # which it has a m2m relation. This shouldn't cause a name clash between # the automatically created m2m intermediary table FK field names when # running syncdb class User(models.Model): name = models.CharField(max_length=30) friends = models.ManyToManyField(auth.User)
1,930
Python
.py
45
39.2
80
0.755342
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,961
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/m2m_regress/tests.py
from django.core.exceptions import FieldError from django.test import TestCase from models import (SelfRefer, Tag, TagCollection, Entry, SelfReferChild, SelfReferChildSibling, Worksheet) class M2MRegressionTests(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_multiple_m2m(self): # Multiple m2m references to model must be distinguished when # accessing the relations through an instance attribute. s1 = SelfRefer.objects.create(name='s1') s2 = SelfRefer.objects.create(name='s2') s3 = SelfRefer.objects.create(name='s3') s1.references.add(s2) s1.related.add(s3) e1 = Entry.objects.create(name='e1') t1 = Tag.objects.create(name='t1') t2 = Tag.objects.create(name='t2') e1.topics.add(t1) e1.related.add(t2) self.assertQuerysetEqual(s1.references.all(), ["<SelfRefer: s2>"]) self.assertQuerysetEqual(s1.related.all(), ["<SelfRefer: s3>"]) self.assertQuerysetEqual(e1.topics.all(), ["<Tag: t1>"]) self.assertQuerysetEqual(e1.related.all(), ["<Tag: t2>"]) def test_internal_related_name_not_in_error_msg(self): # The secret internal related names for self-referential many-to-many # fields shouldn't appear in the list when an error is made. self.assertRaisesErrorWithMessage(FieldError, "Cannot resolve keyword 'porcupine' into field. Choices are: id, name, references, related, selfreferchild, selfreferchildsibling", lambda: SelfRefer.objects.filter(porcupine='fred') ) def test_m2m_inheritance_symmetry(self): # Test to ensure that the relationship between two inherited models # with a self-referential m2m field maintains symmetry sr_child = SelfReferChild(name="Hanna") sr_child.save() sr_sibling = SelfReferChildSibling(name="Beth") sr_sibling.save() sr_child.related.add(sr_sibling) self.assertQuerysetEqual(sr_child.related.all(), ["<SelfRefer: Beth>"]) self.assertQuerysetEqual(sr_sibling.related.all(), ["<SelfRefer: Hanna>"]) def test_m2m_pk_field_type(self): # Regression for #11311 - The primary key for models in a m2m relation # doesn't have to be an AutoField w = Worksheet(id='abc') w.save() w.delete() def test_add_m2m_with_base_class(self): # Regression for #11956 -- You can add an object to a m2m with the # base class without causing integrity errors t1 = Tag.objects.create(name='t1') t2 = Tag.objects.create(name='t2') c1 = TagCollection.objects.create(name='c1') c1.tags = [t1,t2] c1 = TagCollection.objects.get(name='c1') self.assertQuerysetEqual(c1.tags.all(), ["<Tag: t1>", "<Tag: t2>"]) self.assertQuerysetEqual(t1.tag_collections.all(), ["<TagCollection: c1>"])
3,145
Python
.py
61
42.934426
143
0.663728
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,962
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/admin_inlines/models.py
""" Testing of admin inline formsets. """ from django.db import models from django.contrib import admin from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class Parent(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class Child(models.Model): name = models.CharField(max_length=50) teacher = models.ForeignKey(Teacher) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() parent = generic.GenericForeignKey() def __unicode__(self): return u'I am %s, a child of %s' % (self.name, self.parent) class Book(models.Model): name = models.CharField(max_length=50) class Author(models.Model): name = models.CharField(max_length=50) books = models.ManyToManyField(Book) class BookInline(admin.TabularInline): model = Author.books.through class AuthorAdmin(admin.ModelAdmin): inlines = [BookInline] admin.site.register(Author, AuthorAdmin) class Holder(models.Model): dummy = models.IntegerField() class Inner(models.Model): dummy = models.IntegerField() holder = models.ForeignKey(Holder) readonly = models.CharField("Inner readonly label", max_length=1) class InnerInline(admin.StackedInline): model = Inner can_delete = False readonly_fields = ('readonly',) # For bug #13174 tests. class Holder2(models.Model): dummy = models.IntegerField() class Inner2(models.Model): dummy = models.IntegerField() holder = models.ForeignKey(Holder2) class HolderAdmin(admin.ModelAdmin): class Media: js = ('my_awesome_admin_scripts.js',) class InnerInline2(admin.StackedInline): model = Inner2 class Media: js = ('my_awesome_inline_scripts.js',) class Holder3(models.Model): dummy = models.IntegerField() class Inner3(models.Model): dummy = models.IntegerField() holder = models.ForeignKey(Holder3) class InnerInline3(admin.StackedInline): model = Inner3 class Media: js = ('my_awesome_inline_scripts.js',) # Test bug #12561 and #12778 # only ModelAdmin media admin.site.register(Holder, HolderAdmin, inlines=[InnerInline]) # ModelAdmin and Inline media admin.site.register(Holder2, HolderAdmin, inlines=[InnerInline2]) # only Inline media admin.site.register(Holder3, inlines=[InnerInline3]) # Models for #12749 class Person(models.Model): firstname = models.CharField(max_length=15) class OutfitItem(models.Model): name = models.CharField(max_length=15) class Fashionista(models.Model): person = models.OneToOneField(Person, primary_key=True) weaknesses = models.ManyToManyField(OutfitItem, through='ShoppingWeakness', blank=True) class ShoppingWeakness(models.Model): fashionista = models.ForeignKey(Fashionista) item = models.ForeignKey(OutfitItem) class InlineWeakness(admin.TabularInline): model = ShoppingWeakness extra = 1 admin.site.register(Fashionista, inlines=[InlineWeakness])
3,164
Python
.py
86
32.872093
91
0.752221
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,963
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/admin_inlines/tests.py
from django.contrib.admin.helpers import InlineAdminForm from django.contrib.contenttypes.models import ContentType from django.test import TestCase # local test models from models import (Holder, Inner, InnerInline, Holder2, Inner2, Holder3, Inner3, Person, OutfitItem, Fashionista, Teacher, Parent, Child) class TestInline(TestCase): fixtures = ['admin-views-users.xml'] def setUp(self): holder = Holder(dummy=13) holder.save() Inner(dummy=42, holder=holder).save() self.change_url = '/test_admin/admin/admin_inlines/holder/%i/' % holder.id result = self.client.login(username='super', password='secret') self.assertEqual(result, True) def tearDown(self): self.client.logout() def test_can_delete(self): """ can_delete should be passed to inlineformset factory. """ response = self.client.get(self.change_url) inner_formset = response.context[-1]['inline_admin_formsets'][0].formset expected = InnerInline.can_delete actual = inner_formset.can_delete self.assertEqual(expected, actual, 'can_delete must be equal') def test_readonly_stacked_inline_label(self): """Bug #13174.""" holder = Holder.objects.create(dummy=42) inner = Inner.objects.create(holder=holder, dummy=42, readonly='') response = self.client.get('/test_admin/admin/admin_inlines/holder/%i/' % holder.id) self.assertContains(response, '<label>Inner readonly label:</label>') def test_many_to_many_inlines(self): "Autogenerated many-to-many inlines are displayed correctly (#13407)" response = self.client.get('/test_admin/admin/admin_inlines/author/add/') # The heading for the m2m inline block uses the right text self.assertContains(response, '<h2>Author-book relationships</h2>') # The "add another" label is correct self.assertContains(response, 'Add another Author-Book Relationship') # The '+' is dropped from the autogenerated form prefix (Author_books+) self.assertContains(response, 'id="id_Author_books-TOTAL_FORMS"') def test_inline_primary(self): person = Person.objects.create(firstname='Imelda') item = OutfitItem.objects.create(name='Shoes') # Imelda likes shoes, but can't cary her own bags. data = { 'shoppingweakness_set-TOTAL_FORMS': 1, 'shoppingweakness_set-INITIAL_FORMS': 0, 'shoppingweakness_set-MAX_NUM_FORMS': 0, '_save': u'Save', 'person': person.id, 'max_weight': 0, 'shoppingweakness_set-0-item': item.id, } response = self.client.post('/test_admin/admin/admin_inlines/fashionista/add/', data) self.assertEqual(response.status_code, 302) self.assertEqual(len(Fashionista.objects.filter(person__firstname='Imelda')), 1) class TestInlineMedia(TestCase): fixtures = ['admin-views-users.xml'] def setUp(self): result = self.client.login(username='super', password='secret') self.assertEqual(result, True) def tearDown(self): self.client.logout() def test_inline_media_only_base(self): holder = Holder(dummy=13) holder.save() Inner(dummy=42, holder=holder).save() change_url = '/test_admin/admin/admin_inlines/holder/%i/' % holder.id response = self.client.get(change_url) self.assertContains(response, 'my_awesome_admin_scripts.js') def test_inline_media_only_inline(self): holder = Holder3(dummy=13) holder.save() Inner3(dummy=42, holder=holder).save() change_url = '/test_admin/admin/admin_inlines/holder3/%i/' % holder.id response = self.client.get(change_url) self.assertContains(response, 'my_awesome_inline_scripts.js') def test_all_inline_media(self): holder = Holder2(dummy=13) holder.save() Inner2(dummy=42, holder=holder).save() change_url = '/test_admin/admin/admin_inlines/holder2/%i/' % holder.id response = self.client.get(change_url) self.assertContains(response, 'my_awesome_admin_scripts.js') self.assertContains(response, 'my_awesome_inline_scripts.js') class TestInlineAdminForm(TestCase): def test_immutable_content_type(self): """Regression for #9362 The problem depends only on InlineAdminForm and its "original" argument, so we can safely set the other arguments to None/{}. We just need to check that the content_type argument of Child isn't altered by the internals of the inline form.""" sally = Teacher.objects.create(name='Sally') john = Parent.objects.create(name='John') joe = Child.objects.create(name='Joe', teacher=sally, parent=john) iaf = InlineAdminForm(None, None, {}, {}, joe) parent_ct = ContentType.objects.get_for_model(Parent) self.assertEqual(iaf.original.content_type, parent_ct)
5,068
Python
.py
100
42.16
93
0.66606
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,964
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/m2m_through_regress/models.py
from datetime import datetime from django.contrib.auth.models import User from django.core import management from django.db import models # Forward declared intermediate model class Membership(models.Model): person = models.ForeignKey('Person') group = models.ForeignKey('Group') price = models.IntegerField(default=100) def __unicode__(self): return "%s is a member of %s" % (self.person.name, self.group.name) # using custom id column to test ticket #11107 class UserMembership(models.Model): id = models.AutoField(db_column='usermembership_id', primary_key=True) user = models.ForeignKey(User) group = models.ForeignKey('Group') price = models.IntegerField(default=100) def __unicode__(self): return "%s is a user and member of %s" % (self.user.username, self.group.name) class Person(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) # Membership object defined as a class members = models.ManyToManyField(Person, through=Membership) user_members = models.ManyToManyField(User, through='UserMembership') def __unicode__(self): return self.name # A set of models that use an non-abstract inherited model as the 'through' model. class A(models.Model): a_text = models.CharField(max_length=20) class ThroughBase(models.Model): a = models.ForeignKey(A) b = models.ForeignKey('B') class Through(ThroughBase): extra = models.CharField(max_length=20) class B(models.Model): b_text = models.CharField(max_length=20) a_list = models.ManyToManyField(A, through=Through) # Using to_field on the through model class Car(models.Model): make = models.CharField(max_length=20, unique=True) drivers = models.ManyToManyField('Driver', through='CarDriver') def __unicode__(self, ): return self.make class Driver(models.Model): name = models.CharField(max_length=20, unique=True) def __unicode__(self, ): return self.name class CarDriver(models.Model): car = models.ForeignKey('Car', to_field='make') driver = models.ForeignKey('Driver', to_field='name') def __unicode__(self, ): return u"pk=%s car=%s driver=%s" % (str(self.pk), self.car, self.driver)
2,347
Python
.py
56
37.392857
86
0.7163
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,965
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/m2m_through_regress/tests.py
try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.core import management from django.contrib.auth.models import User from django.test import TestCase from models import (Person, Group, Membership, UserMembership, Car, Driver, CarDriver) class M2MThroughTestCase(TestCase): def test_everything(self): bob = Person.objects.create(name="Bob") jim = Person.objects.create(name="Jim") rock = Group.objects.create(name="Rock") roll = Group.objects.create(name="Roll") frank = User.objects.create_user("frank", "[email protected]", "password") jane = User.objects.create_user("jane", "[email protected]", "password") Membership.objects.create(person=bob, group=rock) Membership.objects.create(person=bob, group=roll) Membership.objects.create(person=jim, group=rock) self.assertQuerysetEqual( bob.group_set.all(), [ "<Group: Rock>", "<Group: Roll>", ] ) self.assertQuerysetEqual( roll.members.all(), [ "<Person: Bob>", ] ) self.assertRaises(AttributeError, setattr, bob, "group_set", []) self.assertRaises(AttributeError, setattr, roll, "members", []) self.assertRaises(AttributeError, rock.members.create, name="Anne") self.assertRaises(AttributeError, bob.group_set.create, name="Funk") UserMembership.objects.create(user=frank, group=rock) UserMembership.objects.create(user=frank, group=roll) UserMembership.objects.create(user=jane, group=rock) self.assertQuerysetEqual( frank.group_set.all(), [ "<Group: Rock>", "<Group: Roll>", ] ) self.assertQuerysetEqual( roll.user_members.all(), [ "<User: frank>", ] ) def test_serialization(self): "m2m-through models aren't serialized as m2m fields. Refs #8134" p = Person.objects.create(name="Bob") g = Group.objects.create(name="Roll") m = Membership.objects.create(person=p, group=g) pks = {"p_pk": p.pk, "g_pk": g.pk, "m_pk": m.pk} out = StringIO() management.call_command("dumpdata", "m2m_through_regress", format="json", stdout=out) self.assertEqual(out.getvalue().strip(), """[{"pk": %(m_pk)s, "model": "m2m_through_regress.membership", "fields": {"person": %(p_pk)s, "price": 100, "group": %(g_pk)s}}, {"pk": %(p_pk)s, "model": "m2m_through_regress.person", "fields": {"name": "Bob"}}, {"pk": %(g_pk)s, "model": "m2m_through_regress.group", "fields": {"name": "Roll"}}]""" % pks) out = StringIO() management.call_command("dumpdata", "m2m_through_regress", format="xml", indent=2, stdout=out) self.assertEqual(out.getvalue().strip(), """ <?xml version="1.0" encoding="utf-8"?> <django-objects version="1.0"> <object pk="%(m_pk)s" model="m2m_through_regress.membership"> <field to="m2m_through_regress.person" name="person" rel="ManyToOneRel">%(p_pk)s</field> <field to="m2m_through_regress.group" name="group" rel="ManyToOneRel">%(g_pk)s</field> <field type="IntegerField" name="price">100</field> </object> <object pk="%(p_pk)s" model="m2m_through_regress.person"> <field type="CharField" name="name">Bob</field> </object> <object pk="%(g_pk)s" model="m2m_through_regress.group"> <field type="CharField" name="name">Roll</field> </object> </django-objects> """.strip() % pks) def test_join_trimming(self): "Check that we don't involve too many copies of the intermediate table when doing a join. Refs #8046, #8254" bob = Person.objects.create(name="Bob") jim = Person.objects.create(name="Jim") rock = Group.objects.create(name="Rock") roll = Group.objects.create(name="Roll") Membership.objects.create(person=bob, group=rock) Membership.objects.create(person=jim, group=rock, price=50) Membership.objects.create(person=bob, group=roll, price=50) self.assertQuerysetEqual( rock.members.filter(membership__price=50), [ "<Person: Jim>", ] ) self.assertQuerysetEqual( bob.group_set.filter(membership__price=50), [ "<Group: Roll>", ] ) class ToFieldThroughTests(TestCase): def setUp(self): self.car = Car.objects.create(make="Toyota") self.driver = Driver.objects.create(name="Ryan Briscoe") CarDriver.objects.create(car=self.car, driver=self.driver) def test_to_field(self): self.assertQuerysetEqual( self.car.drivers.all(), ["<Driver: Ryan Briscoe>"] ) def test_to_field_reverse(self): self.assertQuerysetEqual( self.driver.car_set.all(), ["<Car: Toyota>"] ) class ThroughLoadDataTestCase(TestCase): fixtures = ["m2m_through"] def test_sequence_creation(self): "Check that sequences on an m2m_through are created for the through model, not a phantom auto-generated m2m table. Refs #11107" out = StringIO() management.call_command("dumpdata", "m2m_through_regress", format="json", stdout=out) self.assertEqual(out.getvalue().strip(), """[{"pk": 1, "model": "m2m_through_regress.usermembership", "fields": {"price": 100, "group": 1, "user": 1}}, {"pk": 1, "model": "m2m_through_regress.person", "fields": {"name": "Guido"}}, {"pk": 1, "model": "m2m_through_regress.group", "fields": {"name": "Python Core Group"}}]""")
5,744
Python
.py
118
39.762712
356
0.619192
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,966
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/select_related_onetoone/models.py
from django.db import models class User(models.Model): username = models.CharField(max_length=100) email = models.EmailField() def __unicode__(self): return self.username class UserProfile(models.Model): user = models.OneToOneField(User) city = models.CharField(max_length=100) state = models.CharField(max_length=2) def __unicode__(self): return "%s, %s" % (self.city, self.state) class UserStatResult(models.Model): results = models.CharField(max_length=50) def __unicode__(self): return 'UserStatResults, results = %s' % (self.results,) class UserStat(models.Model): user = models.OneToOneField(User, primary_key=True) posts = models.IntegerField() results = models.ForeignKey(UserStatResult) def __unicode__(self): return 'UserStat, posts = %s' % (self.posts,) class StatDetails(models.Model): base_stats = models.OneToOneField(UserStat) comments = models.IntegerField() def __unicode__(self): return 'StatDetails, comments = %s' % (self.comments,) class AdvancedUserStat(UserStat): karma = models.IntegerField() class Image(models.Model): name = models.CharField(max_length=100) class Product(models.Model): name = models.CharField(max_length=100) image = models.OneToOneField(Image, null=True)
1,340
Python
.py
34
34.294118
64
0.705288
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,967
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/select_related_onetoone/tests.py
from django import db from django.conf import settings from django.test import TestCase from models import (User, UserProfile, UserStat, UserStatResult, StatDetails, AdvancedUserStat, Image, Product) class ReverseSelectRelatedTestCase(TestCase): def setUp(self): # Explicitly enable debug for these tests - we need to count # the queries that have been issued. self.old_debug = settings.DEBUG settings.DEBUG = True user = User.objects.create(username="test") userprofile = UserProfile.objects.create(user=user, state="KS", city="Lawrence") results = UserStatResult.objects.create(results='first results') userstat = UserStat.objects.create(user=user, posts=150, results=results) details = StatDetails.objects.create(base_stats=userstat, comments=259) user2 = User.objects.create(username="bob") results2 = UserStatResult.objects.create(results='moar results') advstat = AdvancedUserStat.objects.create(user=user2, posts=200, karma=5, results=results2) StatDetails.objects.create(base_stats=advstat, comments=250) db.reset_queries() def assertQueries(self, queries): self.assertEqual(len(db.connection.queries), queries) def tearDown(self): settings.DEBUG = self.old_debug def test_basic(self): u = User.objects.select_related("userprofile").get(username="test") self.assertEqual(u.userprofile.state, "KS") self.assertQueries(1) def test_follow_next_level(self): u = User.objects.select_related("userstat__results").get(username="test") self.assertEqual(u.userstat.posts, 150) self.assertEqual(u.userstat.results.results, 'first results') self.assertQueries(1) def test_follow_two(self): u = User.objects.select_related("userprofile", "userstat").get(username="test") self.assertEqual(u.userprofile.state, "KS") self.assertEqual(u.userstat.posts, 150) self.assertQueries(1) def test_follow_two_next_level(self): u = User.objects.select_related("userstat__results", "userstat__statdetails").get(username="test") self.assertEqual(u.userstat.results.results, 'first results') self.assertEqual(u.userstat.statdetails.comments, 259) self.assertQueries(1) def test_forward_and_back(self): stat = UserStat.objects.select_related("user__userprofile").get(user__username="test") self.assertEqual(stat.user.userprofile.state, 'KS') self.assertEqual(stat.user.userstat.posts, 150) self.assertQueries(1) def test_back_and_forward(self): u = User.objects.select_related("userstat").get(username="test") self.assertEqual(u.userstat.user.username, 'test') self.assertQueries(1) def test_not_followed_by_default(self): u = User.objects.select_related().get(username="test") self.assertEqual(u.userstat.posts, 150) self.assertQueries(2) def test_follow_from_child_class(self): stat = AdvancedUserStat.objects.select_related('user', 'statdetails').get(posts=200) self.assertEqual(stat.statdetails.comments, 250) self.assertEqual(stat.user.username, 'bob') self.assertQueries(1) def test_follow_inheritance(self): stat = UserStat.objects.select_related('user', 'advanceduserstat').get(posts=200) self.assertEqual(stat.advanceduserstat.posts, 200) self.assertEqual(stat.user.username, 'bob') self.assertEqual(stat.advanceduserstat.user.username, 'bob') self.assertQueries(1) def test_nullable_relation(self): im = Image.objects.create(name="imag1") p1 = Product.objects.create(name="Django Plushie", image=im) p2 = Product.objects.create(name="Talking Django Plushie") self.assertEqual(len(Product.objects.select_related("image")), 2)
4,062
Python
.py
76
43.921053
106
0.676411
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,968
included_urls2.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/urlpatterns_reverse/included_urls2.py
""" These URL patterns are included in two different ways in the main urls.py, with an extra argument present in one case. Thus, there are two different ways for each name to resolve and Django must distinguish the possibilities based on the argument list. """ from django.conf.urls.defaults import * from views import empty_view urlpatterns = patterns('', url(r'^part/(?P<value>\w+)/$', empty_view, name="part"), url(r'^part2/(?:(?P<value>\w+)/)?$', empty_view, name="part2"), )
490
Python
.py
12
39
79
0.726891
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,969
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/urlpatterns_reverse/urls.py
from django.conf.urls.defaults import * from views import empty_view, absolute_kwargs_view other_patterns = patterns('', url(r'non_path_include/$', empty_view, name='non_path_include'), ) urlpatterns = patterns('', url(r'^places/(\d+)/$', empty_view, name='places'), url(r'^places?/$', empty_view, name="places?"), url(r'^places+/$', empty_view, name="places+"), url(r'^places*/$', empty_view, name="places*"), url(r'^(?:places/)?$', empty_view, name="places2?"), url(r'^(?:places/)+$', empty_view, name="places2+"), url(r'^(?:places/)*$', empty_view, name="places2*"), url(r'^places/(\d+|[a-z_]+)/', empty_view, name="places3"), url(r'^places/(?P<id>\d+)/$', empty_view, name="places4"), url(r'^people/(?P<name>\w+)/$', empty_view, name="people"), url(r'^people/(?:name/)', empty_view, name="people2"), url(r'^people/(?:name/(\w+)/)?', empty_view, name="people2a"), url(r'^optional/(?P<name>.*)/(?:.+/)?', empty_view, name="optional"), url(r'^hardcoded/$', 'hardcoded/', empty_view, name="hardcoded"), url(r'^hardcoded/doc\.pdf$', empty_view, name="hardcoded2"), url(r'^people/(?P<state>\w\w)/(?P<name>\w+)/$', empty_view, name="people3"), url(r'^people/(?P<state>\w\w)/(?P<name>\d)/$', empty_view, name="people4"), url(r'^people/((?P<state>\w\w)/test)?/(\w+)/$', empty_view, name="people6"), url(r'^character_set/[abcdef0-9]/$', empty_view, name="range"), url(r'^character_set/[\w]/$', empty_view, name="range2"), url(r'^price/\$(\d+)/$', empty_view, name="price"), url(r'^price/[$](\d+)/$', empty_view, name="price2"), url(r'^price/[\$](\d+)/$', empty_view, name="price3"), url(r'^product/(?P<product>\w+)\+\(\$(?P<price>\d+(\.\d+)?)\)/$', empty_view, name="product"), url(r'^headlines/(?P<year>\d+)\.(?P<month>\d+)\.(?P<day>\d+)/$', empty_view, name="headlines"), url(r'^windows_path/(?P<drive_name>[A-Z]):\\(?P<path>.+)/$', empty_view, name="windows"), url(r'^special_chars/(.+)/$', empty_view, name="special"), url(r'^(?P<name>.+)/\d+/$', empty_view, name="mixed"), url(r'^repeats/a{1,2}/$', empty_view, name="repeats"), url(r'^repeats/a{2,4}/$', empty_view, name="repeats2"), url(r'^repeats/a{2}/$', empty_view, name="repeats3"), url(r'^(?i)CaseInsensitive/(\w+)', empty_view, name="insensitive"), url(r'^test/1/?', empty_view, name="test"), url(r'^(?i)test/2/?$', empty_view, name="test2"), url(r'^outer/(?P<outer>\d+)/', include('regressiontests.urlpatterns_reverse.included_urls')), url('', include('regressiontests.urlpatterns_reverse.extra_urls')), # This is non-reversible, but we shouldn't blow up when parsing it. url(r'^(?:foo|bar)(\w+)/$', empty_view, name="disjunction"), # Regression views for #9038. See tests for more details url(r'arg_view/$', 'kwargs_view'), url(r'arg_view/(?P<arg1>\d+)/$', 'kwargs_view'), url(r'absolute_arg_view/(?P<arg1>\d+)/$', absolute_kwargs_view), url(r'absolute_arg_view/$', absolute_kwargs_view), url('^includes/', include(other_patterns)), )
3,133
Python
.py
55
51.6
80
0.582192
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,970
extra_urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/urlpatterns_reverse/extra_urls.py
""" Some extra URL patterns that are included at the top level. """ from django.conf.urls.defaults import * from views import empty_view urlpatterns = patterns('', url(r'^e-places/(\d+)/$', empty_view, name='extra-places'), url(r'^e-people/(?P<name>\w+)/$', empty_view, name="extra-people"), url('', include('regressiontests.urlpatterns_reverse.included_urls2')), url(r'^prefix/(?P<prefix>\w+)/', include('regressiontests.urlpatterns_reverse.included_urls2')), )
481
Python
.py
11
41.090909
100
0.698718
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,971
urlconf_outer.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/urlpatterns_reverse/urlconf_outer.py
from django.conf.urls.defaults import * import urlconf_inner urlpatterns = patterns('', url(r'^test/me/$', urlconf_inner.inner_view, name='outer'), url(r'^inner_urlconf/', include(urlconf_inner.__name__)) )
217
Python
.py
6
33.5
63
0.708134
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,972
included_urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/urlpatterns_reverse/included_urls.py
from django.conf.urls.defaults import * from views import empty_view urlpatterns = patterns('', url(r'^$', empty_view, name="inner-nothing"), url(r'^extra/(?P<extra>\w+)/$', empty_view, name="inner-extra"), url(r'^(?P<one>\d+)|(?P<two>\d+)/$', empty_view, name="inner-disjunction"), )
298
Python
.py
7
39.714286
79
0.641379
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,973
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/urlpatterns_reverse/tests.py
""" Unit tests for reverse URL lookups. """ import unittest from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import reverse, resolve, NoReverseMatch, Resolver404, RegexURLResolver from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect from django.shortcuts import redirect from django.test import TestCase import urlconf_outer import urlconf_inner import middleware test_data = ( ('places', '/places/3/', [3], {}), ('places', '/places/3/', ['3'], {}), ('places', NoReverseMatch, ['a'], {}), ('places', NoReverseMatch, [], {}), ('places?', '/place/', [], {}), ('places+', '/places/', [], {}), ('places*', '/place/', [], {}), ('places2?', '/', [], {}), ('places2+', '/places/', [], {}), ('places2*', '/', [], {}), ('places3', '/places/4/', [4], {}), ('places3', '/places/harlem/', ['harlem'], {}), ('places3', NoReverseMatch, ['harlem64'], {}), ('places4', '/places/3/', [], {'id': 3}), ('people', NoReverseMatch, [], {}), ('people', '/people/adrian/', ['adrian'], {}), ('people', '/people/adrian/', [], {'name': 'adrian'}), ('people', NoReverseMatch, ['name with spaces'], {}), ('people', NoReverseMatch, [], {'name': 'name with spaces'}), ('people2', '/people/name/', [], {}), ('people2a', '/people/name/fred/', ['fred'], {}), ('optional', '/optional/fred/', [], {'name': 'fred'}), ('optional', '/optional/fred/', ['fred'], {}), ('hardcoded', '/hardcoded/', [], {}), ('hardcoded2', '/hardcoded/doc.pdf', [], {}), ('people3', '/people/il/adrian/', [], {'state': 'il', 'name': 'adrian'}), ('people3', NoReverseMatch, [], {'state': 'il'}), ('people3', NoReverseMatch, [], {'name': 'adrian'}), ('people4', NoReverseMatch, [], {'state': 'il', 'name': 'adrian'}), ('people6', '/people/il/test/adrian/', ['il/test', 'adrian'], {}), ('people6', '/people//adrian/', ['adrian'], {}), ('range', '/character_set/a/', [], {}), ('range2', '/character_set/x/', [], {}), ('price', '/price/$10/', ['10'], {}), ('price2', '/price/$10/', ['10'], {}), ('price3', '/price/$10/', ['10'], {}), ('product', '/product/chocolate+($2.00)/', [], {'price': '2.00', 'product': 'chocolate'}), ('headlines', '/headlines/2007.5.21/', [], dict(year=2007, month=5, day=21)), ('windows', r'/windows_path/C:%5CDocuments%20and%20Settings%5Cspam/', [], dict(drive_name='C', path=r'Documents and Settings\spam')), ('special', r'/special_chars/+%5C$*/', [r'+\$*'], {}), ('special', NoReverseMatch, [''], {}), ('mixed', '/john/0/', [], {'name': 'john'}), ('repeats', '/repeats/a/', [], {}), ('repeats2', '/repeats/aa/', [], {}), ('repeats3', '/repeats/aa/', [], {}), ('insensitive', '/CaseInsensitive/fred', ['fred'], {}), ('test', '/test/1', [], {}), ('test2', '/test/2', [], {}), ('inner-nothing', '/outer/42/', [], {'outer': '42'}), ('inner-nothing', '/outer/42/', ['42'], {}), ('inner-nothing', NoReverseMatch, ['foo'], {}), ('inner-extra', '/outer/42/extra/inner/', [], {'extra': 'inner', 'outer': '42'}), ('inner-extra', '/outer/42/extra/inner/', ['42', 'inner'], {}), ('inner-extra', NoReverseMatch, ['fred', 'inner'], {}), ('disjunction', NoReverseMatch, ['foo'], {}), ('inner-disjunction', NoReverseMatch, ['10', '11'], {}), ('extra-places', '/e-places/10/', ['10'], {}), ('extra-people', '/e-people/fred/', ['fred'], {}), ('extra-people', '/e-people/fred/', [], {'name': 'fred'}), ('part', '/part/one/', [], {'value': 'one'}), ('part', '/prefix/xx/part/one/', [], {'value': 'one', 'prefix': 'xx'}), ('part2', '/part2/one/', [], {'value': 'one'}), ('part2', '/part2/', [], {}), ('part2', '/prefix/xx/part2/one/', [], {'value': 'one', 'prefix': 'xx'}), ('part2', '/prefix/xx/part2/', [], {'prefix': 'xx'}), # Regression for #9038 # These views are resolved by method name. Each method is deployed twice - # once with an explicit argument, and once using the default value on # the method. This is potentially ambiguous, as you have to pick the # correct view for the arguments provided. ('kwargs_view', '/arg_view/', [], {}), ('kwargs_view', '/arg_view/10/', [], {'arg1':10}), ('regressiontests.urlpatterns_reverse.views.absolute_kwargs_view', '/absolute_arg_view/', [], {}), ('regressiontests.urlpatterns_reverse.views.absolute_kwargs_view', '/absolute_arg_view/10/', [], {'arg1':10}), ('non_path_include', '/includes/non_path_include/', [], {}) ) class NoURLPatternsTests(TestCase): urls = 'regressiontests.urlpatterns_reverse.no_urls' 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_no_urls_exception(self): """ RegexURLResolver should raise an exception when no urlpatterns exist. """ resolver = RegexURLResolver(r'^$', self.urls) self.assertRaisesErrorWithMessage(ImproperlyConfigured, "The included urlconf regressiontests.urlpatterns_reverse.no_urls "\ "doesn't have any patterns in it", getattr, resolver, 'url_patterns') class URLPatternReverse(TestCase): urls = 'regressiontests.urlpatterns_reverse.urls' def test_urlpattern_reverse(self): for name, expected, args, kwargs in test_data: try: got = reverse(name, args=args, kwargs=kwargs) except NoReverseMatch, e: self.assertEqual(expected, NoReverseMatch) else: self.assertEquals(got, expected) def test_reverse_none(self): # Reversing None should raise an error, not return the last un-named view. self.assertRaises(NoReverseMatch, reverse, None) class ResolverTests(unittest.TestCase): def test_non_regex(self): """ Verifies that we raise a Resolver404 if what we are resolving doesn't meet the basic requirements of a path to match - i.e., at the very least, it matches the root pattern '^/'. We must never return None from resolve, or we will get a TypeError further down the line. Regression for #10834. """ self.assertRaises(Resolver404, resolve, '') self.assertRaises(Resolver404, resolve, 'a') self.assertRaises(Resolver404, resolve, '\\') self.assertRaises(Resolver404, resolve, '.') class ReverseShortcutTests(TestCase): urls = 'regressiontests.urlpatterns_reverse.urls' def test_redirect_to_object(self): # We don't really need a model; just something with a get_absolute_url class FakeObj(object): def get_absolute_url(self): return "/hi-there/" res = redirect(FakeObj()) self.assert_(isinstance(res, HttpResponseRedirect)) self.assertEqual(res['Location'], '/hi-there/') res = redirect(FakeObj(), permanent=True) self.assert_(isinstance(res, HttpResponsePermanentRedirect)) self.assertEqual(res['Location'], '/hi-there/') def test_redirect_to_view_name(self): res = redirect('hardcoded2') self.assertEqual(res['Location'], '/hardcoded/doc.pdf') res = redirect('places', 1) self.assertEqual(res['Location'], '/places/1/') res = redirect('headlines', year='2008', month='02', day='17') self.assertEqual(res['Location'], '/headlines/2008.02.17/') self.assertRaises(NoReverseMatch, redirect, 'not-a-view') def test_redirect_to_url(self): res = redirect('/foo/') self.assertEqual(res['Location'], '/foo/') res = redirect('http://example.com/') self.assertEqual(res['Location'], 'http://example.com/') def test_redirect_view_object(self): from views import absolute_kwargs_view res = redirect(absolute_kwargs_view) self.assertEqual(res['Location'], '/absolute_arg_view/') self.assertRaises(NoReverseMatch, redirect, absolute_kwargs_view, wrong_argument=None) class NamespaceTests(TestCase): urls = 'regressiontests.urlpatterns_reverse.namespace_urls' def test_ambiguous_object(self): "Names deployed via dynamic URL objects that require namespaces can't be resolved" self.assertRaises(NoReverseMatch, reverse, 'urlobject-view') self.assertRaises(NoReverseMatch, reverse, 'urlobject-view', args=[37,42]) self.assertRaises(NoReverseMatch, reverse, 'urlobject-view', kwargs={'arg1':42, 'arg2':37}) def test_ambiguous_urlpattern(self): "Names deployed via dynamic URL objects that require namespaces can't be resolved" self.assertRaises(NoReverseMatch, reverse, 'inner-nothing') self.assertRaises(NoReverseMatch, reverse, 'inner-nothing', args=[37,42]) self.assertRaises(NoReverseMatch, reverse, 'inner-nothing', kwargs={'arg1':42, 'arg2':37}) def test_non_existent_namespace(self): "Non-existent namespaces raise errors" self.assertRaises(NoReverseMatch, reverse, 'blahblah:urlobject-view') self.assertRaises(NoReverseMatch, reverse, 'test-ns1:blahblah:urlobject-view') def test_normal_name(self): "Normal lookups work as expected" self.assertEquals('/normal/', reverse('normal-view')) self.assertEquals('/normal/37/42/', reverse('normal-view', args=[37,42])) self.assertEquals('/normal/42/37/', reverse('normal-view', kwargs={'arg1':42, 'arg2':37})) def test_simple_included_name(self): "Normal lookups work on names included from other patterns" self.assertEquals('/included/normal/', reverse('inc-normal-view')) self.assertEquals('/included/normal/37/42/', reverse('inc-normal-view', args=[37,42])) self.assertEquals('/included/normal/42/37/', reverse('inc-normal-view', kwargs={'arg1':42, 'arg2':37})) def test_namespace_object(self): "Dynamic URL objects can be found using a namespace" self.assertEquals('/test1/inner/', reverse('test-ns1:urlobject-view')) self.assertEquals('/test1/inner/37/42/', reverse('test-ns1:urlobject-view', args=[37,42])) self.assertEquals('/test1/inner/42/37/', reverse('test-ns1:urlobject-view', kwargs={'arg1':42, 'arg2':37})) def test_embedded_namespace_object(self): "Namespaces can be installed anywhere in the URL pattern tree" self.assertEquals('/included/test3/inner/', reverse('test-ns3:urlobject-view')) self.assertEquals('/included/test3/inner/37/42/', reverse('test-ns3:urlobject-view', args=[37,42])) self.assertEquals('/included/test3/inner/42/37/', reverse('test-ns3:urlobject-view', kwargs={'arg1':42, 'arg2':37})) def test_namespace_pattern(self): "Namespaces can be applied to include()'d urlpatterns" self.assertEquals('/ns-included1/normal/', reverse('inc-ns1:inc-normal-view')) self.assertEquals('/ns-included1/normal/37/42/', reverse('inc-ns1:inc-normal-view', args=[37,42])) self.assertEquals('/ns-included1/normal/42/37/', reverse('inc-ns1:inc-normal-view', kwargs={'arg1':42, 'arg2':37})) def test_multiple_namespace_pattern(self): "Namespaces can be embedded" self.assertEquals('/ns-included1/test3/inner/', reverse('inc-ns1:test-ns3:urlobject-view')) self.assertEquals('/ns-included1/test3/inner/37/42/', reverse('inc-ns1:test-ns3:urlobject-view', args=[37,42])) self.assertEquals('/ns-included1/test3/inner/42/37/', reverse('inc-ns1:test-ns3:urlobject-view', kwargs={'arg1':42, 'arg2':37})) def test_app_lookup_object(self): "A default application namespace can be used for lookup" self.assertEquals('/default/inner/', reverse('testapp:urlobject-view')) self.assertEquals('/default/inner/37/42/', reverse('testapp:urlobject-view', args=[37,42])) self.assertEquals('/default/inner/42/37/', reverse('testapp:urlobject-view', kwargs={'arg1':42, 'arg2':37})) def test_app_lookup_object_with_default(self): "A default application namespace is sensitive to the 'current' app can be used for lookup" self.assertEquals('/included/test3/inner/', reverse('testapp:urlobject-view', current_app='test-ns3')) self.assertEquals('/included/test3/inner/37/42/', reverse('testapp:urlobject-view', args=[37,42], current_app='test-ns3')) self.assertEquals('/included/test3/inner/42/37/', reverse('testapp:urlobject-view', kwargs={'arg1':42, 'arg2':37}, current_app='test-ns3')) def test_app_lookup_object_without_default(self): "An application namespace without a default is sensitive to the 'current' app can be used for lookup" self.assertEquals('/other2/inner/', reverse('nodefault:urlobject-view')) self.assertEquals('/other2/inner/37/42/', reverse('nodefault:urlobject-view', args=[37,42])) self.assertEquals('/other2/inner/42/37/', reverse('nodefault:urlobject-view', kwargs={'arg1':42, 'arg2':37})) self.assertEquals('/other1/inner/', reverse('nodefault:urlobject-view', current_app='other-ns1')) self.assertEquals('/other1/inner/37/42/', reverse('nodefault:urlobject-view', args=[37,42], current_app='other-ns1')) self.assertEquals('/other1/inner/42/37/', reverse('nodefault:urlobject-view', kwargs={'arg1':42, 'arg2':37}, current_app='other-ns1')) class RequestURLconfTests(TestCase): def setUp(self): self.root_urlconf = settings.ROOT_URLCONF self.middleware_classes = settings.MIDDLEWARE_CLASSES settings.ROOT_URLCONF = urlconf_outer.__name__ def tearDown(self): settings.ROOT_URLCONF = self.root_urlconf settings.MIDDLEWARE_CLASSES = self.middleware_classes def test_urlconf(self): response = self.client.get('/test/me/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'outer:/test/me/,' 'inner:/inner_urlconf/second_test/') response = self.client.get('/inner_urlconf/second_test/') self.assertEqual(response.status_code, 200) response = self.client.get('/second_test/') self.assertEqual(response.status_code, 404) def test_urlconf_overridden(self): settings.MIDDLEWARE_CLASSES += ( '%s.ChangeURLconfMiddleware' % middleware.__name__, ) response = self.client.get('/test/me/') self.assertEqual(response.status_code, 404) response = self.client.get('/inner_urlconf/second_test/') self.assertEqual(response.status_code, 404) response = self.client.get('/second_test/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'outer:,inner:/second_test/') def test_urlconf_overridden_with_null(self): settings.MIDDLEWARE_CLASSES += ( '%s.NullChangeURLconfMiddleware' % middleware.__name__, ) self.assertRaises(ImproperlyConfigured, self.client.get, '/test/me/') class ErrorHandlerResolutionTests(TestCase): """Tests for handler404 and handler500""" def setUp(self): urlconf = 'regressiontests.urlpatterns_reverse.urls_error_handlers' urlconf_callables = 'regressiontests.urlpatterns_reverse.urls_error_handlers_callables' self.resolver = RegexURLResolver(r'^$', urlconf) self.callable_resolver = RegexURLResolver(r'^$', urlconf_callables) def test_named_handlers(self): from views import empty_view handler = (empty_view, {}) self.assertEqual(self.resolver.resolve404(), handler) self.assertEqual(self.resolver.resolve500(), handler) def test_callable_handers(self): from views import empty_view handler = (empty_view, {}) self.assertEqual(self.callable_resolver.resolve404(), handler) self.assertEqual(self.callable_resolver.resolve500(), handler) class NoRootUrlConfTests(TestCase): """Tests for handler404 and handler500 if urlconf is None""" urls = None def test_no_handler_exception(self): self.assertRaises(ImproperlyConfigured, self.client.get, '/test/me/')
16,357
Python
.py
283
50.487633
147
0.641168
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,974
included_namespace_urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/urlpatterns_reverse/included_namespace_urls.py
from django.conf.urls.defaults import * from namespace_urls import URLObject testobj3 = URLObject('testapp', 'test-ns3') urlpatterns = patterns('regressiontests.urlpatterns_reverse.views', url(r'^normal/$', 'empty_view', name='inc-normal-view'), url(r'^normal/(?P<arg1>\d+)/(?P<arg2>\d+)/$', 'empty_view', name='inc-normal-view'), (r'^test3/', include(testobj3.urls)), (r'^ns-included3/', include('regressiontests.urlpatterns_reverse.included_urls', namespace='inc-ns3')), )
495
Python
.py
9
51.777778
107
0.705394
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,975
middleware.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/urlpatterns_reverse/middleware.py
from django.core.urlresolvers import set_urlconf import urlconf_inner class ChangeURLconfMiddleware(object): def process_request(self, request): request.urlconf = urlconf_inner.__name__ class NullChangeURLconfMiddleware(object): def process_request(self, request): request.urlconf = None
315
Python
.py
8
35
48
0.776316
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,976
urls_error_handlers.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/urlpatterns_reverse/urls_error_handlers.py
# Used by the ErrorHandlerResolutionTests test case. from django.conf.urls.defaults import patterns urlpatterns = patterns('') handler404 = 'regressiontests.urlpatterns_reverse.views.empty_view' handler500 = 'regressiontests.urlpatterns_reverse.views.empty_view'
266
Python
.py
5
51.6
67
0.841085
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,977
urlconf_inner.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/urlpatterns_reverse/urlconf_inner.py
from django.conf.urls.defaults import * from django.template import Template, Context from django.http import HttpResponse def inner_view(request): content = Template('{% url outer as outer_url %}outer:{{ outer_url }},' '{% url inner as inner_url %}inner:{{ inner_url }}').render(Context()) return HttpResponse(content) urlpatterns = patterns('', url(r'^second_test/$', inner_view, name='inner'), )
435
Python
.py
10
38.9
93
0.679245
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,978
urls_error_handlers_callables.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/urlpatterns_reverse/urls_error_handlers_callables.py
# Used by the ErrorHandlerResolutionTests test case. from django.conf.urls.defaults import patterns from views import empty_view urlpatterns = patterns('') handler404 = empty_view handler500 = empty_view
207
Python
.py
6
33
52
0.833333
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,979
views.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/urlpatterns_reverse/views.py
def empty_view(request, *args, **kwargs): pass def kwargs_view(request, arg1=1, arg2=2): pass def absolute_kwargs_view(request, arg1=1, arg2=2): pass
164
Python
.py
6
24
50
0.698718
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,980
namespace_urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/urlpatterns_reverse/namespace_urls.py
from django.conf.urls.defaults import * class URLObject(object): def __init__(self, app_name, namespace): self.app_name = app_name self.namespace = namespace def urls(self): return patterns('', url(r'^inner/$', 'empty_view', name='urlobject-view'), url(r'^inner/(?P<arg1>\d+)/(?P<arg2>\d+)/$', 'empty_view', name='urlobject-view'), ), self.app_name, self.namespace urls = property(urls) testobj1 = URLObject('testapp', 'test-ns1') testobj2 = URLObject('testapp', 'test-ns2') default_testobj = URLObject('testapp', 'testapp') otherobj1 = URLObject('nodefault', 'other-ns1') otherobj2 = URLObject('nodefault', 'other-ns2') urlpatterns = patterns('regressiontests.urlpatterns_reverse.views', url(r'^normal/$', 'empty_view', name='normal-view'), url(r'^normal/(?P<arg1>\d+)/(?P<arg2>\d+)/$', 'empty_view', name='normal-view'), (r'^test1/', include(testobj1.urls)), (r'^test2/', include(testobj2.urls)), (r'^default/', include(default_testobj.urls)), (r'^other1/', include(otherobj1.urls)), (r'^other2/', include(otherobj2.urls)), (r'^ns-included1/', include('regressiontests.urlpatterns_reverse.included_namespace_urls', namespace='inc-ns1')), (r'^ns-included2/', include('regressiontests.urlpatterns_reverse.included_namespace_urls', namespace='inc-ns2')), (r'^included/', include('regressiontests.urlpatterns_reverse.included_namespace_urls')), )
1,463
Python
.py
28
47.035714
117
0.668772
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,981
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/extra_regress/models.py
import datetime import django.utils.copycompat as copy from django.contrib.auth.models import User from django.db import models class RevisionableModel(models.Model): base = models.ForeignKey('self', null=True) title = models.CharField(blank=True, max_length=255) when = models.DateTimeField(default=datetime.datetime.now) def __unicode__(self): return u"%s (%s, %s)" % (self.title, self.id, self.base.id) def save(self, *args, **kwargs): super(RevisionableModel, self).save(*args, **kwargs) if not self.base: self.base = self kwargs.pop('force_insert', None) kwargs.pop('force_update', None) super(RevisionableModel, self).save(*args, **kwargs) def new_revision(self): new_revision = copy.copy(self) new_revision.pk = None return new_revision class Order(models.Model): created_by = models.ForeignKey(User) text = models.TextField() class TestObject(models.Model): first = models.CharField(max_length=20) second = models.CharField(max_length=20) third = models.CharField(max_length=20) def __unicode__(self): return u'TestObject: %s,%s,%s' % (self.first,self.second,self.third)
1,241
Python
.py
30
34.966667
76
0.676103
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,982
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/extra_regress/tests.py
from django.test import TestCase from django.utils.datastructures import SortedDict from django.contrib.auth.models import User from regressiontests.extra_regress.models import TestObject, Order, \ RevisionableModel import datetime class ExtraRegressTests(TestCase): def setUp(self): self.u = User.objects.create_user( username="fred", password="secret", email="[email protected]" ) def test_regression_7314_7372(self): """ Regression tests for #7314 and #7372 """ rm = RevisionableModel.objects.create( title='First Revision', when=datetime.datetime(2008, 9, 28, 10, 30, 0) ) self.assertEqual(rm.pk, rm.base.pk) rm2 = rm.new_revision() rm2.title = "Second Revision" rm.when = datetime.datetime(2008, 9, 28, 14, 25, 0) rm2.save() self.assertEqual(rm2.title, 'Second Revision') self.assertEqual(rm2.base.title, 'First Revision') self.assertNotEqual(rm2.pk, rm.pk) self.assertEqual(rm2.base.pk, rm.pk) # Queryset to match most recent revision: qs = RevisionableModel.objects.extra( where=["%(table)s.id IN (SELECT MAX(rev.id) FROM %(table)s rev GROUP BY rev.base_id)" % { 'table': RevisionableModel._meta.db_table, }] ) self.assertQuerysetEqual(qs, [('Second Revision', 'First Revision')], transform=lambda r: (r.title, r.base.title) ) # Queryset to search for string in title: qs2 = RevisionableModel.objects.filter(title__contains="Revision") self.assertQuerysetEqual(qs2, [ ('First Revision', 'First Revision'), ('Second Revision', 'First Revision'), ], transform=lambda r: (r.title, r.base.title) ) # Following queryset should return the most recent revision: self.assertQuerysetEqual(qs & qs2, [('Second Revision', 'First Revision')], transform=lambda r: (r.title, r.base.title) ) def test_extra_stay_tied(self): # Extra select parameters should stay tied to their corresponding # select portions. Applies when portions are updated or otherwise # moved around. qs = User.objects.extra( select=SortedDict((("alpha", "%s"), ("beta", "2"), ("gamma", "%s"))), select_params=(1, 3) ) qs = qs.extra(select={"beta": 4}) qs = qs.extra(select={"alpha": "%s"}, select_params=[5]) self.assertEqual( list(qs.filter(id=self.u.id).values('alpha', 'beta', 'gamma')), [{'alpha': 5, 'beta': 4, 'gamma': 3}] ) def test_regression_7957(self): """ Regression test for #7957: Combining extra() calls should leave the corresponding parameters associated with the right extra() bit. I.e. internal dictionary must remain sorted. """ self.assertEqual( User.objects.extra(select={"alpha": "%s"}, select_params=(1,) ).extra(select={"beta": "%s"}, select_params=(2,))[0].alpha, 1) self.assertEqual( User.objects.extra(select={"beta": "%s"}, select_params=(1,) ).extra(select={"alpha": "%s"}, select_params=(2,))[0].alpha, 2) def test_regression_7961(self): """ Regression test for #7961: When not using a portion of an extra(...) in a query, remove any corresponding parameters from the query as well. """ self.assertEqual( list(User.objects.extra(select={"alpha": "%s"}, select_params=(-6,) ).filter(id=self.u.id).values_list('id', flat=True)), [self.u.id] ) def test_regression_8063(self): """ Regression test for #8063: limiting a query shouldn't discard any extra() bits. """ qs = User.objects.all().extra(where=['id=%s'], params=[self.u.id]) self.assertQuerysetEqual(qs, ['<User: fred>']) self.assertQuerysetEqual(qs[:1], ['<User: fred>']) def test_regression_8039(self): """ Regression test for #8039: Ordering sometimes removed relevant tables from extra(). This test is the critical case: ordering uses a table, but then removes the reference because of an optimisation. The table should still be present because of the extra() call. """ self.assertQuerysetEqual( Order.objects.extra(where=["username=%s"], params=["fred"], tables=["auth_user"] ).order_by('created_by'), [] ) def test_regression_8819(self): """ Regression test for #8819: Fields in the extra(select=...) list should be available to extra(order_by=...). """ self.assertQuerysetEqual( User.objects.filter(pk=self.u.id).extra(select={'extra_field': 1}).distinct(), ['<User: fred>'] ) self.assertQuerysetEqual( User.objects.filter(pk=self.u.id).extra(select={'extra_field': 1}, order_by=['extra_field']), ['<User: fred>'] ) self.assertQuerysetEqual( User.objects.filter(pk=self.u.id).extra(select={'extra_field': 1}, order_by=['extra_field']).distinct(), ['<User: fred>'] ) def test_dates_query(self): """ When calling the dates() method on a queryset with extra selection columns, we can (and should) ignore those columns. They don't change the result and cause incorrect SQL to be produced otherwise. """ rm = RevisionableModel.objects.create( title='First Revision', when=datetime.datetime(2008, 9, 28, 10, 30, 0) ) self.assertQuerysetEqual( RevisionableModel.objects.extra(select={"the_answer": 'id'}).dates('when', 'month'), ['datetime.datetime(2008, 9, 1, 0, 0)'] ) def test_values_with_extra(self): """ Regression test for #10256... If there is a values() clause, Extra columns are only returned if they are explicitly mentioned. """ obj = TestObject(first='first', second='second', third='third') obj.save() self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values()), [{'bar': u'second', 'third': u'third', 'second': u'second', 'whiz': u'third', 'foo': u'first', 'id': obj.pk, 'first': u'first'}] ) # Extra clauses after an empty values clause are still included self.assertEqual( list(TestObject.objects.values().extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third'))))), [{'bar': u'second', 'third': u'third', 'second': u'second', 'whiz': u'third', 'foo': u'first', 'id': obj.pk, 'first': u'first'}] ) # Extra columns are ignored if not mentioned in the values() clause self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values('first', 'second')), [{'second': u'second', 'first': u'first'}] ) # Extra columns after a non-empty values() clause are ignored self.assertEqual( list(TestObject.objects.values('first', 'second').extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third'))))), [{'second': u'second', 'first': u'first'}] ) # Extra columns can be partially returned self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values('first', 'second', 'foo')), [{'second': u'second', 'foo': u'first', 'first': u'first'}] ) # Also works if only extra columns are included self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values('foo', 'whiz')), [{'foo': u'first', 'whiz': u'third'}] ) # Values list works the same way # All columns are returned for an empty values_list() self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list()), [(u'first', u'second', u'third', obj.pk, u'first', u'second', u'third')] ) # Extra columns after an empty values_list() are still included self.assertEqual( list(TestObject.objects.values_list().extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third'))))), [(u'first', u'second', u'third', obj.pk, u'first', u'second', u'third')] ) # Extra columns ignored completely if not mentioned in values_list() self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('first', 'second')), [(u'first', u'second')] ) # Extra columns after a non-empty values_list() clause are ignored completely self.assertEqual( list(TestObject.objects.values_list('first', 'second').extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third'))))), [(u'first', u'second')] ) self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('second', flat=True)), [u'second'] ) # Only the extra columns specified in the values_list() are returned self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('first', 'second', 'whiz')), [(u'first', u'second', u'third')] ) # ...also works if only extra columns are included self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('foo','whiz')), [(u'first', u'third')] ) self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('whiz', flat=True)), [u'third'] ) # ... and values are returned in the order they are specified self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('whiz','foo')), [(u'third', u'first')] ) self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('first','id')), [(u'first', obj.pk)] ) self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('whiz', 'first', 'bar', 'id')), [(u'third', u'first', u'second', obj.pk)] ) def test_regression_10847(self): """ Regression for #10847: the list of extra columns can always be accurately evaluated. Using an inner query ensures that as_sql() is producing correct output without requiring full evaluation and execution of the inner query. """ obj = TestObject(first='first', second='second', third='third') obj.save() self.assertEqual( list(TestObject.objects.extra(select={'extra': 1}).values('pk')), [{'pk': obj.pk}] ) self.assertQuerysetEqual( TestObject.objects.filter( pk__in=TestObject.objects.extra(select={'extra': 1}).values('pk') ), ['<TestObject: TestObject: first,second,third>'] ) self.assertEqual( list(TestObject.objects.values('pk').extra(select={'extra': 1})), [{'pk': obj.pk}] ) self.assertQuerysetEqual( TestObject.objects.filter( pk__in=TestObject.objects.values('pk').extra(select={'extra': 1}) ), ['<TestObject: TestObject: first,second,third>'] ) self.assertQuerysetEqual( TestObject.objects.filter(pk=obj.pk) | TestObject.objects.extra(where=["id > %s"], params=[obj.pk]), ['<TestObject: TestObject: first,second,third>'] )
12,934
Python
.py
268
37.350746
159
0.567829
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,983
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/mail/tests.py
# coding: utf-8 import asyncore import email import os import shutil import smtpd import sys from StringIO import StringIO import tempfile import threading from django.conf import settings from django.core import mail from django.core.mail import EmailMessage, mail_admins, mail_managers, EmailMultiAlternatives from django.core.mail import send_mail, send_mass_mail from django.core.mail.backends import console, dummy, locmem, filebased, smtp from django.core.mail.message import BadHeaderError from django.test import TestCase from django.utils.translation import ugettext_lazy from django.utils.functional import wraps def alter_django_settings(**kwargs): oldvalues = {} nonexistant = [] for setting, newvalue in kwargs.iteritems(): try: oldvalues[setting] = getattr(settings, setting) except AttributeError: nonexistant.append(setting) setattr(settings, setting, newvalue) return oldvalues, nonexistant def restore_django_settings(state): oldvalues, nonexistant = state for setting, oldvalue in oldvalues.iteritems(): setattr(settings, setting, oldvalue) for setting in nonexistant: delattr(settings, setting) def with_django_settings(**kwargs): def decorator(test): @wraps(test) def decorated_test(self): state = alter_django_settings(**kwargs) try: return test(self) finally: restore_django_settings(state) return decorated_test return decorator class MailTests(TestCase): """ Non-backend specific tests. """ def test_ascii(self): email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]']) message = email.message() self.assertEqual(message['Subject'].encode(), 'Subject') self.assertEqual(message.get_payload(), 'Content') self.assertEqual(message['From'], '[email protected]') self.assertEqual(message['To'], '[email protected]') def test_multiple_recipients(self): email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]', '[email protected]']) message = email.message() self.assertEqual(message['Subject'].encode(), 'Subject') self.assertEqual(message.get_payload(), 'Content') self.assertEqual(message['From'], '[email protected]') self.assertEqual(message['To'], '[email protected], [email protected]') def test_header_injection(self): email = EmailMessage('Subject\nInjection Test', 'Content', '[email protected]', ['[email protected]']) self.assertRaises(BadHeaderError, email.message) email = EmailMessage(ugettext_lazy('Subject\nInjection Test'), 'Content', '[email protected]', ['[email protected]']) self.assertRaises(BadHeaderError, email.message) def test_space_continuation(self): """ Test for space continuation character in long (ascii) subject headers (#7747) """ email = EmailMessage('Long subject lines that get wrapped should use a space continuation character to get expected behaviour in Outlook and Thunderbird', 'Content', '[email protected]', ['[email protected]']) message = email.message() self.assertEqual(message['Subject'], 'Long subject lines that get wrapped should use a space continuation\n character to get expected behaviour in Outlook and Thunderbird') def test_message_header_overrides(self): """ Specifying dates or message-ids in the extra headers overrides the default values (#9233) """ headers = {"date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} email = EmailMessage('subject', 'content', '[email protected]', ['[email protected]'], headers=headers) self.assertEqual(email.message().as_string(), 'Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: subject\nFrom: [email protected]\nTo: [email protected]\ndate: Fri, 09 Nov 2001 01:08:47 -0000\nMessage-ID: foo\n\ncontent') def test_from_header(self): """ Make sure we can manually set the From header (#9214) """ email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}) message = email.message() self.assertEqual(message['From'], '[email protected]') def test_multiple_message_call(self): """ Regression for #13259 - Make sure that headers are not changed when calling EmailMessage.message() """ email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}) message = email.message() self.assertEqual(message['From'], '[email protected]') message = email.message() self.assertEqual(message['From'], '[email protected]') def test_unicode_address_header(self): """ Regression for #11144 - When a to/from/cc header contains unicode, make sure the email addresses are parsed correctly (especially with regards to commas) """ email = EmailMessage('Subject', 'Content', '[email protected]', ['"Firstname Sürname" <[email protected]>', '[email protected]']) self.assertEqual(email.message()['To'], '=?utf-8?q?Firstname_S=C3=BCrname?= <[email protected]>, [email protected]') email = EmailMessage('Subject', 'Content', '[email protected]', ['"Sürname, Firstname" <[email protected]>', '[email protected]']) self.assertEqual(email.message()['To'], '=?utf-8?q?S=C3=BCrname=2C_Firstname?= <[email protected]>, [email protected]') def test_unicode_headers(self): email = EmailMessage(u"Gżegżółka", "Content", "[email protected]", ["[email protected]"], headers={"Sender": '"Firstname Sürname" <[email protected]>', "Comments": 'My Sürname is non-ASCII'}) message = email.message() self.assertEqual(message['Subject'], '=?utf-8?b?R8W8ZWfFvMOzxYJrYQ==?=') self.assertEqual(message['Sender'], '=?utf-8?q?Firstname_S=C3=BCrname?= <[email protected]>') self.assertEqual(message['Comments'], '=?utf-8?q?My_S=C3=BCrname_is_non-ASCII?=') def test_safe_mime_multipart(self): """ Make sure headers can be set with a different encoding than utf-8 in SafeMIMEMultipart as well """ headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} subject, from_email, to = 'hello', '[email protected]', '"Sürname, Firstname" <[email protected]>' text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives('Message from Firstname Sürname', text_content, from_email, [to], headers=headers) msg.attach_alternative(html_content, "text/html") msg.encoding = 'iso-8859-1' self.assertEqual(msg.message()['To'], '=?iso-8859-1?q?S=FCrname=2C_Firstname?= <[email protected]>') self.assertEqual(msg.message()['Subject'].encode(), u'=?iso-8859-1?q?Message_from_Firstname_S=FCrname?=') def test_encoding(self): """ Regression for #12791 - Encode body correctly with other encodings than utf-8 """ email = EmailMessage('Subject', 'Firstname Sürname is a great guy.', '[email protected]', ['[email protected]']) email.encoding = 'iso-8859-1' message = email.message() self.assertTrue(message.as_string().startswith('Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: Subject\nFrom: [email protected]\nTo: [email protected]')) self.assertEqual(message.get_payload(), 'Firstname S=FCrname is a great guy.') # Make sure MIME attachments also works correctly with other encodings than utf-8 text_content = 'Firstname Sürname is a great guy.' html_content = '<p>Firstname Sürname is a <strong>great</strong> guy.</p>' msg = EmailMultiAlternatives('Subject', text_content, '[email protected]', ['[email protected]']) msg.encoding = 'iso-8859-1' msg.attach_alternative(html_content, "text/html") self.assertEqual(msg.message().get_payload(0).as_string(), 'Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\nFirstname S=FCrname is a great guy.') self.assertEqual(msg.message().get_payload(1).as_string(), 'Content-Type: text/html; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>') def test_attachments(self): """Regression test for #9367""" headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} subject, from_email, to = 'hello', '[email protected]', '[email protected]' text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to], headers=headers) msg.attach_alternative(html_content, "text/html") msg.attach("an attachment.pdf", "%PDF-1.4.%...", mimetype="application/pdf") msg_str = msg.message().as_string() message = email.message_from_string(msg_str) self.assertTrue(message.is_multipart()) self.assertEqual(message.get_content_type(), 'multipart/mixed') self.assertEqual(message.get_default_type(), 'text/plain') payload = message.get_payload() self.assertEqual(payload[0].get_content_type(), 'multipart/alternative') self.assertEqual(payload[1].get_content_type(), 'application/pdf') def test_dummy_backend(self): """ Make sure that dummy backends returns correct number of sent messages """ connection = dummy.EmailBackend() email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}) self.assertEqual(connection.send_messages([email, email, email]), 3) def test_arbitrary_keyword(self): """ Make sure that get_connection() accepts arbitrary keyword that might be used with custom backends. """ c = mail.get_connection(fail_silently=True, foo='bar') self.assertTrue(c.fail_silently) def test_custom_backend(self): """Test custom backend defined in this suite.""" conn = mail.get_connection('regressiontests.mail.custombackend.EmailBackend') self.assertTrue(hasattr(conn, 'test_outbox')) email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}) conn.send_messages([email]) self.assertEqual(len(conn.test_outbox), 1) def test_backend_arg(self): """Test backend argument of mail.get_connection()""" self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.smtp.EmailBackend'), smtp.EmailBackend)) self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.locmem.EmailBackend'), locmem.EmailBackend)) self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.dummy.EmailBackend'), dummy.EmailBackend)) self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.console.EmailBackend'), console.EmailBackend)) tmp_dir = tempfile.mkdtemp() try: self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.filebased.EmailBackend', file_path=tmp_dir), filebased.EmailBackend)) finally: shutil.rmtree(tmp_dir) self.assertTrue(isinstance(mail.get_connection(), locmem.EmailBackend)) @with_django_settings( EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend', ADMINS=[('nobody', '[email protected]')], MANAGERS=[('nobody', '[email protected]')]) def test_connection_arg(self): """Test connection argument to send_mail(), et. al.""" mail.outbox = [] # Send using non-default connection connection = mail.get_connection('regressiontests.mail.custombackend.EmailBackend') send_mail('Subject', 'Content', '[email protected]', ['[email protected]'], connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, 'Subject') connection = mail.get_connection('regressiontests.mail.custombackend.EmailBackend') send_mass_mail([ ('Subject1', 'Content1', '[email protected]', ['[email protected]']), ('Subject2', 'Content2', '[email protected]', ['[email protected]']), ], connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 2) self.assertEqual(connection.test_outbox[0].subject, 'Subject1') self.assertEqual(connection.test_outbox[1].subject, 'Subject2') connection = mail.get_connection('regressiontests.mail.custombackend.EmailBackend') mail_admins('Admin message', 'Content', connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, '[Django] Admin message') connection = mail.get_connection('regressiontests.mail.custombackend.EmailBackend') mail_managers('Manager message', 'Content', connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, '[Django] Manager message') class BaseEmailBackendTests(object): email_backend = None def setUp(self): self.__settings_state = alter_django_settings(EMAIL_BACKEND=self.email_backend) def tearDown(self): restore_django_settings(self.__settings_state) def assertStartsWith(self, first, second): if not first.startswith(second): self.longMessage = True self.assertEqual(first[:len(second)], second, "First string doesn't start with the second.") def get_mailbox_content(self): raise NotImplementedError def flush_mailbox(self): raise NotImplementedError def get_the_message(self): mailbox = self.get_mailbox_content() self.assertEqual(len(mailbox), 1, "Expected exactly one message, got %d.\n%r" % (len(mailbox), [ m.as_string() for m in mailbox])) return mailbox[0] def test_send(self): email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]']) num_sent = mail.get_connection().send_messages([email]) self.assertEqual(num_sent, 1) message = self.get_the_message() self.assertEqual(message["subject"], "Subject") self.assertEqual(message.get_payload(), "Content") self.assertEqual(message["from"], "[email protected]") self.assertEqual(message.get_all("to"), ["[email protected]"]) def test_send_many(self): email1 = EmailMessage('Subject', 'Content1', '[email protected]', ['[email protected]']) email2 = EmailMessage('Subject', 'Content2', '[email protected]', ['[email protected]']) num_sent = mail.get_connection().send_messages([email1, email2]) self.assertEqual(num_sent, 2) messages = self.get_mailbox_content() self.assertEquals(len(messages), 2) self.assertEqual(messages[0].get_payload(), "Content1") self.assertEqual(messages[1].get_payload(), "Content2") def test_send_verbose_name(self): email = EmailMessage("Subject", "Content", '"Firstname Sürname" <[email protected]>', ["[email protected]"]) email.send() message = self.get_the_message() self.assertEqual(message["subject"], "Subject") self.assertEqual(message.get_payload(), "Content") self.assertEqual(message["from"], "=?utf-8?q?Firstname_S=C3=BCrname?= <[email protected]>") @with_django_settings(ADMINS=[('nobody', '[email protected]')], MANAGERS=[('nobody', '[email protected]')]) def test_manager_and_admin_mail_prefix(self): """ String prefix + lazy translated subject = bad output Regression for #13494 """ mail_managers(ugettext_lazy('Subject'), 'Content') message = self.get_the_message() self.assertEqual(message.get('subject'), '[Django] Subject') self.flush_mailbox() mail_admins(ugettext_lazy('Subject'), 'Content') message = self.get_the_message() self.assertEqual(message.get('subject'), '[Django] Subject') @with_django_settings(ADMINS=(), MANAGERS=()) def test_empty_admins(self): """ Test that mail_admins/mail_managers doesn't connect to the mail server if there are no recipients (#9383) """ mail_admins('hi', 'there') self.assertEqual(self.get_mailbox_content(), []) mail_managers('hi', 'there') self.assertEqual(self.get_mailbox_content(), []) def test_idn_send(self): """ Regression test for #14301 """ self.assertTrue(send_mail('Subject', 'Content', 'from@öäü.com', [u'to@öäü.com'])) message = self.get_the_message() self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), '[email protected]') self.assertEqual(message.get('to'), '[email protected]') self.flush_mailbox() m = EmailMessage('Subject', 'Content', 'from@öäü.com', [u'to@öäü.com']) m.send() message = self.get_the_message() self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), '[email protected]') self.assertEqual(message.get('to'), '[email protected]') def test_recipient_without_domain(self): """ Regression test for #15042 """ self.assertTrue(send_mail("Subject", "Content", "tester", ["django"])) message = self.get_the_message() self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), "tester") self.assertEqual(message.get('to'), "django") class LocmemBackendTests(BaseEmailBackendTests, TestCase): email_backend = 'django.core.mail.backends.locmem.EmailBackend' def get_mailbox_content(self): return [m.message() for m in mail.outbox] def flush_mailbox(self): mail.outbox = [] def tearDown(self): super(LocmemBackendTests, self).tearDown() mail.outbox = [] def test_locmem_shared_messages(self): """ Make sure that the locmen backend populates the outbox. """ connection = locmem.EmailBackend() connection2 = locmem.EmailBackend() email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}) connection.send_messages([email]) connection2.send_messages([email]) self.assertEqual(len(mail.outbox), 2) class FileBackendTests(BaseEmailBackendTests, TestCase): email_backend = 'django.core.mail.backends.filebased.EmailBackend' def setUp(self): super(FileBackendTests, self).setUp() self.tmp_dir = tempfile.mkdtemp() self.__settings_state = alter_django_settings(EMAIL_FILE_PATH=self.tmp_dir) def tearDown(self): restore_django_settings(self.__settings_state) shutil.rmtree(self.tmp_dir) super(FileBackendTests, self).tearDown() def flush_mailbox(self): for filename in os.listdir(self.tmp_dir): os.unlink(os.path.join(self.tmp_dir, filename)) def get_mailbox_content(self): messages = [] for filename in os.listdir(self.tmp_dir): session = open(os.path.join(self.tmp_dir, filename)).read().split('\n' + ('-' * 79) + '\n') messages.extend(email.message_from_string(m) for m in session if m) return messages def test_file_sessions(self): """Make sure opening a connection creates a new file""" msg = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}) connection = mail.get_connection() connection.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 1) message = email.message_from_file(open(os.path.join(self.tmp_dir, os.listdir(self.tmp_dir)[0]))) self.assertEqual(message.get_content_type(), 'text/plain') self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), '[email protected]') self.assertEqual(message.get('to'), '[email protected]') connection2 = mail.get_connection() connection2.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 2) connection.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 2) msg.connection = mail.get_connection() self.assertTrue(connection.open()) msg.send() self.assertEqual(len(os.listdir(self.tmp_dir)), 3) msg.send() self.assertEqual(len(os.listdir(self.tmp_dir)), 3) class ConsoleBackendTests(BaseEmailBackendTests, TestCase): email_backend = 'django.core.mail.backends.console.EmailBackend' def setUp(self): super(ConsoleBackendTests, self).setUp() self.__stdout = sys.stdout self.stream = sys.stdout = StringIO() def tearDown(self): del self.stream sys.stdout = self.__stdout del self.__stdout super(ConsoleBackendTests, self).tearDown() def flush_mailbox(self): self.stream = sys.stdout = StringIO() def get_mailbox_content(self): messages = self.stream.getvalue().split('\n' + ('-' * 79) + '\n') return [email.message_from_string(m) for m in messages if m] def test_console_stream_kwarg(self): """ Test that the console backend can be pointed at an arbitrary stream. """ s = StringIO() connection = mail.get_connection('django.core.mail.backends.console.EmailBackend', stream=s) send_mail('Subject', 'Content', '[email protected]', ['[email protected]'], connection=connection) self.assertTrue(s.getvalue().startswith('Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: Subject\nFrom: [email protected]\nTo: [email protected]\nDate: ')) class FakeSMTPServer(smtpd.SMTPServer, threading.Thread): """ Asyncore SMTP server wrapped into a thread. Based on DummyFTPServer from: http://svn.python.org/view/python/branches/py3k/Lib/test/test_ftplib.py?revision=86061&view=markup """ def __init__(self, *args, **kwargs): threading.Thread.__init__(self) smtpd.SMTPServer.__init__(self, *args, **kwargs) self._sink = [] self.active = False self.active_lock = threading.Lock() self.sink_lock = threading.Lock() def process_message(self, peer, mailfrom, rcpttos, data): m = email.message_from_string(data) maddr = email.Utils.parseaddr(m.get('from'))[1] if mailfrom != maddr: return "553 '%s' != '%s'" % (mailfrom, maddr) self.sink_lock.acquire() self._sink.append(m) self.sink_lock.release() def get_sink(self): self.sink_lock.acquire() try: return self._sink[:] finally: self.sink_lock.release() def flush_sink(self): self.sink_lock.acquire() self._sink[:] = [] self.sink_lock.release() def start(self): assert not self.active self.__flag = threading.Event() threading.Thread.start(self) self.__flag.wait() def run(self): self.active = True self.__flag.set() while self.active and asyncore.socket_map: self.active_lock.acquire() asyncore.loop(timeout=0.1, count=1) self.active_lock.release() asyncore.close_all() def stop(self): assert self.active self.active = False self.join() class SMTPBackendTests(BaseEmailBackendTests, TestCase): email_backend = 'django.core.mail.backends.smtp.EmailBackend' def setUp(self): super(SMTPBackendTests, self).setUp() self.server = FakeSMTPServer(('127.0.0.1', 0), None) self.settings = alter_django_settings( EMAIL_HOST="127.0.0.1", EMAIL_PORT=self.server.socket.getsockname()[1]) self.server.start() def tearDown(self): self.server.stop() super(SMTPBackendTests, self).tearDown() def flush_mailbox(self): self.server.flush_sink() def get_mailbox_content(self): return self.server.get_sink()
25,337
Python
.py
476
44.659664
291
0.657427
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,984
custombackend.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/mail/custombackend.py
"""A custom backend for testing.""" from django.core.mail.backends.base import BaseEmailBackend class EmailBackend(BaseEmailBackend): def __init__(self, *args, **kwargs): super(EmailBackend, self).__init__(*args, **kwargs) self.test_outbox = [] def send_messages(self, email_messages): # Messages are stored in a instance variable for testing. self.test_outbox.extend(email_messages) return len(email_messages)
464
Python
.py
10
40.1
65
0.694878
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,985
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/inspectdb/models.py
from django.db import models class People(models.Model): name = models.CharField(max_length=255) class Message(models.Model): from_field = models.ForeignKey(People, db_column='from_id')
197
Python
.py
5
36.2
63
0.767196
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,986
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/inspectdb/tests.py
from StringIO import StringIO from django.core.management import call_command from django.test import TestCase class InspectDBTestCase(TestCase): def test_attribute_name_not_python_keyword(self): out = StringIO() call_command('inspectdb', stdout=out) error_message = "inspectdb generated an attribute name which is a python keyword" self.assertFalse("from = models.ForeignKey(InspectdbPeople)" in out.getvalue(), msg=error_message) self.assertTrue("from_field = models.ForeignKey(InspectdbPeople)" in out.getvalue()) out.close()
584
Python
.py
11
47.090909
106
0.74386
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,987
test_saferef.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/dispatch/tests/test_saferef.py
from django.dispatch.saferef import * import unittest class Test1(object): def x(self): pass def test2(obj): pass class Test2(object): def __call__(self, obj): pass class Tester(unittest.TestCase): def setUp(self): ts = [] ss = [] for x in xrange(5000): t = Test1() ts.append(t) s = safeRef(t.x, self._closure) ss.append(s) ts.append(test2) ss.append(safeRef(test2, self._closure)) for x in xrange(30): t = Test2() ts.append(t) s = safeRef(t, self._closure) ss.append(s) self.ts = ts self.ss = ss self.closureCount = 0 def tearDown(self): del self.ts del self.ss def testIn(self): """Test the "in" operator for safe references (cmp)""" for t in self.ts[:50]: self.assert_(safeRef(t.x) in self.ss) def testValid(self): """Test that the references are valid (return instance methods)""" for s in self.ss: self.assert_(s()) def testShortCircuit (self): """Test that creation short-circuits to reuse existing references""" sd = {} for s in self.ss: sd[s] = 1 for t in self.ts: if hasattr(t, 'x'): self.assert_(sd.has_key(safeRef(t.x))) self.assert_(safeRef(t.x) in sd) else: self.assert_(sd.has_key(safeRef(t))) self.assert_(safeRef(t) in sd) def testRepresentation (self): """Test that the reference object's representation works XXX Doesn't currently check the results, just that no error is raised """ repr(self.ss[-1]) def _closure(self, ref): """Dumb utility mechanism to increment deletion counter""" self.closureCount +=1 def getSuite(): return unittest.makeSuite(Tester,'test') if __name__ == "__main__": unittest.main()
2,071
Python
.py
65
22.461538
76
0.551125
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,988
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/dispatch/tests/__init__.py
""" Unit-tests for the dispatch project """ from test_saferef import * from test_dispatcher import *
102
Python
.py
5
19.2
35
0.78125
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,989
test_dispatcher.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/dispatch/tests/test_dispatcher.py
from django.dispatch import Signal import unittest import sys import gc import django.utils.copycompat as copy if sys.platform.startswith('java'): def garbage_collect(): """Run the garbage collector and wait a bit to let it do his work""" import time gc.collect() time.sleep(0.1) else: def garbage_collect(): gc.collect() def receiver_1_arg(val, **kwargs): return val class Callable(object): def __call__(self, val, **kwargs): return val def a(self, val, **kwargs): return val a_signal = Signal(providing_args=["val"]) class DispatcherTests(unittest.TestCase): """Test suite for dispatcher (barely started)""" def _testIsClean(self, signal): """Assert that everything has been cleaned up automatically""" self.assertEqual(signal.receivers, []) # force cleanup just in case signal.receivers = [] def testExact(self): a_signal.connect(receiver_1_arg, sender=self) expected = [(receiver_1_arg,"test")] result = a_signal.send(sender=self, val="test") self.assertEqual(result, expected) a_signal.disconnect(receiver_1_arg, sender=self) self._testIsClean(a_signal) def testIgnoredSender(self): a_signal.connect(receiver_1_arg) expected = [(receiver_1_arg,"test")] result = a_signal.send(sender=self, val="test") self.assertEqual(result, expected) a_signal.disconnect(receiver_1_arg) self._testIsClean(a_signal) def testGarbageCollected(self): a = Callable() a_signal.connect(a.a, sender=self) expected = [] del a garbage_collect() result = a_signal.send(sender=self, val="test") self.assertEqual(result, expected) self._testIsClean(a_signal) def testMultipleRegistration(self): a = Callable() a_signal.connect(a) a_signal.connect(a) a_signal.connect(a) a_signal.connect(a) a_signal.connect(a) a_signal.connect(a) result = a_signal.send(sender=self, val="test") self.assertEqual(len(result), 1) self.assertEqual(len(a_signal.receivers), 1) del a del result garbage_collect() self._testIsClean(a_signal) def testUidRegistration(self): def uid_based_receiver_1(**kwargs): pass def uid_based_receiver_2(**kwargs): pass a_signal.connect(uid_based_receiver_1, dispatch_uid = "uid") a_signal.connect(uid_based_receiver_2, dispatch_uid = "uid") self.assertEqual(len(a_signal.receivers), 1) a_signal.disconnect(dispatch_uid = "uid") self._testIsClean(a_signal) def testRobust(self): """Test the sendRobust function""" def fails(val, **kwargs): raise ValueError('this') a_signal.connect(fails) result = a_signal.send_robust(sender=self, val="test") err = result[0][1] self.assert_(isinstance(err, ValueError)) self.assertEqual(err.args, ('this',)) a_signal.disconnect(fails) self._testIsClean(a_signal) def testDisconnection(self): receiver_1 = Callable() receiver_2 = Callable() receiver_3 = Callable() a_signal.connect(receiver_1) a_signal.connect(receiver_2) a_signal.connect(receiver_3) a_signal.disconnect(receiver_1) del receiver_2 garbage_collect() a_signal.disconnect(receiver_3) self._testIsClean(a_signal) def getSuite(): return unittest.makeSuite(DispatcherTests,'test') if __name__ == "__main__": unittest.main()
3,724
Python
.py
104
27.932692
76
0.631667
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,990
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/builtin_server/tests.py
from unittest import TestCase from StringIO import StringIO from django.core.servers.basehttp import ServerHandler # # Tests for #9659: wsgi.file_wrapper in the builtin server. # We need to mock a couple of of handlers and keep track of what # gets called when using a couple kinds of WSGI apps. # class DummyHandler(object): def log_request(*args, **kwargs): pass class FileWrapperHandler(ServerHandler): def __init__(self, *args, **kwargs): ServerHandler.__init__(self, *args, **kwargs) self.request_handler = DummyHandler() self._used_sendfile = False def sendfile(self): self._used_sendfile = True return True def wsgi_app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return ['Hello World!'] def wsgi_app_file_wrapper(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return environ['wsgi.file_wrapper'](StringIO('foo')) class WSGIFileWrapperTests(TestCase): """ Test that the wsgi.file_wrapper works for the builting server. """ def test_file_wrapper_uses_sendfile(self): env = {'SERVER_PROTOCOL': 'HTTP/1.0'} err = StringIO() handler = FileWrapperHandler(None, StringIO(), err, env) handler.run(wsgi_app_file_wrapper) self.assert_(handler._used_sendfile) def test_file_wrapper_no_sendfile(self): env = {'SERVER_PROTOCOL': 'HTTP/1.0'} err = StringIO() handler = FileWrapperHandler(None, StringIO(), err, env) handler.run(wsgi_app) self.assertFalse(handler._used_sendfile) self.assertEqual(handler.stdout.getvalue().splitlines()[-1],'Hello World!')
1,721
Python
.py
42
35.380952
83
0.682635
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,991
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/model_fields/models.py
import os import tempfile # Try to import PIL in either of the two ways it can end up installed. # Checking for the existence of Image is enough for CPython, but for PyPy, # you need to check for the underlying modules. try: from PIL import Image, _imaging except ImportError: try: import Image, _imaging except ImportError: Image = None from django.core.files.storage import FileSystemStorage from django.db import models from django.db.models.fields.files import ImageFieldFile, ImageField class Foo(models.Model): a = models.CharField(max_length=10) d = models.DecimalField(max_digits=5, decimal_places=3) def get_foo(): return Foo.objects.get(id=1) class Bar(models.Model): b = models.CharField(max_length=10) a = models.ForeignKey(Foo, default=get_foo) class Whiz(models.Model): CHOICES = ( ('Group 1', ( (1,'First'), (2,'Second'), ) ), ('Group 2', ( (3,'Third'), (4,'Fourth'), ) ), (0,'Other'), ) c = models.IntegerField(choices=CHOICES, null=True) class BigD(models.Model): d = models.DecimalField(max_digits=38, decimal_places=30) class BigS(models.Model): s = models.SlugField(max_length=255) class BigInt(models.Model): value = models.BigIntegerField() null_value = models.BigIntegerField(null = True, blank = True) class Post(models.Model): title = models.CharField(max_length=100) body = models.TextField() class NullBooleanModel(models.Model): nbfield = models.NullBooleanField() class BooleanModel(models.Model): bfield = models.BooleanField() string = models.CharField(max_length=10, default='abc') ############################################################################### # ImageField # If PIL available, do these tests. if Image: class TestImageFieldFile(ImageFieldFile): """ Custom Field File class that records whether or not the underlying file was opened. """ def __init__(self, *args, **kwargs): self.was_opened = False super(TestImageFieldFile, self).__init__(*args,**kwargs) def open(self): self.was_opened = True super(TestImageFieldFile, self).open() class TestImageField(ImageField): attr_class = TestImageFieldFile # Set up a temp directory for file storage. temp_storage_dir = tempfile.mkdtemp() temp_storage = FileSystemStorage(temp_storage_dir) temp_upload_to_dir = os.path.join(temp_storage.location, 'tests') class Person(models.Model): """ Model that defines an ImageField with no dimension fields. """ name = models.CharField(max_length=50) mugshot = TestImageField(storage=temp_storage, upload_to='tests') class PersonWithHeight(models.Model): """ Model that defines an ImageField with only one dimension field. """ name = models.CharField(max_length=50) mugshot = TestImageField(storage=temp_storage, upload_to='tests', height_field='mugshot_height') mugshot_height = models.PositiveSmallIntegerField() class PersonWithHeightAndWidth(models.Model): """ Model that defines height and width fields after the ImageField. """ name = models.CharField(max_length=50) mugshot = TestImageField(storage=temp_storage, upload_to='tests', height_field='mugshot_height', width_field='mugshot_width') mugshot_height = models.PositiveSmallIntegerField() mugshot_width = models.PositiveSmallIntegerField() class PersonDimensionsFirst(models.Model): """ Model that defines height and width fields before the ImageField. """ name = models.CharField(max_length=50) mugshot_height = models.PositiveSmallIntegerField() mugshot_width = models.PositiveSmallIntegerField() mugshot = TestImageField(storage=temp_storage, upload_to='tests', height_field='mugshot_height', width_field='mugshot_width') class PersonTwoImages(models.Model): """ Model that: * Defines two ImageFields * Defines the height/width fields before the ImageFields * Has a nullalble ImageField """ name = models.CharField(max_length=50) mugshot_height = models.PositiveSmallIntegerField() mugshot_width = models.PositiveSmallIntegerField() mugshot = TestImageField(storage=temp_storage, upload_to='tests', height_field='mugshot_height', width_field='mugshot_width') headshot_height = models.PositiveSmallIntegerField( blank=True, null=True) headshot_width = models.PositiveSmallIntegerField( blank=True, null=True) headshot = TestImageField(blank=True, null=True, storage=temp_storage, upload_to='tests', height_field='headshot_height', width_field='headshot_width') ###############################################################################
5,401
Python
.py
130
32.353846
79
0.615018
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,992
imagefield.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/model_fields/imagefield.py
import os import shutil from django.core.files import File from django.core.files.base import ContentFile from django.core.files.images import ImageFile from django.test import TestCase from models import Image, Person, PersonWithHeight, PersonWithHeightAndWidth, \ PersonDimensionsFirst, PersonTwoImages, TestImageFieldFile # If PIL available, do these tests. if Image: from models import temp_storage_dir class ImageFieldTestMixin(object): """ Mixin class to provide common functionality to ImageField test classes. """ # Person model to use for tests. PersonModel = PersonWithHeightAndWidth # File class to use for file instances. File = ImageFile def setUp(self): """ Creates a pristine temp directory (or deletes and recreates if it already exists) that the model uses as its storage directory. Sets up two ImageFile instances for use in tests. """ if os.path.exists(temp_storage_dir): shutil.rmtree(temp_storage_dir) os.mkdir(temp_storage_dir) file_path1 = os.path.join(os.path.dirname(__file__), "4x8.png") self.file1 = self.File(open(file_path1, 'rb')) file_path2 = os.path.join(os.path.dirname(__file__), "8x4.png") self.file2 = self.File(open(file_path2, 'rb')) def tearDown(self): """ Removes temp directory and all its contents. """ shutil.rmtree(temp_storage_dir) def check_dimensions(self, instance, width, height, field_name='mugshot'): """ Asserts that the given width and height values match both the field's height and width attributes and the height and width fields (if defined) the image field is caching to. Note, this method will check for dimension fields named by adding "_width" or "_height" to the name of the ImageField. So, the models used in these tests must have their fields named accordingly. By default, we check the field named "mugshot", but this can be specified by passing the field_name parameter. """ field = getattr(instance, field_name) # Check height/width attributes of field. if width is None and height is None: self.assertRaises(ValueError, getattr, field, 'width') self.assertRaises(ValueError, getattr, field, 'height') else: self.assertEqual(field.width, width) self.assertEqual(field.height, height) # Check height/width fields of model, if defined. width_field_name = field_name + '_width' if hasattr(instance, width_field_name): self.assertEqual(getattr(instance, width_field_name), width) height_field_name = field_name + '_height' if hasattr(instance, height_field_name): self.assertEqual(getattr(instance, height_field_name), height) class ImageFieldTests(ImageFieldTestMixin, TestCase): """ Tests for ImageField that don't need to be run with each of the different test model classes. """ def test_equal_notequal_hash(self): """ Bug #9786: Ensure '==' and '!=' work correctly. Bug #9508: make sure hash() works as expected (equal items must hash to the same value). """ # Create two Persons with different mugshots. p1 = self.PersonModel(name="Joe") p1.mugshot.save("mug", self.file1) p2 = self.PersonModel(name="Bob") p2.mugshot.save("mug", self.file2) self.assertEqual(p1.mugshot == p2.mugshot, False) self.assertEqual(p1.mugshot != p2.mugshot, True) # Test again with an instance fetched from the db. p1_db = self.PersonModel.objects.get(name="Joe") self.assertEqual(p1_db.mugshot == p2.mugshot, False) self.assertEqual(p1_db.mugshot != p2.mugshot, True) # Instance from db should match the local instance. self.assertEqual(p1_db.mugshot == p1.mugshot, True) self.assertEqual(hash(p1_db.mugshot), hash(p1.mugshot)) self.assertEqual(p1_db.mugshot != p1.mugshot, False) def test_instantiate_missing(self): """ If the underlying file is unavailable, still create instantiate the object without error. """ p = self.PersonModel(name="Joan") p.mugshot.save("shot", self.file1) p = self.PersonModel.objects.get(name="Joan") path = p.mugshot.path shutil.move(path, path + '.moved') p2 = self.PersonModel.objects.get(name="Joan") def test_delete_when_missing(self): """ Bug #8175: correctly delete an object where the file no longer exists on the file system. """ p = self.PersonModel(name="Fred") p.mugshot.save("shot", self.file1) os.remove(p.mugshot.path) p.delete() def test_size_method(self): """ Bug #8534: FileField.size should not leave the file open. """ p = self.PersonModel(name="Joan") p.mugshot.save("shot", self.file1) # Get a "clean" model instance p = self.PersonModel.objects.get(name="Joan") # It won't have an opened file. self.assertEqual(p.mugshot.closed, True) # After asking for the size, the file should still be closed. _ = p.mugshot.size self.assertEqual(p.mugshot.closed, True) def test_pickle(self): """ Tests that ImageField can be pickled, unpickled, and that the image of the unpickled version is the same as the original. """ import pickle p = Person(name="Joe") p.mugshot.save("mug", self.file1) dump = pickle.dumps(p) p2 = Person(name="Bob") p2.mugshot = self.file1 loaded_p = pickle.loads(dump) self.assertEqual(p.mugshot, loaded_p.mugshot) class ImageFieldTwoDimensionsTests(ImageFieldTestMixin, TestCase): """ Tests behavior of an ImageField and its dimensions fields. """ def test_constructor(self): """ Tests assigning an image field through the model's constructor. """ p = self.PersonModel(name='Joe', mugshot=self.file1) self.check_dimensions(p, 4, 8) p.save() self.check_dimensions(p, 4, 8) def test_image_after_constructor(self): """ Tests behavior when image is not passed in constructor. """ p = self.PersonModel(name='Joe') # TestImageField value will default to being an instance of its # attr_class, a TestImageFieldFile, with name == None, which will # cause it to evaluate as False. self.assertEqual(isinstance(p.mugshot, TestImageFieldFile), True) self.assertEqual(bool(p.mugshot), False) # Test setting a fresh created model instance. p = self.PersonModel(name='Joe') p.mugshot = self.file1 self.check_dimensions(p, 4, 8) def test_create(self): """ Tests assigning an image in Manager.create(). """ p = self.PersonModel.objects.create(name='Joe', mugshot=self.file1) self.check_dimensions(p, 4, 8) def test_default_value(self): """ Tests that the default value for an ImageField is an instance of the field's attr_class (TestImageFieldFile in this case) with no name (name set to None). """ p = self.PersonModel() self.assertEqual(isinstance(p.mugshot, TestImageFieldFile), True) self.assertEqual(bool(p.mugshot), False) def test_assignment_to_None(self): """ Tests that assigning ImageField to None clears dimensions. """ p = self.PersonModel(name='Joe', mugshot=self.file1) self.check_dimensions(p, 4, 8) # If image assigned to None, dimension fields should be cleared. p.mugshot = None self.check_dimensions(p, None, None) p.mugshot = self.file2 self.check_dimensions(p, 8, 4) def test_field_save_and_delete_methods(self): """ Tests assignment using the field's save method and deletion using the field's delete method. """ p = self.PersonModel(name='Joe') p.mugshot.save("mug", self.file1) self.check_dimensions(p, 4, 8) # A new file should update dimensions. p.mugshot.save("mug", self.file2) self.check_dimensions(p, 8, 4) # Field and dimensions should be cleared after a delete. p.mugshot.delete(save=False) self.assertEqual(p.mugshot, None) self.check_dimensions(p, None, None) def test_dimensions(self): """ Checks that dimensions are updated correctly in various situations. """ p = self.PersonModel(name='Joe') # Dimensions should get set if file is saved. p.mugshot.save("mug", self.file1) self.check_dimensions(p, 4, 8) # Test dimensions after fetching from database. p = self.PersonModel.objects.get(name='Joe') # Bug 11084: Dimensions should not get recalculated if file is # coming from the database. We test this by checking if the file # was opened. self.assertEqual(p.mugshot.was_opened, False) self.check_dimensions(p, 4, 8) # After checking dimensions on the image field, the file will have # opened. self.assertEqual(p.mugshot.was_opened, True) # Dimensions should now be cached, and if we reset was_opened and # check dimensions again, the file should not have opened. p.mugshot.was_opened = False self.check_dimensions(p, 4, 8) self.assertEqual(p.mugshot.was_opened, False) # If we assign a new image to the instance, the dimensions should # update. p.mugshot = self.file2 self.check_dimensions(p, 8, 4) # Dimensions were recalculated, and hence file should have opened. self.assertEqual(p.mugshot.was_opened, True) class ImageFieldNoDimensionsTests(ImageFieldTwoDimensionsTests): """ Tests behavior of an ImageField with no dimension fields. """ PersonModel = Person class ImageFieldOneDimensionTests(ImageFieldTwoDimensionsTests): """ Tests behavior of an ImageField with one dimensions field. """ PersonModel = PersonWithHeight class ImageFieldDimensionsFirstTests(ImageFieldTwoDimensionsTests): """ Tests behavior of an ImageField where the dimensions fields are defined before the ImageField. """ PersonModel = PersonDimensionsFirst class ImageFieldUsingFileTests(ImageFieldTwoDimensionsTests): """ Tests behavior of an ImageField when assigning it a File instance rather than an ImageFile instance. """ PersonModel = PersonDimensionsFirst File = File class TwoImageFieldTests(ImageFieldTestMixin, TestCase): """ Tests a model with two ImageFields. """ PersonModel = PersonTwoImages def test_constructor(self): p = self.PersonModel(mugshot=self.file1, headshot=self.file2) self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') p.save() self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') def test_create(self): p = self.PersonModel.objects.create(mugshot=self.file1, headshot=self.file2) self.check_dimensions(p, 4, 8) self.check_dimensions(p, 8, 4, 'headshot') def test_assignment(self): p = self.PersonModel() self.check_dimensions(p, None, None, 'mugshot') self.check_dimensions(p, None, None, 'headshot') p.mugshot = self.file1 self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, None, None, 'headshot') p.headshot = self.file2 self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') # Clear the ImageFields one at a time. p.mugshot = None self.check_dimensions(p, None, None, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') p.headshot = None self.check_dimensions(p, None, None, 'mugshot') self.check_dimensions(p, None, None, 'headshot') def test_field_save_and_delete_methods(self): p = self.PersonModel(name='Joe') p.mugshot.save("mug", self.file1) self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, None, None, 'headshot') p.headshot.save("head", self.file2) self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') # We can use save=True when deleting the image field with null=True # dimension fields and the other field has an image. p.headshot.delete(save=True) self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, None, None, 'headshot') p.mugshot.delete(save=False) self.check_dimensions(p, None, None, 'mugshot') self.check_dimensions(p, None, None, 'headshot') def test_dimensions(self): """ Checks that dimensions are updated correctly in various situations. """ p = self.PersonModel(name='Joe') # Dimensions should get set for the saved file. p.mugshot.save("mug", self.file1) p.headshot.save("head", self.file2) self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') # Test dimensions after fetching from database. p = self.PersonModel.objects.get(name='Joe') # Bug 11084: Dimensions should not get recalculated if file is # coming from the database. We test this by checking if the file # was opened. self.assertEqual(p.mugshot.was_opened, False) self.assertEqual(p.headshot.was_opened, False) self.check_dimensions(p, 4, 8,'mugshot') self.check_dimensions(p, 8, 4, 'headshot') # After checking dimensions on the image fields, the files will # have been opened. self.assertEqual(p.mugshot.was_opened, True) self.assertEqual(p.headshot.was_opened, True) # Dimensions should now be cached, and if we reset was_opened and # check dimensions again, the file should not have opened. p.mugshot.was_opened = False p.headshot.was_opened = False self.check_dimensions(p, 4, 8,'mugshot') self.check_dimensions(p, 8, 4, 'headshot') self.assertEqual(p.mugshot.was_opened, False) self.assertEqual(p.headshot.was_opened, False) # If we assign a new image to the instance, the dimensions should # update. p.mugshot = self.file2 p.headshot = self.file1 self.check_dimensions(p, 8, 4, 'mugshot') self.check_dimensions(p, 4, 8, 'headshot') # Dimensions were recalculated, and hence file should have opened. self.assertEqual(p.mugshot.was_opened, True) self.assertEqual(p.headshot.was_opened, True)
16,535
Python
.py
346
35.531792
79
0.59485
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,993
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/model_fields/tests.py
import datetime import unittest from decimal import Decimal import django.test from django import forms from django.db import models from django.core.exceptions import ValidationError from models import Foo, Bar, Whiz, BigD, BigS, Image, BigInt, Post, NullBooleanModel, BooleanModel # If PIL available, do these tests. if Image: from imagefield import \ ImageFieldTests, \ ImageFieldTwoDimensionsTests, \ ImageFieldNoDimensionsTests, \ ImageFieldOneDimensionTests, \ ImageFieldDimensionsFirstTests, \ ImageFieldUsingFileTests, \ TwoImageFieldTests class BasicFieldTests(django.test.TestCase): def test_show_hidden_initial(self): """ Regression test for #12913. Make sure fields with choices respect show_hidden_initial as a kwarg to models.Field.formfield() """ choices = [(0, 0), (1, 1)] model_field = models.Field(choices=choices) form_field = model_field.formfield(show_hidden_initial=True) self.assertTrue(form_field.show_hidden_initial) form_field = model_field.formfield(show_hidden_initial=False) self.assertFalse(form_field.show_hidden_initial) def test_nullbooleanfield_blank(self): """ Regression test for #13071: NullBooleanField should not throw a validation error when given a value of None. """ nullboolean = NullBooleanModel(nbfield=None) try: nullboolean.full_clean() except ValidationError, e: self.fail("NullBooleanField failed validation with value of None: %s" % e.messages) class DecimalFieldTests(django.test.TestCase): def test_to_python(self): f = models.DecimalField(max_digits=4, decimal_places=2) self.assertEqual(f.to_python(3), Decimal("3")) self.assertEqual(f.to_python("3.14"), Decimal("3.14")) self.assertRaises(ValidationError, f.to_python, "abc") def test_default(self): f = models.DecimalField(default=Decimal("0.00")) self.assertEqual(f.get_default(), Decimal("0.00")) def test_format(self): f = models.DecimalField(max_digits=5, decimal_places=1) self.assertEqual(f._format(f.to_python(2)), u'2.0') self.assertEqual(f._format(f.to_python('2.6')), u'2.6') self.assertEqual(f._format(None), None) def test_get_db_prep_lookup(self): from django.db import connection f = models.DecimalField(max_digits=5, decimal_places=1) self.assertEqual(f.get_db_prep_lookup('exact', None, connection=connection), [None]) def test_filter_with_strings(self): """ We should be able to filter decimal fields using strings (#8023) """ Foo.objects.create(id=1, a='abc', d=Decimal("12.34")) self.assertEqual(list(Foo.objects.filter(d=u'1.23')), []) def test_save_without_float_conversion(self): """ Ensure decimals don't go through a corrupting float conversion during save (#5079). """ bd = BigD(d="12.9") bd.save() bd = BigD.objects.get(pk=bd.pk) self.assertEqual(bd.d, Decimal("12.9")) def test_lookup_really_big_value(self): """ Ensure that really big values can be used in a filter statement, even with older Python versions. """ # This should not crash. That counts as a win for our purposes. Foo.objects.filter(d__gte=100000000000) class ForeignKeyTests(django.test.TestCase): def test_callable_default(self): """Test the use of a lazy callable for ForeignKey.default""" a = Foo.objects.create(id=1, a='abc', d=Decimal("12.34")) b = Bar.objects.create(b="bcd") self.assertEqual(b.a, a) class DateTimeFieldTests(unittest.TestCase): def test_datetimefield_to_python_usecs(self): """DateTimeField.to_python should support usecs""" f = models.DateTimeField() self.assertEqual(f.to_python('2001-01-02 03:04:05.000006'), datetime.datetime(2001, 1, 2, 3, 4, 5, 6)) self.assertEqual(f.to_python('2001-01-02 03:04:05.999999'), datetime.datetime(2001, 1, 2, 3, 4, 5, 999999)) def test_timefield_to_python_usecs(self): """TimeField.to_python should support usecs""" f = models.TimeField() self.assertEqual(f.to_python('01:02:03.000004'), datetime.time(1, 2, 3, 4)) self.assertEqual(f.to_python('01:02:03.999999'), datetime.time(1, 2, 3, 999999)) class BooleanFieldTests(unittest.TestCase): def _test_get_db_prep_lookup(self, f): from django.db import connection self.assertEqual(f.get_db_prep_lookup('exact', True, connection=connection), [True]) self.assertEqual(f.get_db_prep_lookup('exact', '1', connection=connection), [True]) self.assertEqual(f.get_db_prep_lookup('exact', 1, connection=connection), [True]) self.assertEqual(f.get_db_prep_lookup('exact', False, connection=connection), [False]) self.assertEqual(f.get_db_prep_lookup('exact', '0', connection=connection), [False]) self.assertEqual(f.get_db_prep_lookup('exact', 0, connection=connection), [False]) self.assertEqual(f.get_db_prep_lookup('exact', None, connection=connection), [None]) def _test_to_python(self, f): self.assertTrue(f.to_python(1) is True) self.assertTrue(f.to_python(0) is False) def test_booleanfield_get_db_prep_lookup(self): self._test_get_db_prep_lookup(models.BooleanField()) def test_nullbooleanfield_get_db_prep_lookup(self): self._test_get_db_prep_lookup(models.NullBooleanField()) def test_booleanfield_to_python(self): self._test_to_python(models.BooleanField()) def test_nullbooleanfield_to_python(self): self._test_to_python(models.NullBooleanField()) def test_booleanfield_choices_blank(self): """ Test that BooleanField with choices and defaults doesn't generate a formfield with the blank option (#9640, #10549). """ choices = [(1, u'Si'), (2, 'No')] f = models.BooleanField(choices=choices, default=1, null=True) self.assertEqual(f.formfield().choices, [('', '---------')] + choices) f = models.BooleanField(choices=choices, default=1, null=False) self.assertEqual(f.formfield().choices, choices) def test_return_type(self): b = BooleanModel() b.bfield = True b.save() b2 = BooleanModel.objects.get(pk=b.pk) self.assertTrue(isinstance(b2.bfield, bool)) self.assertEqual(b2.bfield, True) b3 = BooleanModel() b3.bfield = False b3.save() b4 = BooleanModel.objects.get(pk=b3.pk) self.assertTrue(isinstance(b4.bfield, bool)) self.assertEqual(b4.bfield, False) b = NullBooleanModel() b.nbfield = True b.save() b2 = NullBooleanModel.objects.get(pk=b.pk) self.assertTrue(isinstance(b2.nbfield, bool)) self.assertEqual(b2.nbfield, True) b3 = NullBooleanModel() b3.nbfield = False b3.save() b4 = NullBooleanModel.objects.get(pk=b3.pk) self.assertTrue(isinstance(b4.nbfield, bool)) self.assertEqual(b4.nbfield, False) # http://code.djangoproject.com/ticket/13293 # Verify that when an extra clause exists, the boolean # conversions are applied with an offset b5 = BooleanModel.objects.all().extra( select={'string_length': 'LENGTH(string)'})[0] self.assertFalse(isinstance(b5.pk, bool)) class ChoicesTests(django.test.TestCase): def test_choices_and_field_display(self): """ Check that get_choices and get_flatchoices interact with get_FIELD_display to return the expected values (#7913). """ self.assertEqual(Whiz(c=1).get_c_display(), 'First') # A nested value self.assertEqual(Whiz(c=0).get_c_display(), 'Other') # A top level value self.assertEqual(Whiz(c=9).get_c_display(), 9) # Invalid value self.assertEqual(Whiz(c=None).get_c_display(), None) # Blank value self.assertEqual(Whiz(c='').get_c_display(), '') # Empty value class SlugFieldTests(django.test.TestCase): def test_slugfield_max_length(self): """ Make sure SlugField honors max_length (#9706) """ bs = BigS.objects.create(s = 'slug'*50) bs = BigS.objects.get(pk=bs.pk) self.assertEqual(bs.s, 'slug'*50) class ValidationTest(django.test.TestCase): def test_charfield_raises_error_on_empty_string(self): f = models.CharField() self.assertRaises(ValidationError, f.clean, "", None) def test_charfield_cleans_empty_string_when_blank_true(self): f = models.CharField(blank=True) self.assertEqual('', f.clean('', None)) def test_integerfield_cleans_valid_string(self): f = models.IntegerField() self.assertEqual(2, f.clean('2', None)) def test_integerfield_raises_error_on_invalid_intput(self): f = models.IntegerField() self.assertRaises(ValidationError, f.clean, "a", None) def test_charfield_with_choices_cleans_valid_choice(self): f = models.CharField(max_length=1, choices=[('a','A'), ('b','B')]) self.assertEqual('a', f.clean('a', None)) def test_charfield_with_choices_raises_error_on_invalid_choice(self): f = models.CharField(choices=[('a','A'), ('b','B')]) self.assertRaises(ValidationError, f.clean, "not a", None) def test_choices_validation_supports_named_groups(self): f = models.IntegerField(choices=(('group',((10,'A'),(20,'B'))),(30,'C'))) self.assertEqual(10, f.clean(10, None)) def test_nullable_integerfield_raises_error_with_blank_false(self): f = models.IntegerField(null=True, blank=False) self.assertRaises(ValidationError, f.clean, None, None) def test_nullable_integerfield_cleans_none_on_null_and_blank_true(self): f = models.IntegerField(null=True, blank=True) self.assertEqual(None, f.clean(None, None)) def test_integerfield_raises_error_on_empty_input(self): f = models.IntegerField(null=False) self.assertRaises(ValidationError, f.clean, None, None) self.assertRaises(ValidationError, f.clean, '', None) def test_charfield_raises_error_on_empty_input(self): f = models.CharField(null=False) self.assertRaises(ValidationError, f.clean, None, None) def test_datefield_cleans_date(self): f = models.DateField() self.assertEqual(datetime.date(2008, 10, 10), f.clean('2008-10-10', None)) def test_boolean_field_doesnt_accept_empty_input(self): f = models.BooleanField() self.assertRaises(ValidationError, f.clean, None, None) class BigIntegerFieldTests(django.test.TestCase): def test_limits(self): # Ensure that values that are right at the limits can be saved # and then retrieved without corruption. maxval = 9223372036854775807 minval = -maxval - 1 BigInt.objects.create(value=maxval) qs = BigInt.objects.filter(value__gte=maxval) self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].value, maxval) BigInt.objects.create(value=minval) qs = BigInt.objects.filter(value__lte=minval) self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].value, minval) def test_types(self): b = BigInt(value = 0) self.assertTrue(isinstance(b.value, (int, long))) b.save() self.assertTrue(isinstance(b.value, (int, long))) b = BigInt.objects.all()[0] self.assertTrue(isinstance(b.value, (int, long))) def test_coercing(self): BigInt.objects.create(value ='10') b = BigInt.objects.get(value = '10') self.assertEqual(b.value, 10) class TypeCoercionTests(django.test.TestCase): """ Test that database lookups can accept the wrong types and convert them with no error: especially on Postgres 8.3+ which does not do automatic casting at the DB level. See #10015. """ def test_lookup_integer_in_charfield(self): self.assertEquals(Post.objects.filter(title=9).count(), 0) def test_lookup_integer_in_textfield(self): self.assertEquals(Post.objects.filter(body=24).count(), 0)
12,549
Python
.py
258
40.341085
98
0.655034
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,994
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/fixtures_regress/models.py
from django.db import models, DEFAULT_DB_ALIAS from django.contrib.auth.models import User from django.conf import settings class Animal(models.Model): name = models.CharField(max_length=150) latin_name = models.CharField(max_length=150) count = models.IntegerField() weight = models.FloatField() # use a non-default name for the default manager specimens = models.Manager() def __unicode__(self): return self.name class Plant(models.Model): name = models.CharField(max_length=150) class Meta: # For testing when upper case letter in app name; regression for #4057 db_table = "Fixtures_regress_plant" class Stuff(models.Model): name = models.CharField(max_length=20, null=True) owner = models.ForeignKey(User, null=True) def __unicode__(self): return unicode(self.name) + u' is owned by ' + unicode(self.owner) class Absolute(models.Model): name = models.CharField(max_length=40) load_count = 0 def __init__(self, *args, **kwargs): super(Absolute, self).__init__(*args, **kwargs) Absolute.load_count += 1 class Parent(models.Model): name = models.CharField(max_length=10) class Meta: ordering = ('id',) class Child(Parent): data = models.CharField(max_length=10) # Models to regression test #7572 class Channel(models.Model): name = models.CharField(max_length=255) class Article(models.Model): title = models.CharField(max_length=255) channels = models.ManyToManyField(Channel) class Meta: ordering = ('id',) # Models to regression test #11428 class Widget(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __unicode__(self): return self.name class WidgetProxy(Widget): class Meta: proxy = True # Check for forward references in FKs and M2Ms with natural keys class TestManager(models.Manager): def get_by_natural_key(self, key): return self.get(name=key) class Store(models.Model): objects = TestManager() name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __unicode__(self): return self.name def natural_key(self): return (self.name,) class Person(models.Model): objects = TestManager() name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __unicode__(self): return self.name # Person doesn't actually have a dependency on store, but we need to define # one to test the behaviour of the dependency resolution algorithm. def natural_key(self): return (self.name,) natural_key.dependencies = ['fixtures_regress.store'] class Book(models.Model): name = models.CharField(max_length=255) author = models.ForeignKey(Person) stores = models.ManyToManyField(Store) class Meta: ordering = ('name',) def __unicode__(self): return u'%s by %s (available at %s)' % ( self.name, self.author.name, ', '.join(s.name for s in self.stores.all()) ) class NKManager(models.Manager): def get_by_natural_key(self, data): return self.get(data=data) class NKChild(Parent): data = models.CharField(max_length=10, unique=True) objects = NKManager() def natural_key(self): return self.data def __unicode__(self): return u'NKChild %s:%s' % (self.name, self.data) class RefToNKChild(models.Model): text = models.CharField(max_length=10) nk_fk = models.ForeignKey(NKChild, related_name='ref_fks') nk_m2m = models.ManyToManyField(NKChild, related_name='ref_m2ms') def __unicode__(self): return u'%s: Reference to %s [%s]' % ( self.text, self.nk_fk, ', '.join(str(o) for o in self.nk_m2m.all()) ) # ome models with pathological circular dependencies class Circle1(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle2'] class Circle2(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle1'] class Circle3(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle3'] class Circle4(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle5'] class Circle5(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle6'] class Circle6(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle4'] class ExternalDependency(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.book'] # Model for regression test of #11101 class Thingy(models.Model): name = models.CharField(max_length=255)
5,399
Python
.py
148
30.635135
79
0.681484
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,995
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/fixtures_regress/tests.py
# -*- coding: utf-8 -*- # Unittests for fixtures. import os import re import sys try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.conf import settings from django.core import management from django.core.management.commands.dumpdata import sort_dependencies from django.core.management.base import CommandError from django.db.models import signals from django.db import DEFAULT_DB_ALIAS, transaction from django.test import TestCase, TransactionTestCase from models import Animal, Stuff from models import Absolute, Parent, Child from models import Article, Widget from models import Store, Person, Book from models import NKChild, RefToNKChild from models import Circle1, Circle2, Circle3 from models import ExternalDependency from models import Thingy pre_save_checks = [] def animal_pre_save_check(signal, sender, instance, **kwargs): "A signal that is used to check the type of data loaded from fixtures" pre_save_checks.append( ( 'Count = %s (%s)' % (instance.count, type(instance.count)), 'Weight = %s (%s)' % (instance.weight, type(instance.weight)), ) ) class TestFixtures(TestCase): def test_duplicate_pk(self): """ This is a regression test for ticket #3790. """ # Load a fixture that uses PK=1 management.call_command( 'loaddata', 'sequence', verbosity=0, commit=False ) # Create a new animal. Without a sequence reset, this new object # will take a PK of 1 (on Postgres), and the save will fail. animal = Animal( name='Platypus', latin_name='Ornithorhynchus anatinus', count=2, weight=2.2 ) animal.save() self.assertTrue(animal.id > 1) if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.oracle': def test_pretty_print_xml(self): """ Regression test for ticket #4558 -- pretty printing of XML fixtures doesn't affect parsing of None values. """ # Load a pretty-printed XML fixture with Nulls. management.call_command( 'loaddata', 'pretty.xml', verbosity=0, commit=False ) self.assertEqual(Stuff.objects.all()[0].name, None) self.assertEqual(Stuff.objects.all()[0].owner, None) if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.oracle': def test_pretty_print_xml_empty_strings(self): """ Regression test for ticket #4558 -- pretty printing of XML fixtures doesn't affect parsing of None values. """ # Load a pretty-printed XML fixture with Nulls. management.call_command( 'loaddata', 'pretty.xml', verbosity=0, commit=False ) self.assertEqual(Stuff.objects.all()[0].name, u'') self.assertEqual(Stuff.objects.all()[0].owner, None) def test_absolute_path(self): """ Regression test for ticket #6436 -- os.path.join will throw away the initial parts of a path if it encounters an absolute path. This means that if a fixture is specified as an absolute path, we need to make sure we don't discover the absolute path in every fixture directory. """ load_absolute_path = os.path.join( os.path.dirname(__file__), 'fixtures', 'absolute.json' ) management.call_command( 'loaddata', load_absolute_path, verbosity=0, commit=False ) self.assertEqual(Absolute.load_count, 1) def test_unknown_format(self): """ Test for ticket #4371 -- Loading data of an unknown format should fail Validate that error conditions are caught correctly """ stderr = StringIO() management.call_command( 'loaddata', 'bad_fixture1.unkn', verbosity=0, commit=False, stderr=stderr, ) self.assertEqual( stderr.getvalue(), "Problem installing fixture 'bad_fixture1': unkn is not a known serialization format.\n" ) def test_invalid_data(self): """ Test for ticket #4371 -- Loading a fixture file with invalid data using explicit filename. Validate that error conditions are caught correctly """ stderr = StringIO() management.call_command( 'loaddata', 'bad_fixture2.xml', verbosity=0, commit=False, stderr=stderr, ) self.assertEqual( stderr.getvalue(), "No fixture data found for 'bad_fixture2'. (File format may be invalid.)\n" ) def test_invalid_data_no_ext(self): """ Test for ticket #4371 -- Loading a fixture file with invalid data without file extension. Validate that error conditions are caught correctly """ stderr = StringIO() management.call_command( 'loaddata', 'bad_fixture2', verbosity=0, commit=False, stderr=stderr, ) self.assertEqual( stderr.getvalue(), "No fixture data found for 'bad_fixture2'. (File format may be invalid.)\n" ) def test_empty(self): """ Test for ticket #4371 -- Loading a fixture file with no data returns an error. Validate that error conditions are caught correctly """ stderr = StringIO() management.call_command( 'loaddata', 'empty', verbosity=0, commit=False, stderr=stderr, ) self.assertEqual( stderr.getvalue(), "No fixture data found for 'empty'. (File format may be invalid.)\n" ) def test_abort_loaddata_on_error(self): """ Test for ticket #4371 -- If any of the fixtures contain an error, loading is aborted. Validate that error conditions are caught correctly """ stderr = StringIO() management.call_command( 'loaddata', 'empty', verbosity=0, commit=False, stderr=stderr, ) self.assertEqual( stderr.getvalue(), "No fixture data found for 'empty'. (File format may be invalid.)\n" ) def test_error_message(self): """ (Regression for #9011 - error message is correct) """ stderr = StringIO() management.call_command( 'loaddata', 'bad_fixture2', 'animal', verbosity=0, commit=False, stderr=stderr, ) self.assertEqual( stderr.getvalue(), "No fixture data found for 'bad_fixture2'. (File format may be invalid.)\n" ) def test_pg_sequence_resetting_checks(self): """ Test for ticket #7565 -- PostgreSQL sequence resetting checks shouldn't ascend to parent models when inheritance is used (since they are treated individually). """ management.call_command( 'loaddata', 'model-inheritance.json', verbosity=0, commit=False ) self.assertEqual(Parent.objects.all()[0].id, 1) self.assertEqual(Child.objects.all()[0].id, 1) def test_close_connection_after_loaddata(self): """ Test for ticket #7572 -- MySQL has a problem if the same connection is used to create tables, load data, and then query over that data. To compensate, we close the connection after running loaddata. This ensures that a new connection is opened when test queries are issued. """ management.call_command( 'loaddata', 'big-fixture.json', verbosity=0, commit=False ) articles = Article.objects.exclude(id=9) self.assertEqual( list(articles.values_list('id', flat=True)), [1, 2, 3, 4, 5, 6, 7, 8] ) # Just for good measure, run the same query again. # Under the influence of ticket #7572, this will # give a different result to the previous call. self.assertEqual( list(articles.values_list('id', flat=True)), [1, 2, 3, 4, 5, 6, 7, 8] ) def test_field_value_coerce(self): """ Test for tickets #8298, #9942 - Field values should be coerced into the correct type by the deserializer, not as part of the database write. """ global pre_save_checks pre_save_checks = [] signals.pre_save.connect(animal_pre_save_check) management.call_command( 'loaddata', 'animal.xml', verbosity=0, commit=False, ) self.assertEqual( pre_save_checks, [ ("Count = 42 (<type 'int'>)", "Weight = 1.2 (<type 'float'>)") ] ) signals.pre_save.disconnect(animal_pre_save_check) def test_dumpdata_uses_default_manager(self): """ Regression for #11286 Ensure that dumpdata honors the default manager Dump the current contents of the database as a JSON fixture """ management.call_command( 'loaddata', 'animal.xml', verbosity=0, commit=False, ) management.call_command( 'loaddata', 'sequence.json', verbosity=0, commit=False, ) animal = Animal( name='Platypus', latin_name='Ornithorhynchus anatinus', count=2, weight=2.2 ) animal.save() stdout = StringIO() management.call_command( 'dumpdata', 'fixtures_regress.animal', format='json', stdout=stdout ) # Output order isn't guaranteed, so check for parts data = stdout.getvalue() # Get rid of artifacts like '000000002' to eliminate the differences # between different Python versions. data = re.sub('0{6,}\d', '', data) lion_json = '{"pk": 1, "model": "fixtures_regress.animal", "fields": {"count": 3, "weight": 1.2, "name": "Lion", "latin_name": "Panthera leo"}}' emu_json = '{"pk": 10, "model": "fixtures_regress.animal", "fields": {"count": 42, "weight": 1.2, "name": "Emu", "latin_name": "Dromaius novaehollandiae"}}' platypus_json = '{"pk": %d, "model": "fixtures_regress.animal", "fields": {"count": 2, "weight": 2.2, "name": "Platypus", "latin_name": "Ornithorhynchus anatinus"}}' platypus_json = platypus_json % animal.pk self.assertEqual(len(data), len('[%s]' % ', '.join([lion_json, emu_json, platypus_json]))) self.assertTrue(lion_json in data) self.assertTrue(emu_json in data) self.assertTrue(platypus_json in data) def test_proxy_model_included(self): """ Regression for #11428 - Proxy models aren't included when you dumpdata """ stdout = StringIO() # Create an instance of the concrete class Widget(name='grommet').save() management.call_command( 'dumpdata', 'fixtures_regress.widget', 'fixtures_regress.widgetproxy', format='json', stdout=stdout ) self.assertEqual( stdout.getvalue(), """[{"pk": 1, "model": "fixtures_regress.widget", "fields": {"name": "grommet"}}]""" ) class NaturalKeyFixtureTests(TestCase): def assertRaisesMessage(self, exc, msg, func, *args, **kwargs): try: func(*args, **kwargs) except Exception, e: self.assertEqual(msg, str(e)) self.assertTrue(isinstance(e, exc), "Expected %s, got %s" % (exc, type(e))) def test_nk_deserialize(self): """ Test for ticket #13030 - Python based parser version natural keys deserialize with fk to inheriting model """ management.call_command( 'loaddata', 'model-inheritance.json', verbosity=0, commit=False ) management.call_command( 'loaddata', 'nk-inheritance.json', verbosity=0, commit=False ) self.assertEqual( NKChild.objects.get(pk=1).data, 'apple' ) self.assertEqual( RefToNKChild.objects.get(pk=1).nk_fk.data, 'apple' ) def test_nk_deserialize_xml(self): """ Test for ticket #13030 - XML version natural keys deserialize with fk to inheriting model """ management.call_command( 'loaddata', 'model-inheritance.json', verbosity=0, commit=False ) management.call_command( 'loaddata', 'nk-inheritance.json', verbosity=0, commit=False ) management.call_command( 'loaddata', 'nk-inheritance2.xml', verbosity=0, commit=False ) self.assertEqual( NKChild.objects.get(pk=2).data, 'banana' ) self.assertEqual( RefToNKChild.objects.get(pk=2).nk_fk.data, 'apple' ) def test_nk_on_serialize(self): """ Check that natural key requirements are taken into account when serializing models """ management.call_command( 'loaddata', 'forward_ref_lookup.json', verbosity=0, commit=False ) stdout = StringIO() management.call_command( 'dumpdata', 'fixtures_regress.book', 'fixtures_regress.person', 'fixtures_regress.store', verbosity=0, format='json', use_natural_keys=True, stdout=stdout, ) self.assertEqual( stdout.getvalue(), """[{"pk": 2, "model": "fixtures_regress.store", "fields": {"name": "Amazon"}}, {"pk": 3, "model": "fixtures_regress.store", "fields": {"name": "Borders"}}, {"pk": 4, "model": "fixtures_regress.person", "fields": {"name": "Neal Stephenson"}}, {"pk": 1, "model": "fixtures_regress.book", "fields": {"stores": [["Amazon"], ["Borders"]], "name": "Cryptonomicon", "author": ["Neal Stephenson"]}}]""" ) def test_dependency_sorting(self): """ Now lets check the dependency sorting explicitly It doesn't matter what order you mention the models Store *must* be serialized before then Person, and both must be serialized before Book. """ sorted_deps = sort_dependencies( [('fixtures_regress', [Book, Person, Store])] ) self.assertEqual( sorted_deps, [Store, Person, Book] ) def test_dependency_sorting_2(self): sorted_deps = sort_dependencies( [('fixtures_regress', [Book, Store, Person])] ) self.assertEqual( sorted_deps, [Store, Person, Book] ) def test_dependency_sorting_3(self): sorted_deps = sort_dependencies( [('fixtures_regress', [Store, Book, Person])] ) self.assertEqual( sorted_deps, [Store, Person, Book] ) def test_dependency_sorting_4(self): sorted_deps = sort_dependencies( [('fixtures_regress', [Store, Person, Book])] ) self.assertEqual( sorted_deps, [Store, Person, Book] ) def test_dependency_sorting_5(self): sorted_deps = sort_dependencies( [('fixtures_regress', [Person, Book, Store])] ) self.assertEqual( sorted_deps, [Store, Person, Book] ) def test_dependency_sorting_6(self): sorted_deps = sort_dependencies( [('fixtures_regress', [Person, Store, Book])] ) self.assertEqual( sorted_deps, [Store, Person, Book] ) def test_dependency_sorting_dangling(self): sorted_deps = sort_dependencies( [('fixtures_regress', [Person, Circle1, Store, Book])] ) self.assertEqual( sorted_deps, [Circle1, Store, Person, Book] ) def test_dependency_sorting_tight_circular(self): self.assertRaisesMessage( CommandError, """Can't resolve dependencies for fixtures_regress.Circle1, fixtures_regress.Circle2 in serialized app list.""", sort_dependencies, [('fixtures_regress', [Person, Circle2, Circle1, Store, Book])], ) def test_dependency_sorting_tight_circular_2(self): self.assertRaisesMessage( CommandError, """Can't resolve dependencies for fixtures_regress.Circle1, fixtures_regress.Circle2 in serialized app list.""", sort_dependencies, [('fixtures_regress', [Circle1, Book, Circle2])], ) def test_dependency_self_referential(self): self.assertRaisesMessage( CommandError, """Can't resolve dependencies for fixtures_regress.Circle3 in serialized app list.""", sort_dependencies, [('fixtures_regress', [Book, Circle3])], ) def test_dependency_sorting_long(self): self.assertRaisesMessage( CommandError, """Can't resolve dependencies for fixtures_regress.Circle1, fixtures_regress.Circle2, fixtures_regress.Circle3 in serialized app list.""", sort_dependencies, [('fixtures_regress', [Person, Circle2, Circle1, Circle3, Store, Book])], ) def test_dependency_sorting_normal(self): sorted_deps = sort_dependencies( [('fixtures_regress', [Person, ExternalDependency, Book])] ) self.assertEqual( sorted_deps, [Person, Book, ExternalDependency] ) def test_normal_pk(self): """ Check that normal primary keys still work on a model with natural key capabilities """ management.call_command( 'loaddata', 'non_natural_1.json', verbosity=0, commit=False ) management.call_command( 'loaddata', 'forward_ref_lookup.json', verbosity=0, commit=False ) management.call_command( 'loaddata', 'non_natural_2.xml', verbosity=0, commit=False ) books = Book.objects.all() self.assertEqual( books.__repr__(), """[<Book: Cryptonomicon by Neal Stephenson (available at Amazon, Borders)>, <Book: Ender's Game by Orson Scott Card (available at Collins Bookstore)>, <Book: Permutation City by Greg Egan (available at Angus and Robertson)>]""" ) class TestTicket11101(TransactionTestCase): def ticket_11101(self): management.call_command( 'loaddata', 'thingy.json', verbosity=0, commit=False ) self.assertEqual(Thingy.objects.count(), 1) transaction.rollback() self.assertEqual(Thingy.objects.count(), 0) if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.mysql': def test_ticket_11101(self): """Test that fixtures can be rolled back (ticket #11101).""" ticket_11101 = transaction.commit_manually(self.ticket_11101) ticket_11101()
20,296
Python
.py
566
25.685512
407
0.56896
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,996
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/comment_tests/models.py
""" Comments may be attached to any object. See the comment documentation for more information. """ from django.db import models from django.test import TestCase class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def __str__(self): return '%s %s' % (self.first_name, self.last_name) class Article(models.Model): author = models.ForeignKey(Author) headline = models.CharField(max_length=100) def __str__(self): return self.headline class Entry(models.Model): title = models.CharField(max_length=250) body = models.TextField() pub_date = models.DateField() enable_comments = models.BooleanField() def __str__(self): return self.title class Book(models.Model): dewey_decimal = models.DecimalField(primary_key = True, decimal_places=2, max_digits=5)
896
Python
.py
25
31.48
91
0.715949
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,997
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/comment_tests/urls.py
from django.conf.urls.defaults import * from django.contrib.comments.feeds import LatestCommentFeed feeds = { 'comments': LatestCommentFeed, } urlpatterns = patterns('regressiontests.comment_tests.custom_comments.views', url(r'^post/$', 'custom_submit_comment'), url(r'^flag/(\d+)/$', 'custom_flag_comment'), url(r'^delete/(\d+)/$', 'custom_delete_comment'), url(r'^approve/(\d+)/$', 'custom_approve_comment'), ) urlpatterns += patterns('', (r'^rss/legacy/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}), (r'^rss/comments/$', LatestCommentFeed()), )
626
Python
.py
15
38.6
98
0.662829
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,998
urls_admin.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/comment_tests/urls_admin.py
from django.conf.urls.defaults import * from django.contrib import admin from django.contrib.comments.admin import CommentsAdmin from django.contrib.comments.models import Comment # Make a new AdminSite to avoid picking up the deliberately broken admin # modules in other tests. admin_site = admin.AdminSite() admin_site.register(Comment, CommentsAdmin) # To demonstrate proper functionality even when ``delete_selected`` is removed. admin_site2 = admin.AdminSite() admin_site2.disable_action('delete_selected') admin_site2.register(Comment, CommentsAdmin) urlpatterns = patterns('', (r'^admin/', include(admin_site.urls)), (r'^admin2/', include(admin_site2.urls)), )
679
Python
.py
16
40.75
79
0.79697
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,999
feed_tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/tests/regressiontests/comment_tests/tests/feed_tests.py
import warnings from django.test.utils import get_warnings_state, restore_warnings_state from regressiontests.comment_tests.tests import CommentTestCase class CommentFeedTests(CommentTestCase): urls = 'regressiontests.comment_tests.urls' feed_url = '/rss/comments/' def test_feed(self): response = self.client.get(self.feed_url) self.assertEquals(response.status_code, 200) self.assertEquals(response['Content-Type'], 'application/rss+xml') self.assertContains(response, '<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">') self.assertContains(response, '<title>example.com comments</title>') self.assertContains(response, '<link>http://example.com/</link>') self.assertContains(response, '</rss>') class LegacyCommentFeedTests(CommentFeedTests): feed_url = '/rss/legacy/comments/' def setUp(self): self._warnings_state = get_warnings_state() warnings.filterwarnings("ignore", category=DeprecationWarning, module='django.contrib.syndication.views') warnings.filterwarnings("ignore", category=DeprecationWarning, module='django.contrib.syndication.feeds') def tearDown(self): restore_warnings_state(self._warnings_state)
1,316
Python
.py
24
46.125
101
0.699143
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)