Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

PEP8 cleanup

Signed-off-by: Jason Myers <jason@jasonamyers.com>
  • Loading branch information...
commit 7a61c68c50d3837c50e35c252fd76220f08b5290 1 parent 0fdb692
@jasonamyers jasonamyers authored
Showing with 739 additions and 206 deletions.
  1. +15 −0 tests/admin_changelist/models.py
  2. +2 −0  tests/admin_custom_urls/models.py
  3. +2 −0  tests/admin_docs/views.py
  4. +1 −0  tests/admin_filters/models.py
  5. +3 −0  tests/admin_inlines/admin.py
  6. +21 −0 tests/admin_inlines/models.py
  7. +13 −11 tests/admin_inlines/tests.py
  8. +4 −0 tests/admin_ordering/models.py
  9. +1 −0  tests/admin_ordering/tests.py
  10. +9 −0 tests/admin_scripts/tests.py
  11. +5 −0 tests/admin_util/models.py
  12. +3 −3 tests/admin_util/tests.py
  13. +3 −0  tests/admin_validation/tests.py
  14. +22 −0 tests/admin_views/models.py
  15. +15 −20 tests/admin_views/tests.py
  16. +1 −0  tests/admin_views/views.py
  17. +14 −0 tests/admin_widgets/models.py
  18. +15 −1 tests/admin_widgets/tests.py
  19. +3 −0  tests/aggregation/models.py
  20. +5 −1 tests/aggregation_regress/models.py
  21. +10 −8 tests/backends/tests.py
  22. +2 −0  tests/basic/models.py
  23. +32 −16 tests/basic/tests.py
  24. +2 −0  tests/bug639/models.py
  25. +5 −0 tests/bulk_create/models.py
  26. +1 −0  tests/cache/closeable_cache.py
  27. +1 −0  tests/cache/liberal_backend.py
  28. +1 −0  tests/cache/models.py
  29. +6 −0 tests/cache/tests.py
  30. +2 −0  tests/check/models.py
  31. +1 −0  tests/check/tests.py
  32. +1 −0  tests/choices/models.py
  33. +1 −0  tests/commands_sql/tests.py
  34. +1 −0  tests/conditional_processing/tests.py
  35. +4 −0 tests/conditional_processing/views.py
  36. +2 −0  tests/contenttypes_tests/models.py
  37. +1 −0  tests/contenttypes_tests/tests.py
  38. +5 −0 tests/csrf_tests/tests.py
  39. +1 −0  tests/custom_columns/models.py
  40. +1 −0  tests/custom_columns_regress/models.py
  41. +1 −0  tests/custom_columns_regress/tests.py
  42. +10 −0 tests/custom_managers/models.py
  43. +3 −0  tests/custom_managers_regress/models.py
  44. +1 −0  tests/custom_pk/fields.py
  45. +3 −1 tests/custom_pk/models.py
  46. +1 −0  tests/datatypes/models.py
  47. +2 −0  tests/dates/models.py
  48. +2 −0  tests/datetimes/models.py
  49. +1 −0  tests/db_typecasts/tests.py
  50. +1 −0  tests/defer_regress/tests.py
  51. +6 −0 tests/delete/models.py
  52. +2 −1  tests/delete/tests.py
  53. +28 −0 tests/delete_regress/models.py
  54. +2 −1  tests/delete_regress/tests.py
  55. +5 −3 tests/dispatch/tests/test_dispatcher.py
  56. +4 −0 tests/dispatch/tests/test_saferef.py
  57. +5 −0 tests/distinct_on_fields/models.py
  58. +2 −1  tests/distinct_on_fields/tests.py
  59. +1 −0  tests/expressions/models.py
  60. +1 −0  tests/expressions_regress/models.py
  61. +35 −35 tests/expressions_regress/tests.py
  62. +2 −0  tests/extra_regress/models.py
  63. +2 −0  tests/field_subclassing/fields.py
  64. +2 −0  tests/field_subclassing/models.py
  65. +1 −0  tests/file_storage/models.py
  66. +5 −0 tests/file_storage/tests.py
  67. +2 −1  tests/file_uploads/tests.py
  68. +3 −1 tests/file_uploads/uploadhandler.py
  69. +10 −0 tests/file_uploads/views.py
  70. +8 −0 tests/fixtures/models.py
  71. +1 −0  tests/fixtures_model_package/models/__init__.py
  72. +1 −0  tests/fixtures_regress/models.py
  73. +4 −0 tests/force_insert_update/models.py
  74. +11 −0 tests/foreign_object/models.py
  75. +2 −0  tests/foreign_object/tests.py
  76. +4 −1 tests/forms_tests/models.py
  77. +1 −0  tests/forms_tests/tests/test_error_messages.py
  78. +3 −0  tests/forms_tests/tests/test_extra.py
  79. +5 −1 tests/forms_tests/tests/test_formsets.py
  80. +2 −0  tests/forms_tests/tests/test_input_formats.py
  81. +3 −1 tests/forms_tests/tests/test_widgets.py
  82. +1 −0  tests/forms_tests/tests/tests.py
  83. +1 −0  tests/generic_inline_admin/admin.py
  84. +2 −0  tests/generic_inline_admin/models.py
  85. +3 −0  tests/generic_inline_admin/tests.py
  86. +2 −0  tests/generic_relations/tests.py
  87. +25 −0 tests/generic_relations_regress/models.py
  88. +4 −0 tests/generic_views/models.py
  89. +1 −0  tests/generic_views/test_base.py
  90. +2 −1  tests/generic_views/test_dates.py
  91. +19 −0 tests/generic_views/views.py
  92. +2 −0  tests/get_object_or_404/models.py
  93. +2 −0  tests/get_or_create_regress/models.py
  94. +5 −0 tests/handlers/views.py
  95. +5 −0 tests/httpwrappers/tests.py
  96. +2 −0  tests/i18n/forms.py
  97. +1 −0  tests/i18n/models.py
  98. +12 −6 tests/i18n/test_extraction.py
  99. +3 −0  tests/i18n/tests.py
  100. +4 −0 tests/inline_formsets/models.py
  101. +6 −0 tests/inspectdb/models.py
  102. +2 −1  tests/inspectdb/tests.py
  103. +4 −0 tests/known_related_objects/models.py
  104. +1 −0  tests/known_related_objects/tests.py
  105. +2 −0  tests/logging_tests/tests.py
  106. +5 −0 tests/lookup/models.py
  107. +2 −0  tests/m2m_and_m2o/models.py
  108. +2 −1  tests/m2m_and_m2o/tests.py
  109. +2 −0  tests/m2m_intermediary/models.py
  110. +9 −0 tests/m2m_regress/models.py
  111. +3 −0  tests/m2m_signals/models.py
  112. +6 −0 tests/m2m_through/models.py
  113. +9 −0 tests/m2m_through_regress/models.py
  114. +1 −0  tests/m2o_recursive/models.py
  115. +1 −0  tests/m2o_recursive/tests.py
  116. +1 −0  tests/many_to_many/models.py
  117. +1 −0  tests/many_to_one/models.py
  118. +1 −0  tests/many_to_one_null/models.py
  119. +10 −1 tests/many_to_one_regress/models.py
  120. +1 −0  tests/max_lengths/models.py
  121. +1 −0  tests/max_lengths/tests.py
  122. +7 −5 tests/middleware/tests.py
  123. +2 −0  tests/middleware_exceptions/tests.py
  124. +6 −0 tests/middleware_exceptions/views.py
  125. +8 −0 tests/model_fields/tests.py
  126. +28 −0 tests/model_forms/models.py
  127. +1 −0  tests/model_inheritance_same_model_name/models.py
  128. +96 −84 tests/multiple_database/tests.py
View
15 tests/admin_changelist/models.py
@@ -1,26 +1,32 @@
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
+
class Event(models.Model):
# Oracle can have problems with a column named "date"
date = models.DateField(db_column="event_date")
+
class Parent(models.Model):
name = models.CharField(max_length=128)
+
class Child(models.Model):
parent = models.ForeignKey(Parent, editable=False, null=True)
name = models.CharField(max_length=30, blank=True)
age = models.IntegerField(null=True, blank=True)
+
class Genre(models.Model):
name = models.CharField(max_length=20)
+
class Band(models.Model):
name = models.CharField(max_length=20)
nr_of_members = models.PositiveIntegerField()
genres = models.ManyToManyField(Genre)
+
@python_2_unicode_compatible
class Musician(models.Model):
name = models.CharField(max_length=30)
@@ -28,6 +34,7 @@ class Musician(models.Model):
def __str__(self):
return self.name
+
@python_2_unicode_compatible
class Group(models.Model):
name = models.CharField(max_length=30)
@@ -36,26 +43,32 @@ class Group(models.Model):
def __str__(self):
return self.name
+
class Membership(models.Model):
music = models.ForeignKey(Musician)
group = models.ForeignKey(Group)
role = models.CharField(max_length=15)
+
class Quartet(Group):
pass
+
class ChordsMusician(Musician):
pass
+
class ChordsBand(models.Model):
name = models.CharField(max_length=30)
members = models.ManyToManyField(ChordsMusician, through='Invitation')
+
class Invitation(models.Model):
player = models.ForeignKey(ChordsMusician)
band = models.ForeignKey(ChordsBand)
instrument = models.CharField(max_length=15)
+
class Swallow(models.Model):
origin = models.CharField(max_length=255)
load = models.FloatField()
@@ -77,6 +90,7 @@ class OrderedObjectManager(models.Manager):
def get_queryset(self):
return super(OrderedObjectManager, self).get_queryset().order_by('number')
+
class OrderedObject(models.Model):
"""
Model with Manager that defines a default order.
@@ -88,5 +102,6 @@ class OrderedObject(models.Model):
objects = OrderedObjectManager()
+
class CustomIdUser(models.Model):
uuid = models.AutoField(primary_key=True)
View
2  tests/admin_custom_urls/models.py
@@ -54,6 +54,7 @@ def wrapper(*args, **kwargs):
class Person(models.Model):
name = models.CharField(max_length=20)
+
class PersonAdmin(admin.ModelAdmin):
def response_post_save_add(self, request, obj):
@@ -68,6 +69,7 @@ def response_post_save_change(self, request, obj):
class Car(models.Model):
name = models.CharField(max_length=20)
+
class CarAdmin(admin.ModelAdmin):
def response_add(self, request, obj, post_url_continue=None):
View
2  tests/admin_docs/views.py
@@ -5,9 +5,11 @@
xview_dec = decorator_from_middleware(XViewMiddleware)
+
def xview(request):
return HttpResponse()
+
class XViewClass(View):
def get(self, request):
return HttpResponse()
View
1  tests/admin_filters/models.py
@@ -27,6 +27,7 @@ class Department(models.Model):
def __str__(self):
return self.description
+
@python_2_unicode_compatible
class Employee(models.Model):
department = models.ForeignKey(Department, to_field="code")
View
3  tests/admin_inlines/admin.py
@@ -153,6 +153,7 @@ class ChildModel1Inline(admin.TabularInline):
class ChildModel2Inline(admin.StackedInline):
model = ChildModel2
+
# admin for #19425 and #18388
class BinaryTreeAdmin(admin.TabularInline):
model = BinaryTree
@@ -169,10 +170,12 @@ def get_max_num(self, request, obj=None, **kwargs):
return max_num - obj.binarytree_set.count()
return max_num
+
# admin for #19524
class SightingInline(admin.TabularInline):
model = Sighting
+
# admin and form for #18263
class SomeChildModelForm(forms.ModelForm):
View
21 tests/admin_inlines/models.py
@@ -89,6 +89,7 @@ class Inner2(models.Model):
dummy = models.IntegerField()
holder = models.ForeignKey(Holder2)
+
class Holder3(models.Model):
dummy = models.IntegerField()
@@ -99,38 +100,47 @@ class Inner3(models.Model):
# Models for ticket #8190
+
class Holder4(models.Model):
dummy = models.IntegerField()
+
class Inner4Stacked(models.Model):
dummy = models.IntegerField(help_text="Awesome stacked help text is awesome.")
holder = models.ForeignKey(Holder4)
+
class Inner4Tabular(models.Model):
dummy = models.IntegerField(help_text="Awesome tabular help text is awesome.")
holder = models.ForeignKey(Holder4)
# 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)
# Models for #13510
+
class TitleCollection(models.Model):
pass
+
class Title(models.Model):
collection = models.ForeignKey(TitleCollection, blank=True, null=True)
title1 = models.CharField(max_length=100)
@@ -138,19 +148,24 @@ class Title(models.Model):
# Models for #15424
+
class Poll(models.Model):
name = models.CharField(max_length=40)
+
class Question(models.Model):
poll = models.ForeignKey(Poll)
+
class Novel(models.Model):
name = models.CharField(max_length=40)
+
class Chapter(models.Model):
name = models.CharField(max_length=40)
novel = models.ForeignKey(Novel)
+
class FootNote(models.Model):
"""
Model added for ticket 19838
@@ -160,6 +175,7 @@ class FootNote(models.Model):
# Models for #16838
+
class CapoFamiglia(models.Model):
name = models.CharField(max_length=100)
@@ -211,12 +227,15 @@ class BinaryTree(models.Model):
# Models for #19524
+
class LifeForm(models.Model):
pass
+
class ExtraTerrestrial(LifeForm):
name = models.CharField(max_length=100)
+
class Sighting(models.Model):
et = models.ForeignKey(ExtraTerrestrial)
place = models.CharField(max_length=100)
@@ -234,9 +253,11 @@ class SomeChildModel(models.Model):
# Other models
+
class ProfileCollection(models.Model):
pass
+
class Profile(models.Model):
collection = models.ForeignKey(ProfileCollection, blank=True, null=True)
first_name = models.CharField(max_length=100)
View
24 tests/admin_inlines/tests.py
@@ -279,6 +279,7 @@ def test_all_inline_media(self):
self.assertContains(response, 'my_awesome_admin_scripts.js')
self.assertContains(response, 'my_awesome_inline_scripts.js')
+
class TestInlineAdminForm(TestCase):
urls = "admin_inlines.urls"
@@ -465,9 +466,9 @@ def test_inline_change_fk_add_perm(self):
self.assertContains(response, 'Add another Inner2')
# 3 extra forms only, not the existing instance form
self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" '
- 'value="3" name="inner2_set-TOTAL_FORMS" />', html=True)
+ 'value="3" name="inner2_set-TOTAL_FORMS" />', html=True)
self.assertNotContains(response, '<input type="hidden" id="id_inner2_set-0-id" '
- 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
+ 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
def test_inline_change_fk_change_perm(self):
permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct)
@@ -477,12 +478,12 @@ def test_inline_change_fk_change_perm(self):
self.assertContains(response, '<h2>Inner2s</h2>')
# Just the one form for existing instances
self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" '
- 'value="1" name="inner2_set-TOTAL_FORMS" />', html=True)
+ 'value="1" name="inner2_set-TOTAL_FORMS" />', html=True)
self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" '
- 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
+ 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
# max-num 0 means we can't add new ones
self.assertContains(response, '<input type="hidden" id="id_inner2_set-MAX_NUM_FORMS" '
- 'value="0" name="inner2_set-MAX_NUM_FORMS" />', html=True)
+ 'value="0" name="inner2_set-MAX_NUM_FORMS" />', html=True)
def test_inline_change_fk_add_change_perm(self):
permission = Permission.objects.get(codename='add_inner2', content_type=self.inner_ct)
@@ -494,9 +495,9 @@ def test_inline_change_fk_add_change_perm(self):
self.assertContains(response, '<h2>Inner2s</h2>')
# One form for existing instance and three extra for new
self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" '
- 'value="4" name="inner2_set-TOTAL_FORMS" />', html=True)
+ 'value="4" name="inner2_set-TOTAL_FORMS" />', html=True)
self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" '
- 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
+ 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
def test_inline_change_fk_change_del_perm(self):
permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct)
@@ -508,9 +509,9 @@ def test_inline_change_fk_change_del_perm(self):
self.assertContains(response, '<h2>Inner2s</h2>')
# One form for existing instance only, no new
self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" '
- 'value="1" name="inner2_set-TOTAL_FORMS" />', html=True)
+ 'value="1" name="inner2_set-TOTAL_FORMS" />', html=True)
self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" '
- 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
+ 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
self.assertContains(response, 'id="id_inner2_set-0-DELETE"')
def test_inline_change_fk_all_perms(self):
@@ -525,9 +526,9 @@ def test_inline_change_fk_all_perms(self):
self.assertContains(response, '<h2>Inner2s</h2>')
# One form for existing instance only, three for new
self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" '
- 'value="4" name="inner2_set-TOTAL_FORMS" />', html=True)
+ 'value="4" name="inner2_set-TOTAL_FORMS" />', html=True)
self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" '
- 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
+ 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
self.assertContains(response, 'id="id_inner2_set-0-DELETE"')
@@ -698,5 +699,6 @@ def test_alternating_rows(self):
class SeleniumChromeTests(SeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
+
class SeleniumIETests(SeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
View
4 tests/admin_ordering/models.py
@@ -11,6 +11,7 @@ class Band(models.Model):
class Meta:
ordering = ('name',)
+
class Song(models.Model):
band = models.ForeignKey(Band)
name = models.CharField(max_length=100)
@@ -20,13 +21,16 @@ class Song(models.Model):
class Meta:
ordering = ('name',)
+
class SongInlineDefaultOrdering(admin.StackedInline):
model = Song
+
class SongInlineNewOrdering(admin.StackedInline):
model = Song
ordering = ('duration', )
+
class DynOrderingBandAdmin(admin.ModelAdmin):
def get_ordering(self, request):
View
1  tests/admin_ordering/tests.py
@@ -12,6 +12,7 @@
class MockRequest(object):
pass
+
class MockSuperUser(object):
def has_perm(self, perm):
return True
View
9 tests/admin_scripts/tests.py
@@ -289,6 +289,7 @@ def test_custom_command_with_environment(self):
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE:NoArgsCommand")
+
class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase):
"""A series of tests for django-admin.py when using a settings.py file that
contains the test application specified using a full path.
@@ -355,6 +356,7 @@ def test_custom_command_with_environment(self):
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE:NoArgsCommand")
+
class DjangoAdminMinimalSettings(AdminScriptTestCase):
"""A series of tests for django-admin.py when using a settings.py file that
doesn't contain the test application.
@@ -421,6 +423,7 @@ def test_custom_command_with_environment(self):
self.assertNoOutput(out)
self.assertOutput(err, "Unknown command: 'noargs_command'")
+
class DjangoAdminAlternateSettings(AdminScriptTestCase):
"""A series of tests for django-admin.py when using a settings file
with a name other than 'settings.py'.
@@ -796,6 +799,7 @@ def test_custom_command_with_environment(self):
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE:NoArgsCommand")
+
class ManageMinimalSettings(AdminScriptTestCase):
"""A series of tests for manage.py when using a settings.py file that
doesn't contain the test application.
@@ -862,6 +866,7 @@ def test_custom_command_with_environment(self):
self.assertNoOutput(out)
self.assertOutput(err, "Unknown command: 'noargs_command'")
+
class ManageAlternateSettings(AdminScriptTestCase):
"""A series of tests for manage.py when using a settings file
with a name other than 'settings.py'.
@@ -1121,6 +1126,7 @@ def __init__(self, *args, **kwargs):
def run_tests(self, test_labels, extra_tests=None, **kwargs):
pass
+
class ManageTestCommand(AdminScriptTestCase):
def setUp(self):
from django.core.management.commands.test import Command as TestCommand
@@ -1214,6 +1220,7 @@ def test_runner_ambiguous(self):
self.cmd.handle(addrport="deadbeef:7654")
self.assertServerSettings('deadbeef', '7654')
+
class ManageRunserverEmptyAllowedHosts(AdminScriptTestCase):
def setUp(self):
self.write_settings('settings.py', sdict={
@@ -1464,6 +1471,7 @@ def test_label_command_multiple_label(self):
self.assertOutput(out, str_prefix("EXECUTE:LabelCommand label=testlabel, options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', %(_)s'1')]"))
self.assertOutput(out, str_prefix("EXECUTE:LabelCommand label=anotherlabel, options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', %(_)s'1')]"))
+
class ArgumentOrder(AdminScriptTestCase):
"""Tests for 2-stage argument parsing scheme.
@@ -1751,6 +1759,7 @@ def test_all(self):
self.assertNoOutput(err)
self.assertOutput(out, "### STATIC_URL = None")
+
class Dumpdata(AdminScriptTestCase):
"""Tests for dumpdata management command."""
View
5 tests/admin_util/models.py
@@ -19,6 +19,7 @@ def test_from_model_with_override(self):
return "nothing"
test_from_model_with_override.short_description = "not What you Expect"
+
@python_2_unicode_compatible
class Count(models.Model):
num = models.PositiveSmallIntegerField()
@@ -27,12 +28,15 @@ class Count(models.Model):
def __str__(self):
return six.text_type(self.num)
+
class Event(models.Model):
date = models.DateTimeField(auto_now_add=True)
+
class Location(models.Model):
event = models.OneToOneField(Event, verbose_name='awesome event')
+
class Guest(models.Model):
event = models.OneToOneField(Event)
name = models.CharField(max_length=255)
@@ -40,5 +44,6 @@ class Guest(models.Model):
class Meta:
verbose_name = "awesome guest"
+
class EventGuide(models.Model):
event = models.ForeignKey(Event, on_delete=models.DO_NOTHING)
View
6 tests/admin_util/tests.py
@@ -80,6 +80,7 @@ def test_on_delete_do_nothing(self):
# One for Location, one for Guest, and no query for EventGuide
n.collect(objs)
+
class UtilTests(SimpleTestCase):
def test_values_from_lookup_field(self):
"""
@@ -228,9 +229,8 @@ def test_from_model(self, obj):
)
self.assertEqual(
label_for_field("test_from_model", Article,
- model_admin = MockModelAdmin,
- return_attr = True
- ),
+ model_admin=MockModelAdmin,
+ return_attr=True),
("not Really the Model", MockModelAdmin.test_from_model)
)
View
3  tests/admin_validation/tests.py
@@ -12,10 +12,12 @@
class SongForm(forms.ModelForm):
pass
+
class ValidFields(admin.ModelAdmin):
form = SongForm
fields = ['title']
+
class ValidFormFieldsets(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
class ExtraFieldForm(SongForm):
@@ -28,6 +30,7 @@ class ExtraFieldForm(SongForm):
}),
)
+
class ValidationTestCase(TestCase):
def test_readonly_and_editable(self):
View
22 tests/admin_views/models.py
@@ -120,11 +120,13 @@ class Color(models.Model):
def __str__(self):
return self.value
+
# we replicate Color to register with another ModelAdmin
class Color2(Color):
class Meta:
proxy = True
+
@python_2_unicode_compatible
class Thing(models.Model):
title = models.CharField(max_length=20)
@@ -613,10 +615,12 @@ class PrePopulatedPostLargeSlug(models.Model):
published = models.BooleanField(default=False)
slug = models.SlugField(max_length=1000)
+
class AdminOrderedField(models.Model):
order = models.IntegerField()
stuff = models.CharField(max_length=200)
+
class AdminOrderedModelMethod(models.Model):
order = models.IntegerField()
stuff = models.CharField(max_length=200)
@@ -625,14 +629,17 @@ def some_order(self):
return self.order
some_order.admin_order_field = 'order'
+
class AdminOrderedAdminMethod(models.Model):
order = models.IntegerField()
stuff = models.CharField(max_length=200)
+
class AdminOrderedCallable(models.Model):
order = models.IntegerField()
stuff = models.CharField(max_length=200)
+
@python_2_unicode_compatible
class Report(models.Model):
title = models.CharField(max_length=100)
@@ -651,6 +658,7 @@ class MainPrepopulated(models.Model):
slug1 = models.SlugField(blank=True)
slug2 = models.SlugField(blank=True)
+
class RelatedPrepopulated(models.Model):
parent = models.ForeignKey(MainPrepopulated)
name = models.CharField(max_length=75)
@@ -671,6 +679,7 @@ class UnorderedObject(models.Model):
name = models.CharField(max_length=255)
bool = models.BooleanField(default=True)
+
class UndeletableObject(models.Model):
"""
Model whose show_delete in admin change_view has been disabled
@@ -678,30 +687,36 @@ class UndeletableObject(models.Model):
"""
name = models.CharField(max_length=255)
+
class UnchangeableObject(models.Model):
"""
Model whose change_view is disabled in admin
Refs #20640.
"""
+
class UserMessenger(models.Model):
"""
Dummy class for testing message_user functions on ModelAdmin
"""
+
class Simple(models.Model):
"""
Simple model with nothing on it for use in testing
"""
+
class Choice(models.Model):
choice = models.IntegerField(blank=True, null=True,
choices=((1, 'Yes'), (0, 'No'), (None, 'No opinion')))
+
class _Manager(models.Manager):
def get_queryset(self):
return super(_Manager, self).get_queryset().filter(pk__gt=1)
+
class FilteredManager(models.Model):
def __str__(self):
return "PK=%d" % self.pk
@@ -709,26 +724,33 @@ def __str__(self):
pk_gt_1 = _Manager()
objects = models.Manager()
+
class EmptyModelVisible(models.Model):
""" See ticket #11277. """
+
class EmptyModelHidden(models.Model):
""" See ticket #11277. """
+
class EmptyModelMixin(models.Model):
""" See ticket #11277. """
+
class State(models.Model):
name = models.CharField(max_length=100)
+
class City(models.Model):
state = models.ForeignKey(State)
name = models.CharField(max_length=100)
+
class Restaurant(models.Model):
city = models.ForeignKey(City)
name = models.CharField(max_length=100)
+
class Worker(models.Model):
work_at = models.ForeignKey(Restaurant)
name = models.CharField(max_length=50)
View
35 tests/admin_views/tests.py
@@ -84,8 +84,8 @@ def assertContentBefore(self, response, text1, text2, failing_msg=None):
"""
self.assertEqual(response.status_code, 200)
self.assertTrue(response.content.index(force_bytes(text1)) < response.content.index(force_bytes(text2)),
- failing_msg
- )
+ failing_msg)
+
class AdminViewBasicTest(AdminViewBasicTestCase):
def testTrailingSlashRequired(self):
@@ -94,8 +94,8 @@ def testTrailingSlashRequired(self):
"""
response = self.client.get('/test_admin/%s/admin_views/article/add' % self.urlbit)
self.assertRedirects(response,
- '/test_admin/%s/admin_views/article/add/' % self.urlbit, status_code=301
- )
+ '/test_admin/%s/admin_views/article/add/' % self.urlbit,
+ status_code=301)
def testBasicAddGet(self):
"""
@@ -109,8 +109,7 @@ def testAddWithGETArgs(self):
response = self.client.get('/test_admin/%s/admin_views/section/add/' % self.urlbit, {'name': 'My Section'})
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'value="My Section"',
- msg_prefix="Couldn't find an input with the right value in the response"
- )
+ msg_prefix="Couldn't find an input with the right value in the response")
def testBasicEditGet(self):
"""
@@ -394,11 +393,9 @@ def testLimitedFilter(self):
response = self.client.get('/test_admin/%s/admin_views/thing/' % self.urlbit)
self.assertEqual(response.status_code, 200)
self.assertContains(response, '<div id="changelist-filter">',
- msg_prefix="Expected filter not found in changelist view"
- )
+ msg_prefix="Expected filter not found in changelist view")
self.assertNotContains(response, '<a href="?color__id__exact=3">Blue</a>',
- msg_prefix="Changelist filter not correctly limited by limit_choices_to"
- )
+ msg_prefix="Changelist filter not correctly limited by limit_choices_to")
def testRelationSpanningFilters(self):
response = self.client.get('/test_admin/%s/admin_views/chapterxtra1/' %
@@ -1557,7 +1554,7 @@ def test_recentactions_without_content_type(self):
response = self.client.get('/test_admin/admin/')
counted_presence_after = response.content.count(force_bytes(should_contain))
self.assertEqual(counted_presence_before - 1,
- counted_presence_after)
+ counted_presence_after)
def test_logentry_get_admin_url(self):
"LogEntry.get_admin_url returns a URL to edit the entry's object or None for non-existent (possibly deleted) models"
@@ -1612,13 +1609,13 @@ def test_shortcut_view_with_escaping(self):
def test_change_view_history_link(self):
"""Object history button link should work and contain the pk value quoted."""
url = reverse('admin:%s_modelwithstringprimarykey_change' %
- ModelWithStringPrimaryKey._meta.app_label,
- args=(quote(self.pk),))
+ ModelWithStringPrimaryKey._meta.app_label,
+ args=(quote(self.pk),))
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
expected_link = reverse('admin:%s_modelwithstringprimarykey_history' %
- ModelWithStringPrimaryKey._meta.app_label,
- args=(quote(self.pk),))
+ ModelWithStringPrimaryKey._meta.app_label,
+ args=(quote(self.pk),))
self.assertContains(response, '<a href="%s" class="historylink"' % expected_link)
@@ -2553,8 +2550,7 @@ def test_model_without_action_still_has_jquery(self):
response = self.client.get('/test_admin/admin/admin_views/oldsubscriber/')
self.assertEqual(response.context["action_form"], None)
self.assertContains(response, 'jquery.min.js',
- msg_prefix="jQuery missing from admin pages for model with no admin actions"
- )
+ msg_prefix="jQuery missing from admin pages for model with no admin actions")
def test_action_column_class(self):
"Tests that the checkbox column class is present in the response"
@@ -3631,8 +3627,7 @@ def test_readonly_get(self):
self.assertContains(response, "InlineMultiline<br />test<br />string")
self.assertContains(response,
- formats.localize(datetime.date.today() - datetime.timedelta(days=7))
- )
+ formats.localize(datetime.date.today() - datetime.timedelta(days=7)))
self.assertContains(response, '<div class="form-row field-coolness">')
self.assertContains(response, '<div class="form-row field-awesomeness_level">')
@@ -3829,7 +3824,7 @@ def test_password_mismatch(self):
adminform = response.context['adminform']
self.assertTrue('password' not in adminform.form.errors)
self.assertEqual(adminform.form.errors['password2'],
- ["The two password fields didn't match."])
+ ["The two password fields didn't match."])
def test_user_fk_popup(self):
"""Quick user addition in a FK popup shouldn't invoke view for further user customization"""
View
1  tests/admin_views/views.py
@@ -1,6 +1,7 @@
from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpResponse
+
@staff_member_required
def secure_view(request):
return HttpResponse('%s' % request.POST)
View
14 tests/admin_widgets/models.py
@@ -8,6 +8,7 @@
class MyFileField(models.FileField):
pass
+
@python_2_unicode_compatible
class Member(models.Model):
name = models.CharField(max_length=100)
@@ -18,6 +19,7 @@ class Member(models.Model):
def __str__(self):
return self.name
+
@python_2_unicode_compatible
class Band(models.Model):
name = models.CharField(max_length=100)
@@ -27,6 +29,7 @@ class Band(models.Model):
def __str__(self):
return self.name
+
@python_2_unicode_compatible
class Album(models.Model):
band = models.ForeignKey(Band)
@@ -37,10 +40,12 @@ class Album(models.Model):
def __str__(self):
return self.name
+
class HiddenInventoryManager(models.Manager):
def get_queryset(self):
return super(HiddenInventoryManager, self).get_queryset().filter(hidden=False)
+
@python_2_unicode_compatible
class Inventory(models.Model):
barcode = models.PositiveIntegerField(unique=True)
@@ -55,6 +60,7 @@ class Inventory(models.Model):
def __str__(self):
return self.name
+
class Event(models.Model):
main_band = models.ForeignKey(Band, limit_choices_to=models.Q(pk__gt=0), related_name='events_main_band_at')
supporting_bands = models.ManyToManyField(Band, null=True, blank=True, related_name='events_supporting_band_at')
@@ -64,6 +70,7 @@ class Event(models.Model):
link = models.URLField(blank=True)
min_age = models.IntegerField(blank=True, null=True)
+
@python_2_unicode_compatible
class Car(models.Model):
owner = models.ForeignKey(User)
@@ -73,15 +80,18 @@ class Car(models.Model):
def __str__(self):
return "%s %s" % (self.make, self.model)
+
class CarTire(models.Model):
"""
A single car tire. This to test that a user can only select their own cars.
"""
car = models.ForeignKey(Car)
+
class Honeycomb(models.Model):
location = models.CharField(max_length=20)
+
class Bee(models.Model):
"""
A model with a FK to a model that won't be registered with the admin
@@ -90,6 +100,7 @@ class Bee(models.Model):
"""
honeycomb = models.ForeignKey(Honeycomb)
+
class Individual(models.Model):
"""
A model with a FK to itself. It won't be registered with the admin, so the
@@ -99,9 +110,11 @@ class Individual(models.Model):
name = models.CharField(max_length=20)
parent = models.ForeignKey('self', null=True)
+
class Company(models.Model):
name = models.CharField(max_length=20)
+
class Advisor(models.Model):
"""
A model with a m2m to a model that won't be registered with the admin
@@ -122,6 +135,7 @@ def __str__(self):
class Meta:
ordering = ('name',)
+
@python_2_unicode_compatible
class School(models.Model):
name = models.CharField(max_length=255)
View
16 tests/admin_widgets/tests.py
@@ -25,6 +25,7 @@
'ADMIN_STATIC_PREFIX': "%sadmin/" % settings.STATIC_URL,
}
+
class AdminFormfieldForDBFieldTests(TestCase):
"""
Tests for correct behavior of ModelAdmin.formfield_for_dbfield
@@ -269,6 +270,7 @@ def test_stacked_render(self):
'<select multiple="multiple" name="test" class="selectfilterstacked">\n</select><script type="text/javascript">addEvent(window, "load", function(e) {SelectFilter.init("id_test", "test", 1, "%(ADMIN_STATIC_PREFIX)s"); });</script>\n' % admin_static_prefix()
)
+
class AdminDateWidgetTest(DjangoTestCase):
def test_attrs(self):
"""
@@ -287,6 +289,7 @@ def test_attrs(self):
'<input value="2007-12-01" type="text" class="myDateField" name="test" size="20" />',
)
+
class AdminTimeWidgetTest(DjangoTestCase):
def test_attrs(self):
"""
@@ -305,6 +308,7 @@ def test_attrs(self):
'<input value="09:30:00" type="text" class="myTimeField" name="test" size="20" />',
)
+
class AdminSplitDateTimeWidgetTest(DjangoTestCase):
def test_render(self):
w = widgets.AdminSplitDateTime()
@@ -495,6 +499,7 @@ def test_m2m_related_model_not_in_admin(self):
'<input type="text" name="company_widget2" value="%(c1pk)s" />' % {'c1pk': c1.pk}
)
+
class RelatedFieldWidgetWrapperTests(DjangoTestCase):
def test_no_can_add_related(self):
rel = models.Individual._meta.get_field('parent').rel
@@ -631,6 +636,7 @@ def test_calendar_no_selected_class(self):
class DateTimePickerSeleniumChromeTests(DateTimePickerSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
+
class DateTimePickerSeleniumIETests(DateTimePickerSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@@ -686,9 +692,11 @@ def test_date_time_picker_shortcuts(self):
self.assertGreater(member.birthdate, now - error_margin)
self.assertLess(member.birthdate, now + error_margin)
+
class DateTimePickerShortcutsSeleniumChromeTests(DateTimePickerShortcutsSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
+
class DateTimePickerShortcutsSeleniumIETests(DateTimePickerShortcutsSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@@ -714,7 +722,7 @@ def setUp(self):
super(HorizontalVerticalFilterSeleniumFirefoxTests, self).setUp()
def assertActiveButtons(self, mode, field_name, choose, remove,
- choose_all=None, remove_all=None):
+ choose_all=None, remove_all=None):
choose_link = '#id_%s_add_link' % field_name
choose_all_link = '#id_%s_add_all_link' % field_name
remove_link = '#id_%s_remove_link' % field_name
@@ -928,9 +936,11 @@ def test_filter(self):
self.assertEqual(list(self.school.alumni.all()),
[self.jason, self.peter])
+
class HorizontalVerticalFilterSeleniumChromeTests(HorizontalVerticalFilterSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
+
class HorizontalVerticalFilterSeleniumIETests(HorizontalVerticalFilterSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@@ -1025,9 +1035,11 @@ def test_many_to_many(self):
self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'),
'42,98')
+
class AdminRawIdWidgetSeleniumChromeTests(AdminRawIdWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
+
class AdminRawIdWidgetSeleniumIETests(AdminRawIdWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@@ -1072,8 +1084,10 @@ def test_foreign_key_using_to_field(self):
self.assertEqual(len(profiles), 1)
self.assertEqual(profiles[0].user.username, username_value)
+
class RelatedFieldWidgetSeleniumChromeTests(RelatedFieldWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
+
class RelatedFieldWidgetSeleniumIETests(RelatedFieldWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
View
3  tests/aggregation/models.py
@@ -12,6 +12,7 @@ class Author(models.Model):
def __str__(self):
return self.name
+
@python_2_unicode_compatible
class Publisher(models.Model):
name = models.CharField(max_length=255)
@@ -20,6 +21,7 @@ class Publisher(models.Model):
def __str__(self):
return self.name
+
@python_2_unicode_compatible
class Book(models.Model):
isbn = models.CharField(max_length=9)
@@ -35,6 +37,7 @@ class Book(models.Model):
def __str__(self):
return self.name
+
@python_2_unicode_compatible
class Store(models.Model):
name = models.CharField(max_length=255)
View
6 tests/aggregation_regress/models.py
@@ -61,6 +61,7 @@ class Store(models.Model):
def __str__(self):
return self.name
+
class Entries(models.Model):
EntryID = models.AutoField(primary_key=True, db_column='Entry ID')
Entry = models.CharField(unique=True, max_length=50)
@@ -69,7 +70,7 @@ class Entries(models.Model):
class Clues(models.Model):
ID = models.AutoField(primary_key=True)
- EntryID = models.ForeignKey(Entries, verbose_name='Entry', db_column = 'Entry ID')
+ EntryID = models.ForeignKey(Entries, verbose_name='Entry', db_column='Entry ID')
Clue = models.CharField(max_length=150)
@@ -88,13 +89,16 @@ class HardbackBook(Book):
def __str__(self):
return "%s (hardback): %s" % (self.name, self.weight)
+
# Models for ticket #21150
class Alfa(models.Model):
name = models.CharField(max_length=10, null=True)
+
class Bravo(models.Model):
pass
+
class Charlie(models.Model):
alfa = models.ForeignKey(Alfa, null=True)
bravo = models.ForeignKey(Bravo, null=True)
View
18 tests/backends/tests.py
@@ -432,6 +432,7 @@ def test_sqlite_parameter_escaping(self):
# response should be an non-zero integer
self.assertTrue(int(response))
+
@override_settings(DEBUG=True)
class EscapingChecksDebug(EscapingChecks):
pass
@@ -509,12 +510,12 @@ def create_squares(self, args, paramstyle, multiple):
def test_cursor_executemany(self):
#4896: Test cursor.executemany
- args = [(i, i**2) for i in range(-5, 6)]
+ args = [(i, i ** 2) for i in range(-5, 6)]
self.create_squares_with_executemany(args)
self.assertEqual(models.Square.objects.count(), 11)
for i in range(-5, 6):
square = models.Square.objects.get(root=i)
- self.assertEqual(square.square, i**2)
+ self.assertEqual(square.square, i ** 2)
def test_cursor_executemany_with_empty_params_list(self):
#4765: executemany with params=[] does nothing
@@ -524,11 +525,11 @@ def test_cursor_executemany_with_empty_params_list(self):
def test_cursor_executemany_with_iterator(self):
#10320: executemany accepts iterators
- args = iter((i, i**2) for i in range(-3, 2))
+ args = iter((i, i ** 2) for i in range(-3, 2))
self.create_squares_with_executemany(args)
self.assertEqual(models.Square.objects.count(), 5)
- args = iter((i, i**2) for i in range(3, 7))
+ args = iter((i, i ** 2) for i in range(3, 7))
with override_settings(DEBUG=True):
# same test for DebugCursorWrapper
self.create_squares_with_executemany(args)
@@ -544,20 +545,20 @@ def test_cursor_execute_with_pyformat(self):
@skipUnlessDBFeature('supports_paramstyle_pyformat')
def test_cursor_executemany_with_pyformat(self):
#10070: Support pyformat style passing of paramters
- args = [{'root': i, 'square': i**2} for i in range(-5, 6)]
+ args = [{'root': i, 'square': i ** 2} for i in range(-5, 6)]
self.create_squares(args, 'pyformat', multiple=True)
self.assertEqual(models.Square.objects.count(), 11)
for i in range(-5, 6):
square = models.Square.objects.get(root=i)
- self.assertEqual(square.square, i**2)
+ self.assertEqual(square.square, i ** 2)
@skipUnlessDBFeature('supports_paramstyle_pyformat')
def test_cursor_executemany_with_pyformat_iterator(self):
- args = iter({'root': i, 'square': i**2} for i in range(-3, 2))
+ args = iter({'root': i, 'square': i ** 2} for i in range(-3, 2))
self.create_squares(args, 'pyformat', multiple=True)
self.assertEqual(models.Square.objects.count(), 5)
- args = iter({'root': i, 'square': i**2} for i in range(3, 7))
+ args = iter({'root': i, 'square': i ** 2} for i in range(3, 7))
with override_settings(DEBUG=True):
# same test for DebugCursorWrapper
self.create_squares(args, 'pyformat', multiple=True)
@@ -987,6 +988,7 @@ def equal(value, max_d, places, result):
equal('0.1234567890', 12, 0,
'0')
+
@unittest.skipUnless(
connection.vendor == 'postgresql',
"This test applies only to PostgreSQL")
View
2  tests/basic/models.py
@@ -19,11 +19,13 @@ class Meta:
def __str__(self):
return self.headline
+
class ArticleSelectOnSave(Article):
class Meta:
proxy = True
select_on_save = True
+
@python_2_unicode_compatible
class SelfRef(models.Model):
selfref = models.ForeignKey('self', null=True, blank=True,
View
48 tests/basic/tests.py
@@ -87,7 +87,8 @@ def test_lookup(self):
# Django raises an Article.DoesNotExist exception for get() if the
# parameters don't match any object.
- six.assertRaisesRegex(self,
+ six.assertRaisesRegex(
+ self,
ObjectDoesNotExist,
"Article matching query does not exist.",
Article.objects.get,
@@ -102,7 +103,8 @@ def test_lookup(self):
pub_date__month=8,
)
- six.assertRaisesRegex(self,
+ six.assertRaisesRegex(
+ self,
ObjectDoesNotExist,
"Article matching query does not exist.",
Article.objects.get,
@@ -135,21 +137,24 @@ def test_lookup(self):
# Django raises an Article.MultipleObjectsReturned exception if the
# lookup matches more than one object
- six.assertRaisesRegex(self,
+ six.assertRaisesRegex(
+ self,
MultipleObjectsReturned,
"get\(\) returned more than one Article -- it returned 2!",
Article.objects.get,
headline__startswith='Area',
)
- six.assertRaisesRegex(self,
+ six.assertRaisesRegex(
+ self,
MultipleObjectsReturned,
"get\(\) returned more than one Article -- it returned 2!",
Article.objects.get,
pub_date__year=2005,
)
- six.assertRaisesRegex(self,
+ six.assertRaisesRegex(
+ self,
MultipleObjectsReturned,
"get\(\) returned more than one Article -- it returned 2!",
Article.objects.get,
@@ -165,14 +170,16 @@ def test_multiple_objects_max_num_fetched(self):
Article(headline='Area %s' % i, pub_date=datetime(2005, 7, 28))
for i in range(MAX_GET_RESULTS)
)
- six.assertRaisesRegex(self,
+ six.assertRaisesRegex(
+ self,
MultipleObjectsReturned,
"get\(\) returned more than one Article -- it returned %d!" % MAX_GET_RESULTS,
Article.objects.get,
headline__startswith='Area',
)
Article.objects.create(headline='Area %s' % MAX_GET_RESULTS, pub_date=datetime(2005, 7, 28))
- six.assertRaisesRegex(self,
+ six.assertRaisesRegex(
+ self,
MultipleObjectsReturned,
"get\(\) returned more than one Article -- it returned more than %d!" % MAX_GET_RESULTS,
Article.objects.get,
@@ -219,7 +226,8 @@ def test_object_creation(self):
self.assertEqual(a4.headline, 'Fourth article')
# Don't use invalid keyword arguments.
- six.assertRaisesRegex(self,
+ six.assertRaisesRegex(
+ self,
TypeError,
"'foo' is an invalid keyword argument for this function",
Article,
@@ -315,7 +323,8 @@ def test_object_creation(self):
Article.objects.dates,
)
- six.assertRaisesRegex(self,
+ six.assertRaisesRegex(
+ self,
FieldDoesNotExist,
"Article has no field named 'invalid_field'",
Article.objects.dates,
@@ -323,7 +332,8 @@ def test_object_creation(self):
"year",
)
- six.assertRaisesRegex(self,
+ six.assertRaisesRegex(
+ self,
AssertionError,
"'kind' must be one of 'year', 'month' or 'day'.",
Article.objects.dates,
@@ -331,7 +341,8 @@ def test_object_creation(self):
"bad_kind",
)
- six.assertRaisesRegex(self,
+ six.assertRaisesRegex(
+ self,
AssertionError,
"'order' must be either 'ASC' or 'DESC'.",
Article.objects.dates,
@@ -419,14 +430,16 @@ def test_object_creation(self):
"<Article: Updated article 8>"])
# Also, once you have sliced you can't filter, re-order or combine
- six.assertRaisesRegex(self,
+ six.assertRaisesRegex(
+ self,
AssertionError,
"Cannot filter a query once a slice has been taken.",
Article.objects.all()[0:5].filter,
id=a.id,
)
- six.assertRaisesRegex(self,
+ six.assertRaisesRegex(
+ self,
AssertionError,
"Cannot reorder a query once a slice has been taken.",
Article.objects.all()[0:5].order_by,
@@ -461,7 +474,8 @@ def test_object_creation(self):
# An Article instance doesn't have access to the "objects" attribute.
# That's only available on the class.
- six.assertRaisesRegex(self,
+ six.assertRaisesRegex(
+ self,
AttributeError,
"Manager isn't accessible via Article instances",
getattr,
@@ -605,8 +619,8 @@ def test_extra_method_select_argument_with_dashes_and_values(self):
)
dicts = Article.objects.filter(
- pub_date__year=2008).extra(select={'dashed-value': '1'}
- ).values('headline', 'dashed-value')
+ pub_date__year=2008).extra(
+ select={'dashed-value': '1'}).values('headline', 'dashed-value')
self.assertEqual([sorted(d.items()) for d in dicts],
[[('dashed-value', 1), ('headline', 'Article 11')], [('dashed-value', 1), ('headline', 'Article 12')]])
@@ -723,6 +737,7 @@ def test_hash(self):
# hash)
hash(Article())
+
class ConcurrentSaveTests(TransactionTestCase):
available_apps = ['basic']
@@ -808,6 +823,7 @@ def test_manager_methods(self):
sorted(self.QUERYSET_PROXY_METHODS),
)
+
class SelectOnSaveTests(TestCase):
def test_select_on_save(self):
a1 = Article.objects.create(pub_date=datetime.now())
View
2  tests/bug639/models.py
@@ -8,6 +8,7 @@
temp_storage_dir = tempfile.mkdtemp()
temp_storage = FileSystemStorage(temp_storage_dir)
+
class Photo(models.Model):
title = models.CharField(max_length=30)
image = models.FileField(storage=temp_storage, upload_to='tests')
@@ -22,6 +23,7 @@ def save(self, force_insert=False, force_update=False):
super(Photo, self).save(force_insert, force_update)
self._savecount += 1
+
class PhotoForm(ModelForm):
class Meta:
model = Photo
View
5 tests/bulk_create/models.py
@@ -5,21 +5,26 @@ class Country(models.Model):
name = models.CharField(max_length=255)
iso_two_letter = models.CharField(max_length=2)
+
class Place(models.Model):
name = models.CharField(max_length=100)
class Meta:
abstract = True
+
class Restaurant(Place):
pass
+
class Pizzeria(Restaurant):
pass
+
class State(models.Model):
two_letter_code = models.CharField(max_length=2, primary_key=True)
+
class TwoFields(models.Model):
f1 = models.IntegerField(unique=True)
f2 = models.IntegerField(unique=True)
View
1  tests/cache/closeable_cache.py
@@ -7,5 +7,6 @@ class CloseHookMixin(object):
def close(self, **kwargs):
self.closed = True
+
class CacheClass(CloseHookMixin, LocMemCache):
pass
View
1  tests/cache/liberal_backend.py
@@ -5,5 +5,6 @@ class LiberalKeyValidationMixin(object):
def validate_key(self, key):
pass
+
class CacheClass(LiberalKeyValidationMixin, LocMemCache):
pass
View
1  tests/cache/models.py
@@ -7,6 +7,7 @@ def expensive_calculation():
expensive_calculation.num_runs += 1
return timezone.now()
+
class Poll(models.Model):
question = models.CharField(max_length=200)
answer = models.CharField(max_length=200)
View
6 tests/cache/tests.py
@@ -40,10 +40,12 @@
from .models import Poll, expensive_calculation
+
# functions/classes for complex data type tests
def f():
return 42
+
class C:
def m(n):
return 24
@@ -823,6 +825,7 @@ def test_cache_write_unpickable_object(self):
self.assertEqual(get_cache_data.content, content.encode('utf-8'))
self.assertEqual(get_cache_data.cookies, response.cookies)
+
def custom_key_func(key, key_prefix, version):
"A customized cache key function"
return 'CUSTOM-' + '-'.join([key_prefix, str(version), key])
@@ -1004,6 +1007,7 @@ def test_incr_decr_timeout(self):
self.cache.decr(key)
self.assertEqual(expire, self.cache._expire_info[_key])
+
# memcached backend isn't guaranteed to be available.
# To check the memcached backend, the test settings file will
# need to contain at least one cache backend setting that points at
@@ -1581,6 +1585,7 @@ def test_middleware_doesnt_cache_streaming_response(self):
get_cache_data = FetchFromCacheMiddleware().process_request(request)
self.assertIsNone(get_cache_data)
+
@override_settings(
CACHES={
'default': {
@@ -1816,6 +1821,7 @@ def test_view_decorator(self):
response = other_with_prefix_view(request, '16')
self.assertEqual(response.content, b'Hello World 16')
+
@override_settings(
CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
CACHE_MIDDLEWARE_SECONDS=1,
View
2  tests/check/models.py
@@ -1,9 +1,11 @@
from django.db import models
+
class Book(models.Model):
title = models.CharField(max_length=250)
is_published = models.BooleanField(default=False)
+
class BlogPost(models.Model):
title = models.CharField(max_length=250)
is_published = models.BooleanField(default=False)
View
1  tests/check/tests.py
@@ -7,6 +7,7 @@
from .models import Book
+
class StubCheckModule(object):
# Has no ``run_checks`` attribute & will trigger a warning.
__name__ = 'StubCheckModule'
View
1  tests/choices/models.py
@@ -18,6 +18,7 @@
('F', 'Female'),
)
+
@python_2_unicode_compatible
class Person(models.Model):
name = models.CharField(max_length=20)
View
1  tests/commands_sql/tests.py
@@ -58,6 +58,7 @@ class TestRouter(object):
def allow_migrate(self, db, model):
return False
+
class SQLCommandsRouterTestCase(TestCase):
def setUp(self):
self._old_routers = router.routers
View
1  tests/conditional_processing/tests.py
@@ -15,6 +15,7 @@
ETAG = 'b4246ffc4f62314ca13147c9d4f76974'
EXPIRED_ETAG = '7fae4cd4b0f81e7d2914700043aa8ed6'
+
class ConditionalGet(TestCase):
urls = 'conditional_processing.urls'
View
4 tests/conditional_processing/views.py
@@ -8,18 +8,22 @@ def index(request):
return HttpResponse(FULL_RESPONSE)
index = condition(lambda r: ETAG, lambda r: LAST_MODIFIED)(index)
+
def last_modified_view1(request):
return HttpResponse(FULL_RESPONSE)
last_modified_view1 = condition(last_modified_func=lambda r: LAST_MODIFIED)(last_modified_view1)
+
def last_modified_view2(request):
return HttpResponse(FULL_RESPONSE)
last_modified_view2 = last_modified(lambda r: LAST_MODIFIED)(last_modified_view2)
+
def etag_view1(request):
return HttpResponse(FULL_RESPONSE)
etag_view1 = condition(etag_func=lambda r: ETAG)(etag_view1)
+
def etag_view2(request):
return HttpResponse(FULL_RESPONSE)
etag_view2 = etag(lambda r: ETAG)(etag_view2)
View
2  tests/contenttypes_tests/models.py
@@ -3,6 +3,7 @@
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
+
@python_2_unicode_compatible
class Author(models.Model):
name = models.CharField(max_length=100)
@@ -13,6 +14,7 @@ def __str__(self):
def get_absolute_url(self):
return '/views/authors/%s/' % self.id
+
@python_2_unicode_compatible
class Article(models.Model):
title = models.CharField(max_length=100)
View
1  tests/contenttypes_tests/tests.py
@@ -5,6 +5,7 @@
from .models import Author, Article
+
class ContentTypesViewsTests(TestCase):
fixtures = ['testdata.json']
urls = 'contenttypes_tests.urls'
View
5 tests/csrf_tests/tests.py
@@ -19,10 +19,12 @@ def post_form_response():
""", mimetype="text/html")
return resp
+
def post_form_view(request):
"""A view that returns a POST form (without a token)"""
return post_form_response()
+
# Response/views used for template tag tests
def token_view(request):
@@ -31,6 +33,7 @@ def token_view(request):
template = Template("{% csrf_token %}")
return HttpResponse(template.render(context))
+
def non_token_view_using_request_processor(request):
"""
A view that doesn't use the token, but does use the csrf view processor.
@@ -39,6 +42,7 @@ def non_token_view_using_request_processor(request):
template = Template("")
return HttpResponse(template.render(context))
+
class TestingHttpRequest(HttpRequest):
"""
A version of HttpRequest that allows us to change some things
@@ -47,6 +51,7 @@ class TestingHttpRequest(HttpRequest):
def is_secure(self):
return getattr(self, '_is_secure_override', False)
+
class CsrfViewMiddlewareTest(TestCase):
# The csrf token is potentially from an untrusted source, so could have
# characters that need dealing with.
View
1  tests/custom_columns/models.py
@@ -33,6 +33,7 @@ class Meta:
db_table = 'my_author_table'
ordering = ('last_name', 'first_name')
+
@python_2_unicode_compatible
class Article(models.Model):
headline = models.CharField(max_length=100)
View
1  tests/custom_columns_regress/models.py
@@ -24,6 +24,7 @@ def __str__(self):
class Meta:
ordering = ('headline',)
+
@python_2_unicode_compatible
class Author(models.Model):
Author_ID = models.AutoField(primary_key=True, db_column='Author ID')
View
1  tests/custom_columns_regress/tests.py
@@ -10,6 +10,7 @@ def pks(objects):
""" Return pks to be able to compare lists"""
return [o.pk for o in objects]
+
class CustomColumnRegression(TestCase):
def setUp(self):
View
10 tests/custom_managers/models.py
@@ -17,18 +17,21 @@
# An example of a custom manager called "objects".
+
class PersonManager(models.Manager):
def get_fun_people(self):
return self.filter(fun=True)
# An example of a custom manager that sets get_queryset().
+
class PublishedBookManager(models.Manager):
def get_queryset(self):
return super(PublishedBookManager, self).get_queryset().filter(is_published=True)
# An example of a custom queryset that copies its methods onto the manager.
+
class CustomQuerySet(models.QuerySet):
def filter(self, *args, **kwargs):
queryset = super(CustomQuerySet, self).filter(fun=True)
@@ -49,6 +52,7 @@ def _optin_private_method(self, *args, **kwargs):
return self.all()
_optin_private_method.queryset_only = False
+
class BaseCustomManager(models.Manager):
def __init__(self, arg):
super(BaseCustomManager, self).__init__()
@@ -64,14 +68,17 @@ def manager_only(self):
CustomManager = BaseCustomManager.from_queryset(CustomQuerySet)
+
class FunPeopleManager(models.Manager):
def get_queryset(self):
return super(FunPeopleManager, self).get_queryset().filter(fun=True)
+
class BoringPeopleManager(models.Manager):
def get_queryset(self):
return super(BoringPeopleManager, self).get_queryset().filter(fun=False)
+
@python_2_unicode_compatible
class Person(models.Model):
first_name = models.CharField(max_length=30)
@@ -93,6 +100,7 @@ class Person(models.Model):
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
+
@python_2_unicode_compatible
class Book(models.Model):
title = models.CharField(max_length=50)
@@ -109,10 +117,12 @@ def __str__(self):
# An example of providing multiple custom managers.
+
class FastCarManager(models.Manager):
def get_queryset(self):
return super(FastCarManager, self).get_queryset().filter(top_speed__gt=150)
+
@python_2_unicode_compatible
class Car(models.Model):
name = models.CharField(max_length=10)
View
3  tests/custom_managers_regress/models.py
@@ -13,6 +13,7 @@ class RestrictedManager(models.Manager):
def get_queryset(self):
return super(RestrictedManager, self).get_queryset().filter(is_public=True)
+
@python_2_unicode_compatible
class RelatedModel(models.Model):
name = models.CharField(max_length=50)
@@ -20,6 +21,7 @@ class RelatedModel(models.Model):
def __str__(self):
return self.name
+
@python_2_unicode_compatible
class RestrictedModel(models.Model):
name = models.CharField(max_length=50)
@@ -32,6 +34,7 @@ class RestrictedModel(models.Model):
def __str__(self):
return self.name
+
@python_2_unicode_compatible
class OneToOneRestrictedModel(models.Model):
name = models.CharField(max_length=50)
View
1  tests/custom_pk/fields.py
@@ -22,6 +22,7 @@ def __eq__(self, other):
return self.value == other.value
return self.value == other
+
class MyAutoField(six.with_metaclass(models.SubfieldBase, models.CharField)):
def __init__(self, *args, **kwargs):
View
4 tests/custom_pk/models.py
@@ -16,7 +16,7 @@
@python_2_unicode_compatible
class Employee(models.Model):
- employee_code = models.IntegerField(primary_key=True, db_column = 'code')
+ employee_code = models.IntegerField(primary_key=True, db_column='code')
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
@@ -26,6 +26,7 @@ class Meta:
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
+
@python_2_unicode_compatible
class Business(models.Model):
name = models.CharField(max_length=20, primary_key=True)
@@ -37,6 +38,7 @@ class Meta:
def __str__(self):
return self.name
+
@python_2_unicode_compatible
class Bar(models.Model):
id = MyAutoField(primary_key=True, db_index=True)
View
1  tests/datatypes/models.py
@@ -23,6 +23,7 @@ class Meta:
def __str__(self):
return self.name
+
class RumBaba(models.Model):
baked_date = models.DateField(auto_now_add=True)
baked_timestamp = models.DateTimeField(auto_now_add=True)
View
2  tests/dates/models.py
@@ -14,6 +14,7 @@ class Article(models.Model):
def __str__(self):
return self.title
+
@python_2_unicode_compatible
class Comment(models.Model):
article = models.ForeignKey(Article, related_name="comments")
@@ -24,5 +25,6 @@ class Comment(models.Model):
def __str__(self):
return 'Comment to %s (%s)' % (self.article.title, self.pub_date)
+
class Category(models.Model):
name = models.CharField(max_length=255)
View
2  tests/datetimes/models.py
@@ -14,6 +14,7 @@ class Article(models.Model):
def __str__(self):
return self.title
+
@python_2_unicode_compatible
class Comment(models.Model):
article = models.ForeignKey(Article, related_name="comments")
@@ -24,5 +25,6 @@ class Comment(models.Model):
def __str__(self):
return 'Comment to %s (%s)' % (self.article.title, self.pub_date)
+
class Category(models.Model):
name = models.CharField(max_length=255)
View
1  tests/db_typecasts/tests.py
@@ -48,6 +48,7 @@
),
}
+
class DBTypeCasts(unittest.TestCase):
def test_typeCasts(self):
for k, v in six.iteritems(TEST_CASES):