1
0
mirror of https://github.com/django/django.git synced 2025-07-05 10:19:20 +00:00

Merge branch 'master' into local/gsoc

git-svn-id: http://code.djangoproject.com/svn/django/branches/soc2009/test-improvements@10890 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Kevin Kubasik 2009-06-02 14:53:25 +00:00
parent 295beee70b
commit f0489dffb9
10 changed files with 567 additions and 318 deletions

File diff suppressed because it is too large Load Diff

View File

@ -143,7 +143,7 @@ class GoogleMap(object):
@property @property
def icons(self): def icons(self):
"Returns a sequence of GIcon objects in this map." "Returns a sequence of GIcon objects in this map."
return [marker.icon for marker in self.markers if marker.icon] return set([marker.icon for marker in self.markers if marker.icon])
class GoogleMapSet(GoogleMap): class GoogleMapSet(GoogleMap):
@ -221,6 +221,6 @@ class GoogleMapSet(GoogleMap):
@property @property
def icons(self): def icons(self):
"Returns a sequence of all icons in each map of the set." "Returns a sequence of all icons in each map of the set."
icons = [] icons = set()
for map in self.maps: icons.extend(map.icons) for map in self.maps: icons |= map.icons
return icons return icons

View File

@ -231,6 +231,14 @@ class GIcon(object):
self.iconanchor = iconanchor self.iconanchor = iconanchor
self.infowindowanchor = infowindowanchor self.infowindowanchor = infowindowanchor
def __cmp__(self, other):
return cmp(self.varname, other.varname)
def __hash__(self):
# XOR with hash of GIcon type so that hash('varname') won't
# equal hash(GIcon('varname')).
return hash(self.__class__) ^ hash(self.varname)
class GMarker(GOverlayBase): class GMarker(GOverlayBase):
""" """
A Python wrapper for the Google GMarker object. For more information A Python wrapper for the Google GMarker object. For more information

View File

@ -12,12 +12,12 @@ from django.contrib.gis.gdal.field import OFTDate, OFTDateTime, OFTInteger, OFTR
def mapping(data_source, geom_name='geom', layer_key=0, multi_geom=False): def mapping(data_source, geom_name='geom', layer_key=0, multi_geom=False):
""" """
Given a DataSource, generates a dictionary that may be used Given a DataSource, generates a dictionary that may be used
for invoking the LayerMapping utility. for invoking the LayerMapping utility.
Keyword Arguments: Keyword Arguments:
`geom_name` => The name of the geometry field to use for the model. `geom_name` => The name of the geometry field to use for the model.
`layer_key` => The key for specifying which layer in the DataSource to use; `layer_key` => The key for specifying which layer in the DataSource to use;
defaults to 0 (the first layer). May be an integer index or a string defaults to 0 (the first layer). May be an integer index or a string
identifier for the layer. identifier for the layer.
@ -31,7 +31,7 @@ def mapping(data_source, geom_name='geom', layer_key=0, multi_geom=False):
pass pass
else: else:
raise TypeError('Data source parameter must be a string or a DataSource object.') raise TypeError('Data source parameter must be a string or a DataSource object.')
# Creating the dictionary. # Creating the dictionary.
_mapping = {} _mapping = {}
@ -52,32 +52,32 @@ def ogrinspect(*args, **kwargs):
model name this function will generate a GeoDjango model. model name this function will generate a GeoDjango model.
Usage: Usage:
>>> from django.contrib.gis.utils import ogrinspect >>> from django.contrib.gis.utils import ogrinspect
>>> ogrinspect('/path/to/shapefile.shp','NewModel') >>> ogrinspect('/path/to/shapefile.shp','NewModel')
...will print model definition to stout ...will print model definition to stout
or put this in a python script and use to redirect the output to a new or put this in a python script and use to redirect the output to a new
model like: model like:
$ python generate_model.py > myapp/models.py $ python generate_model.py > myapp/models.py
# generate_model.py # generate_model.py
from django.contrib.gis.utils import ogrinspect from django.contrib.gis.utils import ogrinspect
shp_file = 'data/mapping_hacks/world_borders.shp' shp_file = 'data/mapping_hacks/world_borders.shp'
model_name = 'WorldBorders' model_name = 'WorldBorders'
print ogrinspect(shp_file, model_name, multi_geom=True, srid=4326, print ogrinspect(shp_file, model_name, multi_geom=True, srid=4326,
geom_name='shapes', blank=True) geom_name='shapes', blank=True)
Required Arguments Required Arguments
`datasource` => string or DataSource object to file pointer `datasource` => string or DataSource object to file pointer
`model name` => string of name of new model class to create `model name` => string of name of new model class to create
Optional Keyword Arguments Optional Keyword Arguments
`geom_name` => For specifying the model name for the Geometry Field. `geom_name` => For specifying the model name for the Geometry Field.
Otherwise will default to `geom` Otherwise will default to `geom`
`layer_key` => The key for specifying which layer in the DataSource to use; `layer_key` => The key for specifying which layer in the DataSource to use;
@ -86,24 +86,24 @@ def ogrinspect(*args, **kwargs):
`srid` => The SRID to use for the Geometry Field. If it can be determined, `srid` => The SRID to use for the Geometry Field. If it can be determined,
the SRID of the datasource is used. the SRID of the datasource is used.
`multi_geom` => Boolean (default: False) - specify as multigeometry. `multi_geom` => Boolean (default: False) - specify as multigeometry.
`name_field` => String - specifies a field name to return for the `name_field` => String - specifies a field name to return for the
`__unicode__` function (which will be generated if specified). `__unicode__` function (which will be generated if specified).
`imports` => Boolean (default: True) - set to False to omit the `imports` => Boolean (default: True) - set to False to omit the
`from django.contrib.gis.db import models` code from the `from django.contrib.gis.db import models` code from the
autogenerated models thus avoiding duplicated imports when building autogenerated models thus avoiding duplicated imports when building
more than one model by batching ogrinspect() more than one model by batching ogrinspect()
`decimal` => Boolean or sequence (default: False). When set to True `decimal` => Boolean or sequence (default: False). When set to True
all generated model fields corresponding to the `OFTReal` type will all generated model fields corresponding to the `OFTReal` type will
be `DecimalField` instead of `FloatField`. A sequence of specific be `DecimalField` instead of `FloatField`. A sequence of specific
field names to generate as `DecimalField` may also be used. field names to generate as `DecimalField` may also be used.
`blank` => Boolean or sequence (default: False). When set to True all `blank` => Boolean or sequence (default: False). When set to True all
generated model fields will have `blank=True`. If the user wants to generated model fields will have `blank=True`. If the user wants to
give specific fields to have blank, then a list/tuple of OGR field give specific fields to have blank, then a list/tuple of OGR field
names may be used. names may be used.
@ -111,13 +111,13 @@ def ogrinspect(*args, **kwargs):
model fields will have `null=True`. If the user wants to specify model fields will have `null=True`. If the user wants to specify
give specific fields to have null, then a list/tuple of OGR field give specific fields to have null, then a list/tuple of OGR field
names may be used. names may be used.
Note: This routine calls the _ogrinspect() helper to do the heavy lifting. Note: This routine calls the _ogrinspect() helper to do the heavy lifting.
""" """
return '\n'.join(s for s in _ogrinspect(*args, **kwargs)) return '\n'.join(s for s in _ogrinspect(*args, **kwargs))
def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=None, def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=None,
multi_geom=False, name_field=None, imports=True, multi_geom=False, name_field=None, imports=True,
decimal=False, blank=False, null=False): decimal=False, blank=False, null=False):
""" """
Helper routine for `ogrinspect` that generates GeoDjango models corresponding Helper routine for `ogrinspect` that generates GeoDjango models corresponding
@ -140,7 +140,7 @@ def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=Non
# keyword arguments. # keyword arguments.
def process_kwarg(kwarg): def process_kwarg(kwarg):
if isinstance(kwarg, (list, tuple)): if isinstance(kwarg, (list, tuple)):
return [s.lower() for s in kwarg] return [s.lower() for s in kwarg]
elif kwarg: elif kwarg:
return [s.lower() for s in ogr_fields] return [s.lower() for s in ogr_fields]
else: else:
@ -164,18 +164,18 @@ def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=Non
yield '' yield ''
yield 'class %s(models.Model):' % model_name yield 'class %s(models.Model):' % model_name
for field_name, width, precision, field_type in izip(ogr_fields, layer.field_widths, layer.field_precisions, layer.field_types): for field_name, width, precision, field_type in izip(ogr_fields, layer.field_widths, layer.field_precisions, layer.field_types):
# The model field name. # The model field name.
mfield = field_name.lower() mfield = field_name.lower()
if mfield[-1:] == '_': mfield += 'field' if mfield[-1:] == '_': mfield += 'field'
# Getting the keyword args string. # Getting the keyword args string.
kwargs_str = get_kwargs_str(field_name) kwargs_str = get_kwargs_str(field_name)
if field_type is OFTReal: if field_type is OFTReal:
# By default OFTReals are mapped to `FloatField`, however, they # By default OFTReals are mapped to `FloatField`, however, they
# may also be mapped to `DecimalField` if specified in the # may also be mapped to `DecimalField` if specified in the
# `decimal` keyword. # `decimal` keyword.
if field_name.lower() in decimal_fields: if field_name.lower() in decimal_fields:
yield ' %s = models.DecimalField(max_digits=%d, decimal_places=%d%s)' % (mfield, width, precision, kwargs_str) yield ' %s = models.DecimalField(max_digits=%d, decimal_places=%d%s)' % (mfield, width, precision, kwargs_str)
@ -192,8 +192,8 @@ def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=Non
elif field_type is OFTDate: elif field_type is OFTDate:
yield ' %s = models.TimeField(%s)' % (mfield, kwargs_str[2:]) yield ' %s = models.TimeField(%s)' % (mfield, kwargs_str[2:])
else: else:
raise TypeError('Unknown field type %s in %s' % (fld_type, mfield)) raise TypeError('Unknown field type %s in %s' % (field_type, mfield))
# TODO: Autodetection of multigeometry types (see #7218). # TODO: Autodetection of multigeometry types (see #7218).
gtype = layer.geom_type gtype = layer.geom_type
if multi_geom and gtype.num in (1, 2, 3): if multi_geom and gtype.num in (1, 2, 3):

View File

@ -689,7 +689,7 @@ class BaseQuery(object):
If 'with_aliases' is true, any column names that are duplicated If 'with_aliases' is true, any column names that are duplicated
(without the table names) are given unique aliases. This is needed in (without the table names) are given unique aliases. This is needed in
some cases to avoid ambiguitity with nested queries. some cases to avoid ambiguity with nested queries.
""" """
qn = self.quote_name_unless_alias qn = self.quote_name_unless_alias
qn2 = self.connection.ops.quote_name qn2 = self.connection.ops.quote_name
@ -1303,7 +1303,7 @@ class BaseQuery(object):
opts = self.model._meta opts = self.model._meta
root_alias = self.tables[0] root_alias = self.tables[0]
seen = {None: root_alias} seen = {None: root_alias}
# Skip all proxy to the root proxied model # Skip all proxy to the root proxied model
proxied_model = get_proxied_model(opts) proxied_model = get_proxied_model(opts)
@ -1732,7 +1732,7 @@ class BaseQuery(object):
raise MultiJoin(pos + 1) raise MultiJoin(pos + 1)
if model: if model:
# The field lives on a base class of the current model. # The field lives on a base class of the current model.
# Skip the chain of proxy to the concrete proxied model # Skip the chain of proxy to the concrete proxied model
proxied_model = get_proxied_model(opts) proxied_model = get_proxied_model(opts)
for int_model in opts.get_base_chain(model): for int_model in opts.get_base_chain(model):
@ -2362,7 +2362,7 @@ class BaseQuery(object):
return cursor return cursor
if result_type == SINGLE: if result_type == SINGLE:
if self.ordering_aliases: if self.ordering_aliases:
return cursor.fetchone()[:-len(results.ordering_aliases)] return cursor.fetchone()[:-len(self.ordering_aliases)]
return cursor.fetchone() return cursor.fetchone()
# The MULTI case. # The MULTI case.

View File

@ -584,7 +584,7 @@ class BaseModelFormSet(BaseFormSet):
else: else:
return ugettext("Please correct the duplicate data for %(field)s, " return ugettext("Please correct the duplicate data for %(field)s, "
"which must be unique.") % { "which must be unique.") % {
"field": get_text_list(unique_check, _("and")), "field": get_text_list(unique_check, unicode(_("and"))),
} }
def get_date_error_message(self, date_check): def get_date_error_message(self, date_check):

View File

@ -536,7 +536,7 @@ class DjangoAdminSettingsDirectory(AdminScriptTestCase):
args = ['startapp','settings_test'] args = ['startapp','settings_test']
out, err = self.run_django_admin(args,'settings') out, err = self.run_django_admin(args,'settings')
self.assertNoOutput(err) self.assertNoOutput(err)
self.assertTrue(os.path.exists(os.path.join(test_dir, 'settings_test'))) self.assert_(os.path.exists(os.path.join(test_dir, 'settings_test')))
shutil.rmtree(os.path.join(test_dir, 'settings_test')) shutil.rmtree(os.path.join(test_dir, 'settings_test'))
def test_builtin_command(self): def test_builtin_command(self):

View File

@ -161,9 +161,9 @@ class FileStoragePathParsing(TestCase):
self.storage.save('dotted.path/test', ContentFile("1")) self.storage.save('dotted.path/test', ContentFile("1"))
self.storage.save('dotted.path/test', ContentFile("2")) self.storage.save('dotted.path/test', ContentFile("2"))
self.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path'))) self.failIf(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path')))
self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test'))) self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test')))
self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test_'))) self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test_')))
def test_first_character_dot(self): def test_first_character_dot(self):
""" """
@ -173,13 +173,13 @@ class FileStoragePathParsing(TestCase):
self.storage.save('dotted.path/.test', ContentFile("1")) self.storage.save('dotted.path/.test', ContentFile("1"))
self.storage.save('dotted.path/.test', ContentFile("2")) self.storage.save('dotted.path/.test', ContentFile("2"))
self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test'))) self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test')))
# Before 2.6, a leading dot was treated as an extension, and so # Before 2.6, a leading dot was treated as an extension, and so
# underscore gets added to beginning instead of end. # underscore gets added to beginning instead of end.
if sys.version_info < (2, 6): if sys.version_info < (2, 6):
self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/_.test'))) self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/_.test')))
else: else:
self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test_'))) self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test_')))
if Image is not None: if Image is not None:
class DimensionClosingBug(TestCase): class DimensionClosingBug(TestCase):

View File

@ -150,6 +150,23 @@ if Image:
_ = p.mugshot.size _ = p.mugshot.size
self.assertEqual(p.mugshot.closed, True) self.assertEqual(p.mugshot.closed, True)
def test_pickle(self):
"""
Tests that ImageField can be pickled, unpickled, and that the
image of the unpickled version is the same as the original.
"""
import pickle
p = Person(name="Joe")
p.mugshot.save("mug", self.file1)
dump = pickle.dumps(p)
p2 = Person(name="Bob")
p2.mugshot = self.file1
loaded_p = pickle.loads(dump)
self.assertEqual(p.mugshot, loaded_p.mugshot)
class ImageFieldTwoDimensionsTests(ImageFieldTestMixin, TestCase): class ImageFieldTwoDimensionsTests(ImageFieldTestMixin, TestCase):
""" """