1
0
mirror of https://github.com/django/django.git synced 2024-12-22 17:16:24 +00:00

Fixed #21298 -- Fixed E301 pep8 warnings

This commit is contained in:
Alasdair Nicol 2013-10-22 11:21:07 +01:00
parent 317040a73b
commit c3aa2948c6
83 changed files with 180 additions and 2 deletions

View File

@ -222,6 +222,7 @@ class TestUtilsHashPass(unittest.TestCase):
for algo in ('sha1', 'md5'):
encoded = make_password('lètmein', hasher=algo)
state = {'upgraded': False}
def setter(password):
state['upgraded'] = True
self.assertTrue(check_password('lètmein', encoded, setter))
@ -230,6 +231,7 @@ class TestUtilsHashPass(unittest.TestCase):
def test_no_upgrade(self):
encoded = make_password('lètmein')
state = {'upgraded': False}
def setter():
state['upgraded'] = True
self.assertFalse(check_password('WRONG', encoded, setter))
@ -240,6 +242,7 @@ class TestUtilsHashPass(unittest.TestCase):
for algo in ('sha1', 'md5'):
encoded = make_password('lètmein', hasher=algo)
state = {'upgraded': False}
def setter():
state['upgraded'] = True
self.assertFalse(check_password('WRONG', encoded, setter))
@ -259,6 +262,7 @@ class TestUtilsHashPass(unittest.TestCase):
self.assertEqual(iterations, '1')
state = {'upgraded': False}
def setter(password):
state['upgraded'] = True

View File

@ -43,6 +43,7 @@ class TokenGeneratorTest(TestCase):
class Mocked(PasswordResetTokenGenerator):
def __init__(self, today):
self._today_val = today
def _today(self):
return self._today_val

View File

@ -418,8 +418,10 @@ class WizardInlineFormSetTests(TestCase):
def test_set_instance(self):
# Regression test for #21259
poet = self.poet
class InlineFormSetWizard(CookieWizardView):
instance = None
def get_form_instance(self, step):
if self.instance is None:
self.instance = poet

View File

@ -87,6 +87,7 @@ class OpenLayersWidget(Textarea):
# JavaScript construction utilities for the Bounds and Projection.
def ol_bounds(extent):
return 'new OpenLayers.Bounds(%s)' % str(extent)
def ol_projection(srid):
return 'new OpenLayers.Projection("EPSG:%s")' % srid

View File

@ -18,6 +18,7 @@ class GeometryColumns(models.Model):
column_name = models.CharField(max_length=1024)
srid = models.IntegerField(primary_key=True)
# TODO: Add support for `diminfo` column (type MDSYS.SDO_DIM_ARRAY).
class Meta:
db_table = 'USER_SDO_GEOM_METADATA'
managed = False

View File

@ -44,6 +44,7 @@ class PostGISSpheroidDistance(PostGISFunction):
"For PostGIS spherical distance operations (using the spheroid)."
dist_func = 'distance_spheroid'
sql_template = '%(function)s(%(geo_col)s, %(geometry)s, %%s) %(operator)s %%s'
def __init__(self, prefix, operator):
# An extra parameter in `end_subst` is needed for the spheroid string.
super(PostGISSpheroidDistance, self).__init__(prefix, self.dist_func,
@ -137,6 +138,7 @@ class PostGISOperations(DatabaseOperations, BaseSpatialOperations):
# Valid distance types and substitutions
dtypes = (Decimal, Distance, float) + six.integer_types
def get_dist_ops(operator):
"Returns operations for both regular and spherical distances."
return {'cartesian' : PostGISDistance(prefix, operator),
@ -455,6 +457,7 @@ class PostGISOperations(DatabaseOperations, BaseSpatialOperations):
"""
def exactly_two(np):
return np == 2
def two_to_three(np):
return np >= 2 and np <= 3
if (lookup_type in self.distance_functions and

View File

@ -40,6 +40,7 @@ class SpatiaLiteDistance(SpatiaLiteFunction):
class SpatiaLiteRelate(SpatiaLiteFunctionParam):
"For SpatiaLite Relate(<geom>, <pattern>) calls."
pattern_regex = re.compile(r'^[012TF\*]{9}$')
def __init__(self, pattern):
if not self.pattern_regex.match(pattern):
raise ValueError('Invalid intersection matrix pattern "%s".' % pattern)

View File

@ -5,6 +5,7 @@ to convert geospatial values from the database.
class BaseField(object):
empty_strings_allowed = True
def get_internal_type(self):
"Overloaded method so OracleQuery.convert_values doesn't balk."
return None

View File

@ -79,6 +79,7 @@ class BaseGeometryWidget(Widget):
class OpenLayersWidget(BaseGeometryWidget):
template_name = 'gis/openlayers.html'
class Media:
js = (
'http://openlayers.org/api/2.13/OpenLayers.js',

View File

@ -36,6 +36,7 @@ def geom_output(func, argtypes, offset=None):
else:
# Error code returned, geometry is returned by-reference.
func.restype = c_int
def geomerrcheck(result, func, cargs):
return check_geom_offset(result, func, cargs, offset)
func.errcheck = geomerrcheck

View File

@ -291,6 +291,7 @@ class ListMixin(object):
# we're not changing the length of the sequence
newLen = len(self)
newVals = dict(zip(indexList, valueList))
def newItems():
for i in xrange(newLen):
if i in newVals:
@ -317,6 +318,7 @@ class ListMixin(object):
origLen = len(self)
stop = max(start, stop)
newLen = origLen - stop + start + len(valueList)
def newItems():
for i in xrange(origLen + 1):
if i == start:

View File

@ -51,6 +51,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
# This one only accepts pointers to floats
c_float_p = ctypes.POINTER(ctypes.c_float)
class FakeGeom2(GEOSBase):
ptr_type = c_float_p

View File

@ -12,6 +12,7 @@ from django.utils import six
class UserListA(ListMixin):
_mytype = tuple
def __init__(self, i_list, *args, **kwargs):
self._list = self._mytype(i_list)
super(UserListA, self).__init__(*args, **kwargs)
@ -211,8 +212,10 @@ class ListMixinTest(unittest.TestCase):
'Out of range exceptions'
def setfcn(x, i):
x[i] = 20
def getfcn(x, i):
return x[i]
def delfcn(x, i):
del x[i]
pl, ul = self.lists_of_len()
@ -252,6 +255,7 @@ class ListMixinTest(unittest.TestCase):
self.assertEqual(pl[:], ul[:], 'after pop')
pl, ul = self.lists_of_len()
def popfcn(x, i):
x.pop(i)
self.assertRaises(IndexError, popfcn, ul, self.limit)
@ -272,6 +276,7 @@ class ListMixinTest(unittest.TestCase):
def indexfcn(x, v):
return x.index(v)
def removefcn(x, v):
return x.remove(v)
self.assertRaises(ValueError, indexfcn, ul, 40)
@ -283,6 +288,7 @@ class ListMixinTest(unittest.TestCase):
ul._allowed = six.integer_types
ul[1] = 50
ul[:2] = [60, 70, 80]
def setfcn(x, i, v):
x[i] = v
self.assertRaises(TypeError, setfcn, ul, 2, 'hello')
@ -292,8 +298,10 @@ class ListMixinTest(unittest.TestCase):
'Length limits'
pl, ul = self.lists_of_len()
ul._minlength = 1
def delfcn(x,i):
del x[:i]
def setfcn(x,i):
x[:i] = []
for i in range(self.limit - ul._minlength + 1, self.limit + 1):
@ -309,6 +317,7 @@ class ListMixinTest(unittest.TestCase):
def test09_iterable_check(self):
'Error on assigning non-iterable to slice'
pl, ul = self.lists_of_len(self.limit + 1)
def setfcn(x, i, v):
x[i] = v
self.assertRaises(TypeError, setfcn, ul, slice(0,3,2), 2)

View File

@ -148,6 +148,7 @@ def get_ogr_db_string():
# Build the params of the OGR database connection string
params = [db_str % {'db_name': db['NAME']}]
def add(key, template):
value = db.get(key, None)
# Don't add the parameter if it is not in django's settings

View File

@ -263,6 +263,7 @@ class CustomGeometryWidgetTest(SimpleTestCase):
class CustomGeometryWidget(forms.BaseGeometryWidget):
template_name = 'gis/openlayers.html'
deserialize_called = 0
def serialize(self, value):
return value.json if value else ''

View File

@ -101,6 +101,7 @@ class CookieStorage(BaseStorage):
# data is going to be stored eventually by SimpleCookie, which
# adds it's own overhead, which we must account for.
cookie = SimpleCookie() # create outside the loop
def stored_length(val):
return len(cookie.value_encode(val)[1])

View File

@ -142,6 +142,7 @@ class HTTPSitemapTests(SitemapTestsBase):
Sitemap.get_url() url result.
"""
test_sitemap = GenericSitemap({'queryset': TestModel.objects.all()})
def is_testmodel(url):
return isinstance(url['item'], TestModel)
item_in_url_info = all(map(is_testmodel, test_sitemap.get_urls()))

View File

@ -12,6 +12,7 @@ try:
from shutil import copystat
except ImportError:
import stat
def copystat(src, dst):
"""Copy all stat info (mode bits, atime and mtime) from src to dst"""
st = os.stat(src)

View File

@ -93,6 +93,7 @@ class MigrationGraph(object):
Dynamic programming based depth first search, for finding dependencies.
"""
cache = {}
def _dfs(start, get_children, path):
# If we already computed this, use that (dynamic programming)
if (start, get_children) in cache:

View File

@ -20,6 +20,7 @@ class MigrationRecorder(object):
app = models.CharField(max_length=255)
name = models.CharField(max_length=255)
applied = models.DateTimeField(default=now)
class Meta:
app_cache = BaseAppCache()
app_label = "migrations"

View File

@ -241,6 +241,7 @@ class BaseFormSet(object):
# None should be sorted below anything else. Allowing None as
# a comparison value makes it so we can leave ordering fields
# blank.
def compare_ordering_key(k):
if k[1] is None:
return (1, 0) # +infinity, larger than any number

View File

@ -602,6 +602,7 @@ class BaseModelFormSet(BaseFormSet):
"""
if not commit:
self.saved_forms = []
def save_m2m():
for form in self.saved_forms:
form.save_m2m()
@ -754,6 +755,7 @@ class BaseModelFormSet(BaseFormSet):
# data back. Generally, pk.editable should be false, but for some
# reason, auto_created pk fields and AutoField's editable attribute is
# True, so check for that as well.
def pk_is_not_editable(pk):
return ((not pk.editable) or (pk.auto_created or isinstance(pk, AutoField))
or (pk.rel and pk.rel.parent_link and pk_is_not_editable(pk.rel.to._meta.pk)))

View File

@ -406,6 +406,7 @@ class Textarea(Widget):
class DateTimeBaseInput(TextInput):
format_key = ''
def __init__(self, attrs=None, format=None):
super(DateTimeBaseInput, self).__init__(attrs)
self.format = format if format else None

View File

@ -591,6 +591,7 @@ def unordered_list(value, autoescape=None):
escaper = conditional_escape
else:
escaper = lambda x: x
def convert_old_style_list(list_):
"""
Converts old style lists to the new easier to understand format.
@ -621,6 +622,7 @@ def unordered_list(value, autoescape=None):
if old_style_list:
second_item = new_second_item
return [first_item, second_item], old_style_list
def _helper(list_, tabs=1):
indent = '\t' * tabs
output = []

View File

@ -245,6 +245,7 @@ def compare_xml(want, got):
Based on http://codespeak.net/svn/lxml/trunk/src/lxml/doctestcompare.py
"""
_norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+')
def norm_whitespace(v):
return _norm_whitespace_re.sub(' ', v)
@ -405,6 +406,7 @@ def patch_logger(logger_name, log_level):
and provides a simple mock-like list of messages received
"""
calls = []
def replacement(msg):
calls.append(msg)
logger = logging.getLogger(logger_name)

View File

@ -30,6 +30,7 @@ def method_decorator(decorator):
# In case 'decorator' adds attributes to the function it decorates, we
# want to copy those. We don't have access to bound_func in this scope,
# but we can cheat by using it on a dummy function.
@decorator
def dummy(*args, **kwargs):
pass
@ -84,6 +85,7 @@ def available_attrs(fn):
def make_middleware_decorator(middleware_class):
def _make_decorator(*m_args, **m_kwargs):
middleware = middleware_class(*m_args, **m_kwargs)
def _decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):

View File

@ -213,6 +213,7 @@ class Enclosure(object):
class RssFeed(SyndicationFeed):
mime_type = 'application/rss+xml; charset=utf-8'
def write(self, outfile, encoding):
handler = SimplerXMLGenerator(outfile, encoding)
handler.startDocument()
@ -255,6 +256,7 @@ class RssFeed(SyndicationFeed):
class RssUserland091Feed(RssFeed):
_version = "0.91"
def add_item_elements(self, handler, item):
handler.addQuickElement("title", item['title'])
handler.addQuickElement("link", item['link'])
@ -264,6 +266,7 @@ class RssUserland091Feed(RssFeed):
class Rss201rev2Feed(RssFeed):
# Spec: http://blogs.law.harvard.edu/tech/rss
_version = "2.0"
def add_item_elements(self, handler, item):
handler.addQuickElement("title", item['title'])
handler.addQuickElement("link", item['link'])

View File

@ -118,12 +118,16 @@ class MLStripper(HTMLParser):
HTMLParser.__init__(self)
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def handle_entityref(self, name):
self.fed.append('&%s;' % name)
def handle_charref(self, name):
self.fed.append('&#%s;' % name)
def get_data(self):
return ''.join(self.fed)
@ -285,6 +289,7 @@ def clean_html(text):
# Trim stupid HTML such as <br clear="all">.
text = html_gunk_re.sub('', text)
# Convert hard-coded bullets into HTML unordered lists.
def replace_p_tags(match):
s = match.group().replace('</p>', '</li>')
for d in DOTS:

View File

@ -444,6 +444,7 @@ def iterlists(d, **kw):
if PY3:
def b(s):
return s.encode("latin-1")
def u(s):
return s
unichr = chr
@ -462,14 +463,18 @@ if PY3:
else:
def b(s):
return s
def u(s):
return unicode(s, "unicode_escape")
unichr = unichr
int2byte = chr
def byte2int(bs):
return ord(bs[0])
def indexbytes(buf, i):
return ord(buf[i])
def iterbytes(buf):
return (ord(byte) for byte in buf)
import StringIO
@ -512,6 +517,7 @@ else:
fp = kwargs.pop("file", sys.stdout)
if fp is None:
return
def write(data):
if not isinstance(data, basestring):
data = str(data)

View File

@ -32,6 +32,7 @@ def wrap(text, width):
the text. Expects that existing line breaks are posix newlines.
"""
text = force_text(text)
def _generator():
it = iter(text.split(' '))
word = next(it)

View File

@ -3,8 +3,8 @@ doc_files = docs extras AUTHORS INSTALL LICENSE README.rst
install-script = scripts/rpm-install.sh
[flake8]
exclude=./django/utils/dictconfig.py,./django/contrib/comments/*,./django/utils/unittest.py,./tests/comment_tests/*,./django/test/_doctest.py
ignore=E124,E125,E127,E128,E226,E241,E251,E302,E501,E203,E231,E261,E301,F401,F403,W601
exclude=./django/utils/dictconfig.py,./django/contrib/comments/*,./django/utils/unittest.py,./tests/comment_tests/*,./django/test/_doctest.py,./django/utils/six.py
ignore=E124,E125,E127,E128,E226,E241,E251,E302,E501,E203,E231,E261,F401,F403,W601
[metadata]
license-file = LICENSE

View File

@ -5,5 +5,6 @@ from ..admin import foo
class Bar(models.Model):
name = models.CharField(max_length=5)
class Meta:
app_label = 'complex_app'

View File

@ -3,5 +3,6 @@ from django.db import models
class Foo(models.Model):
name = models.CharField(max_length=5)
class Meta:
app_label = 'complex_app'

View File

@ -1342,6 +1342,7 @@ class CommandTypes(AdminScriptTestCase):
Also test proper traceback display.
"""
command = BaseCommand()
def raise_command_error(*args, **kwargs):
raise CommandError("Custom error")

View File

@ -127,6 +127,7 @@ class ValidationTestCase(TestCase):
model = TwoAlbumFKAndAnE
exclude = ("e",)
fk_name = "album1"
class MyAdmin(admin.ModelAdmin):
inlines = [TwoAlbumFKAndAnEInline]
MyAdmin.validate(Album)
@ -134,6 +135,7 @@ class ValidationTestCase(TestCase):
def test_inline_self_validation(self):
class TwoAlbumFKAndAnEInline(admin.TabularInline):
model = TwoAlbumFKAndAnE
class MyAdmin(admin.ModelAdmin):
inlines = [TwoAlbumFKAndAnEInline]
@ -291,6 +293,7 @@ class ValidationTestCase(TestCase):
"""
class SongForm(forms.ModelForm):
extra_data = forms.CharField()
class Meta:
model = Song
fields = '__all__'

View File

@ -116,6 +116,7 @@ class ModelWithStringPrimaryKey(models.Model):
class Color(models.Model):
value = models.CharField(max_length=10)
warm = models.BooleanField(default=False)
def __str__(self):
return self.value
@ -129,6 +130,7 @@ class Thing(models.Model):
title = models.CharField(max_length=20)
color = models.ForeignKey(Color, limit_choices_to={'warm': True})
pub_date = models.DateField(blank=True, null=True)
def __str__(self):
return self.title
@ -138,6 +140,7 @@ class Actor(models.Model):
name = models.CharField(max_length=50)
age = models.IntegerField()
title = models.CharField(max_length=50, null=True, blank=True)
def __str__(self):
return self.name
@ -199,6 +202,7 @@ class Persona(models.Model):
accounts which inherit from a common accounts class.
"""
name = models.CharField(blank=False, max_length=80)
def __str__(self):
return self.name
@ -616,6 +620,7 @@ class AdminOrderedField(models.Model):
class AdminOrderedModelMethod(models.Model):
order = models.IntegerField()
stuff = models.CharField(max_length=200)
def some_order(self):
return self.order
some_order.admin_order_field = 'order'

View File

@ -673,6 +673,7 @@ class ModelTest(TestCase):
def test_emptyqs_customqs(self):
# A hacky test for custom QuerySet subclass - refs #17271
Article.objects.create(headline='foo', pub_date=datetime.now())
class CustomQuerySet(QuerySet):
def do_something(self):
return 'did something'
@ -734,6 +735,7 @@ class ConcurrentSaveTests(TransactionTestCase):
"""
a = Article.objects.create(headline='foo', pub_date=datetime.now())
exceptions = []
def deleter():
try:
# Do not delete a directly - doing so alters its state.

View File

@ -1479,6 +1479,7 @@ class CacheI18nTest(TestCase):
# Regression test for #17476
class CustomTzName(timezone.UTC):
name = ''
def tzname(self, dt):
return self.name

View File

@ -19,6 +19,7 @@ class Employee(models.Model):
employee_code = models.IntegerField(primary_key=True, db_column = 'code')
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
class Meta:
ordering = ('last_name', 'first_name')
@ -29,6 +30,7 @@ class Employee(models.Model):
class Business(models.Model):
name = models.CharField(max_length=20, primary_key=True)
employees = models.ManyToManyField(Employee)
class Meta:
verbose_name_plural = 'businesses'

View File

@ -22,6 +22,7 @@ fully_decorated.anything = "Expected __dict__"
def compose(*functions):
# compose(f, g)(*args, **kwargs) == f(g(*args, **kwargs))
functions = list(reversed(functions))
def _inner(*args, **kwargs):
result = functions[0](*args, **kwargs)
for f in functions[1:]:

View File

@ -73,6 +73,7 @@ class DefaultFiltersTests(TestCase):
class FloatWrapper(object):
def __init__(self, value):
self.value = value
def __float__(self):
return self.value
@ -510,6 +511,7 @@ class DefaultFiltersTests(TestCase):
class ULItem(object):
def __init__(self, title):
self.title = title
def __str__(self):
return 'ulitem-%s' % str(self.title)

View File

@ -65,6 +65,7 @@ class OnDeleteTests(TestCase):
# Testing DO_NOTHING is a bit harder: It would raise IntegrityError for a normal model,
# so we connect to pre_delete and set the fk to a known value.
replacement_r = R.objects.create()
def check_do_nothing(sender, **kwargs):
obj = kwargs['instance']
obj.donothing_set.update(donothing=replacement_r)
@ -178,6 +179,7 @@ class DeletionTests(TestCase):
def test_instance_update(self):
deleted = []
related_setnull_sets = []
def pre_delete(sender, **kwargs):
obj = kwargs['instance']
deleted.append(obj)
@ -264,6 +266,7 @@ class DeletionTests(TestCase):
# Attach a signal to make sure we will not do fast_deletes.
calls = []
def noop(*args, **kwargs):
calls.append('')
models.signals.post_delete.connect(noop, sender=User)
@ -281,6 +284,7 @@ class DeletionTests(TestCase):
)
# Attach a signal to make sure we will not do fast_deletes.
calls = []
def noop(*args, **kwargs):
calls.append('')
models.signals.post_delete.connect(noop, sender=User)

View File

@ -148,6 +148,7 @@ class LargeDeleteTests(TestCase):
for x in range(300):
Book.objects.create(pagecount=x+100)
# attach a signal to make sure we will not fast-delete
def noop(*args, **kwargs):
pass
models.signals.post_delete.connect(noop, sender=Book)

View File

@ -26,6 +26,7 @@ class RenameMethodsTests(SimpleTestCase):
"""
with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('always')
class Manager(six.with_metaclass(RenameManagerMethods)):
def old(self):
pass
@ -40,6 +41,7 @@ class RenameMethodsTests(SimpleTestCase):
"""
with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('ignore')
class Manager(six.with_metaclass(RenameManagerMethods)):
def new(self):
pass
@ -59,6 +61,7 @@ class RenameMethodsTests(SimpleTestCase):
"""
with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('ignore')
class Manager(six.with_metaclass(RenameManagerMethods)):
def old(self):
pass
@ -79,9 +82,11 @@ class RenameMethodsTests(SimpleTestCase):
"""
with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('ignore')
class Renamed(six.with_metaclass(RenameManagerMethods)):
def new(self):
pass
class Deprecated(Renamed):
def old(self):
super(Deprecated, self).old()
@ -108,9 +113,11 @@ class RenameMethodsTests(SimpleTestCase):
"""
with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('ignore')
class Deprecated(six.with_metaclass(RenameManagerMethods)):
def old(self):
pass
class Renamed(Deprecated):
def new(self):
super(Renamed, self).new()
@ -132,15 +139,19 @@ class RenameMethodsTests(SimpleTestCase):
"""
with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('ignore')
class Renamed(six.with_metaclass(RenameManagerMethods)):
def new(self):
pass
class RenamedMixin(object):
def new(self):
super(RenamedMixin, self).new()
class DeprecatedMixin(object):
def old(self):
super(DeprecatedMixin, self).old()
class Deprecated(DeprecatedMixin, RenamedMixin, Renamed):
pass
warnings.simplefilter('always')

View File

@ -205,6 +205,7 @@ class ExpressionsTests(TestCase):
test_gmbh.point_of_contact = None
test_gmbh.save()
self.assertTrue(test_gmbh.point_of_contact is None)
def test():
test_gmbh.point_of_contact = F("ceo")
self.assertRaises(ValueError, test)

View File

@ -355,6 +355,7 @@ class FileStorageTests(unittest.TestCase):
Test behaviour when file.chunks() is raising an error
"""
f1 = ContentFile('chunks fails')
def failing_chunks():
raise IOError
f1.chunks = failing_chunks
@ -532,10 +533,13 @@ class DimensionClosingBug(unittest.TestCase):
class FileWrapper(object):
_closed = []
def __init__(self, f):
self.f = f
def __getattr__(self, name):
return getattr(self.f, name)
def close(self):
self._closed.append(True)
self.f.close()

View File

@ -68,6 +68,7 @@ class PersonManager(models.Manager):
class Person(models.Model):
objects = PersonManager()
name = models.CharField(max_length=100)
def __str__(self):
return self.name

View File

@ -663,11 +663,13 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin):
if six.PY3:
def __str__(self):
return 'ŠĐĆŽćžšđ'
def __bytes__(self):
return b'Foo'
else:
def __str__(self):
return b'Foo'
def __unicode__(self):
return '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111'

View File

@ -991,6 +991,7 @@ class FieldsTests(SimpleTestCase):
# Make sure we're compatible with MySQL, which uses 0 and 1 for its boolean
# values. (#9609)
NULLBOOL_CHOICES = (('1', 'Yes'), ('0', 'No'), ('', 'Unknown'))
class MySQLNullBooleanForm(Form):
nullbool0 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES))
nullbool1 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES))

View File

@ -824,6 +824,7 @@ class FormsTestCase(TestCase):
""" Test that we are able to modify a form field validators list without polluting
other forms """
from django.core.validators import MaxValueValidator
class MyForm(Form):
myfield = CharField(max_length=25)
@ -1899,6 +1900,7 @@ class FormsTestCase(TestCase):
"""
class CustomJSONField(CharField):
empty_values = [None, '']
def to_python(self, value):
# Fake json.loads
if value == '{}':

View File

@ -429,6 +429,7 @@ class FormsMediaTestCase(TestCase):
class FormWithMedia(Form):
field1 = CharField(max_length=20, widget=MyWidget1())
field2 = CharField(max_length=20, widget=MyWidget2())
class Media:
js = ('/some/form/javascript',)
css = {
@ -880,6 +881,7 @@ class StaticFormsMediaTestCase(TestCase):
class FormWithMedia(Form):
field1 = CharField(max_length=20, widget=MyWidget1())
field2 = CharField(max_length=20, widget=MyWidget2())
class Media:
js = ('/some/form/javascript',)
css = {

View File

@ -273,6 +273,7 @@ class FormsWidgetTestCase(TestCase):
# The 'choices' argument can be any iterable:
from itertools import chain
def get_choices():
for i in range(5):
yield (i, i)
@ -284,6 +285,7 @@ class FormsWidgetTestCase(TestCase):
<option value="4">4</option>
</select>""")
things = ({'id': 1, 'name': 'And Boom'}, {'id': 2, 'name': 'One More Thing!'})
class SomeForm(Form):
somechoice = ChoiceField(choices=chain((('', '-'*9),), [(thing['id'], thing['name']) for thing in things]))
f = SomeForm()
@ -903,6 +905,7 @@ beatle J R Ringo False""")
if value:
return value.split('__')
return ['', '']
def format_output(self, rendered_widgets):
return '<br />'.join(rendered_widgets)
@ -1066,6 +1069,7 @@ class SelectAndTextWidget(MultiWidget):
When choices are set for this widget, we want to pass those along to the Select widget
"""
self.widgets[0].choices = choices
def _get_choices(self):
"""
The choices for this widget are the Select widget's choices

View File

@ -95,6 +95,7 @@ class GenericRelationTests(TestCase):
Link.objects.create(content_object=c)
places = list(Place.objects.order_by('links__id'))
def count_places(place):
return len([p for p in places if p.id == place.id])

View File

@ -242,6 +242,7 @@ class BookSigningConfig(object):
model = BookSigning
date_field = 'event_date'
# use the same templates as for books
def get_template_names(self):
return ['generic_views/book%s.html' % self.template_name_suffix]

View File

@ -38,6 +38,7 @@ class InspectDBTestCase(TestCase):
table_name_filter=lambda tn:tn.startswith('inspectdb_columntypes'),
stdout=out)
output = out.getvalue()
def assertFieldType(name, definition):
out_def = re.search(r'^\s*%s = (models.*)$' % name, output, re.MULTILINE).groups()[0]
self.assertEqual(definition, out_def)

View File

@ -13,6 +13,7 @@ from django.utils.encoding import python_2_unicode_compatible
class Author(models.Model):
name = models.CharField(max_length=100)
class Meta:
ordering = ('name', )
@ -21,6 +22,7 @@ class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateTimeField()
author = models.ForeignKey(Author, blank=True, null=True)
class Meta:
ordering = ('-pub_date', 'headline')
@ -30,6 +32,7 @@ class Article(models.Model):
class Tag(models.Model):
articles = models.ManyToManyField(Article)
name = models.CharField(max_length=100)
class Meta:
ordering = ('name', )

View File

@ -329,6 +329,7 @@ class BrokenLinkEmailsMiddlewareTest(TestCase):
class SubclassedMiddleware(BrokenLinkEmailsMiddleware):
ignored_user_agent_patterns = (re.compile(r'Spider.*'),
re.compile(r'Robot.*'))
def is_ignorable_request(self, request, uri, domain, referer):
'''Check user-agent in addition to normal checks.'''
if super(SubclassedMiddleware, self).is_ignorable_request(request, uri, domain, referer):
@ -347,6 +348,7 @@ class BrokenLinkEmailsMiddlewareTest(TestCase):
class ConditionalGetMiddlewareTest(TestCase):
urls = 'middleware.cond_get_urls'
def setUp(self):
self.req = HttpRequest()
self.req.META = {

View File

@ -347,6 +347,7 @@ class OperationTests(MigrationTestBase):
with self.assertRaises(NotImplementedError):
operation.database_backwards("test_runpython", None, new_state, project_state)
# Now test we can do it with a callable
def inner_method(models, schema_editor):
Pony = models.get_model("test_runpython", "Pony")
Pony.objects.create(pink=1, weight=3.55)

View File

@ -20,6 +20,7 @@ class StateTests(TestCase):
name = models.CharField(max_length=255)
bio = models.TextField()
age = models.IntegerField(blank=True, null=True)
class Meta:
app_label = "migrations"
app_cache = new_app_cache
@ -35,6 +36,7 @@ class StateTests(TestCase):
class Book(models.Model):
title = models.CharField(max_length=1000)
author = models.ForeignKey(Author)
class Meta:
app_label = "migrations"
app_cache = new_app_cache

View File

@ -211,6 +211,7 @@ class DerivedBook(Book, BookXtra):
class ExplicitPK(models.Model):
key = models.CharField(max_length=20, primary_key=True)
desc = models.CharField(max_length=20, blank=True, unique=True)
class Meta:
unique_together = ('key', 'desc')

View File

@ -26,6 +26,7 @@ from .models import (Article, ArticleStatus, BetterWriter, BigInt, Book,
if test_images:
from .models import ImageFile, OptionalImageFile
class ImageFileForm(forms.ModelForm):
class Meta:
model = ImageFile
@ -208,6 +209,7 @@ class ModelFormWithMedia(forms.ModelForm):
css = {
'all': ('/some/form/css',)
}
class Meta:
model = TextFile
fields = '__all__'
@ -1722,6 +1724,7 @@ class OldFormForXTests(TestCase):
class CategoryForm(forms.ModelForm):
description = forms.CharField()
class Meta:
model = Category
fields = ['description', 'url']

View File

@ -35,6 +35,7 @@ class ModelMultipleChoiceFieldTests(TestCase):
Person.objects.create(name="Person %s" % i)
self._validator_run = False
def my_validator(value):
self._validator_run = True

View File

@ -1075,9 +1075,11 @@ class ModelFormsetTest(TestCase):
class MembershipForm(forms.ModelForm):
date_joined = forms.SplitDateTimeField(initial=now)
class Meta:
model = Membership
fields = "__all__"
def __init__(self, **kwargs):
super(MembershipForm, self).__init__(**kwargs)
self.fields['date_joined'].widget = forms.SplitDateTimeWidget()

View File

@ -86,6 +86,7 @@ class SelfRefChild(SelfRefParent):
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateTimeField()
class Meta:
ordering = ('-pub_date', 'headline')

View File

@ -1029,8 +1029,10 @@ class ValidationTests(unittest.TestCase):
class AwesomeFilter(SimpleListFilter):
def get_title(self):
return 'awesomeness'
def get_choices(self, request):
return (('bit', 'A bit awesome'), ('very', 'Very awesome'), )
def get_queryset(self, cl, qs):
return qs

View File

@ -85,6 +85,7 @@ class OneToOneTests(TestCase):
w = self.r.waiter_set.create(name='Joe')
w.save()
self.assertEqual(repr(w), '<Waiter: Joe the waiter at Demon Dogs the restaurant>')
# Query the waiters
def assert_filter_waiters(**params):
self.assertQuerysetEqual(Waiter.objects.filter(**params), [

View File

@ -21,6 +21,7 @@ from django.utils.encoding import python_2_unicode_compatible
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateTimeField()
class Meta:
ordering = ('-pub_date', 'headline')
@ -31,6 +32,7 @@ class Article(models.Model):
class ArticlePKOrdering(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateTimeField()
class Meta:
ordering = ('-pk',)

View File

@ -676,6 +676,7 @@ class Queries1Tests(BaseQuerysetTest):
Item.objects.filter(created__in=[self.time1, self.time2]),
['<Item: one>', '<Item: two>']
)
def test_ticket7235(self):
# An EmptyQuerySet should not raise exceptions if it is filtered.
Eaten.objects.create(meal='m')
@ -757,6 +758,7 @@ class Queries1Tests(BaseQuerysetTest):
def f():
return iter([])
n_obj = Note.objects.all()[0]
def g():
for i in [n_obj.pk]:
yield i
@ -1238,6 +1240,7 @@ class Queries2Tests(TestCase):
# Count should work with a partially read result set.
count = Number.objects.count()
qs = Number.objects.all()
def run():
for obj in qs:
return qs.count() == count

View File

@ -719,6 +719,7 @@ class DatabaseConnectionHandlingTests(TransactionTestCase):
connection.enter_transaction_management()
connection.set_dirty()
# Test that the rollback doesn't succeed (for example network failure
# could cause this).
def fail_horribly():

View File

@ -220,6 +220,7 @@ class SelectForUpdateTests(TransactionTestCase):
raises the correct exception
"""
self.start_blocking_transaction()
def raw(status):
try:
list(

View File

@ -15,6 +15,7 @@ from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Domain(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
@ -22,6 +23,7 @@ class Domain(models.Model):
class Kingdom(models.Model):
name = models.CharField(max_length=50)
domain = models.ForeignKey(Domain)
def __str__(self):
return self.name
@ -29,6 +31,7 @@ class Kingdom(models.Model):
class Phylum(models.Model):
name = models.CharField(max_length=50)
kingdom = models.ForeignKey(Kingdom)
def __str__(self):
return self.name
@ -36,6 +39,7 @@ class Phylum(models.Model):
class Klass(models.Model):
name = models.CharField(max_length=50)
phylum = models.ForeignKey(Phylum)
def __str__(self):
return self.name
@ -43,6 +47,7 @@ class Klass(models.Model):
class Order(models.Model):
name = models.CharField(max_length=50)
klass = models.ForeignKey(Klass)
def __str__(self):
return self.name
@ -50,6 +55,7 @@ class Order(models.Model):
class Family(models.Model):
name = models.CharField(max_length=50)
order = models.ForeignKey(Order)
def __str__(self):
return self.name
@ -57,6 +63,7 @@ class Family(models.Model):
class Genus(models.Model):
name = models.CharField(max_length=50)
family = models.ForeignKey(Family)
def __str__(self):
return self.name
@ -64,6 +71,7 @@ class Genus(models.Model):
class Species(models.Model):
name = models.CharField(max_length=50)
genus = models.ForeignKey(Genus)
def __str__(self):
return self.name
@ -73,5 +81,6 @@ class HybridSpecies(models.Model):
name = models.CharField(max_length=50)
parent_1 = models.ForeignKey(Species, related_name='child_1')
parent_2 = models.ForeignKey(Species, related_name='child_2')
def __str__(self):
return self.name

View File

@ -258,6 +258,7 @@ class ModifyingSaveData(models.Model):
# Regression for #7202, #7350
class AbstractBaseModel(models.Model):
parent_data = models.IntegerField()
class Meta:
abstract = True

View File

@ -18,6 +18,7 @@ class ArticleRef(models.Model):
class Scientist(models.Model):
name = models.CharField(max_length=50)
class Meta:
db_table = 'tablespaces_scientistref'
db_tablespace = 'tbl_tbsp'
@ -28,6 +29,7 @@ class Article(models.Model):
code = models.CharField(max_length=50, unique=True, db_tablespace='idx_tbsp')
authors = models.ManyToManyField(Scientist, related_name='articles_written_set')
reviewers = models.ManyToManyField(Scientist, related_name='articles_reviewed_set', db_tablespace='idx_tbsp')
class Meta:
db_table = 'tablespaces_articleref'
db_tablespace = 'tbl_tbsp'

View File

@ -12,6 +12,7 @@ class CallableVariablesTests(TestCase):
def __init__(self, value):
self.num_calls = 0
self.value = value
def __call__(self):
self.num_calls += 1
return {"the_value": self.value}
@ -38,9 +39,11 @@ class CallableVariablesTests(TestCase):
class Doodad(object):
alters_data = True
def __init__(self, value):
self.num_calls = 0
self.value = value
def __call__(self):
self.num_calls += 1
return {"the_value": self.value}
@ -63,9 +66,11 @@ class CallableVariablesTests(TestCase):
class Doodad(object):
do_not_call_in_templates = True
def __init__(self, value):
self.num_calls = 0
self.value = value
def __call__(self):
self.num_calls += 1
return {"the_value": self.value}
@ -94,9 +99,11 @@ class CallableVariablesTests(TestCase):
class Doodad(object):
do_not_call_in_templates = True
alters_data = True
def __init__(self, value):
self.num_calls = 0
self.value = value
def __call__(self):
self.num_calls += 1
return {"the_value": self.value}

View File

@ -102,18 +102,23 @@ class ParserTests(TestCase):
def test_filter_args_count(self):
p = Parser("")
l = Library()
@l.filter
def no_arguments(value):
pass
@l.filter
def one_argument(value, arg):
pass
@l.filter
def one_opt_argument(value, arg=False):
pass
@l.filter
def two_arguments(value, arg, arg2):
pass
@l.filter
def two_one_opt_arg(value, arg, arg2=False):
pass

View File

@ -134,6 +134,7 @@ class SimpleTemplateResponseTest(TestCase):
def post1(obj):
post.append('post1')
def post2(obj):
post.append('post2')

View File

@ -149,6 +149,7 @@ class TemplateLoaderTests(TestCase):
def test_loaders_security(self):
ad_loader = app_directories.Loader()
fs_loader = filesystem.Loader()
def test_template_sources(path, template_dirs, expected_sources):
if isinstance(expected_sources, list):
# Fix expected sources so they are abspathed

View File

@ -547,6 +547,7 @@ class AssertFormErrorTests(TestCase):
class AssertFormsetErrorTests(TestCase):
msg_prefixes = [("", {}), ("abc: ", {"msg_prefix": "abc"})]
def setUp(self):
"""Makes response object for testing field and non-field errors"""
# For testing field and non-field errors
@ -1201,6 +1202,7 @@ class UnicodePayloadTests(TestCase):
class DummyFile(object):
def __init__(self, filename):
self.name = filename
def read(self):
return b'TEST_FILE_CONTENT'

View File

@ -374,6 +374,7 @@ class SavepointTest(IgnoreDeprecationWarningsMixin, TransactionTestCase):
if (connection.vendor == 'mysql' and
connection.features._mysql_storage_engine == 'MyISAM'):
raise SkipTest("MyISAM MySQL storage engine doesn't support savepoints")
@commit_manually
def work():
mod = Mod.objects.create(fld=1)

View File

@ -192,10 +192,12 @@ class UpdateOnlyFieldsTests(TestCase):
def test_update_fields_signals(self):
p = Person.objects.create(name='Sara', gender='F')
pre_save_data = []
def pre_save_receiver(**kwargs):
pre_save_data.append(kwargs['update_fields'])
pre_save.connect(pre_save_receiver)
post_save_data = []
def post_save_receiver(**kwargs):
post_save_data.append(kwargs['update_fields'])
post_save.connect(post_save_receiver)
@ -222,10 +224,12 @@ class UpdateOnlyFieldsTests(TestCase):
def test_empty_update_fields(self):
s = Person.objects.create(name='Sara', gender='F')
pre_save_data = []
def pre_save_receiver(**kwargs):
pre_save_data.append(kwargs['update_fields'])
pre_save.connect(pre_save_receiver)
post_save_data = []
def post_save_receiver(**kwargs):
post_save_data.append(kwargs['update_fields'])
post_save.connect(post_save_receiver)

View File

@ -28,6 +28,7 @@ class FunctionalTestCase(unittest.TestCase):
def _get_do(self):
raise NotImplementedError
def _set_do(self, value):
raise NotImplementedError
do = lazy_property(_get_do, _set_do)

View File

@ -184,6 +184,7 @@ TEST_DATA = (
def create_simple_test_method(validator, expected, value, num):
if expected is not None and issubclass(expected, Exception):
test_mask = 'test_%s_raises_error_%d'
def test_func(self):
# assertRaises not used, so as to be able to produce an error message
# containing the tested value
@ -196,6 +197,7 @@ def create_simple_test_method(validator, expected, value, num):
expected.__name__, value))
else:
test_mask = 'test_%s_%d'
def test_func(self):
try:
self.assertEqual(expected, validator(value))

View File

@ -76,6 +76,7 @@ class GetInternalWSGIApplicationTest(unittest.TestCase):
"""
# Mock out get_wsgi_application so we know its return value is used
fake_app = object()
def mock_get_wsgi_app():
return fake_app
from django.core.servers import basehttp