/
test_db_manager_gpkg.py
433 lines (329 loc) · 17.3 KB
/
test_db_manager_gpkg.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# -*- coding: utf-8 -*-
"""QGIS Unit tests for the DBManager GPKG plugin
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'Even Rouault'
__date__ = '2016-10-17'
__copyright__ = 'Copyright 2016, Even Rouault'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import qgis # NOQA
import os
import tempfile
import shutil
from osgeo import gdal, ogr, osr
from qgis.core import QgsDataSourceURI
from qgis.PyQt.QtCore import QCoreApplication, QSettings
from qgis.testing import start_app, unittest
from plugins.db_manager.db_plugins import supportedDbTypes, createDbPlugin
from plugins.db_manager.db_plugins.plugin import TableField
def GDAL_COMPUTE_VERSION(maj, min, rev):
return ((maj) * 1000000 + (min) * 10000 + (rev) * 100)
class TestPyQgsDBManagerGpkg(unittest.TestCase):
@classmethod
def setUpClass(cls):
"""Run before all tests"""
QCoreApplication.setOrganizationName("QGIS_Test")
QCoreApplication.setOrganizationDomain("TestPyQgsDBManagerGpkg.com")
QCoreApplication.setApplicationName("TestPyQgsDBManagerGpkg")
QSettings().clear()
start_app()
cls.basetestpath = tempfile.mkdtemp()
cls.test_gpkg = os.path.join(cls.basetestpath, 'TestPyQgsDBManagerGpkg.gpkg')
ds = ogr.GetDriverByName('GPKG').CreateDataSource(cls.test_gpkg)
lyr = ds.CreateLayer('testLayer', geom_type=ogr.wkbLineString, options=['SPATIAL_INDEX=NO'])
cls.supportsAlterFieldDefn = lyr.TestCapability(ogr.OLCAlterFieldDefn) == 1
lyr.CreateField(ogr.FieldDefn('text_field', ogr.OFTString))
f = ogr.Feature(lyr.GetLayerDefn())
f['text_field'] = 'foo'
f.SetGeometry(ogr.CreateGeometryFromWkt('LINESTRING(1 2,3 4)'))
lyr.CreateFeature(f)
f = None
ds = None
@classmethod
def tearDownClass(cls):
"""Run after all tests"""
QSettings().clear()
shutil.rmtree(cls.basetestpath, True)
def testSupportedDbTypes(self):
self.assertIn('gpkg', supportedDbTypes())
def testCreateDbPlugin(self):
plugin = createDbPlugin('gpkg')
self.assertIsNotNone(plugin)
def testConnect(self):
connection_name = 'testConnect'
plugin = createDbPlugin('gpkg')
uri = QgsDataSourceURI()
uri.setDatabase(self.test_gpkg)
self.assertTrue(plugin.addConnection(connection_name, uri))
connections = plugin.connections()
self.assertEqual(len(connections), 1)
connection = createDbPlugin('gpkg', connection_name + '_does_not_exist')
connection_succeeded = False
try:
connection.connect()
connection_succeeded = True
except:
pass
self.assertFalse(connection_succeeded, 'exception should have been raised')
connection = connections[0]
connection.connect()
connection.reconnect()
connection.remove()
self.assertEqual(len(plugin.connections()), 0)
connection = createDbPlugin('gpkg', connection_name)
connection_succeeded = False
try:
connection.connect()
connection_succeeded = True
except:
pass
self.assertFalse(connection_succeeded, 'exception should have been raised')
def testListLayer(self):
connection_name = 'testListLayer'
plugin = createDbPlugin('gpkg')
uri = QgsDataSourceURI()
uri.setDatabase(self.test_gpkg)
self.assertTrue(plugin.addConnection(connection_name, uri))
connection = createDbPlugin('gpkg', connection_name)
connection.connect()
db = connection.database()
self.assertIsNotNone(db)
tables = db.tables()
self.assertEqual(len(tables), 1)
table = tables[0]
self.assertEqual(table.name, 'testLayer')
info = table.info()
expected_html = """<div class="section"><h2>General info</h2><div><table><tr><td>Relation type: </td><td>Table </td></tr><tr><td>Rows: </td><td>1 </td></tr></table></div></div><div class="section"><h2>GeoPackage</h2><div><table><tr><td>Column: </td><td>geom </td></tr><tr><td>Geometry: </td><td>LINESTRING </td></tr><tr><td>Dimension: </td><td>XY </td></tr><tr><td>Spatial ref: </td><td>Undefined (-1) </td></tr><tr><td>Extent: </td><td>1.00000, 2.00000 - 3.00000, 4.00000 </td></tr></table><p><warning> No spatial index defined (<a href="action:spatialindex/create">create it</a>)</p></div></div><div class="section"><h2>Fields</h2><div><table class="header"><tr><th># </th><th>Name </th><th>Type </th><th>Null </th><th>Default </th></tr><tr><td>0 </td><td class="underline">fid </td><td>INTEGER </td><td>Y </td><td> </td></tr><tr><td>1 </td><td>geom </td><td>LINESTRING </td><td>Y </td><td> </td></tr><tr><td>2 </td><td>text_field </td><td>TEXT </td><td>Y </td><td> </td></tr></table></div></div>"""
self.assertEqual(info.toHtml(), expected_html, info.toHtml())
connection.remove()
def testCreateRenameDeleteTable(self):
connection_name = 'testCreateRenameDeleteTable'
plugin = createDbPlugin('gpkg')
uri = QgsDataSourceURI()
test_gpkg_new = os.path.join(self.basetestpath, 'testCreateRenameDeleteTable.gpkg')
shutil.copy(self.test_gpkg, test_gpkg_new)
uri.setDatabase(test_gpkg_new)
self.assertTrue(plugin.addConnection(connection_name, uri))
connection = createDbPlugin('gpkg', connection_name)
connection.connect()
db = connection.database()
self.assertIsNotNone(db)
tables = db.tables()
self.assertEqual(len(tables), 1)
table = tables[0]
self.assertTrue(table.rename('newName'))
self.assertEqual(table.name, 'newName')
connection.reconnect()
db = connection.database()
tables = db.tables()
self.assertEqual(len(tables), 1)
table = tables[0]
self.assertEqual(table.name, 'newName')
fields = []
geom = ['geometry', 'POINT', 4326, 3]
field1 = TableField(table)
field1.name = 'fid'
field1.dataType = 'INTEGER'
field1.notNull = True
field1.primaryKey = True
field2 = TableField(table)
field2.name = 'str_field'
field2.dataType = 'TEXT'
field2.modifier = 20
fields = [field1, field2]
self.assertTrue(db.createVectorTable('newName2', fields, geom))
tables = db.tables()
self.assertEqual(len(tables), 2)
new_table = tables[1]
self.assertEqual(new_table.name, 'newName2')
fields = new_table.fields()
self.assertEqual(len(fields), 3)
self.assertFalse(new_table.hasSpatialIndex())
self.assertTrue(new_table.createSpatialIndex())
self.assertTrue(new_table.hasSpatialIndex())
self.assertTrue(new_table.delete())
tables = db.tables()
self.assertEqual(len(tables), 1)
connection.remove()
def testCreateRenameDeleteFields(self):
if not self.supportsAlterFieldDefn:
return
connection_name = 'testCreateRenameDeleteFields'
plugin = createDbPlugin('gpkg')
uri = QgsDataSourceURI()
test_gpkg_new = os.path.join(self.basetestpath, 'testCreateRenameDeleteFields.gpkg')
shutil.copy(self.test_gpkg, test_gpkg_new)
uri.setDatabase(test_gpkg_new)
self.assertTrue(plugin.addConnection(connection_name, uri))
connection = createDbPlugin('gpkg', connection_name)
connection.connect()
db = connection.database()
self.assertIsNotNone(db)
tables = db.tables()
self.assertEqual(len(tables), 1)
table = tables[0]
field_before_count = len(table.fields())
field = TableField(table)
field.name = 'real_field'
field.dataType = 'DOUBLE'
self.assertTrue(table.addField(field))
self.assertEqual(len(table.fields()), field_before_count + 1)
self.assertTrue(field.update('real_field2', new_type_str='TEXT (30)', new_not_null=True, new_default_str='foo'))
field = table.fields()[field_before_count]
self.assertEqual(field.name, 'real_field2')
self.assertEqual(field.dataType, 'TEXT(30)')
self.assertEqual(field.notNull, 1)
self.assertEqual(field.default, "'foo'")
self.assertTrue(table.deleteField(field))
self.assertEqual(len(table.fields()), field_before_count)
connection.remove()
def testTableDataModel(self):
connection_name = 'testTableDataModel'
plugin = createDbPlugin('gpkg')
uri = QgsDataSourceURI()
uri.setDatabase(self.test_gpkg)
self.assertTrue(plugin.addConnection(connection_name, uri))
connection = createDbPlugin('gpkg', connection_name)
connection.connect()
db = connection.database()
self.assertIsNotNone(db)
tables = db.tables()
self.assertEqual(len(tables), 1)
table = tables[0]
self.assertEqual(table.name, 'testLayer')
model = table.tableDataModel(None)
self.assertEqual(model.rowCount(), 1)
self.assertEqual(model.getData(0, 0), 1) # fid
self.assertEqual(model.getData(0, 1), 'LINESTRING (1 2,3 4)')
self.assertEqual(model.getData(0, 2), 'foo')
connection.remove()
def testRaster(self):
if int(gdal.VersionInfo('VERSION_NUM')) < GDAL_COMPUTE_VERSION(2, 0, 2):
return
connection_name = 'testRaster'
plugin = createDbPlugin('gpkg')
uri = QgsDataSourceURI()
test_gpkg_new = os.path.join(self.basetestpath, 'testRaster.gpkg')
shutil.copy(self.test_gpkg, test_gpkg_new)
mem_ds = gdal.GetDriverByName('MEM').Create('', 20, 20)
mem_ds.SetGeoTransform([2, 0.01, 0, 49, 0, -0.01])
sr = osr.SpatialReference()
sr.ImportFromEPSG(4326)
mem_ds.SetProjection(sr.ExportToWkt())
mem_ds.GetRasterBand(1).Fill(255)
gdal.GetDriverByName('GPKG').CreateCopy(test_gpkg_new, mem_ds, options=['APPEND_SUBDATASET=YES', 'RASTER_TABLE=raster_table'])
mem_ds = None
uri.setDatabase(test_gpkg_new)
self.assertTrue(plugin.addConnection(connection_name, uri))
connection = createDbPlugin('gpkg', connection_name)
connection.connect()
db = connection.database()
self.assertIsNotNone(db)
tables = db.tables()
self.assertEqual(len(tables), 2)
table = None
for i in range(2):
if tables[i].name == 'raster_table':
table = tables[i]
break
self.assertIsNotNone(table)
info = table.info()
expected_html = """<div class="section"><h2>General info</h2><div><table><tr><td>Relation type: </td><td>Table </td></tr><tr><td>Rows: </td><td>Unknown (<a href="action:rows/count">find out</a>) </td></tr></table></div></div><div class="section"><h2>GeoPackage</h2><div><table><tr><td>Column: </td><td> </td></tr><tr><td>Geometry: </td><td>RASTER </td></tr><tr><td>Spatial ref: </td><td>WGS 84 geodetic (4326) </td></tr><tr><td>Extent: </td><td>2.00000, 48.80000 - 2.20000, 49.00000 </td></tr></table></div></div><div class="section"><h2>Fields</h2><div><table class="header"><tr><th># </th><th>Name </th><th>Type </th><th>Null </th><th>Default </th></tr><tr><td>0 </td><td class="underline">id </td><td>INTEGER </td><td>Y </td><td> </td></tr><tr><td>1 </td><td>zoom_level </td><td>INTEGER </td><td>N </td><td> </td></tr><tr><td>2 </td><td>tile_column </td><td>INTEGER </td><td>N </td><td> </td></tr><tr><td>3 </td><td>tile_row </td><td>INTEGER </td><td>N </td><td> </td></tr><tr><td>4 </td><td>tile_data </td><td>BLOB </td><td>N </td><td> </td></tr></table></div></div><div class="section"><h2>Indexes</h2><div><table class="header"><tr><th>Name </th><th>Column(s) </th></tr><tr><td>sqlite_autoindex_raster_table_1 </td><td>zoom_level<br>tile_column<br>tile_row </td></tr></table></div></div>"""
self.assertEqual(info.toHtml(), expected_html, info.toHtml())
connection.remove()
def testTwoRaster(self):
if int(gdal.VersionInfo('VERSION_NUM')) < GDAL_COMPUTE_VERSION(2, 0, 2):
return
connection_name = 'testTwoRaster'
plugin = createDbPlugin('gpkg')
uri = QgsDataSourceURI()
test_gpkg_new = os.path.join(self.basetestpath, 'testTwoRaster.gpkg')
shutil.copy(self.test_gpkg, test_gpkg_new)
mem_ds = gdal.GetDriverByName('MEM').Create('', 20, 20)
mem_ds.SetGeoTransform([2, 0.01, 0, 49, 0, -0.01])
sr = osr.SpatialReference()
sr.ImportFromEPSG(4326)
mem_ds.SetProjection(sr.ExportToWkt())
mem_ds.GetRasterBand(1).Fill(255)
for i in range(2):
gdal.GetDriverByName('GPKG').CreateCopy(test_gpkg_new, mem_ds, options=['APPEND_SUBDATASET=YES', 'RASTER_TABLE=raster_table%d' % (i + 1)])
mem_ds = None
uri.setDatabase(test_gpkg_new)
self.assertTrue(plugin.addConnection(connection_name, uri))
connection = createDbPlugin('gpkg', connection_name)
connection.connect()
db = connection.database()
self.assertIsNotNone(db)
tables = db.tables()
self.assertEqual(len(tables), 3)
table = None
for i in range(2):
if tables[i].name.startswith('raster_table'):
table = tables[i]
info = table.info()
info.toHtml()
connection.remove()
def testNonSpatial(self):
connection_name = 'testNonSpatial'
plugin = createDbPlugin('gpkg')
uri = QgsDataSourceURI()
test_gpkg = os.path.join(self.basetestpath, 'testNonSpatial.gpkg')
ds = ogr.GetDriverByName('GPKG').CreateDataSource(test_gpkg)
lyr = ds.CreateLayer('testNonSpatial', geom_type=ogr.wkbNone)
lyr.CreateField(ogr.FieldDefn('text_field', ogr.OFTString))
f = ogr.Feature(lyr.GetLayerDefn())
f['text_field'] = 'foo'
lyr.CreateFeature(f)
f = None
ds = None
uri.setDatabase(test_gpkg)
self.assertTrue(plugin.addConnection(connection_name, uri))
connection = createDbPlugin('gpkg', connection_name)
connection.connect()
db = connection.database()
self.assertIsNotNone(db)
tables = db.tables()
self.assertEqual(len(tables), 1)
table = tables[0]
self.assertEqual(table.name, 'testNonSpatial')
info = table.info()
expected_html = """<div class="section"><h2>General info</h2><div><table><tr><td>Relation type: </td><td>Table </td></tr><tr><td>Rows: </td><td>1 </td></tr></table></div></div><div class="section"><h2>Fields</h2><div><table class="header"><tr><th># </th><th>Name </th><th>Type </th><th>Null </th><th>Default </th></tr><tr><td>0 </td><td class="underline">fid </td><td>INTEGER </td><td>Y </td><td> </td></tr><tr><td>1 </td><td>text_field </td><td>TEXT </td><td>Y </td><td> </td></tr></table></div></div>"""
self.assertEqual(info.toHtml(), expected_html, info.toHtml())
connection.remove()
def testAllGeometryTypes(self):
connection_name = 'testAllGeometryTypes'
plugin = createDbPlugin('gpkg')
uri = QgsDataSourceURI()
test_gpkg = os.path.join(self.basetestpath, 'testAllGeometryTypes.gpkg')
ds = ogr.GetDriverByName('GPKG').CreateDataSource(test_gpkg)
ds.CreateLayer('testPoint', geom_type=ogr.wkbPoint)
ds.CreateLayer('testLineString', geom_type=ogr.wkbLineString)
ds.CreateLayer('testPolygon', geom_type=ogr.wkbPolygon)
ds.CreateLayer('testMultiPoint', geom_type=ogr.wkbMultiPoint)
ds.CreateLayer('testMultiLineString', geom_type=ogr.wkbMultiLineString)
ds.CreateLayer('testMultiPolygon', geom_type=ogr.wkbMultiPolygon)
ds.CreateLayer('testGeometryCollection', geom_type=ogr.wkbGeometryCollection)
if int(gdal.VersionInfo('VERSION_NUM')) >= GDAL_COMPUTE_VERSION(2, 0, 0):
ds.CreateLayer('testCircularString', geom_type=ogr.wkbCircularString)
ds.CreateLayer('testCompoundCurve', geom_type=ogr.wkbCompoundCurve)
ds.CreateLayer('testCurvePolygon', geom_type=ogr.wkbCurvePolygon)
ds.CreateLayer('testMultiCurve', geom_type=ogr.wkbMultiCurve)
ds.CreateLayer('testMultiSurface', geom_type=ogr.wkbMultiSurface)
ds = None
uri.setDatabase(test_gpkg)
self.assertTrue(plugin.addConnection(connection_name, uri))
connection = createDbPlugin('gpkg', connection_name)
connection.connect()
db = connection.database()
self.assertIsNotNone(db)
tables = db.tables()
for i in range(len(tables)):
table = tables[i]
info = table.info()
connection.remove()
if __name__ == '__main__':
unittest.main()