-
Notifications
You must be signed in to change notification settings - Fork 2k
/
test_update.py
1638 lines (1333 loc) · 54.5 KB
/
test_update.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
# encoding: utf-8
"""Unit tests for ckan/logic/action/update.py."""
import __builtin__ as builtins
import datetime
import mock
import pytest
import ckan
import ckan.lib.app_globals as app_globals
import ckan.logic as logic
import ckan.plugins as p
import ckan.tests.factories as factories
import ckan.tests.helpers as helpers
from ckan import model
from ckan.common import config
from six import StringIO
from pyfakefs import fake_filesystem
real_open = open
fs = fake_filesystem.FakeFilesystem()
fake_os = fake_filesystem.FakeOsModule(fs)
fake_open = fake_filesystem.FakeFileOpen(fs)
def mock_open_if_open_fails(*args, **kwargs):
try:
return real_open(*args, **kwargs)
except (OSError, IOError):
return fake_open(*args, **kwargs)
def datetime_from_string(s):
"""Return a standard datetime.datetime object initialised from a string in
the same format used for timestamps in dictized activities (the format
produced by datetime.datetime.isoformat())
"""
return datetime.datetime.strptime(s, "%Y-%m-%dT%H:%M:%S.%f")
@pytest.mark.usefixtures("clean_db")
class TestUpdate(object):
def teardown(self):
# Since some of the test methods below use the mock module to patch
# things, we use this teardown() method to remove remove all patches.
# (This makes sure the patches always get removed even if the test
# method aborts with an exception or something.)
mock.patch.stopall()
# START-AFTER
def test_user_update_name(self):
"""Test that updating a user's name works successfully."""
# The canonical form of a test has four steps:
# 1. Setup any preconditions needed for the test.
# 2. Call the function that's being tested, once only.
# 3. Make assertions about the return value and/or side-effects of
# of the function that's being tested.
# 4. Do nothing else!
# 1. Setup.
user = factories.User()
user["name"] = "updated"
# 2. Make assertions about the return value and/or side-effects.
with pytest.raises(logic.ValidationError):
helpers.call_action("user_update", **user)
# END-BEFORE
def test_user_generate_apikey(self):
user = factories.User()
context = {"user": user["name"]}
result = helpers.call_action(
"user_generate_apikey", context=context, id=user["id"]
)
updated_user = helpers.call_action(
"user_show", context=context, id=user["id"]
)
assert updated_user["apikey"] != user["apikey"]
assert result["apikey"] == updated_user["apikey"]
def test_user_generate_apikey_sysadmin_user(self):
user = factories.User()
sysadmin = factories.Sysadmin()
context = {"user": sysadmin["name"], "ignore_auth": False}
result = helpers.call_action(
"user_generate_apikey", context=context, id=user["id"]
)
updated_user = helpers.call_action(
"user_show", context=context, id=user["id"]
)
assert updated_user["apikey"] != user["apikey"]
assert result["apikey"] == updated_user["apikey"]
def test_user_generate_apikey_nonexistent_user(self):
user = {
"id": "nonexistent",
"name": "nonexistent",
"email": "does@notexist.com",
}
context = {"user": user["name"]}
with pytest.raises(logic.NotFound):
helpers.call_action(
"user_generate_apikey", context=context, id=user["id"]
)
def test_user_update_with_id_that_does_not_exist(self):
user_dict = factories.User.attributes()
user_dict["id"] = "there's no user with this id"
with pytest.raises(logic.NotFound):
helpers.call_action("user_update", **user_dict)
def test_user_update_with_no_id(self):
user_dict = factories.User.attributes()
assert "id" not in user_dict
with pytest.raises(logic.ValidationError):
helpers.call_action("user_update", **user_dict)
@pytest.mark.parametrize(
"name",
(
"",
"a",
False,
0,
-1,
23,
"new",
"edit",
"search",
"a" * 200,
"Hi!",
"i++%",
),
)
def test_user_update_with_invalid_name(self, name):
user = factories.User()
user["name"] = name
with pytest.raises(logic.ValidationError):
helpers.call_action("user_update", **user)
def test_user_update_to_name_that_already_exists(self):
fred = factories.User(name="fred")
bob = factories.User(name="bob")
# Try to update fred and change his user name to bob, which is already
# bob's user name
fred["name"] = bob["name"]
with pytest.raises(logic.ValidationError):
helpers.call_action("user_update", **fred)
def test_user_update_password(self):
"""Test that updating a user's password works successfully."""
user = factories.User()
# FIXME we have to pass the email address to user_update even though
# we're not updating it, otherwise validation fails.
helpers.call_action(
"user_update",
id=user["id"],
name=user["name"],
email=user["email"],
password="new password",
)
# user_show() never returns the user's password, so we have to access
# the model directly to test it.
import ckan.model as model
updated_user = model.User.get(user["id"])
assert updated_user.validate_password("new password")
def test_user_update_with_short_password(self):
user = factories.User()
user["password"] = "xxx" # This password is too short.
with pytest.raises(logic.ValidationError):
helpers.call_action("user_update", **user)
def test_user_update_with_empty_password(self):
"""If an empty password is passed to user_update, nothing should
happen.
No error (e.g. a validation error) is raised, but the password is not
changed either.
"""
user_dict = factories.User.attributes()
original_password = user_dict["password"]
user_dict = factories.User(**user_dict)
user_dict["password"] = ""
helpers.call_action("user_update", **user_dict)
import ckan.model as model
updated_user = model.User.get(user_dict["id"])
assert updated_user.validate_password(original_password)
def test_user_update_with_null_password(self):
user = factories.User()
user["password"] = None
with pytest.raises(logic.ValidationError):
helpers.call_action("user_update", **user)
def test_user_update_with_invalid_password(self):
user = factories.User()
for password in (False, -1, 23, 30.7):
user["password"] = password
with pytest.raises(logic.ValidationError):
helpers.call_action("user_update", **user)
def test_user_update_without_email_address(self):
"""You have to pass an email address when you call user_update.
Even if you don't want to change the user's email address, you still
have to pass their current email address to user_update.
FIXME: The point of this feature seems to be to prevent people from
removing email addresses from user accounts, but making them post the
current email address every time they post to user update is just
annoying, they should be able to post a dict with no 'email' key to
user_update and it should simply not change the current email.
"""
user = factories.User()
del user["email"]
with pytest.raises(logic.ValidationError):
helpers.call_action("user_update", **user)
# TODO: Valid and invalid values for the rest of the user model's fields.
def test_user_update_activity_stream(self):
"""Test that the right activity is emitted when updating a user."""
user = factories.User()
before = datetime.datetime.utcnow()
# FIXME we have to pass the email address and password to user_update
# even though we're not updating those fields, otherwise validation
# fails.
helpers.call_action(
"user_update",
id=user["id"],
name=user["name"],
email=user["email"],
password=factories.User.attributes()["password"],
fullname="updated full name",
)
activity_stream = helpers.call_action(
"user_activity_list", id=user["id"]
)
latest_activity = activity_stream[0]
assert latest_activity["activity_type"] == "changed user"
assert latest_activity["object_id"] == user["id"]
assert latest_activity["user_id"] == user["id"]
after = datetime.datetime.utcnow()
timestamp = datetime_from_string(latest_activity["timestamp"])
assert timestamp >= before and timestamp <= after
def test_user_update_with_custom_schema(self):
"""Test that custom schemas passed to user_update do get used.
user_update allows a custom validation schema to be passed to it in the
context dict. This is just a simple test that if you pass a custom
schema user_update does at least call a custom method that's given in
the custom schema. We assume this means it did use the custom schema
instead of the default one for validation, so user_update's custom
schema feature does work.
"""
import ckan.logic.schema
user = factories.User()
# A mock validator method, it doesn't do anything but it records what
# params it gets called with and how many times.
mock_validator = mock.MagicMock()
# Build a custom schema by taking the default schema and adding our
# mock method to its 'id' field.
schema = ckan.logic.schema.default_update_user_schema()
schema["id"].append(mock_validator)
# Call user_update and pass our custom schema in the context.
# FIXME: We have to pass email and password even though we're not
# trying to update them, or validation fails.
helpers.call_action(
"user_update",
context={"schema": schema},
id=user["id"],
name=user["name"],
email=user["email"],
password=factories.User.attributes()["password"],
fullname="updated full name",
)
def test_user_update_multiple(self):
"""Test that updating multiple user attributes at once works."""
user = factories.User()
params = {
"id": user["id"],
"fullname": "updated full name",
"about": "updated about",
# FIXME: We shouldn't have to put email here since we're not
# updating it, but user_update sucks.
"email": user["email"],
# FIXME: We shouldn't have to put password here since we're not
# updating it, but user_update sucks.
"password": factories.User.attributes()["password"],
}
helpers.call_action("user_update", **params)
updated_user = helpers.call_action("user_show", id=user["id"])
assert updated_user["fullname"] == "updated full name"
assert updated_user["about"] == "updated about"
def test_user_update_does_not_return_password(self):
"""The user dict that user_update returns should not include the user's
password."""
user = factories.User()
params = {
"id": user["id"],
"fullname": "updated full name",
"about": "updated about",
"email": user["email"],
"password": factories.User.attributes()["password"],
}
updated_user = helpers.call_action("user_update", **params)
assert "password" not in updated_user
def test_user_update_does_not_return_apikey(self):
"""The user dict that user_update returns should not include the user's
API key."""
user = factories.User()
params = {
"id": user["id"],
"fullname": "updated full name",
"about": "updated about",
"email": user["email"],
"password": factories.User.attributes()["password"],
}
updated_user = helpers.call_action("user_update", **params)
assert "apikey" not in updated_user
def test_user_update_does_not_return_reset_key(self):
"""The user dict that user_update returns should not include the user's
reset key."""
import ckan.lib.mailer
import ckan.model
user = factories.User()
ckan.lib.mailer.create_reset_key(ckan.model.User.get(user["id"]))
params = {
"id": user["id"],
"fullname": "updated full name",
"about": "updated about",
"email": user["email"],
"password": factories.User.attributes()["password"],
}
updated_user = helpers.call_action("user_update", **params)
assert "reset_key" not in updated_user
def test_resource_reorder(self):
resource_urls = ["http://a.html", "http://b.html", "http://c.html"]
dataset = {
"name": "basic",
"resources": [{"url": url} for url in resource_urls],
}
dataset = helpers.call_action("package_create", **dataset)
created_resource_urls = [
resource["url"] for resource in dataset["resources"]
]
assert created_resource_urls == resource_urls
mapping = dict(
(resource["url"], resource["id"])
for resource in dataset["resources"]
)
# This should put c.html at the front
reorder = {"id": dataset["id"], "order": [mapping["http://c.html"]]}
helpers.call_action("package_resource_reorder", **reorder)
dataset = helpers.call_action("package_show", id=dataset["id"])
reordered_resource_urls = [
resource["url"] for resource in dataset["resources"]
]
assert reordered_resource_urls == [
"http://c.html",
"http://a.html",
"http://b.html",
]
reorder = {
"id": dataset["id"],
"order": [
mapping["http://b.html"],
mapping["http://c.html"],
mapping["http://a.html"],
],
}
helpers.call_action("package_resource_reorder", **reorder)
dataset = helpers.call_action("package_show", id=dataset["id"])
reordered_resource_urls = [
resource["url"] for resource in dataset["resources"]
]
assert reordered_resource_urls == [
"http://b.html",
"http://c.html",
"http://a.html",
]
def test_update_dataset_cant_change_type(self):
user = factories.User()
dataset = factories.Dataset(
type="dataset", name="unchanging", user=user
)
dataset = helpers.call_action(
"package_update",
id=dataset["id"],
name="unchanging",
type="cabinet",
)
assert dataset["type"] == "dataset"
assert (
helpers.call_action("package_show", id="unchanging")["type"]
== "dataset"
)
def test_update_organization_cant_change_type(self):
user = factories.User()
context = {"user": user["name"]}
org = factories.Organization(
type="organization", name="unchanging", user=user
)
org = helpers.call_action(
"organization_update",
context=context,
id=org["id"],
name="unchanging",
type="ragtagband",
)
assert org["type"] == "organization"
assert (
helpers.call_action("organization_show", id="unchanging")["type"]
== "organization"
)
def test_update_group_cant_change_type(self):
user = factories.User()
context = {"user": user["name"]}
group = factories.Group(type="group", name="unchanging", user=user)
group = helpers.call_action(
"group_update",
context=context,
id=group["id"],
name="unchanging",
type="favouritecolour",
)
assert group["type"] == "group"
assert (
helpers.call_action("group_show", id="unchanging")["type"]
== "group"
)
@pytest.mark.usefixtures("clean_db")
class TestDatasetUpdate(object):
def test_missing_id(self):
user = factories.User()
dataset = factories.Dataset(user=user)
with pytest.raises(logic.ValidationError):
helpers.call_action("package_update")
def test_name(self):
user = factories.User()
dataset = factories.Dataset(user=user)
dataset_ = helpers.call_action(
"package_update", id=dataset["id"], name="new-name"
)
assert dataset_["name"] == "new-name"
assert (
helpers.call_action("package_show", id=dataset["id"])["name"]
== "new-name"
)
def test_title(self):
user = factories.User()
dataset = factories.Dataset(user=user)
dataset_ = helpers.call_action(
"package_update", id=dataset["id"], title="New Title"
)
assert dataset_["title"] == "New Title"
assert (
helpers.call_action("package_show", id=dataset["id"])["title"]
== "New Title"
)
def test_extras(self):
user = factories.User()
dataset = factories.Dataset(user=user)
dataset_ = helpers.call_action(
"package_update",
id=dataset["id"],
extras=[{"key": u"original media", "value": u'"book"'}],
)
assert dataset_["extras"][0]["key"] == "original media"
assert dataset_["extras"][0]["value"] == '"book"'
dataset_ = helpers.call_action("package_show", id=dataset["id"])
assert dataset_["extras"][0]["key"] == "original media"
assert dataset_["extras"][0]["value"] == '"book"'
def test_license(self):
user = factories.User()
dataset = factories.Dataset(user=user)
dataset_ = helpers.call_action(
"package_update", id=dataset["id"], license_id="other-open"
)
assert dataset_["license_id"] == "other-open"
dataset_ = helpers.call_action("package_show", id=dataset["id"])
assert dataset_["license_id"] == "other-open"
def test_notes(self):
user = factories.User()
dataset = factories.Dataset(user=user)
dataset_ = helpers.call_action(
"package_update", id=dataset["id"], notes="some notes"
)
assert dataset_["notes"] == "some notes"
dataset_ = helpers.call_action("package_show", id=dataset["id"])
assert dataset_["notes"] == "some notes"
def test_resources(self):
user = factories.User()
dataset = factories.Dataset(user=user)
dataset_ = helpers.call_action(
"package_update",
id=dataset["id"],
resources=[
{
"alt_url": u"alt123",
"description": u"Full text.",
"somekey": "somevalue", # this is how to do resource extras
"extras": {u"someotherkey": u"alt234"}, # this isnt
"format": u"plain text",
"hash": u"abc123",
"position": 0,
"url": u"http://datahub.io/download/",
},
{
"description": u"Index of the novel",
"format": u"JSON",
"position": 1,
"url": u"http://datahub.io/index.json",
},
],
)
resources_ = dataset_["resources"]
assert resources_[0]["alt_url"] == "alt123"
assert resources_[0]["description"] == "Full text."
assert resources_[0]["somekey"] == "somevalue"
assert "extras" not in resources_[0]
assert "someotherkey" not in resources_[0]
assert resources_[0]["format"] == "plain text"
assert resources_[0]["hash"] == "abc123"
assert resources_[0]["position"] == 0
assert resources_[0]["url"] == "http://datahub.io/download/"
assert resources_[1]["description"] == "Index of the novel"
assert resources_[1]["format"] == "JSON"
assert resources_[1]["url"] == "http://datahub.io/index.json"
assert resources_[1]["position"] == 1
resources_ = helpers.call_action("package_show", id=dataset["id"])[
"resources"
]
assert resources_[0]["alt_url"] == "alt123"
assert resources_[0]["description"] == "Full text."
assert resources_[0]["somekey"] == "somevalue"
assert "extras" not in resources_[0]
assert "someotherkey" not in resources_[0]
assert resources_[0]["format"] == "plain text"
assert resources_[0]["hash"] == "abc123"
assert resources_[0]["position"] == 0
assert resources_[0]["url"] == "http://datahub.io/download/"
assert resources_[1]["description"] == "Index of the novel"
assert resources_[1]["format"] == "JSON"
assert resources_[1]["url"] == "http://datahub.io/index.json"
assert resources_[1]["position"] == 1
def test_tags(self):
user = factories.User()
dataset = factories.Dataset(user=user)
dataset_ = helpers.call_action(
"package_update",
id=dataset["id"],
tags=[{"name": u"russian"}, {"name": u"tolstoy"}],
)
tag_names = sorted([tag_dict["name"] for tag_dict in dataset_["tags"]])
assert tag_names == ["russian", "tolstoy"]
dataset_ = helpers.call_action("package_show", id=dataset["id"])
tag_names = sorted([tag_dict["name"] for tag_dict in dataset_["tags"]])
assert tag_names == ["russian", "tolstoy"]
def test_return_id_only(self):
user = factories.User()
dataset = factories.Dataset(user=user)
updated_dataset = helpers.call_action(
"package_update",
id=dataset["id"],
notes="Test",
context={"return_id_only": True},
)
assert updated_dataset == dataset["id"]
class TestUpdateSendEmailNotifications(object):
@pytest.mark.ckan_config("ckan.activity_streams_email_notifications", True)
@mock.patch("ckan.logic.action.update.request")
def test_calling_through_paster_doesnt_validates_auth(self, mock_request):
mock_request.environ.get.return_value = True
helpers.call_action("send_email_notifications")
@pytest.mark.ckan_config("ckan.activity_streams_email_notifications", True)
@mock.patch("ckan.logic.action.update.request")
def test_not_calling_through_paster_validates_auth(self, mock_request):
mock_request.environ.get.return_value = False
with pytest.raises(logic.NotAuthorized):
helpers.call_action(
"send_email_notifications", context={"ignore_auth": False}
)
@pytest.mark.ckan_config("ckan.plugins", "image_view")
@pytest.mark.usefixtures("clean_db", "with_plugins")
class TestResourceViewUpdate(object):
def test_resource_view_update(self):
resource_view = factories.ResourceView()
params = {
"id": resource_view["id"],
"title": "new title",
"description": "new description",
}
result = helpers.call_action("resource_view_update", **params)
assert result["title"] == params["title"]
assert result["description"] == params["description"]
@mock.patch("ckan.lib.datapreview")
def test_filterable_views_converts_filter_fields_and_values_into_filters_dict(
self, datapreview_mock
):
filterable_view = mock.MagicMock()
filterable_view.info.return_value = {"filterable": True}
datapreview_mock.get_view_plugin.return_value = filterable_view
resource_view = factories.ResourceView()
context = {}
params = {
"id": resource_view["id"],
"filter_fields": ["country", "weather", "country"],
"filter_values": ["Brazil", "warm", "Argentina"],
}
result = helpers.call_action("resource_view_update", context, **params)
expected_filters = {
"country": ["Brazil", "Argentina"],
"weather": ["warm"],
}
assert result["filters"] == expected_filters
def test_resource_view_update_requires_id(self):
params = {}
with pytest.raises(logic.ValidationError):
helpers.call_action("resource_view_update", **params)
def test_resource_view_update_requires_existing_id(self):
params = {"id": "inexistent_id"}
with pytest.raises(logic.NotFound):
helpers.call_action("resource_view_update", **params)
def test_resource_view_list_reorder(self):
resource_view_1 = factories.ResourceView(title="View 1")
resource_id = resource_view_1["resource_id"]
resource_view_2 = factories.ResourceView(
resource_id=resource_id, title="View 2"
)
resource_view_list = helpers.call_action(
"resource_view_list", id=resource_id
)
assert resource_view_list[0]["title"] == "View 1"
assert resource_view_list[1]["title"] == "View 2"
# Reorder views
result = helpers.call_action(
"resource_view_reorder",
id=resource_id,
order=[resource_view_2["id"], resource_view_1["id"]],
)
assert result["order"] == [
resource_view_2["id"],
resource_view_1["id"],
]
resource_view_list = helpers.call_action(
"resource_view_list", id=resource_id
)
assert resource_view_list[0]["title"] == "View 2"
assert resource_view_list[1]["title"] == "View 1"
def test_resource_view_list_reorder_just_one_id(self):
resource_view_1 = factories.ResourceView(title="View 1")
resource_id = resource_view_1["resource_id"]
resource_view_2 = factories.ResourceView(
resource_id=resource_id, title="View 2"
)
# Reorder Views back just by specifiying a single view to go first
result = helpers.call_action(
"resource_view_reorder",
id=resource_id,
order=[resource_view_2["id"]],
)
assert result["order"] == [
resource_view_2["id"],
resource_view_1["id"],
]
resource_view_list = helpers.call_action(
"resource_view_list", id=resource_id
)
assert resource_view_list[0]["title"] == "View 2"
assert resource_view_list[1]["title"] == "View 1"
def test_calling_with_only_id_doesnt_update_anything(self):
resource_view = factories.ResourceView()
params = {"id": resource_view["id"]}
result = helpers.call_action("resource_view_update", **params)
assert result == resource_view
@pytest.mark.ckan_config("ckan.plugins", "image_view recline_view")
@pytest.mark.usefixtures("clean_db", "with_plugins")
class TestResourceUpdate(object):
import cgi
class FakeFileStorage(cgi.FieldStorage):
def __init__(self, fp, filename):
self.file = fp
self.filename = filename
self.name = "upload"
def setup(self):
import ckan.model as model
model.repo.rebuild_db()
def test_url_only(self):
dataset = factories.Dataset()
resource = factories.Resource(package=dataset, url="http://first")
res_returned = helpers.call_action(
"resource_update", id=resource["id"], url="http://second"
)
assert res_returned["url"] == "http://second"
resource = helpers.call_action("resource_show", id=resource["id"])
assert resource["url"] == "http://second"
def test_extra_only(self):
dataset = factories.Dataset()
resource = factories.Resource(package=dataset, newfield="first")
res_returned = helpers.call_action(
"resource_update",
id=resource["id"],
url=resource["url"],
newfield="second",
)
assert res_returned["newfield"] == "second"
resource = helpers.call_action("resource_show", id=resource["id"])
assert resource["newfield"] == "second"
def test_both_extra_and_url(self):
dataset = factories.Dataset()
resource = factories.Resource(
package=dataset, url="http://first", newfield="first"
)
res_returned = helpers.call_action(
"resource_update",
id=resource["id"],
url="http://second",
newfield="second",
)
assert res_returned["url"] == "http://second"
assert res_returned["newfield"] == "second"
resource = helpers.call_action("resource_show", id=resource["id"])
assert res_returned["url"] == "http://second"
assert resource["newfield"] == "second"
def test_extra_gets_deleted_on_both_core_and_extra_update(self):
dataset = factories.Dataset()
resource = factories.Resource(
package=dataset, url="http://first", newfield="first"
)
res_returned = helpers.call_action(
"resource_update",
id=resource["id"],
url="http://second",
anotherfield="second",
)
assert res_returned["url"] == "http://second"
assert res_returned["anotherfield"] == "second"
assert "newfield" not in res_returned
resource = helpers.call_action("resource_show", id=resource["id"])
assert res_returned["url"] == "http://second"
assert res_returned["anotherfield"] == "second"
assert "newfield" not in res_returned
def test_extra_gets_deleted_on_extra_only_update(self):
dataset = factories.Dataset()
resource = factories.Resource(
package=dataset, url="http://first", newfield="first"
)
res_returned = helpers.call_action(
"resource_update",
id=resource["id"],
url="http://first",
anotherfield="second",
)
assert res_returned["url"] == "http://first"
assert res_returned["anotherfield"] == "second"
assert "newfield" not in res_returned
resource = helpers.call_action("resource_show", id=resource["id"])
assert res_returned["url"] == "http://first"
assert res_returned["anotherfield"] == "second"
assert "newfield" not in res_returned
def test_datastore_active_is_persisted_if_true_and_not_provided(self):
dataset = factories.Dataset()
resource = factories.Resource(
package=dataset, url="http://example.com", datastore_active=True
)
res_returned = helpers.call_action(
"resource_update",
id=resource["id"],
url="http://example.com",
name="Test",
)
assert res_returned["datastore_active"]
def test_datastore_active_is_persisted_if_false_and_not_provided(self):
dataset = factories.Dataset()
resource = factories.Resource(
package=dataset, url="http://example.com", datastore_active=False
)
res_returned = helpers.call_action(
"resource_update",
id=resource["id"],
url="http://example.com",
name="Test",
)
assert not res_returned["datastore_active"]
def test_datastore_active_is_updated_if_false_and_provided(self):
dataset = factories.Dataset()
resource = factories.Resource(
package=dataset, url="http://example.com", datastore_active=False
)
res_returned = helpers.call_action(
"resource_update",
id=resource["id"],
url="http://example.com",
name="Test",
datastore_active=True,
)
assert res_returned["datastore_active"]
def test_datastore_active_is_updated_if_true_and_provided(self):
dataset = factories.Dataset()
resource = factories.Resource(
package=dataset, url="http://example.com", datastore_active=True
)
res_returned = helpers.call_action(
"resource_update",
id=resource["id"],
url="http://example.com",
name="Test",
datastore_active=False,
)
assert not res_returned["datastore_active"]
def test_datastore_active_not_present_if_not_provided_and_not_datastore_plugin_enabled(
self,
):
assert not p.plugin_loaded("datastore")
dataset = factories.Dataset()
resource = factories.Resource(
package=dataset, url="http://example.com"
)
res_returned = helpers.call_action(
"resource_update",
id=resource["id"],
url="http://example.com",
name="Test",
)
assert "datastore_active" not in res_returned
@helpers.change_config("ckan.storage_path", "/doesnt_exist")
@mock.patch.object(ckan.lib.uploader, "os", fake_os)
@mock.patch.object(builtins, "open", side_effect=mock_open_if_open_fails)
@mock.patch.object(ckan.lib.uploader, "_storage_path", new="/doesnt_exist")
def test_mimetype_by_url(self, mock_open):
"""