forked from geopython/pygeoapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_api.py
More file actions
2262 lines (1814 loc) · 82.9 KB
/
test_api.py
File metadata and controls
2262 lines (1814 loc) · 82.9 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
999
1000
# =================================================================
#
# Authors: Tom Kralidis <tomkralidis@gmail.com>
# John A Stevenson <jostev@bgs.ac.uk>
# Colin Blackburn <colb@bgs.ac.uk>
#
# Copyright (c) 2023 Tom Kralidis
# Copyright (c) 2022 John A Stevenson and Colin Blackburn
#
# 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.
#
# =================================================================
import copy
import json
import logging
import time
import gzip
from http import HTTPStatus
from unittest import mock
from pyld import jsonld
import pytest
import pyproj
from shapely.geometry import Point
from pygeoapi.api import (
API, APIRequest, FORMAT_TYPES, validate_bbox, validate_datetime,
validate_subset, F_HTML, F_JSON, F_JSONLD, F_GZIP, __version__
)
from pygeoapi.util import (yaml_load, get_crs_from_uri,
get_api_rules, get_base_url)
from .util import (get_test_file_path, mock_request,
mock_flask, mock_starlette)
from pygeoapi.models.provider.base import TileMatrixSetEnum
LOGGER = logging.getLogger(__name__)
@pytest.fixture()
def config():
with open(get_test_file_path('pygeoapi-test-config.yml')) as fh:
return yaml_load(fh)
@pytest.fixture()
def config_with_rules() -> dict:
""" Returns a pygeoapi configuration with default API rules. """
with open(get_test_file_path('pygeoapi-test-config-apirules.yml')) as fh:
return yaml_load(fh)
@pytest.fixture()
def config_enclosure() -> dict:
""" Returns a pygeoapi configuration with enclosure links. """
with open(get_test_file_path('pygeoapi-test-config-enclosure.yml')) as fh:
return yaml_load(fh)
@pytest.fixture()
def config_hidden_resources():
filename = 'pygeoapi-test-config-hidden-resources.yml'
with open(get_test_file_path(filename)) as fh:
return yaml_load(fh)
@pytest.fixture()
def openapi():
with open(get_test_file_path('pygeoapi-test-openapi.yml')) as fh:
return yaml_load(fh)
@pytest.fixture()
def api_(config, openapi):
return API(config, openapi)
@pytest.fixture()
def enclosure_api(config_enclosure, openapi):
""" Returns an API instance with a collection with enclosure links. """
return API(config_enclosure, openapi)
@pytest.fixture()
def rules_api(config_with_rules, openapi):
""" Returns an API instance with URL prefix and strict slashes policy.
The API version is extracted from the current version here.
"""
return API(config_with_rules, openapi)
@pytest.fixture()
def api_hidden_resources(config_hidden_resources, openapi):
return API(config_hidden_resources, openapi)
def test_apirequest(api_):
# Test without (valid) locales
with pytest.raises(ValueError):
req = mock_request()
APIRequest(req, [])
APIRequest(req, None)
APIRequest(req, ['zz'])
# Test all supported formats from query args
for f, mt in FORMAT_TYPES.items():
req = mock_request({'f': f})
apireq = APIRequest(req, api_.locales)
assert apireq.is_valid()
assert apireq.format == f
assert apireq.get_response_headers()['Content-Type'] == mt
# Test all supported formats from Accept header
for f, mt in FORMAT_TYPES.items():
req = mock_request(HTTP_ACCEPT=mt)
apireq = APIRequest(req, api_.locales)
assert apireq.is_valid()
assert apireq.format == f
assert apireq.get_response_headers()['Content-Type'] == mt
# Test nonsense format
req = mock_request({'f': 'foo'})
apireq = APIRequest(req, api_.locales)
assert not apireq.is_valid()
assert apireq.format == 'foo'
assert apireq.is_valid(('foo',))
assert apireq.get_response_headers()['Content-Type'] == \
FORMAT_TYPES[F_JSON]
# Test without format
req = mock_request()
apireq = APIRequest(req, api_.locales)
assert apireq.is_valid()
assert apireq.format is None
assert apireq.get_response_headers()['Content-Type'] == \
FORMAT_TYPES[F_JSON]
assert apireq.get_linkrel(F_JSON) == 'self'
assert apireq.get_linkrel(F_HTML) == 'alternate'
# Test complex format string
hh = 'text/html,application/xhtml+xml,application/xml;q=0.9,'
req = mock_request(HTTP_ACCEPT=hh)
apireq = APIRequest(req, api_.locales)
assert apireq.is_valid()
assert apireq.format == F_HTML
assert apireq.get_response_headers()['Content-Type'] == \
FORMAT_TYPES[F_HTML]
assert apireq.get_linkrel(F_HTML) == 'self'
assert apireq.get_linkrel(F_JSON) == 'alternate'
# Test accept header with multiple valid formats
hh = 'plain/text,application/ld+json,application/json;q=0.9,'
req = mock_request(HTTP_ACCEPT=hh)
apireq = APIRequest(req, api_.locales)
assert apireq.is_valid()
assert apireq.format == F_JSONLD
assert apireq.get_response_headers()['Content-Type'] == \
FORMAT_TYPES[F_JSONLD]
assert apireq.get_linkrel(F_JSONLD) == 'self'
assert apireq.get_linkrel(F_HTML) == 'alternate'
# Overrule HTTP content negotiation
req = mock_request({'f': 'html'}, HTTP_ACCEPT='application/json') # noqa
apireq = APIRequest(req, api_.locales)
assert apireq.is_valid()
assert apireq.format == F_HTML
assert apireq.get_response_headers()['Content-Type'] == \
FORMAT_TYPES[F_HTML]
# Test data
for d in (None, '', 'test', {'key': 'value'}):
req = mock_request(data=d)
apireq = APIRequest.with_data(req, api_.locales)
if not d:
assert apireq.data == b''
elif isinstance(d, dict):
assert d == json.loads(apireq.data)
else:
assert apireq.data == d.encode()
# Test multilingual
test_lang = {
'nl': ('en', 'en-US'), # unsupported lang should return default
'en-US': ('en', 'en-US'),
'de_CH': ('en', 'en-US'),
'fr-CH, fr;q=0.9, en;q=0.8': ('fr', 'fr-CA'),
'fr-CH, fr-BE;q=0.9': ('fr', 'fr-CA'),
}
sup_lang = ('en-US', 'fr_CA')
for lang_in, (lang_out, cl_out) in test_lang.items():
# Using l query parameter
req = mock_request({'lang': lang_in})
apireq = APIRequest(req, sup_lang)
assert apireq.raw_locale == lang_in
assert apireq.locale.language == lang_out
assert apireq.get_response_headers()['Content-Language'] == cl_out
# Using Accept-Language header
req = mock_request(HTTP_ACCEPT_LANGUAGE=lang_in)
apireq = APIRequest(req, sup_lang)
assert apireq.raw_locale == lang_in
assert apireq.locale.language == lang_out
assert apireq.get_response_headers()['Content-Language'] == cl_out
# Test language override
req = mock_request({'lang': 'fr'}, HTTP_ACCEPT_LANGUAGE='en_US')
apireq = APIRequest(req, sup_lang)
assert apireq.raw_locale == 'fr'
assert apireq.locale.language == 'fr'
assert apireq.get_response_headers()['Content-Language'] == 'fr-CA'
# Test locale territory
req = mock_request({'lang': 'en-GB'})
apireq = APIRequest(req, sup_lang)
assert apireq.raw_locale == 'en-GB'
assert apireq.locale.language == 'en'
assert apireq.locale.territory == 'US'
assert apireq.get_response_headers()['Content-Language'] == 'en-US'
# Test without Accept-Language header or 'lang' query parameter
# (should return default language from YAML config)
req = mock_request()
apireq = APIRequest(req, api_.locales)
assert apireq.raw_locale is None
assert apireq.locale.language == api_.default_locale.language
assert apireq.get_response_headers()['Content-Language'] == 'en-US'
# Test without Accept-Language header or 'lang' query param
# (should return first in custom list of languages)
sup_lang = ('de', 'fr', 'en')
apireq = APIRequest(req, sup_lang)
assert apireq.raw_locale is None
assert apireq.locale.language == 'de'
assert apireq.get_response_headers()['Content-Language'] == 'de'
def test_apirules_active(config_with_rules, rules_api):
assert rules_api.config == config_with_rules
rules = get_api_rules(config_with_rules)
base_url = get_base_url(config_with_rules)
# Test Flask
flask_prefix = rules.get_url_prefix('flask')
with mock_flask('pygeoapi-test-config-apirules.yml') as flask_client:
# Test happy path
response = flask_client.get(f'{flask_prefix}/conformance')
assert response.status_code == 200
assert response.headers['X-API-Version'] == __version__
assert response.request.url == \
flask_client.application.url_for('pygeoapi.conformance')
response = flask_client.get(f'{flask_prefix}/static/img/pygeoapi.png')
assert response.status_code == 200
# Test that static resources also work without URL prefix
response = flask_client.get('/static/img/pygeoapi.png')
assert response.status_code == 200
# Test strict slashes
response = flask_client.get(f'{flask_prefix}/conformance/')
assert response.status_code == 404
# For the landing page ONLY, trailing slashes are actually preferred.
# See https://docs.opengeospatial.org/is/17-069r4/17-069r4.html#_api_landing_page # noqa
# Omitting the trailing slash should lead to a redirect.
response = flask_client.get(f'{flask_prefix}/')
assert response.status_code == 200
response = flask_client.get(flask_prefix)
assert response.status_code in (307, 308)
# Test links on landing page for correct URLs
response = flask_client.get(flask_prefix, follow_redirects=True)
assert response.status_code == 200
assert response.is_json
links = response.json['links']
assert all(
href.startswith(base_url) for href in (rel['href'] for rel in links) # noqa
)
# Test Starlette
starlette_prefix = rules.get_url_prefix('starlette')
with mock_starlette('pygeoapi-test-config-apirules.yml') as starlette_client: # noqa
# Test happy path
response = starlette_client.get(f'{starlette_prefix}/conformance')
assert response.status_code == 200
assert response.headers['X-API-Version'] == __version__
response = starlette_client.get(f'{starlette_prefix}/static/img/pygeoapi.png') # noqa
assert response.status_code == 200
# Test that static resources also work without URL prefix
response = starlette_client.get('/static/img/pygeoapi.png')
assert response.status_code == 200
# Test strict slashes
response = starlette_client.get(f'{starlette_prefix}/conformance/')
assert response.status_code == 404
# For the landing page ONLY, trailing slashes are actually preferred.
# See https://docs.opengeospatial.org/is/17-069r4/17-069r4.html#_api_landing_page # noqa
# Omitting the trailing slash should lead to a redirect.
response = starlette_client.get(f'{starlette_prefix}/')
assert response.status_code == 200
response = starlette_client.get(starlette_prefix)
assert response.status_code in (307, 308)
# Test links on landing page for correct URLs
response = starlette_client.get(starlette_prefix, follow_redirects=True) # noqa
assert response.status_code == 200
links = response.json()['links']
assert all(
href.startswith(base_url) for href in (rel['href'] for rel in links) # noqa
)
def test_apirules_inactive(config, api_):
assert api_.config == config
rules = get_api_rules(config)
# Test Flask
flask_prefix = rules.get_url_prefix('flask')
assert flask_prefix == ''
with mock_flask('pygeoapi-test-config.yml') as flask_client:
response = flask_client.get('')
assert response.status_code == 200
response = flask_client.get('/conformance')
assert response.status_code == 200
assert 'X-API-Version' not in response.headers
assert response.request.url == \
flask_client.application.url_for('pygeoapi.conformance')
response = flask_client.get('/static/img/pygeoapi.png')
assert response.status_code == 200
# Test trailing slashes
response = flask_client.get('/')
assert response.status_code == 200
response = flask_client.get('/conformance/')
assert response.status_code == 200
assert 'X-API-Version' not in response.headers
# Test Starlette
starlette_prefix = rules.get_url_prefix('starlette')
assert starlette_prefix == ''
with mock_starlette('pygeoapi-test-config.yml') as starlette_client:
response = starlette_client.get('')
assert response.status_code == 200
response = starlette_client.get('/conformance')
assert response.status_code == 200
assert 'X-API-Version' not in response.headers
assert str(response.url) == f"{starlette_client.base_url}/conformance"
response = starlette_client.get('/static/img/pygeoapi.png')
assert response.status_code == 200
# Test trailing slashes
response = starlette_client.get('/')
assert response.status_code == 200
response = starlette_client.get('/conformance/', follow_redirects=True)
assert response.status_code == 200
assert 'X-API-Version' not in response.headers
def test_api(config, api_, openapi):
assert api_.config == config
assert isinstance(api_.config, dict)
req = mock_request(HTTP_ACCEPT='application/json')
rsp_headers, code, response = api_.openapi_(req)
assert rsp_headers['Content-Type'] == 'application/vnd.oai.openapi+json;version=3.0' # noqa
# No language requested: should be set to default from YAML
assert rsp_headers['Content-Language'] == 'en-US'
root = json.loads(response)
assert isinstance(root, dict)
a = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
req = mock_request(HTTP_ACCEPT=a)
rsp_headers, code, response = api_.openapi_(req)
assert rsp_headers['Content-Type'] == FORMAT_TYPES[F_HTML] == \
FORMAT_TYPES[F_HTML]
assert 'Swagger UI' in response
a = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
req = mock_request({'ui': 'redoc'}, HTTP_ACCEPT=a)
rsp_headers, code, response = api_.openapi_(req)
assert rsp_headers['Content-Type'] == FORMAT_TYPES[F_HTML] == \
FORMAT_TYPES[F_HTML]
assert 'ReDoc' in response
req = mock_request({'f': 'foo'})
rsp_headers, code, response = api_.openapi_(req)
assert rsp_headers['Content-Language'] == 'en-US'
assert code == HTTPStatus.BAD_REQUEST
assert api_.get_collections_url() == 'http://localhost:5000/collections'
def test_api_exception(config, api_):
req = mock_request({'f': 'foo'})
rsp_headers, code, response = api_.landing_page(req)
assert rsp_headers['Content-Language'] == 'en-US'
assert code == HTTPStatus.BAD_REQUEST
# When a language is set, the exception should still be English
req = mock_request({'f': 'foo', 'lang': 'fr'})
rsp_headers, code, response = api_.landing_page(req)
assert rsp_headers['Content-Language'] == 'en-US'
assert code == HTTPStatus.BAD_REQUEST
def test_gzip(config, api_):
# Requests for each response type and gzip encoding
req_gzip_json = mock_request(HTTP_ACCEPT=FORMAT_TYPES[F_JSON],
HTTP_ACCEPT_ENCODING=F_GZIP)
req_gzip_jsonld = mock_request(HTTP_ACCEPT=FORMAT_TYPES[F_JSONLD],
HTTP_ACCEPT_ENCODING=F_GZIP)
req_gzip_html = mock_request(HTTP_ACCEPT=FORMAT_TYPES[F_HTML],
HTTP_ACCEPT_ENCODING=F_GZIP)
req_gzip_gzip = mock_request(HTTP_ACCEPT='application/gzip',
HTTP_ACCEPT_ENCODING=F_GZIP)
# Responses from server config without gzip compression
rsp_headers, _, rsp_json = api_.landing_page(req_gzip_json)
assert rsp_headers['Content-Type'] == FORMAT_TYPES[F_JSON]
rsp_headers, _, rsp_jsonld = api_.landing_page(req_gzip_jsonld)
assert rsp_headers['Content-Type'] == FORMAT_TYPES[F_JSONLD]
rsp_headers, _, rsp_html = api_.landing_page(req_gzip_html)
assert rsp_headers['Content-Type'] == FORMAT_TYPES[F_HTML]
rsp_headers, _, _ = api_.landing_page(req_gzip_gzip)
assert rsp_headers['Content-Type'] == FORMAT_TYPES[F_JSON]
# Add gzip to server and use utf-16 encoding
config['server']['gzip'] = True
enc_16 = 'utf-16'
config['server']['encoding'] = enc_16
api_ = API(config, openapi)
# Responses from server with gzip compression
rsp_json_headers, _, rsp_gzip_json = api_.landing_page(req_gzip_json)
rsp_jsonld_headers, _, rsp_gzip_jsonld = api_.landing_page(req_gzip_jsonld)
rsp_html_headers, _, rsp_gzip_html = api_.landing_page(req_gzip_html)
rsp_gzip_headers, _, rsp_gzip_gzip = api_.landing_page(req_gzip_gzip)
# Validate compressed json response
assert rsp_json_headers['Content-Type'] == \
f'{FORMAT_TYPES[F_JSON]}; charset={enc_16}'
assert rsp_json_headers['Content-Encoding'] == F_GZIP
parsed_gzip_json = gzip.decompress(rsp_gzip_json).decode(enc_16)
assert isinstance(parsed_gzip_json, str)
parsed_gzip_json = json.loads(parsed_gzip_json)
assert isinstance(parsed_gzip_json, dict)
assert parsed_gzip_json == json.loads(rsp_json)
# Validate compressed jsonld response
assert rsp_jsonld_headers['Content-Type'] == \
f'{FORMAT_TYPES[F_JSONLD]}; charset={enc_16}'
assert rsp_jsonld_headers['Content-Encoding'] == F_GZIP
parsed_gzip_jsonld = gzip.decompress(rsp_gzip_jsonld).decode(enc_16)
assert isinstance(parsed_gzip_jsonld, str)
parsed_gzip_jsonld = json.loads(parsed_gzip_jsonld)
assert isinstance(parsed_gzip_jsonld, dict)
assert parsed_gzip_jsonld == json.loads(rsp_jsonld)
# Validate compressed html response
assert rsp_html_headers['Content-Type'] == \
f'{FORMAT_TYPES[F_HTML]}; charset={enc_16}'
assert rsp_html_headers['Content-Encoding'] == F_GZIP
parsed_gzip_html = gzip.decompress(rsp_gzip_html).decode(enc_16)
assert isinstance(parsed_gzip_html, str)
assert parsed_gzip_html == rsp_html
# Validate compressed gzip response
assert rsp_gzip_headers['Content-Type'] == \
f'{FORMAT_TYPES[F_GZIP]}; charset={enc_16}'
assert rsp_gzip_headers['Content-Encoding'] == F_GZIP
parsed_gzip_gzip = gzip.decompress(rsp_gzip_gzip).decode(enc_16)
assert isinstance(parsed_gzip_gzip, str)
parsed_gzip_gzip = json.loads(parsed_gzip_gzip)
assert isinstance(parsed_gzip_gzip, dict)
# Requests without content encoding header
req_json = mock_request(HTTP_ACCEPT=FORMAT_TYPES[F_JSON])
req_jsonld = mock_request(HTTP_ACCEPT=FORMAT_TYPES[F_JSONLD])
req_html = mock_request(HTTP_ACCEPT=FORMAT_TYPES[F_HTML])
# Responses without content encoding
_, _, rsp_json_ = api_.landing_page(req_json)
_, _, rsp_jsonld_ = api_.landing_page(req_jsonld)
_, _, rsp_html_ = api_.landing_page(req_html)
# Confirm each request is the same when decompressed
assert rsp_json_ == rsp_json == \
gzip.decompress(rsp_gzip_json).decode(enc_16)
assert rsp_jsonld_ == rsp_jsonld == \
gzip.decompress(rsp_gzip_jsonld).decode(enc_16)
assert rsp_html_ == rsp_html == \
gzip.decompress(rsp_gzip_html).decode(enc_16)
def test_gzip_csv(config, api_):
req_csv = mock_request({'f': 'csv'})
rsp_csv_headers, _, rsp_csv = api_.get_collection_items(req_csv, 'obs')
assert rsp_csv_headers['Content-Type'] == 'text/csv; charset=utf-8'
rsp_csv = rsp_csv.decode('utf-8')
req_csv = mock_request({'f': 'csv'}, HTTP_ACCEPT_ENCODING=F_GZIP)
rsp_csv_headers, _, rsp_csv_gzip = api_.get_collection_items(req_csv, 'obs') # noqa
assert rsp_csv_headers['Content-Type'] == 'text/csv; charset=utf-8'
rsp_csv_ = gzip.decompress(rsp_csv_gzip).decode('utf-8')
assert rsp_csv == rsp_csv_
# Use utf-16 encoding
config['server']['encoding'] = 'utf-16'
api_ = API(config, openapi)
req_csv = mock_request({'f': 'csv'}, HTTP_ACCEPT_ENCODING=F_GZIP)
rsp_csv_headers, _, rsp_csv_gzip = api_.get_collection_items(req_csv, 'obs') # noqa
assert rsp_csv_headers['Content-Type'] == 'text/csv; charset=utf-8'
rsp_csv_ = gzip.decompress(rsp_csv_gzip).decode('utf-8')
assert rsp_csv == rsp_csv_
def test_root(config, api_):
req = mock_request()
rsp_headers, code, response = api_.landing_page(req)
root = json.loads(response)
assert rsp_headers['Content-Type'] == 'application/json' == \
FORMAT_TYPES[F_JSON]
assert rsp_headers['X-Powered-By'].startswith('pygeoapi')
assert rsp_headers['Content-Language'] == 'en-US'
assert isinstance(root, dict)
assert 'links' in root
assert root['links'][0]['rel'] == 'self'
assert root['links'][0]['type'] == FORMAT_TYPES[F_JSON]
assert root['links'][0]['href'].endswith('?f=json')
assert any(link['href'].endswith('f=jsonld') and link['rel'] == 'alternate'
for link in root['links'])
assert any(link['href'].endswith('f=html') and link['rel'] == 'alternate'
for link in root['links'])
assert len(root['links']) == 11
assert 'title' in root
assert root['title'] == 'pygeoapi default instance'
assert 'description' in root
assert root['description'] == 'pygeoapi provides an API to geospatial data'
req = mock_request({'f': 'html'})
rsp_headers, code, response = api_.landing_page(req)
assert rsp_headers['Content-Type'] == FORMAT_TYPES[F_HTML]
assert rsp_headers['Content-Language'] == 'en-US'
def test_root_structured_data(config, api_):
req = mock_request({"f": "jsonld"})
rsp_headers, code, response = api_.landing_page(req)
root = json.loads(response)
assert rsp_headers['Content-Type'] == 'application/ld+json' == \
FORMAT_TYPES[F_JSONLD]
assert rsp_headers['Content-Language'] == 'en-US'
assert rsp_headers['X-Powered-By'].startswith('pygeoapi')
assert isinstance(root, dict)
assert 'description' in root
assert root['description'] == 'pygeoapi provides an API to geospatial data'
assert '@context' in root
assert root['@context'] == 'https://schema.org/docs/jsonldcontext.jsonld'
expanded = jsonld.expand(root)[0]
assert '@type' in expanded
assert 'http://schema.org/DataCatalog' in expanded['@type']
assert 'http://schema.org/description' in expanded
assert root['description'] == expanded['http://schema.org/description'][0][
'@value']
assert 'http://schema.org/keywords' in expanded
assert len(expanded['http://schema.org/keywords']) == 3
assert '@value' in expanded['http://schema.org/keywords'][0].keys()
assert 'http://schema.org/provider' in expanded
assert expanded['http://schema.org/provider'][0]['@type'][
0] == 'http://schema.org/Organization'
assert expanded['http://schema.org/name'][0]['@value'] == root['name']
def test_conformance(config, api_):
req = mock_request()
rsp_headers, code, response = api_.conformance(req)
root = json.loads(response)
assert isinstance(root, dict)
assert 'conformsTo' in root
assert len(root['conformsTo']) == 36
assert 'http://www.opengis.net/spec/ogcapi-features-2/1.0/conf/crs' \
in root['conformsTo']
req = mock_request({'f': 'foo'})
rsp_headers, code, response = api_.conformance(req)
assert code == HTTPStatus.BAD_REQUEST
req = mock_request({'f': 'html'})
rsp_headers, code, response = api_.conformance(req)
assert rsp_headers['Content-Type'] == FORMAT_TYPES[F_HTML]
# No language requested: should be set to default from YAML
assert rsp_headers['Content-Language'] == 'en-US'
def test_tilematrixsets(config, api_):
req = mock_request()
rsp_headers, code, response = api_.tilematrixsets(req)
root = json.loads(response)
assert isinstance(root, dict)
assert 'tileMatrixSets' in root
assert len(root['tileMatrixSets']) == 2
assert 'http://www.opengis.net/def/tilematrixset/OGC/1.0/WorldCRS84Quad' \
in root['tileMatrixSets'][0]['uri']
assert 'http://www.opengis.net/def/tilematrixset/OGC/1.0/WebMercatorQuad' \
in root['tileMatrixSets'][1]['uri']
req = mock_request({'f': 'foo'})
rsp_headers, code, response = api_.tilematrixsets(req)
assert code == HTTPStatus.BAD_REQUEST
req = mock_request({'f': 'html'})
rsp_headers, code, response = api_.tilematrixsets(req)
assert rsp_headers['Content-Type'] == FORMAT_TYPES[F_HTML]
# No language requested: should be set to default from YAML
assert rsp_headers['Content-Language'] == 'en-US'
def test_tilematrixset(config, api_):
req = mock_request()
enums = [e.value for e in TileMatrixSetEnum]
enum = None
for e in enums:
enum = e.tileMatrixSet
rsp_headers, code, response = api_.tilematrixset(req, enum)
root = json.loads(response)
assert isinstance(root, dict)
assert 'id' in root
assert root['id'] == enum
assert 'tileMatrices' in root
assert len(root['tileMatrices']) == 30
rsp_headers, code, response = api_.tilematrixset(req, 'foo')
assert code == HTTPStatus.BAD_REQUEST
req = mock_request({'f': 'html'})
rsp_headers, code, response = api_.tilematrixset(req, enum)
assert rsp_headers['Content-Type'] == FORMAT_TYPES[F_HTML]
# No language requested: should be set to default from YAML
assert rsp_headers['Content-Language'] == 'en-US'
def test_describe_collections(config, api_):
req = mock_request({"f": "foo"})
rsp_headers, code, response = api_.describe_collections(req)
assert code == HTTPStatus.BAD_REQUEST
req = mock_request({"f": "html"})
rsp_headers, code, response = api_.describe_collections(req)
assert rsp_headers['Content-Type'] == FORMAT_TYPES[F_HTML]
req = mock_request()
rsp_headers, code, response = api_.describe_collections(req)
collections = json.loads(response)
assert len(collections) == 2
assert len(collections['collections']) == 9
assert len(collections['links']) == 3
rsp_headers, code, response = api_.describe_collections(req, 'foo')
collection = json.loads(response)
assert code == HTTPStatus.NOT_FOUND
rsp_headers, code, response = api_.describe_collections(req, 'obs')
collection = json.loads(response)
assert rsp_headers['Content-Language'] == 'en-US'
assert collection['id'] == 'obs'
assert collection['title'] == 'Observations'
assert collection['description'] == 'My cool observations'
assert len(collection['links']) == 14
assert collection['extent'] == {
'spatial': {
'bbox': [[-180, -90, 180, 90]],
'crs': 'http://www.opengis.net/def/crs/OGC/1.3/CRS84'
},
'temporal': {
'interval': [
['2000-10-30T18:24:39+00:00', '2007-10-30T08:57:29+00:00']
],
'trs': 'http://www.opengis.net/def/uom/ISO-8601/0/Gregorian'
}
}
# OAPIF Part 2 CRS 6.2.1 A, B, configured CRS + defaults
assert collection['crs'] is not None
crs_set = [
'http://www.opengis.net/def/crs/EPSG/0/28992',
'http://www.opengis.net/def/crs/OGC/1.3/CRS84',
'http://www.opengis.net/def/crs/EPSG/0/4326',
]
for crs in crs_set:
assert crs in collection['crs']
assert collection['storageCRS'] is not None
assert collection['storageCRS'] == 'http://www.opengis.net/def/crs/OGC/1.3/CRS84' # noqa
assert 'storageCrsCoordinateEpoch' not in collection
# French language request
req = mock_request({'lang': 'fr'})
rsp_headers, code, response = api_.describe_collections(req, 'obs')
collection = json.loads(response)
assert rsp_headers['Content-Language'] == 'fr-CA'
assert collection['title'] == 'Observations'
assert collection['description'] == 'Mes belles observations'
# Check HTML request in an unsupported language
req = mock_request({'f': 'html', 'lang': 'de'})
rsp_headers, code, response = api_.describe_collections(req, 'obs')
assert rsp_headers['Content-Type'] == FORMAT_TYPES[F_HTML]
assert rsp_headers['Content-Language'] == 'en-US'
req = mock_request()
rsp_headers, code, response = api_.describe_collections(req,
'gdps-temperature')
collection = json.loads(response)
assert collection['id'] == 'gdps-temperature'
assert len(collection['links']) == 10
assert collection['extent']['spatial']['grid'][0]['cellsCount'] == 2400
assert collection['extent']['spatial']['grid'][0]['resolution'] == 0.15000000000000002 # noqa
assert collection['extent']['spatial']['grid'][1]['cellsCount'] == 1201
assert collection['extent']['spatial']['grid'][1]['resolution'] == 0.15
# hiearchical collections
rsp_headers, code, response = api_.describe_collections(
req, 'naturalearth/lakes')
collection = json.loads(response)
assert collection['id'] == 'naturalearth/lakes'
# OAPIF Part 2 CRS 6.2.1 B, defaults when not configured
assert collection['crs'] is not None
default_crs_list = [
'http://www.opengis.net/def/crs/OGC/1.3/CRS84',
'http://www.opengis.net/def/crs/OGC/1.3/CRS84h',
]
contains_default = False
for crs in default_crs_list:
if crs in default_crs_list:
contains_default = True
assert contains_default
assert collection['storageCRS'] is not None
assert collection['storageCRS'] == 'http://www.opengis.net/def/crs/OGC/1.3/CRS84' # noqa
assert collection['storageCrsCoordinateEpoch'] == 2017.23
def test_describe_collections_hidden_resources(
config_hidden_resources, api_hidden_resources):
req = mock_request({})
rsp_headers, code, response = api_hidden_resources.describe_collections(req) # noqa
assert code == HTTPStatus.OK
assert len(config_hidden_resources['resources']) == 3
collections = json.loads(response)
assert len(collections['collections']) == 1
def test_get_collection_schema(config, api_):
req = mock_request()
rsp_headers, code, response = api_.get_collection_schema(req,
'notfound')
assert code == HTTPStatus.NOT_FOUND
req = mock_request({'f': 'html'})
rsp_headers, code, response = api_.get_collection_schema(req, 'obs')
assert rsp_headers['Content-Type'] == FORMAT_TYPES[F_HTML]
req = mock_request({'f': 'json'})
rsp_headers, code, response = api_.get_collection_schema(req, 'obs')
assert rsp_headers['Content-Type'] == 'application/schema+json'
schema = json.loads(response)
assert 'properties' in schema
assert len(schema['properties']) == 5
req = mock_request({'f': 'json'})
rsp_headers, code, response = api_.get_collection_schema(
req, 'gdps-temperature')
assert rsp_headers['Content-Type'] == 'application/schema+json'
schema = json.loads(response)
assert 'properties' in schema
assert len(schema['properties']) == 1
assert schema['properties']['1']['type'] == 'number'
def test_get_collection_queryables(config, api_):
req = mock_request()
rsp_headers, code, response = api_.get_collection_queryables(req,
'notfound')
assert code == HTTPStatus.NOT_FOUND
req = mock_request({'f': 'html'})
rsp_headers, code, response = api_.get_collection_queryables(req, 'obs')
assert rsp_headers['Content-Type'] == FORMAT_TYPES[F_HTML]
req = mock_request({'f': 'json'})
rsp_headers, code, response = api_.get_collection_queryables(req, 'obs')
assert rsp_headers['Content-Type'] == 'application/schema+json'
queryables = json.loads(response)
assert 'properties' in queryables
assert len(queryables['properties']) == 5
# test with provider filtered properties
api_.config['resources']['obs']['providers'][0]['properties'] = ['stn_id']
rsp_headers, code, response = api_.get_collection_queryables(req, 'obs')
queryables = json.loads(response)
assert 'properties' in queryables
assert len(queryables['properties']) == 2
assert 'geometry' in queryables['properties']
assert queryables['properties']['geometry']['$ref'] == 'https://geojson.org/schema/Geometry.json' # noqa
# No language requested: should be set to default from YAML
assert rsp_headers['Content-Language'] == 'en-US'
def test_describe_collections_json_ld(config, api_):
req = mock_request({'f': 'jsonld'})
rsp_headers, code, response = api_.describe_collections(req, 'obs')
collection = json.loads(response)
assert '@context' in collection
expanded = jsonld.expand(collection)[0]
# Metadata is about a schema:DataCollection that contains a schema:Dataset
assert not expanded['@id'].endswith('obs')
assert 'http://schema.org/dataset' in expanded
assert len(expanded['http://schema.org/dataset']) == 1
dataset = expanded['http://schema.org/dataset'][0]
assert dataset['@type'][0] == 'http://schema.org/Dataset'
assert len(dataset['http://schema.org/distribution']) == 14
assert all(dist['@type'][0] == 'http://schema.org/DataDownload'
for dist in dataset['http://schema.org/distribution'])
assert 'http://schema.org/Organization' in expanded[
'http://schema.org/provider'][0]['@type']
assert 'http://schema.org/Place' in dataset[
'http://schema.org/spatial'][0]['@type']
assert 'http://schema.org/GeoShape' in dataset[
'http://schema.org/spatial'][0]['http://schema.org/geo'][0]['@type']
assert dataset['http://schema.org/spatial'][0]['http://schema.org/geo'][
0]['http://schema.org/box'][0]['@value'] == '-180,-90 180,90'
assert 'http://schema.org/temporalCoverage' in dataset
assert dataset['http://schema.org/temporalCoverage'][0][
'@value'] == '2000-10-30T18:24:39+00:00/2007-10-30T08:57:29+00:00'
# No language requested: should be set to default from YAML
assert rsp_headers['Content-Language'] == 'en-US'
def test_get_collection_items(config, api_):
req = mock_request()
rsp_headers, code, response = api_.get_collection_items(req, 'foo')
features = json.loads(response)
assert code == HTTPStatus.NOT_FOUND
req = mock_request({'f': 'foo'})
rsp_headers, code, response = api_.get_collection_items(req, 'obs')
features = json.loads(response)
assert code == HTTPStatus.BAD_REQUEST
req = mock_request({'bbox': '1,2,3'})
rsp_headers, code, response = api_.get_collection_items(req, 'obs')
features = json.loads(response)
assert code == HTTPStatus.BAD_REQUEST
req = mock_request({'bbox': '1,2,3,4c'})
rsp_headers, code, response = api_.get_collection_items(req, 'obs')
assert code == HTTPStatus.BAD_REQUEST
req = mock_request({'bbox': '1,2,3,4', 'bbox-crs': 'bad_value'})
rsp_headers, code, response = api_.get_collection_items(req, 'obs')
assert code == HTTPStatus.BAD_REQUEST
req = mock_request({'bbox-crs': 'bad_value'})
rsp_headers, code, response = api_.get_collection_items(req, 'obs')
assert code == HTTPStatus.BAD_REQUEST
# bbox-crs must be in configured values for Collection
req = mock_request({'bbox': '1,2,3,4', 'bbox-crs': 'http://www.opengis.net/def/crs/EPSG/0/4258'}) # noqa
rsp_headers, code, response = api_.get_collection_items(req, 'obs')
assert code == HTTPStatus.BAD_REQUEST
# bbox-crs must be in configured values for Collection (CSV will ignore)
req = mock_request({'bbox': '52,4,53,5', 'bbox-crs': 'http://www.opengis.net/def/crs/EPSG/0/4326'}) # noqa
rsp_headers, code, response = api_.get_collection_items(req, 'obs')
assert code == HTTPStatus.OK
# bbox-crs can be a default even if not configured
req = mock_request({'bbox': '4,52,5,53', 'bbox-crs': 'http://www.opengis.net/def/crs/OGC/1.3/CRS84'}) # noqa
rsp_headers, code, response = api_.get_collection_items(req, 'obs')
assert code == HTTPStatus.OK
# bbox-crs can be a default even if not configured
req = mock_request({'bbox': '4,52,5,53'}) # noqa
rsp_headers, code, response = api_.get_collection_items(req, 'obs')
assert code == HTTPStatus.OK
req = mock_request({'f': 'html', 'lang': 'fr'})
rsp_headers, code, response = api_.get_collection_items(req, 'obs')
assert rsp_headers['Content-Type'] == FORMAT_TYPES[F_HTML]
assert rsp_headers['Content-Language'] == 'fr-CA'
req = mock_request()
rsp_headers, code, response = api_.get_collection_items(req, 'obs')
features = json.loads(response)
# No language requested: should be set to default from YAML
assert rsp_headers['Content-Language'] == 'en-US'
assert len(features['features']) == 5
req = mock_request({'resulttype': 'hits'})
rsp_headers, code, response = api_.get_collection_items(req, 'obs')
features = json.loads(response)
assert len(features['features']) == 0
# Invalid limit
req = mock_request({'limit': 0})
rsp_headers, code, response = api_.get_collection_items(req, 'obs')
features = json.loads(response)
assert code == HTTPStatus.BAD_REQUEST
req = mock_request({'stn_id': '35'})
rsp_headers, code, response = api_.get_collection_items(req, 'obs')
features = json.loads(response)
assert len(features['features']) == 2
assert features['numberMatched'] == 2
req = mock_request({'stn_id': '35', 'value': '93.9'})
rsp_headers, code, response = api_.get_collection_items(req, 'obs')
features = json.loads(response)
assert len(features['features']) == 1
assert features['numberMatched'] == 1
req = mock_request({'limit': 2})
rsp_headers, code, response = api_.get_collection_items(req, 'obs')
features = json.loads(response)
assert len(features['features']) == 2
assert features['features'][1]['properties']['stn_id'] == 35
links = features['links']
assert len(links) == 4
assert '/collections/obs/items?f=json' in links[0]['href']
assert links[0]['rel'] == 'self'
assert '/collections/obs/items?f=jsonld' in links[1]['href']