~ubuntu-branches/ubuntu/saucy/python-django/saucy-updates

1.2.12 by Raphaël Hertzog
Import upstream version 1.4
1
from __future__ import absolute_import
2
3
import os
4
5
from django.db import connections
6
from django.test import TestCase
7
from django.contrib.gis.gdal import Driver
8
from django.contrib.gis.geometry.test_data import TEST_DATA
9
from django.contrib.gis.utils.ogrinspect import ogrinspect
10
11
from .models import AllOGRFields
12
13
14
class OGRInspectTest(TestCase):
15
    def test_poly(self):
16
        shp_file = os.path.join(TEST_DATA, 'test_poly', 'test_poly.shp')
17
        model_def = ogrinspect(shp_file, 'MyModel')
18
19
        expected = [
20
            '# This is an auto-generated Django model module created by ogrinspect.',
21
            'from django.contrib.gis.db import models',
22
            '',
23
            'class MyModel(models.Model):',
24
            '    float = models.FloatField()',
25
            '    int = models.FloatField()',
26
            '    str = models.CharField(max_length=80)',
27
            '    geom = models.PolygonField(srid=-1)',
28
            '    objects = models.GeoManager()',
29
        ]
30
31
        self.assertEqual(model_def, '\n'.join(expected))
32
33
    def test_date_field(self):
34
        shp_file = os.path.join(TEST_DATA, 'cities', 'cities.shp')
35
        model_def = ogrinspect(shp_file, 'City')
36
37
        expected = [
38
            '# This is an auto-generated Django model module created by ogrinspect.',
39
            'from django.contrib.gis.db import models',
40
            '',
41
            'class City(models.Model):',
42
            '    name = models.CharField(max_length=80)',
43
            '    population = models.FloatField()',
44
            '    density = models.FloatField()',
45
            '    created = models.DateField()',
46
            '    geom = models.PointField(srid=-1)',
47
            '    objects = models.GeoManager()',
48
        ]
49
50
        self.assertEqual(model_def, '\n'.join(expected))
51
52
    def test_time_field(self):
53
        # Only possible to test this on PostGIS at the momemnt.  MySQL
54
        # complains about permissions, and SpatiaLite/Oracle are
55
        # insanely difficult to get support compiled in for in GDAL.
56
        if not connections['default'].ops.postgis:
57
            return
58
59
        # Getting the database identifier used by OGR, if None returned
60
        # GDAL does not have the support compiled in.
61
        ogr_db = get_ogr_db_string()
62
        if not ogr_db:
63
            return
64
65
        # writing shapefules via GDAL currently does not support writing OGRTime
66
        # fields, so we need to actually use a database
67
        model_def = ogrinspect(ogr_db, 'Measurement',
68
                               layer_key=AllOGRFields._meta.db_table,
69
                               decimal=['f_decimal'])
70
1.2.16 by Raphaël Hertzog
Import upstream version 1.4.4
71
        self.assertTrue(model_def.startswith(
72
            '# This is an auto-generated Django model module created by ogrinspect.\n'
73
            'from django.contrib.gis.db import models\n'
74
            '\n'
75
            'class Measurement(models.Model):\n'
76
        ))
77
78
        # The ordering of model fields might vary depending on several factors (version of GDAL, etc.)
79
        self.assertIn('    f_decimal = models.DecimalField(max_digits=0, decimal_places=0)', model_def)
80
        self.assertIn('    f_int = models.IntegerField()', model_def)
81
        self.assertIn('    f_datetime = models.DateTimeField()', model_def)
82
        self.assertIn('    f_time = models.TimeField()', model_def)
83
        self.assertIn('    f_float = models.FloatField()', model_def)
84
        self.assertIn('    f_char = models.CharField(max_length=10)', model_def)
85
        self.assertIn('    f_date = models.DateField()', model_def)
86
87
        self.assertTrue(model_def.endswith(
88
            '    geom = models.PolygonField()\n'
89
            '    objects = models.GeoManager()'
90
        ))
91
1.2.12 by Raphaël Hertzog
Import upstream version 1.4
92
93
def get_ogr_db_string():
94
    # Construct the DB string that GDAL will use to inspect the database.
95
    # GDAL will create its own connection to the database, so we re-use the
96
    # connection settings from the Django test.  This approach is a bit fragile
97
    # and cannot work on any other database other than PostgreSQL at the moment.
98
    db = connections.databases['default']
99
100
    # Map from the django backend into the OGR driver name and database identifier
101
    # http://www.gdal.org/ogr/ogr_formats.html
102
    #
103
    # TODO: Support Oracle (OCI), MySQL, and SpatiaLite.
104
    drivers = {
105
        'django.contrib.gis.db.backends.postgis': ('PostgreSQL', 'PG'),
106
    }
107
108
    drv_name, db_str = drivers[db['ENGINE']]
109
110
    # Ensure that GDAL library has driver support for the database.
111
    try:
112
        Driver(drv_name)
113
    except:
114
        return None
115
116
    # Build the params of the OGR database connection string
117
    # TODO: connection strings are database-dependent, thus if
118
    #       we ever test other backends, this will need to change.
119
    params = ["dbname='%s'" % db['NAME']]
120
    def add(key, template):
121
        value = db.get(key, None)
122
        # Don't add the parameter if it is not in django's settings
123
        if value:
124
            params.append(template % value)
125
    add('HOST', "host='%s'")
126
    add('PORT', "port='%s'")
127
    add('USER', "user='%s'")
128
    add('PASSWORD', "password='%s'")
129
130
    return '%s:%s' % (db_str, ' '.join(params))