-
Notifications
You must be signed in to change notification settings - Fork 17
/
abstract.py
1025 lines (788 loc) · 35.1 KB
/
abstract.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
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
import datetime
import random
import re
from collections import OrderedDict
import numpy as np
import pandas as pd
import pytest
import requests
from owslib.etree import etree
from owslib.fes2 import PropertyIsEqualTo, SortBy, SortProperty
from pandas import DataFrame
import pydov
from pydov.types.abstract import AbstractField
from pydov.types.fields import ReturnField, ReturnFieldList
from pydov.util.dovutil import build_dov_url
from pydov.util.errors import InvalidFieldError
from pydov.util.location import Box, Within
from pydov.util.query import Join, PropertyInList
class ServiceCheck:
is_service_ok = None
@staticmethod
def service_ok(timeout=5):
"""Check whether DOV services are accessible.
Used to skip online tests when the service is unavailable or
unreachable.
Parameters
----------
timeout : int, optional
Timeout in seconds. Defaults to 5.
Returns
-------
bool
True if the DOV services are reachable, False otherwise.
"""
def check_url(url, timeout):
try:
ok = pydov.session.head(
url, allow_redirects=True, timeout=timeout).ok
except requests.exceptions.ReadTimeout:
ok = False
except requests.exceptions.ConnectTimeout:
ok = False
except Exception:
ok = False
return ok
if ServiceCheck.is_service_ok is None:
ServiceCheck.is_service_ok = (
check_url(build_dov_url('geonetwork'), timeout) and
check_url(build_dov_url('geoserver'), timeout) and
check_url(
build_dov_url('xdov/schema/latest/xsd/kern/dov.xsd'),
timeout))
return ServiceCheck.is_service_ok
def clean_xml(xml):
"""Clean the given XML string of namespace definition, namespace
prefixes and syntactical but otherwise meaningless differences.
Parameters
----------
xml : str
String representation of XML document.
Returns
-------
str
String representation of cleaned XML document.
"""
# remove xmlns namespace definitions
r = re.sub(r'[ ]+xmlns:[^=]+="[^"]+"', '', xml)
# remove namespace prefixes in tags
r = re.sub(r'<(/?)[^:]+:([^ >]+)([ >])', r'<\1\2\3', r)
# remove namespace prefixes in attributes
while re.match(r'<([^ >]+)( [^:]+ )*[^:]+:([^ >]+)([ >])', r):
r = re.sub(r'<([^ >]+)( [^:]+ )*[^:]+:([^ >]+)([ >])', r'<\1\2\3\4', r)
# remove extra spaces in tags
r = re.sub(r'[ ]+/>', '/>', r)
# remove extra spaces between tags
r = re.sub(r'>[ ]+<', '><', r)
return r
class AbstractTestSearch(object):
"""Class grouping common test code for search classes.
Subclasses should implement at least the following public attributes
in order for the tests defined here to be executed.
Attributes
----------
search_instance : pydov.search.abstract.AbstractSearch
Instance of subclass of this type used for searching.
datatype_class : pydov.types.abstract.AbstractDovType
Class reference for the corresponding datatype.
valid_query_single : owslib.fes2.OgcExpression
OGC expression of a valid query returning a single result.
inexistent_field : str
The name of an inexistent field.
wfs_field : str
The name of a WFS field.
xml_field : str
The name of an XML field.
valid_returnfields : tuple of str
A tuple of valid return fields from the main type.
valid_returnfields_subtype : typle of str
A tuple containing valid return fields, including fields from a
subtype.
valid_returnfields_extra : tuple of str
A tuple containing valid return fields, including extra fields
from WFS, not present in the default dataframe.
df_default_columns : list of str
A list of the column names of the default dataframe.
"""
def test_pluggable_type(self):
"""Test whether the search object can be initialised by explicitly
giving the objecttype.
"""
datatype = self.datatype_class
self.search_instance.__class__(objecttype=datatype)
def test_get_fields(self, mp_wfs, mp_get_schema,
mp_remote_describefeaturetype, mp_remote_md,
mp_remote_fc, mp_remote_xsd):
"""Test the get_fields method.
Test whether the returned fields match the format specified
in the documentation.
Parameters
----------
mp_wfs : pytest.fixture
Monkeypatch the call to the remote GetCapabilities request.
mp_get_schema : pytest.fixture
Monkeypatch the call to a remote OWSLib schema.
mp_remote_describefeaturetype : pytest.fixture
Monkeypatch the call to a remote DescribeFeatureType.
mp_remote_md : pytest.fixture
Monkeypatch the call to get the remote metadata.
mp_remote_fc : pytest.fixture
Monkeypatch the call to get the remote feature catalogue.
"""
fields = self.search_instance.get_fields()
assert isinstance(fields, dict)
for field in fields:
assert isinstance(field, str)
f = fields[field]
assert isinstance(f, dict)
assert 'name' in f
assert isinstance(f['name'], str)
assert f['name'] == field
assert 'definition' in f
assert isinstance(f['name'], str)
assert 'type' in f
assert isinstance(f['type'], str)
assert f['type'] in ['string', 'float', 'integer', 'date',
'datetime', 'boolean', 'geometry']
assert 'notnull' in f
assert isinstance(f['notnull'], bool)
assert 'query' in f
assert isinstance(f['query'], bool)
assert 'cost' in f
assert isinstance(f['cost'], int)
assert f['cost'] > 0
if 'values' in f:
assert sorted(f.keys()) == [
'cost', 'definition', 'name', 'notnull', 'query', 'type',
'values']
assert isinstance(f['values'], dict)
for v in f['values'].keys():
assert isinstance(f['values'][v], str) or f[
'values'][v] is None
if f['type'] == 'string':
assert isinstance(v, str)
elif f['type'] == 'float':
assert isinstance(v, float)
elif f['type'] == 'integer':
assert isinstance(v, int)
elif f['type'] == 'date':
assert isinstance(v, datetime.date)
elif f['type'] == 'datetime':
assert isinstance(v, datetime.datetime)
elif f['type'] == 'boolean':
assert isinstance(v, bool)
else:
assert sorted(f.keys()) == ['cost', 'definition', 'name',
'notnull', 'query', 'type']
def test_search_both_location_query(self, mp_get_schema,
mp_remote_describefeaturetype,
mp_remote_wfs_feature):
"""Test the search method providing both a location and a query.
Test whether a dataframe is returned.
Parameters
----------
mp_get_schema : pytest.fixture
Monkeypatch the call to a remote OWSLib schema.
mp_remote_describefeaturetype : pytest.fixture
Monkeypatch the call to a remote DescribeFeatureType.
mp_remote_wfs_feature : pytest.fixture
Monkeypatch the call to get WFS features.
"""
df = self.search_instance.search(
location=Within(Box(1, 2, 3, 4)),
query=self.valid_query_single,
return_fields=self.valid_returnfields)
assert isinstance(df, DataFrame)
def test_search(self, mp_wfs, mp_get_schema, mp_remote_describefeaturetype,
mp_remote_md, mp_remote_fc, mp_remote_wfs_feature,
mp_dov_xml):
"""Test the search method with only the query parameter.
Test whether the result is correct.
Parameters
----------
mp_wfs : pytest.fixture
Monkeypatch the call to the remote GetCapabilities request.
mp_get_schema : pytest.fixture
Monkeypatch the call to a remote OWSLib schema.
mp_remote_describefeaturetype : pytest.fixture
Monkeypatch the call to a remote DescribeFeatureType.
mp_remote_md : pytest.fixture
Monkeypatch the call to get the remote metadata.
mp_remote_fc : pytest.fixture
Monkeypatch the call to get the remote feature catalogue.
mp_remote_wfs_feature : pytest.fixture
Monkeypatch the call to get WFS features.
mp_dov_xml : pytest.fixture
Monkeypatch the call to get the remote XML data.
"""
df = self.search_instance.search(
query=self.valid_query_single)
assert isinstance(df, DataFrame)
assert list(df) == self.df_default_columns
datatype = self.datatype_class
allfields = datatype.get_field_names()
ownfields = datatype.get_field_names(include_subtypes=False)
subfields = [f for f in allfields if f not in ownfields]
assert len(df) >= 1
for field in list(df):
if field in ownfields:
assert len(df[field].unique()) == 1
elif field in subfields:
assert len(df[field].unique()) >= 1
# dtype checks of the resulting df columns
fields = self.search_instance.get_fields()
for field in list(df):
mandatory = fields[field]['notnull']
if mandatory:
assert len(df[field]) == len(df[field].dropna())
for field in list(df):
field_datatype = fields[field]['type']
datatypes = set((type(i) for i in df[field].dropna()))
assert len(datatypes) <= 1
if len(datatypes) > 0:
if field_datatype == 'string':
assert (str in datatypes)
elif field_datatype == 'float':
assert float in datatypes
elif field_datatype == 'integer':
assert (int in datatypes)
elif field_datatype == 'date':
assert datetime.date in datatypes
elif field_datatype == 'boolean':
assert bool in datatypes
def test_search_returnfields(self, mp_remote_wfs_feature):
"""Test the search method with the query parameter and a selection of
return fields.
Test whether the output dataframe contains only the selected return
fields.
Parameters
----------
mp_remote_wfs_feature : pytest.fixture
Monkeypatch the call to get WFS features.
"""
df = self.search_instance.search(
query=self.valid_query_single,
return_fields=self.valid_returnfields)
assert isinstance(df, DataFrame)
assert list(df) == list(self.valid_returnfields.get_names())
def test_search_returnfields_subtype(self, mp_remote_wfs_feature):
"""Test the search method with the query parameter and a selection of
return fields, including fields from a subtype.
Test whether the output dataframe contains only the selected return
fields.
Parameters
----------
mp_remote_wfs_feature : pytest.fixture
Monkeypatch the call to get WFS features.
"""
if self.valid_returnfields_subtype is None:
return
df = self.search_instance.search(
query=self.valid_query_single,
return_fields=self.valid_returnfields_subtype)
assert isinstance(df, DataFrame)
assert list(df) == list(self.valid_returnfields_subtype.get_names())
def test_search_returnfields_order(self, mp_remote_wfs_feature):
"""Test the search method with the query parameter and a selection of
return fields in another ordering.
Test whether the output dataframe contains only the selected return
fields, in the order that is given in the return_fields parameter.
Parameters
----------
mp_remote_wfs_feature : pytest.fixture
Monkeypatch the call to get WFS features.
"""
rf = list(self.valid_returnfields.get_names())
while rf == list(self.valid_returnfields):
random.shuffle(rf)
df = self.search_instance.search(
query=self.valid_query_single,
return_fields=rf)
assert isinstance(df, DataFrame)
assert list(df) == rf
def test_search_wrongreturnfields(self):
"""Test the search method with the query parameter and an inexistent
return field.
Test whether an InvalidFieldError is raised.
"""
return_fields = list(self.valid_returnfields)
return_fields.append(self.inexistent_field)
with pytest.raises(InvalidFieldError):
self.search_instance.search(
query=self.valid_query_single,
return_fields=return_fields)
def test_search_wrongreturnfieldstype(self):
"""Test the search method with the query parameter and a single
return field as string.
Test whether an AttributeError is raised.
"""
with pytest.raises(AttributeError):
self.search_instance.search(
query=self.valid_query_single,
return_fields=self.valid_returnfields[0])
def test_search_query_wrongfield(self):
"""Test the search method with the query parameter using an
inexistent query field.
Test whether an InvalidFieldError is raised.
"""
query = PropertyIsEqualTo(propertyname=self.inexistent_field,
literal='The cat is out of the bag.')
with pytest.raises(InvalidFieldError):
self.search_instance.search(
query=query)
def test_search_query_wrongfield_returnfield(self):
"""Test the search method with the query parameter using an
return-only field as query field.
Test whether an InvalidFieldError is raised.
"""
if self.xml_field is None:
return
query = PropertyIsEqualTo(propertyname=self.xml_field,
literal='Geotechnisch onderzoek')
with pytest.raises(InvalidFieldError):
self.search_instance.search(query=query)
def test_search_extrareturnfields(self, mp_get_schema,
mp_remote_describefeaturetype,
mp_remote_wfs_feature, mp_dov_xml):
"""Test the search method with the query parameter and an extra WFS
field as return field.
Parameters
----------
mp_get_schema : pytest.fixture
Monkeypatch the call to a remote OWSLib schema.
mp_remote_describefeaturetype : pytest.fixture
Monkeypatch the call to a remote DescribeFeatureType.
mp_remote_wfs_feature : pytest.fixture
Monkeypatch the call to get WFS features.
mp_dov_xml : pytest.fixture
Monkeypatch the call to get the remote XML data.
"""
if self.valid_returnfields_extra is None:
return
df = self.search_instance.search(
query=self.valid_query_single,
return_fields=self.valid_returnfields_extra)
assert isinstance(df, DataFrame)
assert list(df) == list(self.valid_returnfields_extra.get_names())
@pytest.mark.online
@pytest.mark.skipif(not ServiceCheck.service_ok(),
reason="DOV service is unreachable")
def test_search_sortby_valid(self):
"""Test the search method with the query parameter and the sort_by
parameter with a valid sort field.
Test whether a dataframe is returned.
"""
df = self.search_instance.search(
query=self.valid_query_single,
sort_by=SortBy([SortProperty(
self.valid_returnfields.get_names()[-1])]))
assert isinstance(df, DataFrame)
def test_search_sortby_invalid(self, mp_get_schema,
mp_remote_describefeaturetype,
mp_remote_wfs_feature, mp_dov_xml):
"""Test the search method with the query parameter and the sort_by
parameter with an invalid sort field.
Test whether an InvalidFieldError is raised.
Parameters
----------
mp_get_schema : pytest.fixture
Monkeypatch the call to a remote OWSLib schema.
mp_remote_describefeaturetype : pytest.fixture
Monkeypatch the call to a remote DescribeFeatureType.
mp_remote_wfs_feature : pytest.fixture
Monkeypatch the call to get WFS features.
mp_dov_xml : pytest.fixture
Monkeypatch the call to get the remote XML data.
"""
if self.xml_field is None:
return
with pytest.raises(InvalidFieldError):
self.search_instance.search(
query=self.valid_query_single,
sort_by=SortBy([SortProperty(
self.xml_field)]))
def test_search_xml_noresolve(self, mp_get_schema,
mp_remote_describefeaturetype,
mp_remote_wfs_feature, mp_dov_xml_broken):
"""Test the search method with return fields from WFS only.
Test whether no XML is resolved.
Parameters
----------
mp_get_schema : pytest.fixture
Monkeypatch the call to a remote OWSLib schema.
mp_remote_describefeaturetype : pytest.fixture
Monkeypatch the call to a remote DescribeFeatureType.
mp_remote_wfs_feature : pytest.fixture
Monkeypatch the call to get WFS features.
mp_dov_xml_broken : pytest.fixture
Monkeypatch the call to break fetching of remote XML data.
"""
self.search_instance.search(
query=self.valid_query_single,
return_fields=self.valid_returnfields_extra)
def test_search_propertyinlist(self, mp_get_schema,
mp_remote_describefeaturetype,
mp_remote_wfs_feature, mp_dov_xml):
"""Test the search method with a PropertyInList query.
Parameters
----------
mp_get_schema : pytest.fixture
Monkeypatch the call to a remote OWSLib schema.
mp_remote_describefeaturetype : pytest.fixture
Monkeypatch the call to a remote DescribeFeatureType.
mp_remote_wfs_feature : pytest.fixture
Monkeypatch the call to get WFS features.
mp_dov_xml : pytest.fixture
Monkeypatch the call to get the remote XML data.
"""
self.search_instance.search(
query=PropertyInList(self.wfs_field, ['a', 'b']))
def test_search_join(self, mp_get_schema, mp_remote_describefeaturetype,
mp_remote_wfs_feature, mp_dov_xml):
"""Test the search method with a Join query.
Parameters
----------
mp_get_schema : pytest.fixture
Monkeypatch the call to a remote OWSLib schema.
mp_remote_describefeaturetype : pytest.fixture
Monkeypatch the call to a remote DescribeFeatureType.
mp_remote_wfs_feature : pytest.fixture
Monkeypatch the call to get WFS features.
mp_dov_xml : pytest.fixture
Monkeypatch the call to get the remote XML data.
"""
df1 = self.search_instance.search(
query=self.valid_query_single)
self.search_instance.search(
query=Join(df1, self.df_default_columns[0]))
def test_get_fields_xsd_values(self, mp_remote_xsd):
"""Test the result of get_fields when the XML field has an XSD type.
Test whether the output from get_fields() returns the values from
the XSD.
Parameters
----------
mp_remote_xsd : pytest.fixture
Monkeypatch the call to get XSD schemas.
"""
xsd_schemas = self.datatype_class.get_xsd_schemas()
if len(xsd_schemas) > 0:
xml_fields = self.datatype_class.get_fields(source='xml')
fields = self.search_instance.get_fields()
for f in xml_fields.values():
if 'xsd_type' in f:
assert 'values' in fields[f['name']]
assert isinstance(fields[f['name']]['values'], dict)
def test_get_fields_no_xsd(self):
"""Test whether no XML fields have an XSD type when no XSD schemas
are available."""
xsd_schemas = self.datatype_class.get_xsd_schemas()
if len(xsd_schemas) == 0:
xml_fields = self.datatype_class.get_fields(source='xml')
for f in xml_fields.values():
assert 'xsd_type' not in f
def test_get_fields_xsd_enums(self):
"""Test whether at least one XML field has an XSD type when there
are XSD schemas available.
Make sure XSD schemas are only listed (and downloaded) when they are
needed.
"""
xsd_schemas = self.datatype_class.get_xsd_schemas()
xsd_type_count = 0
if len(xsd_schemas) > 0:
xml_fields = self.datatype_class.get_fields(source='xml')
for f in xml_fields.values():
if 'xsd_type' in f:
xsd_type_count += 1
assert xsd_type_count > 0
class AbstractTestTypes(object):
"""Class grouping common test code for datatype classes.
Subclasses should implement at least the following public attributes
in order for the tests defined here to be executed.
Attributes
----------
datatype_class : pydov.types.abstract.AbstractDovType
Class reference for the corresponding datatype.
namespace : str
WFS namespace for this type.
pkey_base : str
Base URL for the permanent keys of this datatype.
field_names : list of str
The field names for this type as listed in the documentation in
docs/description_output_dataframes.rst
field_names_subtypes : list of str
The field names of this type that originate from subtypes only.
field_names_nosubtypes : list of str
The field names for this type, without including fields from
subtypes.
valid_returnfields : tuple of str
A tuple of valid return fields from the main type.
valid_returnfields_subtype : typle of str
A tuple containing valid return fields, including fields from a
subtype.
inexistent_field : str
The name of an inexistent field.
"""
def test_get_field_names(self):
"""Test the get_field_names method.
Tests whether the available fields for the type match the
ones we list in docs/description_output_dataframes.rst.
"""
fields = self.datatype_class.get_field_names()
assert fields == self.field_names
def test_get_field_names_nosubtypes(self):
"""Test the get_field_names method without including subtypes.
Tests whether the fields provided in a subtype are not listed when
disabling subtypes.
"""
fields = self.datatype_class.get_field_names(
return_fields=None, include_subtypes=False)
assert fields == self.field_names_nosubtypes
def test_get_field_names_returnfields_nosubtypes(self):
"""Test the get_field_names method when specifying return
fields.
Tests whether the returned fields match the ones provided as return
fields.
"""
fields = self.datatype_class.get_field_names(
return_fields=self.valid_returnfields,
include_subtypes=False)
assert fields == list(self.valid_returnfields.get_names())
def test_get_field_names_returnfields_order(self):
"""Test the get_field_names method when specifying return
fields in a different order.
Tests whether the returned fields match the ones provided as return
fields and that the order is the one given in the return_fields
parameter.
"""
rf = ReturnFieldList(self.valid_returnfields)
while rf == self.valid_returnfields:
random.shuffle(rf)
fields = self.datatype_class.get_field_names(
return_fields=rf,
include_subtypes=False)
assert fields == rf.get_names()
def test_get_field_names_wrongreturnfields(self):
"""Test the get_field_names method when specifying an
inexistent return field.
Test whether an InvalidFieldError is raised.
"""
return_fields = self.valid_returnfields
return_fields.append(ReturnField(self.inexistent_field))
with pytest.raises(InvalidFieldError):
self.datatype_class.get_field_names(
return_fields=return_fields,
include_subtypes=False)
def test_get_field_names_wrongreturnfieldstype(self):
"""Test the get_field_names method when listing a single
return field instead of a list.
Test whether an AttributeError is raised.
"""
with pytest.raises(AttributeError):
self.datatype_class.get_field_names(
return_fields=self.valid_returnfields.get_names()[0],
include_subtypes=False)
def test_get_field_names_wrongreturnfields_nosubtypes(self):
"""Test the get_field_names method when disabling subtypes
and including an otherwise valid return field.
Test whether an InvalidFieldError is raised.
"""
if self.valid_returnfields_subtype is None:
return
with pytest.raises(InvalidFieldError):
self.datatype_class.get_field_names(
return_fields=self.valid_returnfields_subtype,
include_subtypes=False)
def test_get_fields(self):
"""Test the get_fields method.
Test whether the format returned by the method meets the
requirements and the format listed in the docs.
"""
fields = self.datatype_class.get_fields()
assert isinstance(fields, OrderedDict)
for f in fields.keys():
assert isinstance(f, str)
field = fields[f]
assert isinstance(field, AbstractField)
assert 'name' in field
assert isinstance(field['name'], str)
assert field['name'] == f
assert 'source' in field
assert isinstance(field['source'], str)
assert field['source'] in ('wfs', 'xml')
assert 'sourcefield' in field
assert isinstance(field['sourcefield'], str)
assert 'type' in field
assert isinstance(field['type'], str)
assert field['type'] in ['string', 'float', 'integer', 'date',
'datetime', 'boolean', 'geometry']
if field['source'] == 'wfs':
if 'wfs_injected' in field.keys():
assert sorted(field.keys()) == [
'name', 'source', 'sourcefield', 'type',
'wfs_injected']
else:
assert sorted(field.keys()) == [
'name', 'source', 'sourcefield', 'type']
elif field['source'] == 'xml':
assert 'definition' in field
assert isinstance(field['definition'], str)
assert 'notnull' in field
assert isinstance(field['notnull'], bool)
if 'xsd_type' in field:
assert sorted(field.keys()) == [
'definition', 'name', 'notnull', 'source',
'sourcefield', 'type', 'xsd_schema', 'xsd_type']
else:
assert sorted(field.keys()) == [
'definition', 'name', 'notnull', 'source',
'sourcefield', 'type']
def test_get_fields_nosubtypes(self):
"""Test the get_fields method not including subtypes.
Test whether fields provides by subtypes are not listed in the output.
"""
if self.field_names_subtypes is None:
return
fields = self.datatype_class.get_fields(include_subtypes=False)
for field in fields:
assert field not in self.field_names_subtypes
def test_from_wfs_element(self, wfs_feature):
"""Test the from_wfs_element method.
Test whether we can construct an instance from a WFS response element.
Parameters
----------
wfs_feature : pytest.fixture returning etree.Element
Fixture providing an XML element representing a single record of
the WFS layer.
"""
feature = self.datatype_class.from_wfs_element(
wfs_feature, self.namespace)
assert isinstance(feature, self.datatype_class)
if self.pkey_base is not None:
assert feature.pkey.startswith(self.pkey_base)
assert feature.pkey.startswith(
build_dov_url('data/{}/'.format(feature.typename)))
assert isinstance(feature.data, dict)
assert isinstance(feature.subdata, dict)
def test_get_df_array(self, wfs_feature, mp_dov_xml):
"""Test the get_df_array method.
Test whether the output of the dataframe array is correct.
Parameters
----------
wfs_feature : pytest.fixture returning etree.Element
Fixture providing an XML element representing a single record of
the WFS layer.
mp_dov_xml : pytest.fixture
Monkeypatch the call to get the remote XML data.
"""
feature = self.datatype_class.from_wfs_element(
wfs_feature, self.namespace)
fields = [f for f in self.datatype_class.get_fields(
source=('wfs', 'xml', 'custom_wfs', 'custom_xml')).values() if not
f.get('wfs_injected', False)]
df_array = feature.get_df_array()
assert isinstance(df_array, list)
for record in df_array:
assert len(record) == len(fields)
for value, field in zip(record, fields):
if field['type'] == 'string':
assert isinstance(value, str) or np.isnan(value)
elif field['type'] == 'float':
assert isinstance(value, float) or np.isnan(value)
elif field['type'] == 'integer':
assert isinstance(value, int) or np.isnan(value)
elif field['type'] == 'date':
assert isinstance(value, datetime.date) or np.isnan(value)
elif field['type'] == 'boolean':
assert isinstance(value, bool) or np.isnan(value)
if field['name'].startswith('pkey') and not pd.isnull(value):
assert value.startswith(build_dov_url('data/'))
assert not value.endswith('.xml')
def test_get_df_array_wrongreturnfields(self, wfs_feature):
"""Test the get_df_array specifying a nonexistent return field.
Test whether an InvalidFieldError is raised.
Parameters
----------
wfs_feature : pytest.fixture returning etree.Element
Fixture providing an XML element representing a single record of
the WFS layer.
"""
feature = self.datatype_class.from_wfs_element(
wfs_feature, self.namespace)
with pytest.raises(InvalidFieldError):
feature.get_df_array(
return_fields=ReturnFieldList.from_field_names(self.inexistent_field))
def test_from_wfs_str(self, wfs_getfeature):
"""Test the from_wfs method to construct objects from a WFS response,
as str.
Parameters
----------
wfs_getfeature : pytest.fixture returning str
Fixture providing a WFS GetFeature response.
"""
features = self.datatype_class.from_wfs(wfs_getfeature,
self.namespace)
for feature in features:
assert isinstance(feature, self.datatype_class)
def test_from_wfs_bytes(self, wfs_getfeature):
"""Test the from_wfs method to construct objects from a WFS response,
as bytes.
Parameters
----------
wfs_getfeature : pytest.fixture returning str
Fixture providing a WFS GetFeature response.
"""
features = self.datatype_class.from_wfs(wfs_getfeature.encode('utf-8'),
self.namespace)
for feature in features:
assert isinstance(feature, self.datatype_class)
def test_from_wfs_tree(self, wfs_getfeature):
"""Test the from_wfs method to construct objects from a WFS response,
as elementtree.
Parameters
----------
wfs_getfeature : pytest.fixture returning str
Fixture providing a WFS GetFeature response.
"""
tree = etree.fromstring(wfs_getfeature.encode('utf8'))
features = self.datatype_class.from_wfs(tree, self.namespace)
for feature in features:
assert isinstance(feature, self.datatype_class)
def test_from_wfs_list(self, wfs_getfeature):
"""Test the from_wfs method to construct objects from a WFS response,
as list of elements.
Parameters
----------
wfs_getfeature : pytest.fixture returning str
Fixture providing a WFS GetFeature response.
"""
tree = etree.fromstring(wfs_getfeature.encode('utf8'))
feature_members = tree.find(
'.//{http://www.opengis.net/wfs/2.0}member')
if feature_members is not None:
fts = [ft for ft in feature_members]
features = self.datatype_class.from_wfs(fts, self.namespace)
for feature in features:
assert isinstance(feature, self.datatype_class)
def test_missing_pkey(self):
"""Test initialising an object type with a pkey of 'None'.
Test whether a ValueError is raised.
"""