[py3] Removed longs.

This commit is contained in:
Aymeric Augustin 2012-07-20 12:45:19 +02:00
parent f1d5dc81ac
commit 56dbe924a6
26 changed files with 99 additions and 78 deletions

View File

@ -13,6 +13,7 @@ from django.utils.html import format_html
from django.utils.text import capfirst
from django.utils import timezone
from django.utils.encoding import force_unicode, smart_unicode, smart_str
from django.utils import six
from django.utils.translation import ungettext
from django.core.urlresolvers import reverse
@ -349,7 +350,7 @@ def display_for_value(value, boolean=False):
return formats.localize(timezone.template_localtime(value))
elif isinstance(value, (datetime.date, datetime.time)):
return formats.localize(value)
elif isinstance(value, (decimal.Decimal, float, int, long)):
elif isinstance(value, six.integer_types + (decimal.Decimal, float)):
return formats.number_format(value)
else:
return smart_unicode(value)

View File

@ -16,6 +16,7 @@ from django.contrib.gis.db.backends.oracle.adapter import OracleSpatialAdapter
from django.contrib.gis.db.backends.util import SpatialFunction
from django.contrib.gis.geometry.backend import Geometry
from django.contrib.gis.measure import Distance
from django.utils import six
class SDOOperation(SpatialFunction):
"Base class for SDO* Oracle operations."
@ -65,7 +66,7 @@ class SDORelate(SpatialFunction):
super(SDORelate, self).__init__(self.relate_func, mask=mask)
# Valid distance types and substitutions
dtypes = (Decimal, Distance, float, int, long)
dtypes = (Decimal, Distance, float) + six.integer_types
class OracleOperations(DatabaseOperations, BaseSpatialOperations):
compiler_module = "django.contrib.gis.db.backends.oracle.compiler"

View File

@ -10,6 +10,7 @@ from django.contrib.gis.measure import Distance
from django.core.exceptions import ImproperlyConfigured
from django.db.backends.postgresql_psycopg2.base import DatabaseOperations
from django.db.utils import DatabaseError
from django.utils import six
#### Classes used in constructing PostGIS spatial SQL ####
class PostGISOperator(SpatialOperation):
@ -165,7 +166,7 @@ class PostGISOperations(DatabaseOperations, BaseSpatialOperations):
}
# Valid distance types and substitutions
dtypes = (Decimal, Distance, float, int, long)
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),

View File

@ -9,6 +9,7 @@ from django.contrib.gis.measure import Distance
from django.core.exceptions import ImproperlyConfigured
from django.db.backends.sqlite3.base import DatabaseOperations
from django.db.utils import DatabaseError
from django.utils import six
class SpatiaLiteOperator(SpatialOperation):
"For SpatiaLite operators (e.g. `&&`, `~`)."
@ -42,7 +43,7 @@ class SpatiaLiteRelate(SpatiaLiteFunctionParam):
super(SpatiaLiteRelate, self).__init__('Relate')
# Valid distance types and substitutions
dtypes = (Decimal, Distance, float, int, long)
dtypes = (Decimal, Distance, float) + six.integer_types
def get_dist_ops(operator):
"Returns operations for regular distances; spherical distances are not currently supported."
return (SpatiaLiteDistance(operator),)

View File

@ -6,6 +6,7 @@ from django.contrib.gis.db.models.fields import get_srid_info, PointField, LineS
from django.contrib.gis.db.models.sql import AreaField, DistanceField, GeomField, GeoQuery
from django.contrib.gis.geometry.backend import Geometry
from django.contrib.gis.measure import Area, Distance
from django.utils import six
class GeoQuerySet(QuerySet):
"The Geographic QuerySet."
@ -144,7 +145,7 @@ class GeoQuerySet(QuerySet):
if not backend.geojson:
raise NotImplementedError('Only PostGIS 1.3.4+ supports GeoJSON serialization.')
if not isinstance(precision, (int, long)):
if not isinstance(precision, six.integer_types):
raise TypeError('Precision keyword must be set with an integer.')
# Setting the options flag -- which depends on which version of
@ -173,7 +174,7 @@ class GeoQuerySet(QuerySet):
The `precision` keyword may be used to custom the number of
_characters_ used in the output GeoHash, the default is 20.
"""
s = {'desc' : 'GeoHash',
s = {'desc' : 'GeoHash',
'procedure_args': {'precision': precision},
'procedure_fmt': '%(geo_col)s,%(precision)s',
}
@ -309,7 +310,7 @@ class GeoQuerySet(QuerySet):
- 2 arguments: X and Y sizes to snap the grid to.
- 4 arguments: X, Y sizes and the X, Y origins.
"""
if False in [isinstance(arg, (float, int, long)) for arg in args]:
if False in [isinstance(arg, (float,) + six.integer_types) for arg in args]:
raise TypeError('Size argument(s) for the grid must be a float or integer values.')
nargs = len(args)
@ -349,7 +350,7 @@ class GeoQuerySet(QuerySet):
digits used in output (defaults to 8).
"""
relative = int(bool(relative))
if not isinstance(precision, (int, long)):
if not isinstance(precision, six.integer_types):
raise TypeError('SVG precision keyword argument must be an integer.')
s = {'desc' : 'SVG',
'procedure_fmt' : '%(geo_col)s,%(rel)s,%(precision)s',
@ -390,7 +391,7 @@ class GeoQuerySet(QuerySet):
Transforms the given geometry field to the given SRID. If no SRID is
provided, the transformation will default to using 4326 (WGS84).
"""
if not isinstance(srid, (int, long)):
if not isinstance(srid, six.integer_types):
raise TypeError('An integer SRID must be provided.')
field_name = kwargs.get('field_name', None)
tmp, geo_field = self._spatial_setup('transform', field_name=field_name)

View File

@ -1,6 +1,7 @@
from ctypes import c_void_p
from django.contrib.gis.gdal.error import GDALException
from django.utils import six
class GDALBase(object):
"""
@ -24,7 +25,7 @@ class GDALBase(object):
def _set_ptr(self, ptr):
# Only allow the pointer to be set with pointers of the
# compatible type or None (NULL).
if isinstance(ptr, (int, long)):
if isinstance(ptr, six.integer_types):
self._ptr = self.ptr_type(ptr)
elif ptr is None or isinstance(ptr, self.ptr_type):
self._ptr = ptr

View File

@ -57,6 +57,8 @@ from django.contrib.gis.gdal.prototypes import geom as capi, srs as srs_api
# For recognizing geometry input.
from django.contrib.gis.geometry.regex import hex_regex, wkt_regex, json_regex
from django.utils import six
# For more information, see the OGR C API source code:
# http://www.gdal.org/ogr/ogr__api_8h.html
#
@ -281,7 +283,7 @@ class OGRGeometry(GDALBase):
# (decremented) when this geometry's destructor is called.
if isinstance(srs, SpatialReference):
srs_ptr = srs.ptr
elif isinstance(srs, (int, long, basestring)):
elif isinstance(srs, six.integer_types + (basestring,)):
sr = SpatialReference(srs)
srs_ptr = sr.ptr
else:
@ -297,7 +299,7 @@ class OGRGeometry(GDALBase):
return None
def _set_srid(self, srid):
if isinstance(srid, (int, long)):
if isinstance(srid, six.integer_types):
self.srs = srid
else:
raise TypeError('SRID must be set with an integer.')
@ -410,7 +412,7 @@ class OGRGeometry(GDALBase):
capi.geom_transform(self.ptr, coord_trans.ptr)
elif isinstance(coord_trans, SpatialReference):
capi.geom_transform_to(self.ptr, coord_trans.ptr)
elif isinstance(coord_trans, (int, long, basestring)):
elif isinstance(coord_trans, six.integer_types + (basestring,)):
sr = SpatialReference(coord_trans)
capi.geom_transform_to(self.ptr, sr.ptr)
else:

View File

@ -14,6 +14,8 @@ from django.contrib.gis.gdal.srs import SpatialReference
# GDAL ctypes function prototypes.
from django.contrib.gis.gdal.prototypes import ds as capi, geom as geom_api, srs as srs_api
from django.utils import six
# For more information, see the OGR C API source code:
# http://www.gdal.org/ogr/ogr__api_8h.html
#
@ -25,8 +27,8 @@ class Layer(GDALBase):
def __init__(self, layer_ptr, ds):
"""
Initializes on an OGR C pointer to the Layer and the `DataSource` object
that owns this layer. The `DataSource` object is required so that a
reference to it is kept with this Layer. This prevents garbage
that owns this layer. The `DataSource` object is required so that a
reference to it is kept with this Layer. This prevents garbage
collection of the `DataSource` while this Layer is still active.
"""
if not layer_ptr:
@ -39,7 +41,7 @@ class Layer(GDALBase):
def __getitem__(self, index):
"Gets the Feature at the specified index."
if isinstance(index, (int, long)):
if isinstance(index, six.integer_types):
# An integer index was given -- we cannot do a check based on the
# number of features because the beginning and ending feature IDs
# are not guaranteed to be 0 and len(layer)-1, respectively.
@ -85,7 +87,7 @@ class Layer(GDALBase):
# each feature until the given feature ID is encountered.
for feat in self:
if feat.fid == feat_id: return feat
# Should have returned a Feature, raise an OGRIndexError.
# Should have returned a Feature, raise an OGRIndexError.
raise OGRIndexError('Invalid feature id: %s.' % feat_id)
#### Layer properties ####
@ -131,9 +133,9 @@ class Layer(GDALBase):
Returns a list of string names corresponding to each of the Fields
available in this Layer.
"""
return [capi.get_field_name(capi.get_field_defn(self._ldefn, i))
return [capi.get_field_name(capi.get_field_defn(self._ldefn, i))
for i in xrange(self.num_fields) ]
@property
def field_types(self):
"""
@ -145,13 +147,13 @@ class Layer(GDALBase):
return [OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))]
for i in xrange(self.num_fields)]
@property
@property
def field_widths(self):
"Returns a list of the maximum field widths for the features."
return [capi.get_field_width(capi.get_field_defn(self._ldefn, i))
for i in xrange(self.num_fields)]
@property
@property
def field_precisions(self):
"Returns the field precisions for the features."
return [capi.get_field_precision(capi.get_field_defn(self._ldefn, i))

View File

@ -5,9 +5,10 @@
from ctypes import c_void_p, string_at
from django.contrib.gis.gdal.error import check_err, OGRException, SRSException
from django.contrib.gis.gdal.libgdal import lgdal
from django.utils import six
# Helper routines for retrieving pointers and/or values from
# arguments passed in by reference.
# Helper routines for retrieving pointers and/or values from
# arguments passed in by reference.
def arg_byref(args, offset=-1):
"Returns the pointer argument's by-refernece value."
return args[offset]._obj.value
@ -53,7 +54,7 @@ def check_string(result, func, cargs, offset=-1, str_result=False):
ptr = ptr_byref(cargs, offset)
# Getting the string value
s = ptr.value
# Correctly freeing the allocated memory beind GDAL pointer
# Correctly freeing the allocated memory beind GDAL pointer
# w/the VSIFree routine.
if ptr: lgdal.VSIFree(ptr)
return s
@ -71,9 +72,9 @@ def check_geom(result, func, cargs):
"Checks a function that returns a geometry."
# OGR_G_Clone may return an integer, even though the
# restype is set to c_void_p
if isinstance(result, (int, long)):
if isinstance(result, six.integer_types):
result = c_void_p(result)
if not result:
if not result:
raise OGRException('Invalid geometry pointer returned from "%s".' % func.__name__)
return result
@ -85,7 +86,7 @@ def check_geom_offset(result, func, cargs, offset=-1):
### Spatial Reference error-checking routines ###
def check_srs(result, func, cargs):
if isinstance(result, (int, long)):
if isinstance(result, six.integer_types):
result = c_void_p(result)
if not result:
raise SRSException('Invalid spatial reference pointer returned from "%s".' % func.__name__)
@ -109,11 +110,11 @@ def check_errcode(result, func, cargs):
def check_pointer(result, func, cargs):
"Makes sure the result pointer is valid."
if isinstance(result, (int, long)):
if isinstance(result, six.integer_types):
result = c_void_p(result)
if bool(result):
if bool(result):
return result
else:
else:
raise OGRException('Invalid pointer returned from "%s"' % func.__name__)
def check_str_arg(result, func, cargs):

View File

@ -33,11 +33,13 @@ from django.contrib.gis.gdal.base import GDALBase
from django.contrib.gis.gdal.error import SRSException
from django.contrib.gis.gdal.prototypes import srs as capi
from django.utils import six
#### Spatial Reference class. ####
class SpatialReference(GDALBase):
"""
A wrapper for the OGRSpatialReference object. According to the GDAL Web site,
the SpatialReference object "provide[s] services to represent coordinate
the SpatialReference object "provide[s] services to represent coordinate
systems (projections and datums) and to transform between them."
"""
@ -45,8 +47,8 @@ class SpatialReference(GDALBase):
def __init__(self, srs_input=''):
"""
Creates a GDAL OSR Spatial Reference object from the given input.
The input may be string of OGC Well Known Text (WKT), an integer
EPSG code, a PROJ.4 string, and/or a projection "well known" shorthand
The input may be string of OGC Well Known Text (WKT), an integer
EPSG code, a PROJ.4 string, and/or a projection "well known" shorthand
string (one of 'WGS84', 'WGS72', 'NAD27', 'NAD83').
"""
buf = c_char_p('')
@ -63,7 +65,7 @@ class SpatialReference(GDALBase):
srs_input = 'EPSG:%d' % srid
except ValueError:
pass
elif isinstance(srs_input, (int, long)):
elif isinstance(srs_input, six.integer_types):
# EPSG integer code was input.
srs_type = 'epsg'
elif isinstance(srs_input, self.ptr_type):
@ -97,8 +99,8 @@ class SpatialReference(GDALBase):
def __getitem__(self, target):
"""
Returns the value of the given string attribute node, None if the node
doesn't exist. Can also take a tuple as a parameter, (target, child),
Returns the value of the given string attribute node, None if the node
doesn't exist. Can also take a tuple as a parameter, (target, child),
where child is the index of the attribute in the WKT. For example:
>>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]')
@ -140,7 +142,7 @@ class SpatialReference(GDALBase):
def auth_name(self, target):
"Returns the authority name for the given string target node."
return capi.get_auth_name(self.ptr, target)
def auth_code(self, target):
"Returns the authority code for the given string target node."
return capi.get_auth_code(self.ptr, target)
@ -167,7 +169,7 @@ class SpatialReference(GDALBase):
def validate(self):
"Checks to see if the given spatial reference is valid."
capi.srs_validate(self.ptr)
#### Name & SRID properties ####
@property
def name(self):
@ -184,7 +186,7 @@ class SpatialReference(GDALBase):
return int(self.attr_value('AUTHORITY', 1))
except (TypeError, ValueError):
return None
#### Unit Properties ####
@property
def linear_name(self):
@ -213,7 +215,7 @@ class SpatialReference(GDALBase):
@property
def units(self):
"""
Returns a 2-tuple of the units value and the units name,
Returns a 2-tuple of the units value and the units name,
and will automatically determines whether to return the linear
or angular units.
"""
@ -252,7 +254,7 @@ class SpatialReference(GDALBase):
@property
def geographic(self):
"""
Returns True if this SpatialReference is geographic
Returns True if this SpatialReference is geographic
(root node is GEOGCS).
"""
return bool(capi.isgeographic(self.ptr))
@ -265,7 +267,7 @@ class SpatialReference(GDALBase):
@property
def projected(self):
"""
Returns True if this SpatialReference is a projected coordinate system
Returns True if this SpatialReference is a projected coordinate system
(root node is PROJCS).
"""
return bool(capi.isprojected(self.ptr))

View File

@ -9,6 +9,7 @@ See also http://www.aryehleib.com/MutableLists.html
Author: Aryeh Leib Taurog.
"""
from django.utils.functional import total_ordering
from django.utils import six
@total_ordering
class ListMixin(object):
@ -82,12 +83,12 @@ class ListMixin(object):
def __delitem__(self, index):
"Delete the item(s) at the specified index/slice."
if not isinstance(index, (int, long, slice)):
if not isinstance(index, six.integer_types + (slice,)):
raise TypeError("%s is not a legal index" % index)
# calculate new length and dimensions
origLen = len(self)
if isinstance(index, (int, long)):
if isinstance(index, six.integer_types):
index = self._checkindex(index)
indexRange = [index]
else:
@ -195,7 +196,7 @@ class ListMixin(object):
def insert(self, index, val):
"Standard list insert method"
if not isinstance(index, (int, long)):
if not isinstance(index, six.integer_types):
raise TypeError("%s is not a legal index" % index)
self[index:index] = [val]

View File

@ -2,6 +2,7 @@ from ctypes import c_uint
from django.contrib.gis.geos.error import GEOSException
from django.contrib.gis.geos.geometry import GEOSGeometry
from django.contrib.gis.geos import prototypes as capi
from django.utils import six
class Point(GEOSGeometry):
_minlength = 2
@ -20,9 +21,9 @@ class Point(GEOSGeometry):
# Here a tuple or list was passed in under the `x` parameter.
ndim = len(x)
coords = x
elif isinstance(x, (int, float, long)) and isinstance(y, (int, float, long)):
elif isinstance(x, six.integer_types + (float,)) and isinstance(y, six.integer_types + (float,)):
# Here X, Y, and (optionally) Z were passed in individually, as parameters.
if isinstance(z, (int, float, long)):
if isinstance(z, six.integer_types + (float,)):
ndim = 3
coords = [x, y, z]
else:

View File

@ -3,6 +3,7 @@ from django.contrib.gis.geos.geometry import GEOSGeometry
from django.contrib.gis.geos.libgeos import get_pointer_arr, GEOM_PTR
from django.contrib.gis.geos.linestring import LinearRing
from django.contrib.gis.geos import prototypes as capi
from django.utils import six
class Polygon(GEOSGeometry):
_minlength = 1
@ -56,7 +57,7 @@ class Polygon(GEOSGeometry):
"Constructs a Polygon from a bounding box (4-tuple)."
x0, y0, x1, y1 = bbox
for z in bbox:
if not isinstance(z, (int, long, float)):
if not isinstance(z, six.integer_types + (float,)):
return GEOSGeometry('POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))' %
(x0, y0, x0, y1, x1, y1, x1, y0, x0, y0))
return Polygon(((x0, y0), (x0, y1), (x1, y1), (x1, y0), (x0, y0)))

View File

@ -4,6 +4,7 @@
# Modified from original contribution by Aryeh Leib Taurog, which was
# released under the New BSD license.
from django.contrib.gis.geos.mutable_list import ListMixin
from django.utils import six
from django.utils import unittest
@ -267,7 +268,7 @@ class ListMixinTest(unittest.TestCase):
def test07_allowed_types(self):
'Type-restricted list'
pl, ul = self.lists_of_len()
ul._allowed = (int, long)
ul._allowed = six.integer_types
ul[1] = 50
ul[:2] = [60, 70, 80]
def setfcn(x, i, v): x[i] = v

View File

@ -39,8 +39,9 @@ __all__ = ['A', 'Area', 'D', 'Distance']
from decimal import Decimal
from django.utils.functional import total_ordering
from django.utils import six
NUMERIC_TYPES = (int, float, long, Decimal)
NUMERIC_TYPES = six.integer_types + (float, Decimal)
AREA_PREFIX = "sq_"
def pretty_name(obj):

View File

@ -26,7 +26,7 @@ class BaseDatabaseCreation(object):
Generates a 32-bit digest of a set of arguments that can be used to
shorten identifying names.
"""
return '%x' % (abs(hash(args)) % 4294967296L) # 2**32
return '%x' % (abs(hash(args)) % 4294967296) # 2**32
def sql_create_model(self, model, style, known_models=set()):
"""

View File

@ -243,7 +243,7 @@ class DatabaseOperations(BaseDatabaseOperations):
def no_limit_value(self):
# 2**64 - 1, as recommended by the MySQL documentation
return 18446744073709551615L
return 18446744073709551615
def quote_name(self, name):
if name.startswith("`") and name.endswith("`"):

View File

@ -209,7 +209,7 @@ WHEN (new.%(col_name)s IS NULL)
return "DROP SEQUENCE %s;" % self.quote_name(self._get_sequence_name(table))
def fetch_returned_insert_id(self, cursor):
return long(cursor._insert_id_var.getvalue())
return int(cursor._insert_id_var.getvalue())
def field_cast_sql(self, db_type):
if db_type and db_type.endswith('LOB'):

View File

@ -169,7 +169,7 @@ class QuerySet(object):
"""
Retrieves an item or slice from the set of results.
"""
if not isinstance(k, (slice, int, long)):
if not isinstance(k, (slice,) + six.integer_types):
raise TypeError
assert ((not isinstance(k, slice) and (k >= 0))
or (isinstance(k, slice) and (k.start is None or k.start >= 0)

View File

@ -98,7 +98,7 @@ def _bin_to_long(x):
This is a clever optimization for fast xor vector math
"""
return long(x.encode('hex'), 16)
return int(x.encode('hex'), 16)
def _long_to_bin(x, hex_format_string):

View File

@ -7,6 +7,7 @@ import codecs
from decimal import Decimal
from django.utils.functional import Promise
from django.utils import six
class DjangoUnicodeDecodeError(UnicodeDecodeError):
def __init__(self, obj, *args):
@ -45,12 +46,8 @@ def is_protected_type(obj):
Objects of protected types are preserved as-is when passed to
force_unicode(strings_only=True).
"""
return isinstance(obj, (
type(None),
int, long,
datetime.datetime, datetime.date, datetime.time,
float, Decimal)
)
return isinstance(obj, six.integer_types + (type(None), float, Decimal,
datetime.datetime, datetime.date, datetime.time))
def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):
"""

View File

@ -7,6 +7,7 @@ from django.utils.importlib import import_module
from django.utils.encoding import smart_str
from django.utils.functional import lazy
from django.utils.safestring import mark_safe
from django.utils import six
from django.utils.translation import get_language, to_locale, check_for_language
# format_cache is a mapping from (format_type, lang) to the format string.
@ -139,7 +140,7 @@ def localize(value, use_l10n=None):
"""
if isinstance(value, bool):
return mark_safe(unicode(value))
elif isinstance(value, (decimal.Decimal, float, int, long)):
elif isinstance(value, (decimal.Decimal, float) + six.integer_types):
return number_format(value, use_l10n=use_l10n)
elif isinstance(value, datetime.datetime):
return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n)
@ -155,7 +156,7 @@ def localize_input(value, default=None):
Checks if an input value is a localizable type and returns it
formatted with the appropriate formatting string of the current locale.
"""
if isinstance(value, (decimal.Decimal, float, int, long)):
if isinstance(value, (decimal.Decimal, float) + six.integer_types):
return number_format(value)
elif isinstance(value, datetime.datetime):
value = datetime_safe.new_datetime(value)

View File

@ -5,6 +5,7 @@ from datetime import datetime
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.fields import Field, FieldDoesNotExist
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
from django.utils.six import PY3
from django.utils.translation import ugettext_lazy
from .models import Article
@ -321,17 +322,18 @@ class ModelTest(TestCase):
["<Article: Area man programs in Python>",
"<Article: Third article>"])
# Slicing works with longs.
self.assertEqual(Article.objects.all()[0L], a)
self.assertQuerysetEqual(Article.objects.all()[1L:3L],
["<Article: Second article>", "<Article: Third article>"])
self.assertQuerysetEqual((s1 | s2 | s3)[::2L],
["<Article: Area man programs in Python>",
"<Article: Third article>"])
# Slicing works with longs (Python 2 only -- Python 3 doesn't have longs).
if not PY3:
self.assertEqual(Article.objects.all()[long(0)], a)
self.assertQuerysetEqual(Article.objects.all()[long(1):long(3)],
["<Article: Second article>", "<Article: Third article>"])
self.assertQuerysetEqual((s1 | s2 | s3)[::long(2)],
["<Article: Area man programs in Python>",
"<Article: Third article>"])
# And can be mixed with ints.
self.assertQuerysetEqual(Article.objects.all()[1:3L],
["<Article: Second article>", "<Article: Third article>"])
# And can be mixed with ints.
self.assertQuerysetEqual(Article.objects.all()[1:long(3)],
["<Article: Second article>", "<Article: Third article>"])
# Slices (without step) are lazy:
self.assertQuerysetEqual(Article.objects.all()[0:5].filter(),

View File

@ -3,6 +3,7 @@ from __future__ import absolute_import
from datetime import datetime
from django.test import TestCase
from django.utils import six
from .models import Article
@ -13,6 +14,6 @@ class DefaultTests(TestCase):
now = datetime.now()
a.save()
self.assertTrue(isinstance(a.id, (int, long)))
self.assertTrue(isinstance(a.id, six.integer_types))
self.assertEqual(a.headline, "Default headline")
self.assertTrue((now - a.pub_date).seconds < 5)

View File

@ -19,6 +19,7 @@ from django.utils.formats import (get_format, date_format, time_format,
from django.utils.importlib import import_module
from django.utils.numberformat import format as nformat
from django.utils.safestring import mark_safe, SafeString, SafeUnicode
from django.utils.six import PY3
from django.utils.translation import (ugettext, ugettext_lazy, activate,
deactivate, gettext_lazy, pgettext, npgettext, to_locale,
get_language_info, get_language, get_language_from_request)
@ -309,7 +310,7 @@ class FormattingTests(TestCase):
self.d = datetime.date(2009, 12, 31)
self.dt = datetime.datetime(2009, 12, 31, 20, 50)
self.t = datetime.time(10, 15, 48)
self.l = 10000L
self.l = 10000 if PY3 else long(10000)
self.ctxt = Context({
'n': self.n,
't': self.t,

View File

@ -8,6 +8,7 @@ from django import forms
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models.fields.files import FieldFile
from django.utils import six
from django.utils import unittest
from .models import (Foo, Bar, Whiz, BigD, BigS, Image, BigInt, Post,
@ -303,11 +304,11 @@ class BigIntegerFieldTests(test.TestCase):
def test_types(self):
b = BigInt(value = 0)
self.assertTrue(isinstance(b.value, (int, long)))
self.assertTrue(isinstance(b.value, six.integer_types))
b.save()
self.assertTrue(isinstance(b.value, (int, long)))
self.assertTrue(isinstance(b.value, six.integer_types))
b = BigInt.objects.all()[0]
self.assertTrue(isinstance(b.value, (int, long)))
self.assertTrue(isinstance(b.value, six.integer_types))
def test_coercing(self):
BigInt.objects.create(value ='10')