-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathtests.py
2106 lines (1585 loc) · 77.3 KB
/
tests.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
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from StringIO import StringIO
from json import loads, dumps
from urlparse import urlparse
import urllib
import os
import json
import base64
import datetime
import psycopg2
from unittest.case import skip
from django.db import connection
from django.contrib.auth.models import AnonymousUser
from django.contrib.gis.geos import Point
from django.test.utils import override_settings
from django.test.client import Client, RequestFactory, ClientHandler
from django.http import HttpRequest
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.core.files import File
from treemap.lib.udf import udf_create
from treemap.models import Species, Plot, Tree, User, FieldPermission
from treemap.instance import create_stewardship_udfs
from treemap.audit import ReputationMetric, Audit
from treemap.udf import UserDefinedFieldDefinition
from treemap.tests import (make_user, make_request, set_invisible_permissions,
make_instance, LocalMediaTestCase, media_dir,
make_commander_user, set_write_permissions)
from treemap.tests.base import OTMTestCase
from exporter.tests import UserExportsTestCase
from api.test_utils import setupTreemapEnv, mkPlot, mkTree
from api.models import APIAccessCredential
from api.views import (add_photo_endpoint, update_profile_photo_endpoint,
instance_info_endpoint)
from api.instance import (instances_closest_to_point, instance_info,
public_instances)
from api.user import create_user
from api.auth import get_signature_for_request
from api.decorators import (check_signature, SIG_TIMESTAMP_FORMAT,
API_VERSIONS)
LATEST_API = str(max(API_VERSIONS))
API_PFX = "/api/v%s" % LATEST_API
def sign_request_as_user(request, user):
try:
cred = APIAccessCredential.objects.get(user=user)
except APIAccessCredential.DoesNotExist:
cred = APIAccessCredential.create(user=user)
return sign_request(request, cred)
def sign_request(request, cred=None):
if cred is None:
cred = APIAccessCredential.create()
nowstr = datetime.datetime.now().strftime(SIG_TIMESTAMP_FORMAT)
request.GET = request.GET.copy()
request.GET['timestamp'] = nowstr
request.GET['access_key'] = cred.access_key
sig = get_signature_for_request(request, cred.secret_key)
request.GET['signature'] = sig
return request
def _get_path(parsed_url):
"""
Taken from a class method in the Django test client
"""
# If there are parameters, add them
if parsed_url[3]:
return urllib.unquote(parsed_url[2] + ";" + parsed_url[3])
else:
return urllib.unquote(parsed_url[2])
def send_json_body(url, body_object, client, method, user=None):
"""
Serialize a list or dictionary to JSON then send it to an endpoint.
The "post" method exposed by the Django test client assumes that you
are posting form data, so you need to manually setup the parameters
to override that default functionality.
"""
body_string = dumps(body_object)
body_stream = StringIO(body_string)
parsed_url = urlparse(url)
client_params = {
'CONTENT_LENGTH': len(body_string),
'CONTENT_TYPE': 'application/json',
'PATH_INFO': _get_path(parsed_url),
'QUERY_STRING': parsed_url[4],
'REQUEST_METHOD': method,
'wsgi.input': body_stream,
}
return _send_with_client_params(url, client, client_params, user)
class SignedClientHandler(ClientHandler):
def __init__(self, sign, sign_as, *args, **kwargs):
self.sign = sign
self.sign_as = sign_as
super(SignedClientHandler, self).__init__(*args, **kwargs)
def get_response(self, req):
if self.sign:
req = sign_request_as_user(req, self.sign_as)
return super(SignedClientHandler, self).get_response(req)
def get_signed(client, *args, **kwargs):
handler = client.handler
client.handler = SignedClientHandler(True, kwargs.get('user', None))
resp = client.get(*args, **kwargs)
client.handler = handler
return resp
def _send_with_client_params(url, client, client_params, user=None):
handler = client.handler
client.handler = SignedClientHandler(True, user)
resp = client.post(url, **client_params)
client.handler = handler
return resp
def post_json(url, body_object, client, user=None):
"""
Serialize a list or dictionary to JSON then POST it to an endpoint.
The "post" method exposed by the Django test client assumes that you
are posting form data, so you need to manually setup the parameters
to override that default functionality.
"""
return send_json_body(url, body_object, client, 'POST', user)
def put_json(url, body_object, client, user=None):
return send_json_body(url, body_object, client, 'PUT', user)
def assert_reputation(test_case, expected_reputation):
"""
'test_case' object should have attributes 'user' and 'instance'
Tests whether user's reputation is as expected.
Reloads user object from database since reputation may have changed.
"""
user = User.objects.get(pk=test_case.user.id)
reputation = user.get_reputation(test_case.instance)
test_case.assertEqual(expected_reputation, reputation,
'Reputation is %s but %s was expected'
% (reputation, expected_reputation))
class Version(OTMTestCase):
def setUp(self):
setupTreemapEnv()
self.u = User.objects.get(username="jim")
def test_version(self):
settings.OTM_VERSION = "1.2.3"
settings.API_VERSION = "2"
ret = get_signed(self.client, "%s/version" % API_PFX)
self.assertEqual(ret.status_code, 200)
content = loads(ret.content)
self.assertEqual(content["otm_version"], settings.OTM_VERSION)
self.assertEqual(content["api_version"], settings.API_VERSION)
class PlotListing(OTMTestCase):
def setUp(self):
self.instance = setupTreemapEnv()
self.u = User.objects.get(username="commander")
self.client = Client()
def test_edits(self):
# TODO: Test recent edits
return None
user = self.u
get_signed(self.cliend, "%s/user/%s/edits" %
(API_PFX, user.pk))
def setup_edit_flags_test(self):
ghost = AnonymousUser()
self.ghost = ghost
peon = make_user(username="peon", password='pw')
peon.save_with_user(self.u)
duke = make_user(username="duke", password='pw')
duke.save_with_user(self.u)
leroi = make_user(username="leroi", password='pw')
leroi.active = True
leroi.save_with_user(self.u)
p_peon_0 = mkPlot(self.instance, self.u)
p_peon_1 = mkPlot(self.instance, self.u)
p_duke_2 = mkPlot(self.instance, self.u)
t_duke_0 = mkTree(self.instance, self.u, plot=p_peon_0)
t_peon_1 = mkTree(self.instance, self.u, plot=p_peon_1)
t_duke_2 = mkTree(self.instance, self.u, plot=p_duke_2)
p_roi_3 = mkPlot(self.instance, self.u)
t_roi_3 = mkTree(self.instance, self.u, plot=p_roi_3)
self.plots = [p_peon_0, p_peon_1, p_duke_2, p_roi_3]
self.trees = [t_duke_0, t_peon_1, t_duke_2, t_roi_3]
self.users = [ghost, peon, duke, leroi]
def mkd(self, e, d):
return {"can_delete": d, "can_edit": e}
def mkdp(self, pe, pd, te=None, td=None):
d = {"plot": self.mkd(pe, pd)}
if td is not None and te is not None:
d["tree"] = self.mkd(te, td)
return d
@skip("wait until this api is real")
def test_basic_data(self):
p = mkPlot(self.instance, self.u)
p.width = 22
p.length = 44
p.geom = Point(55, 56)
p.readonly = False
p.save_with_user(self.u)
info = self.client.get("%s/instance/%s/plots" %
(API_PFX, self.instance.url_name))
self.assertEqual(info.status_code, 200)
content = loads(info.content)
self.assertEqual(len(content), 1)
record = content[0]
self.assertEqual(record["id"], p.pk)
self.assertEqual(record["plot_width"], 22)
self.assertEqual(record["plot_length"], 44)
self.assertEqual(record["readonly"], False)
self.assertEqual(record["geom"]["srid"], 3857)
self.assertEqual(record["geom"]["x"], 55)
self.assertEqual(record["geom"]["y"], 56)
self.assertEqual(record.get("tree"), None)
@skip("wait for endpoint to be done")
def test_tree_data(self):
p = mkPlot(self.u)
t = mkTree(self.u, plot=p)
t.species = None
t.dbh = None
t.present = True
t.save()
info = self.client.get("%s/plots" % API_PFX)
self.assertEqual(info.status_code, 200)
content = loads(info.content)
self.assertEqual(content(json), 1)
record = content[0]
self.assertEqual(record["tree"]["id"], t.pk)
t.species = Species.objects.all()[0]
t.dbh = 11.2
t.save()
info = self.client.get("%s/plots" % API_PFX)
self.assertEqual(info.status_code, 200)
content = loads(info.content)
self.assertEqual(len(content), 1)
record = content[0]
self.assertEqual(record["tree"]["species"], t.species.pk)
self.assertEqual(record["tree"]["dbh"], t.dbh)
self.assertEqual(record["tree"]["id"], t.pk)
@skip("wait for endpoint to be done")
def test_paging(self):
p0 = mkPlot(self.u)
p0.present = False
p0.save()
p1 = mkPlot(self.u)
p2 = mkPlot(self.u)
p3 = mkPlot(self.u)
r = self.client.get("%s/plots?offset=0&size=2" % API_PFX)
rids = set([p["id"] for p in loads(r.content)])
self.assertEqual(rids, set([p1.pk, p2.pk]))
r = self.client.get("%s/plots?offset=1&size=2" % API_PFX)
rids = set([p["id"] for p in loads(r.content)])
self.assertEqual(rids, set([p2.pk, p3.pk]))
r = self.client.get("%s/plots?offset=2&size=2" % API_PFX)
rids = set([p["id"] for p in loads(r.content)])
self.assertEqual(rids, set([p3.pk]))
r = self.client.get("%s/plots?offset=3&size=2" % API_PFX)
rids = set([p["id"] for p in loads(r.content)])
self.assertEqual(rids, set())
r = self.client.get("%s/plots?offset=0&size=5" % API_PFX)
rids = set([p["id"] for p in loads(r.content)])
self.assertEqual(rids, set([p1.pk, p2.pk, p3.pk]))
class Locations(OTMTestCase):
def setUp(self):
self.instance = setupTreemapEnv()
self.user = User.objects.get(username="commander")
def test_locations_plots_endpoint_with_auth(self):
response = get_signed(
self.client,
"%s/instance/%s/locations/0,0/plots" % (API_PFX,
self.instance.url_name),
user=self.user)
self.assertEqual(response.status_code, 200)
def test_locations_plots_endpoint(self):
response = get_signed(
self.client,
"%s/instance/%s/locations/0,0/plots" % (API_PFX,
self.instance.url_name))
self.assertEqual(response.status_code, 200)
def test_locations_plots_endpoint_max_plots_param_must_be_a_number(self):
response = get_signed(
self.client,
"%s/instance/%s/locations/0,0/plots?max_plots=foo" % (
API_PFX, self.instance.url_name))
self.assertEqual(response.status_code, 400)
self.assertEqual(response.content,
'The max_plots parameter must be '
'a number between 1 and 500')
def test_locations_plots_max_plots_param_cannot_be_greater_than_500(self):
response = get_signed(
self.client,
"%s/instance/%s/locations/0,0/plots?max_plots=501" % (
API_PFX, self.instance.url_name))
self.assertEqual(response.status_code, 400)
self.assertEqual(response.content,
'The max_plots parameter must be '
'a number between 1 and 500')
response = get_signed(
self.client,
"%s/instance/%s/locations/0,0/plots?max_plots=500" %
(API_PFX, self.instance.url_name))
self.assertEqual(response.status_code, 200)
def test_locations_plots_endpoint_max_plots_param_cannot_be_less_than_1(
self):
response = get_signed(
self.client,
"%s/instance/%s/locations/0,0/plots?max_plots=0" %
(API_PFX, self.instance.url_name))
self.assertEqual(response.status_code, 400)
self.assertEqual(response.content,
'The max_plots parameter must be a '
'number between 1 and 500')
response = get_signed(
self.client,
"%s/instance/%s/locations/0,0/plots?max_plots=1" %
(API_PFX, self.instance.url_name))
self.assertEqual(response.status_code, 200)
def test_locations_plots_endpoint_distance_param_must_be_a_number(self):
response = get_signed(
self.client,
"%s/instance/%s/locations/0,0/plots?distance=foo" %
(API_PFX, self.instance.url_name))
self.assertEqual(response.status_code, 400)
self.assertEqual(response.content,
'The distance parameter must be a number')
response = get_signed(
self.client,
"%s/instance/%s/locations/0,0/plots?distance=42" %
(API_PFX, self.instance.url_name))
self.assertEqual(response.status_code, 200)
def test_plots(self):
plot = mkPlot(self.instance, self.user)
plot.save_with_user(self.user)
response = get_signed(
self.client,
"%s/instance/%s/locations/%s,%s/plots" %
(API_PFX, self.instance.url_name,
plot.geom.x, plot.geom.y))
self.assertEqual(response.status_code, 200)
class CreatePlotAndTree(OTMTestCase):
def setUp(self):
self.instance = setupTreemapEnv()
self.user = User.objects.get(username="commander")
rm = ReputationMetric(instance=self.instance, model_name='Plot',
action=Audit.Type.Insert, direct_write_score=2,
approval_score=20, denial_score=5)
rm.save()
def test_create_plot_with_tree(self):
data = {
"plot":
{'geom': {"y": 25,
"x": 35,
"srid": 3857}},
"tree": {
"height": 10.0
}}
# TODO: Need to create reputation metrics
plot_count = Plot.objects.count()
reputation_count = self.user.get_reputation(self.instance)
response = post_json("%s/instance/%s/plots" % (API_PFX,
self.instance.url_name),
data, self.client, self.user)
self.assertEqual(200, response.status_code,
"Create failed:" + response.content)
# Assert that a plot was added
self.assertEqual(plot_count + 1, Plot.objects.count())
# Assert that reputation went up
assert_reputation(self, reputation_count + 6)
response_json = loads(response.content)
self.assertTrue("id" in response_json['plot'])
id = response_json['plot']["id"]
plot = Plot.objects.get(pk=id)
self.assertEqual(35.0, plot.geom.x)
self.assertEqual(25.0, plot.geom.y)
tree = plot.current_tree()
self.assertIsNotNone(tree)
self.assertEqual(10.0, tree.height)
def test_create_plot_with_invalid_tree_returns_400(self):
data = {
"plot":
{'geom': {"y": 25,
"x": 35,
"srid": 3857}},
"tree": {
"height": 1000000
}}
tree_count = Tree.objects.count()
reputation_count = self.user.get_reputation(self.instance)
response = post_json("%s/instance/%s/plots" % (API_PFX,
self.instance.url_name),
data, self.client, self.user)
self.assertEqual(400,
response.status_code,
"Expected creating a million foot "
"tall tree to return 400:" + response.content)
body_dict = loads(response.content)
self.assertTrue('fieldErrors' in body_dict,
"Expected the body JSON to have a 'fieldErrors' key")
fieldErrors = body_dict['fieldErrors']
self.assertTrue('tree.height' in fieldErrors,
'Expected "treeHeight" to be in "fieldErrors"')
self.assertEqual('The height is too large',
fieldErrors['tree.height'][0])
# Assert that a tree was _not_ added
self.assertEqual(tree_count, Tree.objects.count())
# Assert that reputation was _not_ added
assert_reputation(self, reputation_count)
def test_create_plot_with_geometry(self):
data = {
"plot": {
"geom": {
"x": 35,
"y": 25,
"srid": 3857
},
},
"tree": {
"height": 10
}}
plot_count = Plot.objects.count()
reputation_count = self.user.get_reputation(self.instance)
response = post_json("%s/instance/%s/plots" % (API_PFX,
self.instance.url_name),
data, self.client, self.user)
self.assertEqual(200, response.status_code,
"Create failed:" + response.content)
# Assert that a plot was added
self.assertEqual(plot_count + 1, Plot.objects.count())
# Assert that reputation was added
assert_reputation(self, reputation_count + 6)
response_json = loads(response.content)
self.assertTrue("id" in response_json['plot'])
id = response_json['plot']["id"]
plot = Plot.objects.get(pk=id)
self.assertEqual(35.0, plot.geom.x)
self.assertEqual(25.0, plot.geom.y)
tree = plot.current_tree()
self.assertIsNotNone(tree)
self.assertEqual(10.0, tree.height)
class UpdatePlotAndTree(OTMTestCase):
def setUp(self):
psycopg2.extras.register_hstore(connection.cursor(), globally=True)
self.instance = setupTreemapEnv()
self.user = User.objects.get(username="commander")
self.public_user = User.objects.get(username="apprentice")
rm = ReputationMetric(instance=self.instance, model_name='Plot',
action=Audit.Type.Update, direct_write_score=2,
approval_score=5, denial_score=1)
rm.save()
def _makeUdfd(self, name, data_type, model_type='Plot', choices=None):
set_write_permissions(self.instance, self.user, model_type,
['udf:' + name])
datatype_dict = {'type': data_type}
if choices:
datatype_dict['choices'] = choices
UserDefinedFieldDefinition.objects.create(
instance=self.instance,
model_type=model_type,
datatype=json.dumps(datatype_dict),
iscollection=False,
name=name)
def test_invalid_plot_id_returns_404_and_a_json_error(self):
response = put_json("%s/instance/%s/plots/0" %
(API_PFX, self.instance.url_name),
{}, self.client, self.user)
self.assertEqual(404, response.status_code)
def test_update_plot(self):
test_plot = mkPlot(self.instance, self.user)
test_plot.width = 1
test_plot.length = 2
test_plot.geocoded_address = 'foo'
test_plot.save_with_user(self.user)
self.assertEqual(0, test_plot.geom.x)
self.assertEqual(0, test_plot.geom.y)
self.assertEqual(1, test_plot.width)
self.assertEqual(2, test_plot.length)
reputation_count = self.user.get_reputation(self.instance)
# Include `updated_by` because the app does send it,
# and the endpoint must ignore it.
updated_values = {'plot':
{'geom': {'y': 0.001, 'x': 0.001, 'srid': 4326},
'width': 11,
'length': 22,
'updated_by': self.user.pk}}
response = put_json("%s/instance/%s/plots/%d" %
(API_PFX, self.instance.url_name, test_plot.pk),
updated_values, self.client, self.user)
self.assertEqual(200, response.status_code)
response_json = loads(response.content)
self.assertAlmostEqual(0.001, response_json['plot']['geom']['y'])
self.assertAlmostEqual(0.001, response_json['plot']['geom']['x'])
self.assertEqual(11, response_json['plot']['width'])
self.assertEqual(22, response_json['plot']['length'])
assert_reputation(self, reputation_count + 6)
def test_update_plot_with_udfs(self):
self._makeUdfd('abc', 'choice', choices=['a', 'b', 'c'])
self._makeUdfd('def', 'choice', choices=['d', 'e', 'f'])
self._makeUdfd('multi-ghi', 'multichoice', choices=['g', 'h', 'i'])
self._makeUdfd('multi-jkl', 'multichoice', choices=['j', 'k', 'l'])
test_plot = mkPlot(self.instance, self.user)
test_plot.width = 1
test_plot.length = 2
test_plot.geocoded_address = 'foo'
test_plot.udfs['abc'] = 'a'
test_plot.udfs['multi-ghi'] = ['g', 'h']
test_plot.save_with_user(self.user)
self.assertEqual(test_plot.udfs['abc'], 'a')
self.assertEqual(test_plot.udfs['multi-ghi'], ['g', 'h'])
self.assertNotIn('def', test_plot.udfs)
self.assertNotIn('multi-jkl', test_plot.udfs)
# Include `updated_by` because the app does send it,
# and the endpoint must ignore it.
# Likewise, include `udf:def` set to empty string and
# `udf:multi-jkl` set to empty list, for the same reason.
updated_values = {'plot':
{'geom': {'y': 0.001, 'x': 0.001, 'srid': 4326},
'width': 11,
'length': 22,
'udf:abc': 'b',
'udf:def': '',
'udf:multi-ghi': '["g"]',
'udf:multi-jkl': '[]',
'updated_by': self.user.pk}}
response = put_json("%s/instance/%s/plots/%d" %
(API_PFX, self.instance.url_name, test_plot.pk),
updated_values, self.client, self.user)
self.assertEqual(200, response.status_code)
response_json = loads(response.content)
test_plot.refresh_from_db()
# It should have updated the plot.
self.assertEqual(test_plot.udfs['abc'], 'b')
# It should have sent the new value in the response.
self.assertEqual(response_json['plot']['udf:abc'], 'b')
self.assertEqual(test_plot.udfs['multi-ghi'], ['g'])
# It should have sent the new value in the response.
self.assertEqual(response_json['plot']['udf:multi-ghi'], ['g'])
# It should not have added 'def' to the plot udfs.
self.assertNotIn('def', test_plot.udfs)
self.assertEqual(response_json['plot']['udf:def'], None)
# It should not have added 'multi-jkl' to the plot udfs.
self.assertNotIn('multi-jkl', test_plot.udfs)
self.assertEqual(response_json['plot']['udf:multi-jkl'], None)
def test_update_tree_with_udfs(self):
self._makeUdfd('abc', 'choice', model_type='Tree',
choices=['a', 'b', 'c'])
self._makeUdfd('def', 'choice', model_type='Tree',
choices=['d', 'e', 'f'])
self._makeUdfd('multi-ghi', 'multichoice', model_type='Tree',
choices=['g', 'h', 'i'])
self._makeUdfd('multi-jkl', 'multichoice', model_type='Tree',
choices=['j', 'k', 'l'])
test_plot = mkPlot(self.instance, self.user)
test_plot = mkPlot(self.instance, self.user)
test_plot.width = 1
test_plot.length = 2
test_plot.geocoded_address = 'foo'
test_plot.save_with_user(self.user)
test_tree = mkTree(self.instance, self.user, plot=test_plot)
test_tree.udfs['abc'] = 'a'
test_tree.udfs['multi-ghi'] = ['g', 'h']
test_tree.save_with_user(self.user)
# and the endpoint must ignore it.
# Likewise, include `udf:def` set to empty string and
# `udf:multi-jkl` set to empty list, for the same reason.
updated_values = {'tree':
{'udf:abc': 'b',
'udf:def': '',
'udf:multi-ghi': '["g"]',
'udf:multi-jkl': '[]'}}
response = put_json("%s/instance/%s/plots/%d" %
(API_PFX, self.instance.url_name, test_plot.pk),
updated_values, self.client, self.user)
self.assertEqual(200, response.status_code)
response_json = loads(response.content)
test_tree.refresh_from_db()
# It should have updated the plot.
self.assertEqual(test_tree.udfs['abc'], 'b')
# It should have sent the new value in the response.
self.assertEqual(response_json['tree']['udf:abc'], 'b')
self.assertEqual(test_tree.udfs['multi-ghi'], ['g'])
# It should have sent the new value in the response.
self.assertEqual(response_json['tree']['udf:multi-ghi'], ['g'])
# It should not have added 'def' to the plot udfs.
self.assertNotIn('def', test_tree.udfs)
self.assertEqual(response_json['tree']['udf:def'], None)
# It should not have added 'multi-jkl' to the plot udfs.
self.assertNotIn('multi-jkl', test_tree.udfs)
self.assertEqual(response_json['tree']['udf:multi-jkl'], None)
@skip("ignore pending")
def test_update_plot_with_pending(self):
test_plot = mkPlot(self.instance, self.user)
test_plot.width = 1
test_plot.length = 2
test_plot.save_with_user(self.user)
self.assertEqual(50, test_plot.geom.x)
self.assertEqual(50, test_plot.geom.y)
self.assertEqual(1, test_plot.width)
self.assertEqual(2, test_plot.length)
self.assertEqual(0, len(Audit.pending_audits()),
"Expected the test to start with no pending records")
reputation_count = self.user.get_reputation(self.instance)
updated_values = {'geometry':
{'lat': 70, 'lon': 60},
'plot_width': 11,
'plot_length': 22}
# Send the edit request as a public user
response = put_json("%s/instance/%s/plots/%d" %
(API_PFX, self.instance.url_name, test_plot.pk),
updated_values, self.client, self.public_user)
self.assertEqual(200, response.status_code)
# Assert that nothing has changed.
# Pends should have been created instead
response_json = loads(response.content)
self.assertEqual(50, response_json['geom']['y'])
self.assertEqual(50, response_json['geom']['x'])
self.assertEqual(1, response_json['plot_width'])
self.assertEqual(2, response_json['plot_length'])
assert_reputation(self, reputation_count)
self.assertEqual(3, len(Audit.pending_audits()),
"Expected 3 pends, one for each edited field")
self.assertEqual(3, len(response_json['pending_edits'].keys()),
"Expected the json response to have a "
"pending_edits dict with 3 keys, one for each field")
def test_invalid_field_returns_200_field_is_not_in_response(self):
test_plot = mkPlot(self.instance, self.user)
updated_values = {'foo': 'bar'}
response = put_json("%s/instance/%s/plots/%d" %
(API_PFX, self.instance.url_name, test_plot.pk),
updated_values, self.client, self.user)
self.assertEqual(200, response.status_code)
response_json = loads(response.content)
self.assertFalse("error" in response_json.keys(),
"Did not expect an error")
self.assertFalse("foo" in response_json.keys(),
"Did not expect foo to be added to the plot")
def test_update_creates_tree(self):
test_plot = mkPlot(self.instance, self.user)
test_plot_id = test_plot.id
self.assertIsNone(test_plot.current_tree())
updated_values = {'tree': {'diameter': 1.2}}
response = put_json("%s/instance/%s/plots/%d" %
(API_PFX, self.instance.url_name, test_plot.pk),
updated_values, self.client, self.user)
self.assertEqual(200, response.status_code)
tree = Plot.objects.get(pk=test_plot_id).current_tree()
self.assertIsNotNone(tree)
self.assertEqual(1.2, tree.diameter)
# TODO: Waiting for issue to be fixed
# https://github.com/azavea/OTM2/issues/82
# def test_update_creates_tree_with_pending(self):
# test_plot = mkPlot(self.instance, self.user)
# test_plot_id = test_plot.id
# self.assertIsNone(test_plot.current_tree())
# self.assertEqual(0, len(Audit.pending_audits()),
# "Expected the test to start with no pending records")
# updated_values = {'tree': {'diameter': 1.2}}
# response = put_json("%s/instance/%s/plots/%d" %
# (API_PFX, self.instance.url_name, test_plot.pk),
# updated_values, self.client, self.public_user)
# self.assertEqual(200, response.status_code)
# self.assertEqual(0, len(Pending.objects.all()),
# "Expected a new tree to be created, "
# "rather than creating pends")
# tree = Plot.objects.get(pk=test_plot_id).current_tree()
# self.assertIsNotNone(tree)
# self.assertEqual(1.2, tree.dbh)
def test_update_tree(self):
test_plot = mkPlot(self.instance, self.user)
test_tree = mkTree(self.instance, self.user, plot=test_plot)
test_tree_id = test_tree.id
test_tree.diameter = 2.3
test_tree.save_with_user(self.user)
# Include `updated_by` because the app does send it,
# and the endpoint must ignore it.
updated_values = {'tree': {'diameter': 3.9},
'plot': {'updated_by': self.user.pk}}
response = put_json("%s/instance/%s/plots/%d" %
(API_PFX, self.instance.url_name, test_plot.id),
updated_values, self.client, self.user)
self.assertEqual(200, response.status_code)
tree = Tree.objects.get(pk=test_tree_id)
self.assertIsNotNone(tree)
self.assertEqual(3.9, tree.diameter)
def test_invalid_tree_update_returns_400(self):
test_plot = mkPlot(self.instance, self.user)
test_tree = mkTree(self.instance, self.user, plot=test_plot)
test_tree_id = test_tree.id
test_tree.diameter = 2.3
test_tree.save_with_user(self.user)
# Include `updated_by` because the app does send it,
# and the endpoint must ignore it.
updated_values = {'tree': {'diameter': 0}}
response = put_json("%s/instance/%s/plots/%d" %
(API_PFX, self.instance.url_name, test_plot.id),
updated_values, self.client, self.user)
self.assertEqual(400, response.status_code)
# Verify that the diameter was not changed
tree = Tree.objects.get(pk=test_tree_id)
self.assertIsNotNone(tree)
self.assertEqual(2.3, tree.diameter)
@skip("ignore pending")
def test_update_tree_with_pending(self):
test_plot = mkPlot(self.instance, self.user)
test_tree = mkTree(self.instance, self.user, plot=test_plot)
test_tree_id = test_tree.pk
test_tree.diameter = 2.3
test_tree.save_with_user(self.user)
self.assertEqual(0, len(Audit.pending_audits()),
"Expected the test to start with no pending records")
updated_values = {'tree': {'diameter': 3.9}}
response = put_json("%s/instance/%s/plots/%d" %
(API_PFX, self.instance.url_name, test_plot.pk),
updated_values, self.client, self.public_user)
self.assertEqual(200, response.status_code)
tree = Tree.objects.get(pk=test_tree_id)
self.assertIsNotNone(tree)
self.assertEqual(2.3, tree.diameter,
"A pend should have been created instead"
" of editing the tree value.")
self.assertEqual(1, len(Audit.pending_audits()),
"Expected 1 pend record for the edited field.")
response_json = loads(response.content)
self.assertEqual(1, len(response_json['pending_edits'].keys()),
"Expected the json response to have a"
" pending_edits dict with 1 keys")
def test_update_tree_species(self):
test_plot = mkPlot(self.instance, self.user)
test_tree = mkTree(self.instance, self.user, plot=test_plot)
test_tree_id = test_tree.id
first_species = Species.objects.all()[0]
updated_values = {'tree': {'species': {'id': first_species.id}}}
response = put_json("%s/instance/%s/plots/%d" %
(API_PFX, self.instance.url_name, test_plot.pk),
updated_values, self.client, self.user)
self.assertEqual(200, response.status_code)
tree = Tree.objects.get(pk=test_tree_id)
self.assertIsNotNone(tree)
self.assertEqual(first_species, tree.species)
def test_update_tree_returns_404_on_invalid_species_id(self):
test_plot = mkPlot(self.instance, self.user)
mkTree(self.instance, self.user, plot=test_plot)
invalid_species_id = -1
self.assertRaises(Exception,
Species.objects.get, pk=invalid_species_id)
updated_values = {'tree': {'species': {'id': invalid_species_id}}}
response = put_json("%s/instance/%s/plots/%d" %
(API_PFX, self.instance.url_name, test_plot.pk),
updated_values, self.client, self.user)
self.assertEqual(404, response.status_code)
def test_approve_pending_edit_returns_404_for_invalid_pend_id(self):
invalid_pend_id = -1
self.assertRaises(Exception, Audit.objects.get, pk=invalid_pend_id)
url = "%s/instance/%s/pending-edits/%d/approve/" % (
API_PFX, self.instance.url_name, invalid_pend_id)
response = post_json(url, None, self.client, self.user)
self.assertEqual(404, response.status_code,
"Expected approving and invalid "
"pend id to return 404")
def test_reject_pending_edit_returns_404_for_invalid_pend_id(self):
invalid_pend_id = -1
self.assertRaises(Exception, Audit.objects.get, pk=invalid_pend_id)
url = "%s/instance/%s/pending-edits/%d/reject/" % (
API_PFX, self.instance.url_name, invalid_pend_id)
response = post_json(url, None, self.client, self.user)
self.assertEqual(404, response.status_code,
"Expected approving and invalid pend "
" id to return 404")
@skip("waiting for pending integration")
def test_approve_pending_edit(self):
self.assert_pending_edit_operation(Audit.Type.PendingApprove)
@skip("waiting for pending integration")
def test_reject_pending_edit(self):
self.assert_pending_edit_operation(Audit.Type.PendingReject)
def assert_pending_edit_operation(self, action,
original_dbh=2.3, edited_dbh=3.9):
test_plot = mkPlot(self.instance, self.user)
test_tree = mkTree(self.instance, self.user, plot=test_plot)
test_tree_id = test_tree.id
test_tree.diameter = original_dbh
test_tree.save_with_user(self.user)