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

View File

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

View File

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

View File

@ -87,6 +87,7 @@ class OpenLayersWidget(Textarea):
# JavaScript construction utilities for the Bounds and Projection. # JavaScript construction utilities for the Bounds and Projection.
def ol_bounds(extent): def ol_bounds(extent):
return 'new OpenLayers.Bounds(%s)' % str(extent) return 'new OpenLayers.Bounds(%s)' % str(extent)
def ol_projection(srid): def ol_projection(srid):
return 'new OpenLayers.Projection("EPSG:%s")' % 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) column_name = models.CharField(max_length=1024)
srid = models.IntegerField(primary_key=True) srid = models.IntegerField(primary_key=True)
# TODO: Add support for `diminfo` column (type MDSYS.SDO_DIM_ARRAY). # TODO: Add support for `diminfo` column (type MDSYS.SDO_DIM_ARRAY).
class Meta: class Meta:
db_table = 'USER_SDO_GEOM_METADATA' db_table = 'USER_SDO_GEOM_METADATA'
managed = False managed = False

View File

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

View File

@ -40,6 +40,7 @@ class SpatiaLiteDistance(SpatiaLiteFunction):
class SpatiaLiteRelate(SpatiaLiteFunctionParam): class SpatiaLiteRelate(SpatiaLiteFunctionParam):
"For SpatiaLite Relate(<geom>, <pattern>) calls." "For SpatiaLite Relate(<geom>, <pattern>) calls."
pattern_regex = re.compile(r'^[012TF\*]{9}$') pattern_regex = re.compile(r'^[012TF\*]{9}$')
def __init__(self, pattern): def __init__(self, pattern):
if not self.pattern_regex.match(pattern): if not self.pattern_regex.match(pattern):
raise ValueError('Invalid intersection matrix pattern "%s".' % 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): class BaseField(object):
empty_strings_allowed = True empty_strings_allowed = True
def get_internal_type(self): def get_internal_type(self):
"Overloaded method so OracleQuery.convert_values doesn't balk." "Overloaded method so OracleQuery.convert_values doesn't balk."
return None return None

View File

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

View File

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

View File

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

View File

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

View File

@ -12,6 +12,7 @@ from django.utils import six
class UserListA(ListMixin): class UserListA(ListMixin):
_mytype = tuple _mytype = tuple
def __init__(self, i_list, *args, **kwargs): def __init__(self, i_list, *args, **kwargs):
self._list = self._mytype(i_list) self._list = self._mytype(i_list)
super(UserListA, self).__init__(*args, **kwargs) super(UserListA, self).__init__(*args, **kwargs)
@ -211,8 +212,10 @@ class ListMixinTest(unittest.TestCase):
'Out of range exceptions' 'Out of range exceptions'
def setfcn(x, i): def setfcn(x, i):
x[i] = 20 x[i] = 20
def getfcn(x, i): def getfcn(x, i):
return x[i] return x[i]
def delfcn(x, i): def delfcn(x, i):
del x[i] del x[i]
pl, ul = self.lists_of_len() pl, ul = self.lists_of_len()
@ -252,6 +255,7 @@ class ListMixinTest(unittest.TestCase):
self.assertEqual(pl[:], ul[:], 'after pop') self.assertEqual(pl[:], ul[:], 'after pop')
pl, ul = self.lists_of_len() pl, ul = self.lists_of_len()
def popfcn(x, i): def popfcn(x, i):
x.pop(i) x.pop(i)
self.assertRaises(IndexError, popfcn, ul, self.limit) self.assertRaises(IndexError, popfcn, ul, self.limit)
@ -272,6 +276,7 @@ class ListMixinTest(unittest.TestCase):
def indexfcn(x, v): def indexfcn(x, v):
return x.index(v) return x.index(v)
def removefcn(x, v): def removefcn(x, v):
return x.remove(v) return x.remove(v)
self.assertRaises(ValueError, indexfcn, ul, 40) self.assertRaises(ValueError, indexfcn, ul, 40)
@ -283,6 +288,7 @@ class ListMixinTest(unittest.TestCase):
ul._allowed = six.integer_types ul._allowed = six.integer_types
ul[1] = 50 ul[1] = 50
ul[:2] = [60, 70, 80] ul[:2] = [60, 70, 80]
def setfcn(x, i, v): def setfcn(x, i, v):
x[i] = v x[i] = v
self.assertRaises(TypeError, setfcn, ul, 2, 'hello') self.assertRaises(TypeError, setfcn, ul, 2, 'hello')
@ -292,8 +298,10 @@ class ListMixinTest(unittest.TestCase):
'Length limits' 'Length limits'
pl, ul = self.lists_of_len() pl, ul = self.lists_of_len()
ul._minlength = 1 ul._minlength = 1
def delfcn(x,i): def delfcn(x,i):
del x[:i] del x[:i]
def setfcn(x,i): def setfcn(x,i):
x[:i] = [] x[:i] = []
for i in range(self.limit - ul._minlength + 1, self.limit + 1): 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): def test09_iterable_check(self):
'Error on assigning non-iterable to slice' 'Error on assigning non-iterable to slice'
pl, ul = self.lists_of_len(self.limit + 1) pl, ul = self.lists_of_len(self.limit + 1)
def setfcn(x, i, v): def setfcn(x, i, v):
x[i] = v x[i] = v
self.assertRaises(TypeError, setfcn, ul, slice(0,3,2), 2) 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 # Build the params of the OGR database connection string
params = [db_str % {'db_name': db['NAME']}] params = [db_str % {'db_name': db['NAME']}]
def add(key, template): def add(key, template):
value = db.get(key, None) value = db.get(key, None)
# Don't add the parameter if it is not in django's settings # 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): class CustomGeometryWidget(forms.BaseGeometryWidget):
template_name = 'gis/openlayers.html' template_name = 'gis/openlayers.html'
deserialize_called = 0 deserialize_called = 0
def serialize(self, value): def serialize(self, value):
return value.json if value else '' 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 # data is going to be stored eventually by SimpleCookie, which
# adds it's own overhead, which we must account for. # adds it's own overhead, which we must account for.
cookie = SimpleCookie() # create outside the loop cookie = SimpleCookie() # create outside the loop
def stored_length(val): def stored_length(val):
return len(cookie.value_encode(val)[1]) return len(cookie.value_encode(val)[1])

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -602,6 +602,7 @@ class BaseModelFormSet(BaseFormSet):
""" """
if not commit: if not commit:
self.saved_forms = [] self.saved_forms = []
def save_m2m(): def save_m2m():
for form in self.saved_forms: for form in self.saved_forms:
form.save_m2m() form.save_m2m()
@ -754,6 +755,7 @@ class BaseModelFormSet(BaseFormSet):
# data back. Generally, pk.editable should be false, but for some # data back. Generally, pk.editable should be false, but for some
# reason, auto_created pk fields and AutoField's editable attribute is # reason, auto_created pk fields and AutoField's editable attribute is
# True, so check for that as well. # True, so check for that as well.
def pk_is_not_editable(pk): def pk_is_not_editable(pk):
return ((not pk.editable) or (pk.auto_created or isinstance(pk, AutoField)) 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))) 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): class DateTimeBaseInput(TextInput):
format_key = '' format_key = ''
def __init__(self, attrs=None, format=None): def __init__(self, attrs=None, format=None):
super(DateTimeBaseInput, self).__init__(attrs) super(DateTimeBaseInput, self).__init__(attrs)
self.format = format if format else None self.format = format if format else None

View File

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

View File

@ -245,6 +245,7 @@ def compare_xml(want, got):
Based on http://codespeak.net/svn/lxml/trunk/src/lxml/doctestcompare.py Based on http://codespeak.net/svn/lxml/trunk/src/lxml/doctestcompare.py
""" """
_norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+') _norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+')
def norm_whitespace(v): def norm_whitespace(v):
return _norm_whitespace_re.sub(' ', 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 and provides a simple mock-like list of messages received
""" """
calls = [] calls = []
def replacement(msg): def replacement(msg):
calls.append(msg) calls.append(msg)
logger = logging.getLogger(logger_name) 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 # 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, # 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. # but we can cheat by using it on a dummy function.
@decorator @decorator
def dummy(*args, **kwargs): def dummy(*args, **kwargs):
pass pass
@ -84,6 +85,7 @@ def available_attrs(fn):
def make_middleware_decorator(middleware_class): def make_middleware_decorator(middleware_class):
def _make_decorator(*m_args, **m_kwargs): def _make_decorator(*m_args, **m_kwargs):
middleware = middleware_class(*m_args, **m_kwargs) middleware = middleware_class(*m_args, **m_kwargs)
def _decorator(view_func): def _decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func)) @wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs): def _wrapped_view(request, *args, **kwargs):

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -19,6 +19,7 @@ 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) first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20)
class Meta: class Meta:
ordering = ('last_name', 'first_name') ordering = ('last_name', 'first_name')
@ -29,6 +30,7 @@ class Employee(models.Model):
class Business(models.Model): class Business(models.Model):
name = models.CharField(max_length=20, primary_key=True) name = models.CharField(max_length=20, primary_key=True)
employees = models.ManyToManyField(Employee) employees = models.ManyToManyField(Employee)
class Meta: class Meta:
verbose_name_plural = 'businesses' verbose_name_plural = 'businesses'

View File

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

View File

@ -73,6 +73,7 @@ class DefaultFiltersTests(TestCase):
class FloatWrapper(object): class FloatWrapper(object):
def __init__(self, value): def __init__(self, value):
self.value = value self.value = value
def __float__(self): def __float__(self):
return self.value return self.value
@ -510,6 +511,7 @@ class DefaultFiltersTests(TestCase):
class ULItem(object): class ULItem(object):
def __init__(self, title): def __init__(self, title):
self.title = title self.title = title
def __str__(self): def __str__(self):
return 'ulitem-%s' % str(self.title) 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, # 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. # so we connect to pre_delete and set the fk to a known value.
replacement_r = R.objects.create() replacement_r = R.objects.create()
def check_do_nothing(sender, **kwargs): def check_do_nothing(sender, **kwargs):
obj = kwargs['instance'] obj = kwargs['instance']
obj.donothing_set.update(donothing=replacement_r) obj.donothing_set.update(donothing=replacement_r)
@ -178,6 +179,7 @@ class DeletionTests(TestCase):
def test_instance_update(self): def test_instance_update(self):
deleted = [] deleted = []
related_setnull_sets = [] related_setnull_sets = []
def pre_delete(sender, **kwargs): def pre_delete(sender, **kwargs):
obj = kwargs['instance'] obj = kwargs['instance']
deleted.append(obj) deleted.append(obj)
@ -264,6 +266,7 @@ class DeletionTests(TestCase):
# Attach a signal to make sure we will not do fast_deletes. # Attach a signal to make sure we will not do fast_deletes.
calls = [] calls = []
def noop(*args, **kwargs): def noop(*args, **kwargs):
calls.append('') calls.append('')
models.signals.post_delete.connect(noop, sender=User) 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. # Attach a signal to make sure we will not do fast_deletes.
calls = [] calls = []
def noop(*args, **kwargs): def noop(*args, **kwargs):
calls.append('') calls.append('')
models.signals.post_delete.connect(noop, sender=User) models.signals.post_delete.connect(noop, sender=User)

View File

@ -148,6 +148,7 @@ class LargeDeleteTests(TestCase):
for x in range(300): for x in range(300):
Book.objects.create(pagecount=x+100) Book.objects.create(pagecount=x+100)
# attach a signal to make sure we will not fast-delete # attach a signal to make sure we will not fast-delete
def noop(*args, **kwargs): def noop(*args, **kwargs):
pass pass
models.signals.post_delete.connect(noop, sender=Book) 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: with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('always') warnings.simplefilter('always')
class Manager(six.with_metaclass(RenameManagerMethods)): class Manager(six.with_metaclass(RenameManagerMethods)):
def old(self): def old(self):
pass pass
@ -40,6 +41,7 @@ class RenameMethodsTests(SimpleTestCase):
""" """
with warnings.catch_warnings(record=True) as recorded: with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('ignore') warnings.simplefilter('ignore')
class Manager(six.with_metaclass(RenameManagerMethods)): class Manager(six.with_metaclass(RenameManagerMethods)):
def new(self): def new(self):
pass pass
@ -59,6 +61,7 @@ class RenameMethodsTests(SimpleTestCase):
""" """
with warnings.catch_warnings(record=True) as recorded: with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('ignore') warnings.simplefilter('ignore')
class Manager(six.with_metaclass(RenameManagerMethods)): class Manager(six.with_metaclass(RenameManagerMethods)):
def old(self): def old(self):
pass pass
@ -79,9 +82,11 @@ class RenameMethodsTests(SimpleTestCase):
""" """
with warnings.catch_warnings(record=True) as recorded: with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('ignore') warnings.simplefilter('ignore')
class Renamed(six.with_metaclass(RenameManagerMethods)): class Renamed(six.with_metaclass(RenameManagerMethods)):
def new(self): def new(self):
pass pass
class Deprecated(Renamed): class Deprecated(Renamed):
def old(self): def old(self):
super(Deprecated, self).old() super(Deprecated, self).old()
@ -108,9 +113,11 @@ class RenameMethodsTests(SimpleTestCase):
""" """
with warnings.catch_warnings(record=True) as recorded: with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('ignore') warnings.simplefilter('ignore')
class Deprecated(six.with_metaclass(RenameManagerMethods)): class Deprecated(six.with_metaclass(RenameManagerMethods)):
def old(self): def old(self):
pass pass
class Renamed(Deprecated): class Renamed(Deprecated):
def new(self): def new(self):
super(Renamed, self).new() super(Renamed, self).new()
@ -132,15 +139,19 @@ class RenameMethodsTests(SimpleTestCase):
""" """
with warnings.catch_warnings(record=True) as recorded: with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('ignore') warnings.simplefilter('ignore')
class Renamed(six.with_metaclass(RenameManagerMethods)): class Renamed(six.with_metaclass(RenameManagerMethods)):
def new(self): def new(self):
pass pass
class RenamedMixin(object): class RenamedMixin(object):
def new(self): def new(self):
super(RenamedMixin, self).new() super(RenamedMixin, self).new()
class DeprecatedMixin(object): class DeprecatedMixin(object):
def old(self): def old(self):
super(DeprecatedMixin, self).old() super(DeprecatedMixin, self).old()
class Deprecated(DeprecatedMixin, RenamedMixin, Renamed): class Deprecated(DeprecatedMixin, RenamedMixin, Renamed):
pass pass
warnings.simplefilter('always') warnings.simplefilter('always')

View File

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

View File

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

View File

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

View File

@ -663,11 +663,13 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin):
if six.PY3: if six.PY3:
def __str__(self): def __str__(self):
return 'ŠĐĆŽćžšđ' return 'ŠĐĆŽćžšđ'
def __bytes__(self): def __bytes__(self):
return b'Foo' return b'Foo'
else: else:
def __str__(self): def __str__(self):
return b'Foo' return b'Foo'
def __unicode__(self): def __unicode__(self):
return '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111' 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 # Make sure we're compatible with MySQL, which uses 0 and 1 for its boolean
# values. (#9609) # values. (#9609)
NULLBOOL_CHOICES = (('1', 'Yes'), ('0', 'No'), ('', 'Unknown')) NULLBOOL_CHOICES = (('1', 'Yes'), ('0', 'No'), ('', 'Unknown'))
class MySQLNullBooleanForm(Form): class MySQLNullBooleanForm(Form):
nullbool0 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES)) nullbool0 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES))
nullbool1 = 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 """ Test that we are able to modify a form field validators list without polluting
other forms """ other forms """
from django.core.validators import MaxValueValidator from django.core.validators import MaxValueValidator
class MyForm(Form): class MyForm(Form):
myfield = CharField(max_length=25) myfield = CharField(max_length=25)
@ -1899,6 +1900,7 @@ class FormsTestCase(TestCase):
""" """
class CustomJSONField(CharField): class CustomJSONField(CharField):
empty_values = [None, ''] empty_values = [None, '']
def to_python(self, value): def to_python(self, value):
# Fake json.loads # Fake json.loads
if value == '{}': if value == '{}':

View File

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

View File

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

View File

@ -242,6 +242,7 @@ class BookSigningConfig(object):
model = BookSigning model = BookSigning
date_field = 'event_date' date_field = 'event_date'
# use the same templates as for books # use the same templates as for books
def get_template_names(self): def get_template_names(self):
return ['generic_views/book%s.html' % self.template_name_suffix] 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'), table_name_filter=lambda tn:tn.startswith('inspectdb_columntypes'),
stdout=out) stdout=out)
output = out.getvalue() output = out.getvalue()
def assertFieldType(name, definition): def assertFieldType(name, definition):
out_def = re.search(r'^\s*%s = (models.*)$' % name, output, re.MULTILINE).groups()[0] out_def = re.search(r'^\s*%s = (models.*)$' % name, output, re.MULTILINE).groups()[0]
self.assertEqual(definition, out_def) self.assertEqual(definition, out_def)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -85,6 +85,7 @@ class OneToOneTests(TestCase):
w = self.r.waiter_set.create(name='Joe') w = self.r.waiter_set.create(name='Joe')
w.save() w.save()
self.assertEqual(repr(w), '<Waiter: Joe the waiter at Demon Dogs the restaurant>') self.assertEqual(repr(w), '<Waiter: Joe the waiter at Demon Dogs the restaurant>')
# Query the waiters # Query the waiters
def assert_filter_waiters(**params): def assert_filter_waiters(**params):
self.assertQuerysetEqual(Waiter.objects.filter(**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): class Article(models.Model):
headline = models.CharField(max_length=100) headline = models.CharField(max_length=100)
pub_date = models.DateTimeField() pub_date = models.DateTimeField()
class Meta: class Meta:
ordering = ('-pub_date', 'headline') ordering = ('-pub_date', 'headline')
@ -31,6 +32,7 @@ class Article(models.Model):
class ArticlePKOrdering(models.Model): class ArticlePKOrdering(models.Model):
headline = models.CharField(max_length=100) headline = models.CharField(max_length=100)
pub_date = models.DateTimeField() pub_date = models.DateTimeField()
class Meta: class Meta:
ordering = ('-pk',) ordering = ('-pk',)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -184,6 +184,7 @@ TEST_DATA = (
def create_simple_test_method(validator, expected, value, num): def create_simple_test_method(validator, expected, value, num):
if expected is not None and issubclass(expected, Exception): if expected is not None and issubclass(expected, Exception):
test_mask = 'test_%s_raises_error_%d' test_mask = 'test_%s_raises_error_%d'
def test_func(self): def test_func(self):
# assertRaises not used, so as to be able to produce an error message # assertRaises not used, so as to be able to produce an error message
# containing the tested value # containing the tested value
@ -196,6 +197,7 @@ def create_simple_test_method(validator, expected, value, num):
expected.__name__, value)) expected.__name__, value))
else: else:
test_mask = 'test_%s_%d' test_mask = 'test_%s_%d'
def test_func(self): def test_func(self):
try: try:
self.assertEqual(expected, validator(value)) 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 # Mock out get_wsgi_application so we know its return value is used
fake_app = object() fake_app = object()
def mock_get_wsgi_app(): def mock_get_wsgi_app():
return fake_app return fake_app
from django.core.servers import basehttp from django.core.servers import basehttp