-
-
Notifications
You must be signed in to change notification settings - Fork 314
Expand file tree
/
Copy pathtest_postgresql_provider.py
More file actions
998 lines (816 loc) · 33.6 KB
/
test_postgresql_provider.py
File metadata and controls
998 lines (816 loc) · 33.6 KB
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
# =================================================================
#
# Authors: Just van den Broecke <justb4@gmail.com>
# Tom Kralidis <tomkralidis@gmail.com>
# John A Stevenson <jostev@bgs.ac.uk>
# Colin Blackburn <colb@bgs.ac.uk>
# Francesco Bartoli <xbartolone@gmail.com>
# Bernhard Mallinger <bernhard.mallinger@eox.at>
#
# Copyright (c) 2019 Just van den Broecke
# Copyright (c) 2025 Tom Kralidis
# Copyright (c) 2022 John A Stevenson and Colin Blackburn
# Copyright (c) 2025 Francesco Bartoli
# Copyright (c) 2024 Bernhard Mallinger
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# =================================================================
# Needs to be run like: python3 -m pytest
# Testing local postgis with docker:
'''
docker run --name postgis \
--rm \
-p 5432:5432 \
-e ALLOW_IP_RANGE=0.0.0.0/0 \
-e POSTGRES_USER=postgres \
-e POSTGRES_PASS=postgres \
-e POSTGRES_DBNAME=test \
-d -t kartoza/postgis
'''
# test database in Docker
from http import HTTPStatus
import os
import json
import pytest
import pyproj
from shapely.geometry import shape as geojson_to_geom
from pygeofilter.parsers.cql2_text import parse
from pygeoapi.api import API
from pygeoapi.api.itemtypes import (
get_collection_items, get_collection_item, manage_collection_item
)
from pygeoapi.crs import DEFAULT_CRS, get_transform_from_crs, get_crs
from pygeoapi.provider.base import (
ProviderConnectionError,
ProviderItemNotFoundError,
ProviderQueryError
)
from pygeoapi.provider.sql import PostgreSQLProvider
import pygeoapi.provider.sql as postgresql_provider_module
from pygeoapi.util import yaml_load
from ..util import get_test_file_path, mock_api_request
PASSWORD = os.environ.get('POSTGRESQL_PASSWORD', 'postgres')
@pytest.fixture(params=['default', 'connection_string'])
def config(request):
config_ = {
'name': 'PostgreSQL',
'type': 'feature',
'options': {'connect_timeout': 10},
'id_field': 'osm_id',
'table': 'hotosm_bdi_waterways',
'geom_field': 'foo_geom'
}
if request.param == 'default':
config_['data'] = {
'host': '127.0.0.1',
'dbname': 'test',
'user': 'postgres',
'password': PASSWORD,
'search_path': ['osm', 'public']
}
elif request.param == 'connection_string':
config_['data'] = (
f'postgresql://postgres:{PASSWORD}@127.0.0.1:5432/test'
)
config_['options']['search_path'] = ['osm', 'public']
return config_
@pytest.fixture(params=['default', 'connection_string'])
def config_types(request):
config_ = {
'name': 'PostgreSQL',
'type': 'feature',
'options': {'connect_timeout': 10},
'id_field': 'id',
'table': 'foo',
'geom_field': 'the_geom'
}
if request.param == 'default':
config_['data'] = {
'host': '127.0.0.1',
'dbname': 'test',
'user': 'postgres',
'password': PASSWORD,
'search_path': ['public', 'osm']
}
elif request.param == 'connection_string':
config_['data'] = (
f'postgresql://postgres:{PASSWORD}@127.0.0.1:5432/test'
)
config_['options']['search_path'] = ['public', 'osm']
return config_
@pytest.fixture()
def data():
return json.dumps({
'type': 'Feature',
'geometry': {
'type': 'MultiLineString',
'coordinates': [
[[100.0, 0.0], [101.0, 0.0]],
[[101.0, 0.0], [100.0, 1.0]],
]
},
'properties': {
'identifier': 123,
'name': 'Flowy McFlow',
'waterway': 'river'
}
})
@pytest.fixture()
def openapi():
with open(get_test_file_path('pygeoapi-test-openapi.yml')) as fh:
return yaml_load(fh)
# API using PostgreSQL provider
@pytest.fixture()
def pg_api_(openapi):
with open(get_test_file_path('pygeoapi-test-config-postgresql.yml')) as fh:
config = yaml_load(fh)
return API(config, openapi)
def test_valid_connection_options(config):
if config.get('options'):
keys = list(config['options'].keys())
for key in keys:
assert key in ['connect_timeout', 'tcp_user_timeout', 'keepalives',
'keepalives_idle', 'keepalives_count',
'keepalives_interval', 'search_path']
def test_schema_path_search(config):
if isinstance(config['data'], dict):
config['data']['search_path'] = ['public', 'osm']
else:
config['options']['search_path'] = ['public', 'osm']
PostgreSQLProvider(config)
if isinstance(config['data'], dict):
config['data']['search_path'] = ['public', 'notosm']
else:
config['options']['search_path'] = ['public', 'notosm']
with pytest.raises(ProviderQueryError):
PostgreSQLProvider(config)
def test_query(config):
"""Testing query for a valid JSON object with geometry"""
p = PostgreSQLProvider(config)
feature_collection = p.query()
assert feature_collection.get('type') == 'FeatureCollection'
features = feature_collection.get('features')
assert features is not None
feature = features[0]
properties = feature.get('properties')
assert properties is not None
properties_order = [
'osm_id', 'name', 'waterway', 'covered', 'width', 'depth', 'layer',
'blockage', 'tunnel', 'natural', 'water', 'z_index'
]
assert list(properties.keys()) == properties_order
geometry = feature.get('geometry')
assert geometry is not None
def test_query_materialised_view(config):
"""Testing query using a materialised view"""
config_materialised_view = config.copy()
config_materialised_view['table'] = 'hotosm_bdi_drains'
provider = PostgreSQLProvider(config_materialised_view)
# Only ID, width and depth properties should be available
assert set(provider.get_fields().keys()) == {'osm_id', 'width', 'depth'}
def test_query_with_property_filter(config):
"""Test query valid features when filtering by property"""
p = PostgreSQLProvider(config)
feature_collection = p.query(properties=[('waterway', 'stream')])
features = feature_collection.get('features')
stream_features = list(
filter(lambda feature: feature['properties']['waterway'] == 'stream',
features))
assert len(features) == len(stream_features)
feature_collection = p.query(limit=50)
features = feature_collection.get('features')
stream_features = list(
filter(lambda feature: feature['properties']['waterway'] == 'stream',
features))
other_features = list(
filter(lambda feature: feature['properties']['waterway'] != 'stream',
features))
assert len(features) != len(stream_features)
assert len(other_features) != 0
assert feature_collection['numberMatched'] == 14776
assert feature_collection['numberReturned'] == 50
def test_query_with_paging(config):
"""Test query valid features with paging"""
p = PostgreSQLProvider(config)
feature_collection = p.query(limit=50)
assert feature_collection['numberMatched'] == 14776
assert feature_collection['numberReturned'] == 50
offset = feature_collection['numberMatched'] - 10
feature_collection = p.query(offset=offset)
assert feature_collection['numberMatched'] == 14776
assert feature_collection['numberReturned'] == 10
def test_query_with_config_properties(config):
"""
Test that query is restricted by properties in the config.
No properties should be returned that are not requested.
Note that not all requested properties have to exist in the query result.
"""
properties_subset = ['name', 'waterway', 'width', 'does_not_exist']
config.update({'properties': properties_subset})
properties_subset.append('osm_id') # id_field is always included
provider = PostgreSQLProvider(config)
assert provider.properties == properties_subset
result = provider.query()
feature = result.get('features')[0]
properties = feature.get('properties')
for property_name in properties.keys():
assert property_name in config['properties']
@pytest.mark.parametrize('property_filter, expected', [
([], 14776),
([('waterway', 'stream')], 13930),
([('waterway', 'this does not exist')], 0),
])
def test_query_hits_with_property_filter(config, property_filter, expected):
"""Test query resulttype=hits"""
provider = PostgreSQLProvider(config)
results = provider.query(properties=property_filter, resulttype='hits')
assert results['numberMatched'] == expected
def test_query_bbox(config):
"""Test query with a specified bounding box"""
psp = PostgreSQLProvider(config)
boxed_feature_collection = psp.query(
bbox=[29.3373, -3.4099, 29.3761, -3.3924]
)
assert len(boxed_feature_collection['features']) == 5
def test_query_sortby(config):
"""Test query with sorting"""
psp = PostgreSQLProvider(config)
up = psp.query(sortby=[{'property': 'osm_id', 'order': '+'}])
assert up['features'][0]['id'] == 13990765
down = psp.query(sortby=[{'property': 'osm_id', 'order': '-'}])
assert down['features'][0]['id'] == 620735702
name = psp.query(sortby=[{'property': 'name', 'order': '+'}])
assert name['features'][0]['properties']['name'] == 'Agasasa'
def test_query_skip_geometry(config):
"""Test query without geometry"""
provider = PostgreSQLProvider(config)
result = provider.query(skip_geometry=True)
feature = result['features'][0]
assert feature['geometry'] is None
@pytest.mark.parametrize('properties', [
['name'],
['name', 'waterway'],
['name', 'waterway', 'this does not exist']
])
def test_query_select_properties(config, properties):
"""Test query with selected properties"""
provider = PostgreSQLProvider(config)
result = provider.query(select_properties=properties)
feature = result['features'][0]
expected = set(provider.get_fields().keys()).intersection(properties)
assert set(feature['properties'].keys()) == expected
@pytest.mark.parametrize('id_, prev, next_', [
(29701937, 29698243, 29704504),
(13990765, 13990765, 25469515), # First item, prev should be id_
(620735702, 620420337, 620735702), # Last item, next should be id_
])
def test_get_simple(config, id_, prev, next_):
"""Testing query for a specific object and identifying prev/next"""
p = PostgreSQLProvider(config)
result = p.get(id_)
assert result['id'] == id_
assert 'geometry' in result
assert 'properties' in result
assert result['type'] == 'Feature'
assert 'foo_geom' not in result['properties'] # geometry is separate
assert result['prev'] == prev
assert result['next'] == next_
def test_get_with_injection(config):
"""Testing query for injection attack string"""
p = PostgreSQLProvider(config)
feature = p.get('29701937')
assert feature.get('type') == 'Feature'
with pytest.raises(ProviderItemNotFoundError):
p.get('29701937; DROP TABLE location;')
with pytest.raises(ProviderItemNotFoundError):
p.get('29701937<script>alert("We love pygeoapi")</script>')
def test_get_with_config_properties(config):
"""
Test that get is restricted by properties in the config.
No properties should be returned that are not requested.
Note that not all requested properties have to exist in the query result.
"""
properties_subset = ['name', 'waterway', 'width', 'does_not_exist']
config.update({'properties': properties_subset})
provider = PostgreSQLProvider(config)
assert provider.properties == properties_subset
result = provider.get(80835483)
properties = result.get('properties')
for property_name in properties.keys():
assert property_name in config['properties']
def test_get_not_existing_item_raise_exception(config):
"""Testing query for a not existing object"""
p = PostgreSQLProvider(config)
with pytest.raises(ProviderItemNotFoundError):
p.get(-1)
@pytest.mark.parametrize('cql, expected_ids', [
("osm_id BETWEEN 80800000 AND 80900000",
[80827787, 80827793, 80835468, 80835470, 80835472, 80835474,
80835475, 80835478, 80835483, 80835486]),
("osm_id BETWEEN 80800000 AND 80900000 AND waterway = 'stream'",
[80835470]),
("osm_id BETWEEN 80800000 AND 80900000 AND CASEI(waterway) LIKE 'sTrEam'",
[80835470]),
("osm_id BETWEEN 80800000 AND 80900000 AND waterway LIKE 's%'",
[80835470]),
("osm_id BETWEEN 80800000 AND 80900000 AND name IN ('Muhira', 'Mpanda')",
[80835468, 80835472, 80835475, 80835478]),
("osm_id BETWEEN 80800000 AND 80900000 AND name IS NULL",
[80835474, 80835483]),
("osm_id BETWEEN 80800000 AND 80900000 AND BBOX(foo_geom, 29, -2.8, 29.2, -2.9)", # noqa
[80827793, 80835470, 80835472, 80835483, 80835489]),
("osm_id BETWEEN 80800000 AND 80900000 AND "
"CROSSES(foo_geom, LINESTRING(29.091 -2.731, 29.253 -2.845))",
[80835470, 80835472, 80835489])
])
def test_query_cql(config, cql, expected_ids):
"""Test a variety of CQL queries"""
ast = parse(cql)
provider = PostgreSQLProvider(config)
feature_collection = provider.query(filterq=ast)
assert feature_collection.get('type') == 'FeatureCollection'
features = feature_collection.get('features')
ids = [feature['id'] for feature in features]
assert ids == expected_ids
def test_query_cql_properties_bbox_filters(config):
"""Test query with CQL, properties and bbox filters"""
# Arrange
properties = [('waterway', 'stream')]
bbox = [29, -2.8, 29.2, -2.9]
filterq = parse('osm_id BETWEEN 80800000 AND 80900000')
expected_ids = [80835470]
# Act
provider = PostgreSQLProvider(config)
feature_collection = provider.query(filterq=filterq,
properties=properties,
bbox=bbox)
# Assert
ids = [feature['id'] for feature in feature_collection.get('features')]
assert ids == expected_ids
def test_bbox_is_same_as_cql(config):
provider = PostgreSQLProvider(config)
bbox = [30.560389, -3.134991, 30.604849, -3.061970]
fc_bbox = provider.query(bbox=bbox)
bbox_cql = parse('BBOX(foo_geom, {}, {}, {}, {})'.format(*bbox))
fc_bbox_cql = provider.query(filterq=bbox_cql)
assert fc_bbox == fc_bbox_cql
def test_get_fields_types(config_types):
provider = PostgreSQLProvider(config_types)
expected_fields = {
'id': {'type': 'integer', 'format': None},
'field1': {'type': 'number', 'format': None},
'field2': {'type': 'string', 'format': None},
'field3': {'type': 'number', 'format': None},
'dt': {'type': 'string', 'format': 'date-time'}
}
assert provider.get_fields() == expected_fields
assert provider.fields == expected_fields # API uses .fields attribute
def test_get_fields(config):
# Arrange
expected_fields = {
'blockage': {'type': 'string', 'format': None},
'covered': {'type': 'string', 'format': None},
'depth': {'type': 'string', 'format': None},
'layer': {'type': 'string', 'format': None},
'name': {'type': 'string', 'format': None},
'natural': {'type': 'string', 'format': None},
'osm_id': {'type': 'integer', 'format': None},
'tunnel': {'type': 'string', 'format': None},
'water': {'type': 'string', 'format': None},
'waterway': {'type': 'string', 'format': None},
'width': {'type': 'string', 'format': None},
'z_index': {'type': 'string', 'format': None}
}
# Act
provider = PostgreSQLProvider(config)
# Assert
assert provider.get_fields() == expected_fields
assert provider.fields == expected_fields # API uses .fields attribute
def test_instantiation(config):
"""Test attributes are correctly set during instantiation."""
# Act
provider = PostgreSQLProvider(config)
# Assert
assert provider.name == 'PostgreSQL'
assert provider.table == 'hotosm_bdi_waterways'
assert provider.id_field == 'osm_id'
@pytest.mark.parametrize('bad_data, exception, match', [
({'table': 'bad_table'}, ProviderQueryError,
'Table.*not found in schema.*'),
({'data': {'bad': 'data'}}, ProviderConnectionError,
r'Could not connect to postgresql\+psycopg2:\/\/:5432 \(password hidden\).'), # noqa
({'id_field': 'bad_id'}, ProviderQueryError,
r'No such id_field column \(bad_id\) on osm.hotosm_bdi_waterways.'),
])
def test_instantiation_with_bad_config(config, bad_data, exception, match):
# Arrange
config.update(bad_data)
# Make sure we don't use a cached connection or model in the tests
postgresql_provider_module._ENGINE_STORE = {}
postgresql_provider_module._TABLE_MODEL_STORE = {}
# Act and assert
with pytest.raises(exception, match=match):
PostgreSQLProvider(config)
def test_instantiation_with_bad_credentials(config):
# Arrange
if isinstance(config['data'], dict):
config['data'].update({'user': 'bad_user'})
match = r'Could not connect to .*bad_user:\*\*\*@'
else:
config['data'] = config['data'].replace('postgres:', 'bad_user:')
match = r'Could not connect to .*bad_user:\*\*\*@'
# Make sure we don't use a cached connection in the tests
postgresql_provider_module._ENGINE_STORE = {}
# Act and assert
with pytest.raises(ProviderConnectionError, match=match):
PostgreSQLProvider(config)
def test_engine_and_table_model_stores(config):
provider0 = PostgreSQLProvider(config)
# Same config should return same engine and table_model
provider1 = PostgreSQLProvider(config)
assert repr(provider1._engine) == repr(provider0._engine)
assert provider1._engine is provider0._engine
assert provider1.table_model is provider0.table_model
# Same database connection details, but different table
different_table = config.copy()
different_table.update(table='hotosm_bdi_drains')
provider2 = PostgreSQLProvider(different_table)
assert repr(provider2._engine) == repr(provider0._engine)
assert provider2._engine is provider0._engine
assert provider2.table_model is not provider0.table_model
# Although localhost is 127.0.0.1, this should get different engine
# and also a different table_model, as two databases may have different
# tables with the same name
different_host = config.copy()
if isinstance(config['data'], dict):
different_host['data']['host'] = 'localhost'
else:
different_host['data'] = config['data'].replace(
'127.0.0.1', 'localhost')
provider3 = PostgreSQLProvider(different_host)
assert provider3._engine is not provider0._engine
assert provider3.table_model is not provider0.table_model
# START: EXTERNAL API TESTS
def test_get_collection_items_postgresql_cql(pg_api_):
"""
Test for PostgreSQL CQL - requires local PostgreSQL with appropriate
data. See pygeoapi/provider/postgresql.py for details.
"""
# Arrange
cql_query = 'osm_id BETWEEN 80800000 AND 80900000 AND name IS NULL'
expected_ids = [80835474, 80835483]
# Act
req = mock_api_request({
'filter-lang': 'cql-text',
'filter': cql_query
})
rsp_headers, code, response = get_collection_items(
pg_api_, req, 'hot_osm_waterways')
# Assert
assert code == HTTPStatus.OK
features = json.loads(response)
ids = [item['id'] for item in features['features']]
assert ids == expected_ids
# Act, no filter-lang
req = mock_api_request({
'filter': cql_query
})
rsp_headers, code, response = get_collection_items(
pg_api_, req, 'hot_osm_waterways')
# Assert
assert code == HTTPStatus.OK
features = json.loads(response)
ids = [item['id'] for item in features['features']]
assert ids == expected_ids
def test_get_collection_items_postgresql_cql_invalid_filter_language(pg_api_):
"""
Test for PostgreSQL CQL - requires local PostgreSQL with appropriate
data. See pygeoapi/provider/postgresql.py for details.
Test for invalid filter language
"""
# Arrange
cql_query = 'osm_id BETWEEN 80800000 AND 80900000 AND name IS NULL'
# Act
req = mock_api_request({
'filter-lang': 'cql-jsonfoo',
'filter': cql_query
})
rsp_headers, code, response = get_collection_items(
pg_api_, req, 'hot_osm_waterways')
# Assert
assert code == HTTPStatus.BAD_REQUEST
error_response = json.loads(response)
assert error_response['code'] == 'InvalidParameterValue'
assert error_response['description'] == 'Invalid filter language'
@pytest.mark.parametrize('bad_cql', [
'id IN (1, ~)',
'id EATS (1, 2)', # Valid CQL relations only
'id IN (1, 2' # At some point this may return UnexpectedEOF
])
def test_get_collection_items_postgresql_cql_bad_cql(pg_api_, bad_cql):
"""
Test for PostgreSQL CQL - requires local PostgreSQL with appropriate
data. See pygeoapi/provider/postgresql.py for details.
Test for bad cql
"""
# Act
req = mock_api_request({
'filter': bad_cql
})
rsp_headers, code, response = get_collection_items(
pg_api_, req, 'hot_osm_waterways')
# Assert
assert code == HTTPStatus.BAD_REQUEST
error_response = json.loads(response)
assert error_response['code'] == 'InvalidParameterValue'
assert error_response['description'] == 'Bad CQL text'
def test_get_collection_items_postgresql_cql_json(pg_api_):
"""
Test for PostgreSQL CQL - requires local PostgreSQL with appropriate
data. See pygeoapi/provider/postgresql.py for details.
"""
# Arrange
cql = {
'op': 'and',
'args': [{
'op': 'between',
'args': [
{'property': 'osm_id'},
[80800000, 80900000]
]
}, {
# FIXME: the below query is in CQL style, not CQL2
# needs a fix in pygeofilter
# 'op': 'isNull',
# 'args': [
# {'property': 'name'}
# ]
'op': 'isNull',
'args': {'property': 'name'}
}]
}
# werkzeug requests use a value of CONTENT_TYPE 'application/json'
# to create Content-Type in the Request object. So here we need to
# overwrite the default CONTENT_TYPE with the required one.
headers = {'CONTENT_TYPE': 'application/query-cql-json'}
expected_ids = [80835474, 80835483]
# Act
req = mock_api_request({
'filter-lang': 'cql-json'
}, data=cql, **headers)
rsp_headers, code, response = get_collection_items(
pg_api_, req, 'hot_osm_waterways')
# Assert
assert code == HTTPStatus.OK
features = json.loads(response)
ids = [item['id'] for item in features['features']]
assert ids == expected_ids
def test_get_collection_items_postgresql_cql_json_invalid_filter_language(pg_api_): # noqa
"""
Test for PostgreSQL CQL - requires local PostgreSQL with appropriate
data. See pygeoapi/provider/postgresql.py for details.
Test for invalid filter language
"""
# Arrange
# CQL should never be parsed
cql = {'in': {'value': {'property': 'id'}, 'list': [1, 2]}}
headers = {'CONTENT_TYPE': 'application/query-cql-json'}
# Act
req = mock_api_request({
'filter-lang': 'cql-text' # Only cql-json is valid for POST
}, data=cql, **headers)
rsp_headers, code, response = get_collection_items(
pg_api_, req, 'hot_osm_waterways')
# Assert
assert code == HTTPStatus.BAD_REQUEST
error_response = json.loads(response)
assert error_response['code'] == 'InvalidParameterValue'
assert error_response['description'] == 'Bad CQL JSON'
@pytest.mark.parametrize('bad_cql', [
# Valid CQL relations only
{'eats': {'value': {'property': 'id'}, 'list': [1, 2]}},
# At some point this may return UnexpectedEOF
'{"in": {"value": {"property": "id"}, "list": [1, 2}}'
])
def test_get_collection_items_postgresql_cql_json_bad_cql(pg_api_, bad_cql):
"""
Test for PostgreSQL CQL - requires local PostgreSQL with appropriate
data. See pygeoapi/provider/postgresql.py for details.
Test for bad cql
"""
# Arrange
headers = {'CONTENT_TYPE': 'application/query-cql-json'}
# Act
req = mock_api_request({
'filter-lang': 'cql-json'
}, data=bad_cql, **headers)
rsp_headers, code, response = get_collection_items(
pg_api_, req, 'hot_osm_waterways')
# Assert
assert code == HTTPStatus.BAD_REQUEST
error_response = json.loads(response)
assert error_response['code'] == 'InvalidParameterValue'
assert error_response['description'] == 'Bad CQL JSON'
def test_get_collection_items_postgresql_crs(pg_api_):
"""Test the coordinates transformation implementation of
PostgreSQLProvider when using the crs parameter.
"""
storage_crs = DEFAULT_CRS
crs_32735 = 'http://www.opengis.net/def/crs/EPSG/0/32735'
# Without CRS query parameter -> no coordinates transformation
req = mock_api_request({'bbox': '29.0,-2.85,29.05,-2.8'})
rsp_headers, code, response = get_collection_items(
pg_api_, req, 'hot_osm_waterways')
assert code == HTTPStatus.OK
features_orig = json.loads(response)
assert rsp_headers['Content-Crs'] == f'<{DEFAULT_CRS}>'
# With CRS query parameter not resulting in coordinates transformation
# (i.e. 'crs' query parameter is the same as 'storage_crs')
req = mock_api_request(
{'crs': storage_crs, 'bbox': '29.0,-2.85,29.05,-2.8'})
rsp_headers, code, response = get_collection_items(
pg_api_, req, 'hot_osm_waterways')
assert code == HTTPStatus.OK
assert rsp_headers['Content-Crs'] == f'<{storage_crs}>'
features_storage_crs = json.loads(response)
# With CRS query parameter resulting in coordinates transformation
req = mock_api_request({'crs': crs_32735, 'bbox': '29.0,-2.85,29.05,-2.8'})
rsp_headers, code, response = get_collection_items(
pg_api_, req, 'hot_osm_waterways')
assert code == HTTPStatus.OK
assert rsp_headers['Content-Crs'] == f'<{crs_32735}>'
features_32735 = json.loads(response)
# Make sure that we compare the same features
assert (
sorted(f['id'] for f in features_orig['features'])
== sorted(f['id'] for f in features_storage_crs['features'])
== sorted(f['id'] for f in features_32735['features'])
)
# Without 'crs' query parameter or with 'crs' set to 'storage_crs', the
# geometries of the returned features should be the same
for feat_orig in features_orig['features']:
id_ = feat_orig['id']
for feat_storage_crs in features_storage_crs['features']:
if id_ == feat_storage_crs['id']:
assert feat_orig['geometry'] == feat_storage_crs['geometry']
break
transform_func = get_transform_from_crs(
get_crs(DEFAULT_CRS),
pyproj.CRS.from_epsg(32735)
)
# Check that the coordinates of returned features were transformed
for feat_orig in features_orig['features']:
id_ = feat_orig['id']
geom_orig = geojson_to_geom(feat_orig['geometry'])
for feat_32735 in features_32735['features']:
if id_ == feat_32735['id']:
geom_32735 = geojson_to_geom(feat_32735['geometry'])
assert geom_32735.equals_exact(transform_func(geom_orig), 1)
break
def test_get_collection_item_postgresql_crs(pg_api_):
"""Test the coordinates transformation implementation of
PostgreSQLProvider when using the crs parameter.
"""
storage_crs = DEFAULT_CRS
crs_32735 = 'http://www.opengis.net/def/crs/EPSG/0/32735'
# List of feature IDs located in UTM zone 35S
fid_list = [
'439338397',
'198190856',
'93063941',
'586449587',
'80827793',
'587350255',
'586994284',
'587960337',
'586449586',
'422440125',
]
for fid in fid_list:
# Without CRS query parameter -> no coordinates transformation
req = mock_api_request({'f': 'json'})
rsp_headers, code, response = get_collection_item(
pg_api_, req, 'hot_osm_waterways', fid)
assert code == HTTPStatus.OK
assert rsp_headers['Content-Crs'] == f'<{DEFAULT_CRS}>'
feat_orig = json.loads(response)
geom_orig = geojson_to_geom(feat_orig['geometry'])
# With CRS query parameter not resulting in coordinates transformation
# (i.e. 'crs' query parameter is the same as 'storage_crs')
req = mock_api_request({'f': 'json', 'crs': storage_crs})
rsp_headers, code, response = get_collection_item(
pg_api_, req, 'hot_osm_waterways', fid)
assert code == HTTPStatus.OK
assert rsp_headers['Content-Crs'] == f'<{storage_crs}>'
feat_storage_crs = json.loads(response)
# Without 'crs' query parameter or with 'crs' set to 'storage_crs', the
# geometries should be identical, when storage CRS is WGS84 lon,lat.
assert feat_orig['geometry'] == feat_storage_crs['geometry']
# With CRS query parameter resulting in coordinates transformation
req = mock_api_request({'f': 'json', 'crs': crs_32735})
rsp_headers, code, response = get_collection_item(
pg_api_, req, 'hot_osm_waterways', fid)
assert code == HTTPStatus.OK
assert rsp_headers['Content-Crs'] == f'<{crs_32735}>'
feat_32735 = json.loads(response)
geom_32735 = geojson_to_geom(feat_32735['geometry'])
transform_func = get_transform_from_crs(
get_crs(DEFAULT_CRS),
pyproj.CRS.from_epsg(32735),
always_xy=False,
)
# Check that the coordinates of returned feature were transformed
assert geom_32735.equals_exact(transform_func(geom_orig), 1)
def test_get_collection_items_postgresql_automap_naming_conflicts(pg_api_):
"""
Test that PostgreSQLProvider can handle naming conflicts when automapping
classes and relationships from database schema.
"""
req = mock_api_request()
rsp_headers, code, response = get_collection_items(
pg_api_, req, 'dummy_naming_conflicts')
assert code == HTTPStatus.OK
features = json.loads(response).get('features')
assert len(features) == 0
def test_transaction_basic_workflow(pg_api_, data):
# create
req = mock_api_request(data=data)
headers, code, content = manage_collection_item(
pg_api_, req, action='create', dataset='hot_osm_waterways')
assert code == HTTPStatus.CREATED
# update
data_parsed = json.loads(data)
new_name = data_parsed['properties']['name'] + ' Flow'
data_parsed['properties']['name'] = new_name
req = mock_api_request(data=json.dumps(data_parsed))
headers, code, content = manage_collection_item(
pg_api_, req, action='update', dataset='hot_osm_waterways',
identifier=123)
assert code == HTTPStatus.NO_CONTENT
# verify update
req = mock_api_request()
headers, code, content = get_collection_item(
pg_api_, req, 'hot_osm_waterways', 123)
assert json.loads(content)['properties']['name'] == new_name
# delete
req = mock_api_request(data=data)
headers, code, content = manage_collection_item(
pg_api_, req, action='delete', dataset='hot_osm_waterways',
identifier=123)
assert code == HTTPStatus.OK
# delete again (item should not be in backend)
req = mock_api_request(data=data)
headers, code, content = manage_collection_item(
pg_api_, req, action='delete', dataset='hot_osm_waterways',
identifier=123)
assert code == HTTPStatus.NOT_FOUND
def test_transaction_create_handles_invalid_input_data(pg_api_, data):
data_parsed = json.loads(data)
data_parsed['properties']['invalid-column'] = 'foo'
req = mock_api_request(data=json.dumps(data_parsed))
headers, code, content = manage_collection_item(
pg_api_, req, action='create', dataset='hot_osm_waterways')
assert 'generic error' in content
def test_provider_count_default_value(config):
# Arrange
provider = PostgreSQLProvider(config)
# Act
results = provider.query()
# Assert
assert results['numberMatched'] == 14776
def test_provider_count_false(config):
# Arrange
config['count'] = 'false'
provider = PostgreSQLProvider(config)
# Act
results = provider.query()
# Assert
assert 'numberMatched' not in results
def test_provider_count_false_with_resulttype_hits(config):
# Arrange
config['count'] = 'false'
provider = PostgreSQLProvider(config)
# Act
results = provider.query(resulttype='hits')
# Assert
assert results['numberMatched'] == 14776