-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtest_client.py
More file actions
2971 lines (2400 loc) · 115 KB
/
test_client.py
File metadata and controls
2971 lines (2400 loc) · 115 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import logging
import os
import random
import tempfile
import subprocess
import shutil
from datetime import datetime, timedelta, date, timezone
import pytest
import pytz
import sqlite3
import glob
from .. import InvalidProject
from ..client import (
MerginClient,
AuthTokenExpiredError,
ClientError,
MerginProject,
LoginError,
decode_token_data,
TokenError,
ServerType,
WorkspaceRole,
)
from ..client_push import push_project_async, push_project_cancel
from ..client_pull import (
download_project_async,
download_project_wait,
download_project_finalize,
download_project_is_running,
download_project_cancel,
)
from ..utils import (
generate_checksum,
get_versions_with_file_changes,
unique_path_name,
conflicted_copy_file_name,
edit_conflict_file_name,
)
from ..merginproject import pygeodiff
from ..report import create_report
from ..editor import EDITOR_ROLE_NAME, filter_changes, is_editor_enabled
from ..common import ErrorCode, WorkspaceRole, ProjectRole
SERVER_URL = os.environ.get("TEST_MERGIN_URL")
API_USER = os.environ.get("TEST_API_USERNAME")
USER_PWD = os.environ.get("TEST_API_PASSWORD")
API_USER2 = os.environ.get("TEST_API_USERNAME2")
USER_PWD2 = os.environ.get("TEST_API_PASSWORD2")
TMP_DIR = tempfile.gettempdir()
TEST_DATA_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "test_data")
CHANGED_SCHEMA_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "modified_schema")
STORAGE_WORKSPACE = os.environ.get("TEST_STORAGE_WORKSPACE", "testpluginstorage")
json_headers = {"Content-Type": "application/json"}
def get_limit_overrides(storage: int):
return {"storage": storage, "projects": 2, "api_allowed": True}
@pytest.fixture(scope="function")
def mc():
client = create_client(API_USER, USER_PWD)
create_workspace_for_client(client)
return client
@pytest.fixture(scope="function")
def mc2():
client = create_client(API_USER2, USER_PWD2)
create_workspace_for_client(client)
return client
@pytest.fixture(scope="function")
def mcStorage(request):
client = create_client(API_USER, USER_PWD)
workspace_name = create_workspace_for_client(client, STORAGE_WORKSPACE)
client_workspace = None
for workspace in client.workspaces_list():
if workspace["name"] == workspace_name:
client_workspace = workspace
break
client_workspace_id = client_workspace["id"]
client_workspace_storage = client_workspace["storage"]
def teardown():
# back to original values... (1 project, api allowed ...)
client.patch(
f"/v1/tests/workspaces/{client_workspace_id}",
{"limits_override": get_limit_overrides(client_workspace_storage)},
{"Content-Type": "application/json"},
)
request.addfinalizer(teardown)
return client
def create_client(user, pwd):
assert SERVER_URL and SERVER_URL.rstrip("/") != "https://app.merginmaps.com" and user and pwd
return MerginClient(SERVER_URL, login=user, password=pwd)
def create_workspace_for_client(mc: MerginClient, workspace_name=None) -> str:
workspace_name = workspace_name or mc.username()
try:
mc.create_workspace(workspace_name)
except ClientError:
pass
return workspace_name
def cleanup(mc, project, dirs):
# cleanup leftovers from previous test if needed such as remote project and local directories
try:
mc.delete_project_now(project)
except ClientError:
pass
remove_folders(dirs)
def remove_folders(dirs):
# clean given directories
for d in dirs:
if os.path.exists(d):
shutil.rmtree(d)
def sudo_works():
sudo_res = subprocess.run(["sudo", "echo", "test"])
return sudo_res.returncode != 0
def server_has_editor_support(mc, access):
"""
Checks if the server has editor support based on the provided access information.
Returns:
bool: True if the server has editor support, False otherwise.
"""
return "editorsnames" in access and mc.has_editor_support()
def test_client_instance(mc, mc2):
assert isinstance(mc, MerginClient)
assert isinstance(mc2, MerginClient)
def test_login(mc):
token = mc._auth_session["token"]
assert MerginClient(mc.url, auth_token=token)
invalid_token = "Completely invalid token...."
with pytest.raises(TokenError, match=f"Token doesn't start with 'Bearer .': {invalid_token}"):
decode_token_data(invalid_token)
invalid_token = "Bearer .jas646kgfa"
with pytest.raises(TokenError, match=f"Invalid token data: {invalid_token}"):
decode_token_data(invalid_token)
with pytest.raises(LoginError, match="Invalid username or password"):
mc.login("foo", "bar")
def test_create_delete_project(mc: MerginClient):
test_project = "test_create_delete"
project = API_USER + "/" + test_project
project_dir = os.path.join(TMP_DIR, test_project)
download_dir = os.path.join(TMP_DIR, "download", test_project)
cleanup(mc, project, [project_dir, download_dir])
# create new (empty) project on server
mc.create_project(test_project)
projects = mc.projects_list(flag="created")
assert any(p for p in projects if p["name"] == test_project and p["namespace"] == API_USER)
# try again
with pytest.raises(ClientError, match=f"already exists"):
mc.create_project(test_project)
# remove project
mc.delete_project_now(API_USER + "/" + test_project)
projects = mc.projects_list(flag="created")
assert not any(p for p in projects if p["name"] == test_project and p["namespace"] == API_USER)
# try again, nothing to delete
with pytest.raises(ClientError):
mc.delete_project_now(API_USER + "/" + test_project)
# test that using namespace triggers deprecate warning, but creates project correctly
with pytest.deprecated_call(match=r"The usage of `namespace` parameter in `create_project\(\)` is deprecated."):
mc.create_project(test_project, namespace=API_USER)
projects = mc.projects_list(flag="created")
assert any(p for p in projects if p["name"] == test_project and p["namespace"] == API_USER)
mc.delete_project_now(project)
# test that using only project name triggers deprecate warning, but creates project correctly
with pytest.deprecated_call(match=r"The use of only project name in `create_project\(\)` is deprecated"):
mc.create_project(test_project)
projects = mc.projects_list(flag="created")
assert any(p for p in projects if p["name"] == test_project and p["namespace"] == API_USER)
mc.delete_project_now(project)
# test that even if project is specified with full name and namespace is specified a warning is raised, but still create project correctly
with pytest.warns(UserWarning, match="Parameter `namespace` specified with full project name"):
mc.create_project(project, namespace=API_USER)
projects = mc.projects_list(flag="created")
assert any(p for p in projects if p["name"] == test_project and p["namespace"] == API_USER)
mc.delete_project_now(project)
# test that create project with full name works
mc.create_project(project)
projects = mc.projects_list(flag="created")
assert any(p for p in projects if p["name"] == test_project and p["namespace"] == API_USER)
mc.delete_project_now(project)
def test_create_remote_project_from_local(mc):
test_project = "test_project"
project = API_USER + "/" + test_project
project_dir = os.path.join(TMP_DIR, test_project)
download_dir = os.path.join(TMP_DIR, "download", test_project)
cleanup(mc, project, [project_dir, download_dir])
# prepare local project
shutil.copytree(TEST_DATA_DIR, project_dir)
# create remote project
mc.create_project_and_push(project, directory=project_dir)
# verify we have correct metadata
source_mp = MerginProject(project_dir)
assert source_mp.project_full_name() == f"{API_USER}/{test_project}"
assert source_mp.project_name() == test_project
assert source_mp.workspace_name() == API_USER
assert source_mp.version() == "v1"
# check basic metadata about created project
project_info = mc.project_info(project)
assert project_info["version"] == "v1"
assert project_info["name"] == test_project
assert project_info["namespace"] == API_USER
assert project_info["id"] == source_mp.project_id()
# check project metadata retrieval by id
project_info = mc.project_info(source_mp.project_id())
assert project_info["version"] == "v1"
assert project_info["name"] == test_project
assert project_info["namespace"] == API_USER
assert project_info["id"] == source_mp.project_id()
version = mc.project_version_info(project_info.get("id"), "v1")
assert version["name"] == "v1"
assert any(f for f in version["changes"]["added"] if f["path"] == "test.qgs")
# check we can fully download remote project
mc.download_project(project, download_dir)
mp = MerginProject(download_dir)
downloads = {"dir": os.listdir(mp.dir), "meta": os.listdir(mp.meta_dir)}
for f in os.listdir(project_dir) + [".mergin"]:
assert f in downloads["dir"]
if mp.is_versioned_file(f):
assert f in downloads["meta"]
# unable to download to the same directory
with pytest.raises(Exception, match="Project directory already exists"):
mc.download_project(project, download_dir)
def test_push_pull_changes(mc):
test_project = "test_push"
project = API_USER + "/" + test_project
project_dir = os.path.join(TMP_DIR, test_project) # primary project dir for updates
project_dir_2 = os.path.join(TMP_DIR, test_project + "_2") # concurrent project dir
cleanup(mc, project, [project_dir, project_dir_2])
# create remote project
shutil.copytree(TEST_DATA_DIR, project_dir)
mc.create_project_and_push(project, project_dir)
# make sure we have v1 also in concurrent project dir
mc.download_project(project, project_dir_2)
mp2 = MerginProject(project_dir_2)
assert mp2.project_full_name() == f"{API_USER}/{test_project}"
assert mp2.project_name() == test_project
assert mp2.workspace_name() == API_USER
assert mp2.version() == "v1"
# test push changes (add, remove, rename, update)
f_added = "new.txt"
with open(os.path.join(project_dir, f_added), "w") as f:
f.write("new file")
f_removed = "test.txt"
os.remove(os.path.join(project_dir, f_removed))
f_renamed = "test_dir/test2.txt"
shutil.move(
os.path.normpath(os.path.join(project_dir, f_renamed)),
os.path.join(project_dir, "renamed.txt"),
)
f_updated = "test3.txt"
with open(os.path.join(project_dir, f_updated), "w") as f:
f.write("Modified")
# check changes before applied
pull_changes, push_changes, _ = mc.project_status(project_dir)
assert not sum(len(v) for v in pull_changes.values())
assert next((f for f in push_changes["added"] if f["path"] == f_added), None)
assert next((f for f in push_changes["removed"] if f["path"] == f_removed), None)
assert next((f for f in push_changes["updated"] if f["path"] == f_updated), None)
# renamed file will result in removed + added file
assert next((f for f in push_changes["removed"] if f["path"] == f_renamed), None)
assert next((f for f in push_changes["added"] if f["path"] == "renamed.txt"), None)
assert not pull_changes["renamed"] # not supported
mc.push_project(project_dir)
mp = MerginProject(project_dir)
assert mp.project_full_name() == f"{API_USER}/{test_project}"
assert mp.version() == "v2"
project_info = mc.project_info(project)
assert project_info["version"] == "v2"
assert not next((f for f in project_info["files"] if f["path"] == f_removed), None)
assert not next((f for f in project_info["files"] if f["path"] == f_renamed), None)
assert next((f for f in project_info["files"] if f["path"] == "renamed.txt"), None)
assert next((f for f in project_info["files"] if f["path"] == f_added), None)
f_remote_checksum = next((f["checksum"] for f in project_info["files"] if f["path"] == f_updated), None)
assert generate_checksum(os.path.join(project_dir, f_updated)) == f_remote_checksum
assert project_info["id"] == mp.project_id()
assert len(project_info["files"]) == len(mp.inspect_files())
project_version = mc.project_version_info(project_info["id"], "v2")
updated_file = [f for f in project_version["changes"]["updated"] if f["path"] == f_updated][0]
assert "origin_checksum" not in updated_file # internal client info
# test parallel changes
with open(os.path.join(project_dir_2, f_updated), "w") as f:
f.write("Make some conflict")
f_conflict_checksum = generate_checksum(os.path.join(project_dir_2, f_updated))
# not at latest server version
with pytest.raises(ClientError, match="Please update your local copy"):
mc.push_project(project_dir_2)
# check changes in project_dir_2 before applied
pull_changes, push_changes, _ = mc.project_status(project_dir_2)
assert next((f for f in pull_changes["added"] if f["path"] == f_added), None)
assert next((f for f in pull_changes["removed"] if f["path"] == f_removed), None)
assert next((f for f in pull_changes["updated"] if f["path"] == f_updated), None)
assert next((f for f in pull_changes["removed"] if f["path"] == f_renamed), None)
assert next((f for f in pull_changes["added"] if f["path"] == "renamed.txt"), None)
mc.pull_project(project_dir_2)
assert os.path.exists(os.path.join(project_dir_2, f_added))
assert not os.path.exists(os.path.join(project_dir_2, f_removed))
assert not os.path.exists(os.path.join(project_dir_2, f_renamed))
assert os.path.exists(os.path.join(project_dir_2, "renamed.txt"))
assert os.path.exists(os.path.join(project_dir_2, conflicted_copy_file_name(f_updated, API_USER, 1)))
assert (
generate_checksum(os.path.join(project_dir_2, conflicted_copy_file_name(f_updated, API_USER, 1)))
== f_conflict_checksum
)
assert generate_checksum(os.path.join(project_dir_2, f_updated)) == f_remote_checksum
def test_cancel_push(mc):
"""
Start pushing and cancel the process, then try to push again and check if previous sync process was cleanly
finished.
"""
test_project = "test_cancel_push"
project = API_USER + "/" + test_project
project_dir = os.path.join(TMP_DIR, test_project + "_3") # primary project dir for updates
project_dir_2 = os.path.join(TMP_DIR, test_project + "_4")
cleanup(mc, project, [project_dir, project_dir_2])
# create remote project
shutil.copytree(TEST_DATA_DIR, project_dir)
mc.create_project_and_push(project, project_dir)
# modify the project (add, update)
f_added = "new.txt"
with open(os.path.join(project_dir, f_added), "w") as f:
f.write("new file")
f_updated = "test3.txt"
modification = "Modified"
with open(os.path.join(project_dir, f_updated), "w") as f:
f.write(modification)
# check changes before applied
pull_changes, push_changes, _ = mc.project_status(project_dir)
assert not sum(len(v) for v in pull_changes.values())
assert next((f for f in push_changes["added"] if f["path"] == f_added), None)
assert next((f for f in push_changes["updated"] if f["path"] == f_updated), None)
# start pushing and then cancel the job
job = push_project_async(mc, project_dir)
push_project_cancel(job)
# if cancelled properly, we should be now able to do the push without any problem
mc.push_project(project_dir)
# download the project to a different directory and check the version and content
mc.download_project(project, project_dir_2)
mp = MerginProject(project_dir_2)
assert mp.version() == "v2"
assert os.path.exists(os.path.join(project_dir_2, f_added))
with open(os.path.join(project_dir_2, f_updated), "r") as f:
assert f.read() == modification
def test_ignore_files(mc):
test_project = "test_blacklist"
project = API_USER + "/" + test_project
project_dir = os.path.join(TMP_DIR, test_project) # primary project dir for updates
cleanup(mc, project, [project_dir])
# create remote project
shutil.copytree(TEST_DATA_DIR, project_dir)
shutil.copy(os.path.join(project_dir, "test.qgs"), os.path.join(project_dir, "test.qgs~"))
mc.create_project_and_push(project, project_dir)
project_info = mc.project_info(project)
assert not next((f for f in project_info["files"] if f["path"] == "test.qgs~"), None)
with open(os.path.join(project_dir, ".directory"), "w") as f:
f.write("test")
mc.push_project(project_dir)
assert not next((f for f in project_info["files"] if f["path"] == ".directory"), None)
def test_sync_diff(mc):
test_project = f"test_sync_diff"
project = API_USER + "/" + test_project
project_dir = os.path.join(TMP_DIR, test_project) # primary project dir for updates
project_dir_2 = os.path.join(TMP_DIR, test_project + "_2") # concurrent project dir with no changes
project_dir_3 = os.path.join(TMP_DIR, test_project + "_3") # concurrent project dir with local changes
cleanup(mc, project, [project_dir, project_dir_2, project_dir_3])
# create remote project
shutil.copytree(TEST_DATA_DIR, project_dir)
mc.create_project_and_push(project, project_dir)
# make sure we have v1 also in concurrent project dirs
mc.download_project(project, project_dir_2)
mc.download_project(project, project_dir_3)
# test push changes with diffs:
mp = MerginProject(project_dir)
f_updated = "base.gpkg"
# step 1) base.gpkg updated to inserted_1_A (inserted A feature)
shutil.move(mp.fpath(f_updated), mp.fpath_meta(f_updated)) # make local copy for changeset calculation
shutil.copy(mp.fpath("inserted_1_A.gpkg"), mp.fpath(f_updated))
mc.push_project(project_dir)
mp.geodiff.create_changeset(mp.fpath(f_updated), mp.fpath_meta(f_updated), mp.fpath_meta("push_diff"))
assert not mp.geodiff.has_changes(mp.fpath_meta("push_diff"))
# step 2) base.gpkg updated to inserted_1_A_mod (modified 2 features)
shutil.move(mp.fpath(f_updated), mp.fpath_meta(f_updated))
shutil.copy(mp.fpath("inserted_1_A_mod.gpkg"), mp.fpath(f_updated))
# introduce some other changes
f_removed = "inserted_1_B.gpkg"
os.remove(mp.fpath(f_removed))
f_renamed = "test_dir/modified_1_geom.gpkg"
shutil.move(mp.fpath(f_renamed), mp.fpath("renamed.gpkg"))
mc.push_project(project_dir)
# check project after push
project_info = mc.project_info(project)
assert project_info["version"] == "v3"
assert project_info["id"] == mp.project_id()
f_remote = next((f for f in project_info["files"] if f["path"] == f_updated), None)
assert next((f for f in project_info["files"] if f["path"] == "renamed.gpkg"), None)
assert not next((f for f in project_info["files"] if f["path"] == f_removed), None)
assert not os.path.exists(mp.fpath_meta(f_removed))
assert "diff" in f_remote
assert os.path.exists(mp.fpath_meta("renamed.gpkg"))
# pull project in different directory
mp2 = MerginProject(project_dir_2)
mc.pull_project(project_dir_2)
mp2.geodiff.create_changeset(mp.fpath(f_updated), mp2.fpath(f_updated), mp2.fpath_meta("diff"))
assert not mp2.geodiff.has_changes(mp2.fpath_meta("diff"))
# introduce conflict local change (inserted B feature to base)
mp3 = MerginProject(project_dir_3)
shutil.copy(mp3.fpath("inserted_1_B.gpkg"), mp3.fpath(f_updated))
checksum = generate_checksum(mp3.fpath("inserted_1_B.gpkg"))
mc.pull_project(project_dir_3)
assert not os.path.exists(mp3.fpath("base.gpkg_conflict_copy"))
# push new changes from project_3 and pull in original project
mc.push_project(project_dir_3)
mc.pull_project(project_dir)
mp3.geodiff.create_changeset(mp.fpath(f_updated), mp3.fpath(f_updated), mp.fpath_meta("diff"))
assert not mp3.geodiff.has_changes(mp.fpath_meta("diff"))
def test_list_of_push_changes(mc):
PUSH_CHANGES_SUMMARY = {
"base.gpkg": {"geodiff_summary": [{"table": "simple", "insert": 1, "update": 0, "delete": 0}]}
}
test_project = "test_list_of_push_changes"
project = API_USER + "/" + test_project
project_dir = os.path.join(TMP_DIR, test_project) # primary project dir for updates
cleanup(mc, project, [project_dir])
shutil.copytree(TEST_DATA_DIR, project_dir)
mc.create_project_and_push(project, project_dir)
f_updated = "base.gpkg"
mp = MerginProject(project_dir)
shutil.copy(mp.fpath("inserted_1_A.gpkg"), mp.fpath(f_updated))
mc._auth_session["expire"] = datetime.now().replace(tzinfo=pytz.utc) - timedelta(days=1)
pull_changes, push_changes, push_changes_summary = mc.project_status(project_dir)
assert push_changes_summary == PUSH_CHANGES_SUMMARY
def test_token_renewal(mc):
"""Test token regeneration in case it has expired."""
test_project = "test_token_renewal"
project = API_USER + "/" + test_project
project_dir = os.path.join(TMP_DIR, test_project) # primary project dir for updates
cleanup(mc, project, [project_dir])
shutil.copytree(TEST_DATA_DIR, project_dir)
mc.create_project_and_push(project, project_dir)
mc._auth_session["expire"] = datetime.now().replace(tzinfo=pytz.utc) - timedelta(days=1)
pull_changes, push_changes, _ = mc.project_status(project_dir)
to_expire = mc._auth_session["expire"] - datetime.now().replace(tzinfo=pytz.utc)
assert to_expire.total_seconds() > (9 * 3600)
def test_force_gpkg_update(mc):
test_project = "test_force_update"
project = API_USER + "/" + test_project
project_dir = os.path.join(TMP_DIR, test_project) # primary project dir for updates
cleanup(mc, project, [project_dir])
# create remote project
shutil.copytree(TEST_DATA_DIR, project_dir)
mc.create_project_and_push(project, project_dir)
# test push changes with force gpkg file upload:
mp = MerginProject(project_dir)
f_updated = "base.gpkg"
checksum = generate_checksum(mp.fpath(f_updated))
# base.gpkg updated to modified_schema (inserted new column)
shutil.move(
mp.fpath(f_updated), mp.fpath_meta(f_updated)
) # make local copy for changeset calculation (which will fail)
shutil.copy(os.path.join(CHANGED_SCHEMA_DIR, "modified_schema.gpkg"), mp.fpath(f_updated))
shutil.copy(
os.path.join(CHANGED_SCHEMA_DIR, "modified_schema.gpkg-wal"),
mp.fpath(f_updated + "-wal"),
)
mc.push_project(project_dir)
# by this point local file has been updated (changes committed from wal)
updated_checksum = generate_checksum(mp.fpath(f_updated))
assert checksum != updated_checksum
# check project after push
project_info = mc.project_info(project)
assert project_info["version"] == "v2"
f_remote = next((f for f in project_info["files"] if f["path"] == f_updated), None)
assert "diff" not in f_remote
def test_new_project_sync(mc):
"""Create a new project, download it, add a file and then do sync - it should not fail"""
test_project = "test_new_project_sync"
project = API_USER + "/" + test_project
project_dir = os.path.join(TMP_DIR, test_project) # primary project dir for updates
cleanup(mc, project, [project_dir])
# create remote project
mc.create_project(test_project)
# download the project
mc.download_project(project, project_dir)
# add a test file
shutil.copy(os.path.join(TEST_DATA_DIR, "test.txt"), project_dir)
# do a full sync - it should not fail
mc.pull_project(project_dir)
mc.push_project(project_dir)
# make sure everything is up-to-date
mp = MerginProject(project_dir)
local_changes = mp.get_push_changes()
assert not local_changes["added"] and not local_changes["removed"] and not local_changes["updated"]
def test_missing_basefile_pull(mc):
"""Test pull of a project where basefile of a .gpkg is missing for some reason
(it should gracefully handle it by downloading the missing basefile)
"""
test_project = "test_missing_basefile_pull"
project = API_USER + "/" + test_project
project_dir = os.path.join(TMP_DIR, test_project) # primary project dir for updates
project_dir_2 = os.path.join(TMP_DIR, test_project + "_2") # concurrent project dir
test_data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), test_project)
cleanup(mc, project, [project_dir, project_dir_2])
# create remote project
shutil.copytree(test_data_dir, project_dir)
mc.create_project_and_push(project, project_dir)
# update our gpkg in a different directory
mc.download_project(project, project_dir_2)
shutil.copy(
os.path.join(TEST_DATA_DIR, "inserted_1_A.gpkg"),
os.path.join(project_dir_2, "base.gpkg"),
)
mc.pull_project(project_dir_2)
mc.push_project(project_dir_2)
# make some other local change
shutil.copy(
os.path.join(TEST_DATA_DIR, "inserted_1_B.gpkg"),
os.path.join(project_dir, "base.gpkg"),
)
# remove the basefile to simulate the issue
os.remove(os.path.join(project_dir, ".mergin", "base.gpkg"))
# try to sync again -- it should not crash
mc.pull_project(project_dir)
mc.push_project(project_dir)
def test_empty_file_in_subdir(mc):
"""Test pull of a project where there is an empty file in a sub-directory"""
test_project = "test_empty_file_in_subdir"
project = API_USER + "/" + test_project
project_dir = os.path.join(TMP_DIR, test_project) # primary project dir for updates
project_dir_2 = os.path.join(TMP_DIR, test_project + "_2") # concurrent project dir
test_data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), test_project)
cleanup(mc, project, [project_dir, project_dir_2])
# create remote project
shutil.copytree(test_data_dir, project_dir)
mc.create_project_and_push(project, project_dir)
# try to check out the project
mc.download_project(project, project_dir_2)
assert os.path.exists(os.path.join(project_dir_2, "subdir", "empty.txt"))
# add another empty file in a different subdir
os.mkdir(os.path.join(project_dir, "subdir2"))
shutil.copy(
os.path.join(project_dir, "subdir", "empty.txt"),
os.path.join(project_dir, "subdir2", "empty2.txt"),
)
mc.push_project(project_dir)
# check that pull works fine
mc.pull_project(project_dir_2)
assert os.path.exists(os.path.join(project_dir_2, "subdir2", "empty2.txt"))
def test_clone_project(mc: MerginClient):
test_project = "test_clone_project"
test_project_fullname = API_USER + "/" + test_project
# cleanups
project_dir = os.path.join(TMP_DIR, test_project)
cleanup(mc, test_project_fullname, [project_dir])
# create new (empty) project on server
mc.create_project(test_project)
projects = mc.projects_list(flag="created")
assert any(p for p in projects if p["name"] == test_project and p["namespace"] == API_USER)
cloned_project_name = test_project + "_cloned"
test_cloned_project_fullname = API_USER + "/" + cloned_project_name
# cleanup cloned project
cloned_project_dir = os.path.join(TMP_DIR, cloned_project_name)
cleanup(mc, API_USER + "/" + cloned_project_name, [cloned_project_dir])
# clone specifying cloned_project_namespace, does clone but raises deprecation warning
with pytest.deprecated_call(match=r"The usage of `cloned_project_namespace` parameter in `clone_project\(\)`"):
mc.clone_project(test_project_fullname, cloned_project_name, API_USER)
projects = mc.projects_list(flag="created")
assert any(p for p in projects if p["name"] == cloned_project_name and p["namespace"] == API_USER)
cleanup(mc, API_USER + "/" + cloned_project_name, [cloned_project_dir])
# clone without specifying cloned_project_namespace relies on workspace with user name, does clone but raises deprecation warning
with pytest.deprecated_call(match=r"The use of only project name as `cloned_project_name` in `clone_project\(\)`"):
mc.clone_project(test_project_fullname, cloned_project_name)
projects = mc.projects_list(flag="created")
assert any(p for p in projects if p["name"] == cloned_project_name and p["namespace"] == API_USER)
cleanup(mc, API_USER + "/" + cloned_project_name, [cloned_project_dir])
# clone project with full cloned project name with specification of `cloned_project_namespace` raises warning
with pytest.warns(match=r"Parameter `cloned_project_namespace` specified with full cloned project name"):
mc.clone_project(test_project_fullname, test_cloned_project_fullname, API_USER)
projects = mc.projects_list(flag="created")
assert any(p for p in projects if p["name"] == cloned_project_name and p["namespace"] == API_USER)
cleanup(mc, API_USER + "/" + cloned_project_name, [cloned_project_dir])
# clone project using project full name
mc.clone_project(test_project_fullname, test_cloned_project_fullname)
projects = mc.projects_list(flag="created")
assert any(p for p in projects if p["name"] == cloned_project_name and p["namespace"] == API_USER)
cleanup(mc, API_USER + "/" + cloned_project_name, [cloned_project_dir])
def test_set_read_write_access(mc):
test_project = "test_set_read_write_access"
test_project_fullname = API_USER + "/" + test_project
# cleanups
project_dir = os.path.join(TMP_DIR, test_project, API_USER)
cleanup(mc, test_project_fullname, [project_dir])
# create new (empty) project on server
mc.create_project(test_project)
# Add writer access to another client
project_info = get_project_info(mc, API_USER, test_project)
access = project_info["access"]
access["writersnames"].append(API_USER2)
access["readersnames"].append(API_USER2)
editor_support = server_has_editor_support(mc, access)
if editor_support:
access["editorsnames"].append(API_USER2)
mc.set_project_access(test_project_fullname, access)
project_info = get_project_info(mc, API_USER, test_project)
access = project_info["access"]
assert API_USER2 in access["writersnames"]
assert API_USER2 in access["readersnames"]
if editor_support:
assert API_USER2 in access["editorsnames"]
def test_set_editor_access(mc):
test_project = "test_set_editor_access"
test_project_fullname = API_USER + "/" + test_project
# cleanups
project_dir = os.path.join(TMP_DIR, test_project, API_USER)
cleanup(mc, test_project_fullname, [project_dir])
# create new (empty) project on server
mc.create_project(test_project)
project_info = get_project_info(mc, API_USER, test_project)
access = project_info["access"]
# Stop test if server does not support editor access
if not server_has_editor_support(mc, access):
return
access["readersnames"].append(API_USER2)
access["editorsnames"].append(API_USER2)
mc.set_project_access(test_project_fullname, access)
# check access
project_info = get_project_info(mc, API_USER, test_project)
access = project_info["access"]
assert API_USER2 in access["editorsnames"]
assert API_USER2 in access["readersnames"]
assert API_USER2 not in access["writersnames"]
def test_available_workspace_storage(mcStorage):
"""
Testing of storage limit - applies to user pushing changes into own project (namespace matching username).
This test also tests giving read and write access to another user. Additionally tests also uploading of big file.
"""
test_project = "test_available_workspace_storage"
test_project_fullname = STORAGE_WORKSPACE + "/" + test_project
# cleanups
project_dir = os.path.join(TMP_DIR, test_project, API_USER)
cleanup(mcStorage, test_project_fullname, [project_dir])
# create new (empty) project on server
# if namespace is not provided, function is creating project with username
mcStorage.create_project(test_project_fullname)
# download project
mcStorage.download_project(test_project_fullname, project_dir)
# get info about storage capacity
storage_remaining = 0
client_workspace = None
for workspace in mcStorage.workspaces_list():
if workspace["name"] == STORAGE_WORKSPACE:
client_workspace = workspace
break
assert client_workspace is not None
current_storage = client_workspace["storage"]
client_workspace_id = client_workspace["id"]
# 5 MB
testing_storage = 5242880
# add storage limit, to prevent creating too big files
mcStorage.patch(
f"/v1/tests/workspaces/{client_workspace_id}",
{"limits_override": {"storage": testing_storage, "projects": 1, "api_allowed": True}},
{"Content-Type": "application/json"},
)
if mcStorage.server_type() == ServerType.OLD:
user_info = mcStorage.user_info()
storage_remaining = testing_storage - user_info["disk_usage"]
else:
storage_remaining = testing_storage - client_workspace["disk_usage"]
# generate dummy data (remaining storage + extra 1024b)
dummy_data_path = project_dir + "/data.txt"
file_size = storage_remaining + 1024
_generate_big_file(dummy_data_path, file_size)
# try to upload
got_right_err = False
try:
mcStorage.push_project(project_dir)
except ClientError as e:
# Expecting "You have reached a data limit" 400 server error msg.
assert "You have reached a data limit" in str(e)
got_right_err = True
finally:
assert got_right_err
# Expecting empty project
project_info = get_project_info(mcStorage, STORAGE_WORKSPACE, test_project)
assert project_info["version"] == "v0"
assert project_info["disk_usage"] == 0
# remove dummy big file from a disk
remove_folders([project_dir])
def test_available_storage_validation2(mc, mc2):
"""
Testing of storage limit - should not be applied for user pushing changes into project with different namespace.
This should cover the exception of python-api-client that a user can push changes to someone else's project regardless
the user's own storage limitation. Of course, other limitations are still applied (write access, owner of
a modified project has to have enough free storage).
Therefore NOTE that there are following assumptions:
- API_USER2's free storage >= API_USER's free storage + 1024b (size of changes to be pushed)
- both accounts should ideally have a free plan
"""
test_project = "test_available_storage_validation2"
test_project_fullname = API_USER2 + "/" + test_project
# cleanups
project_dir = os.path.join(TMP_DIR, test_project, API_USER)
cleanup(mc, test_project_fullname, [project_dir])
cleanup(mc2, test_project_fullname, [project_dir])
# create new (empty) project on server
mc2.create_project(test_project)
# Add writer access to another client
project_info = get_project_info(mc2, API_USER2, test_project)
access = project_info["access"]
access["writersnames"].append(API_USER)
access["readersnames"].append(API_USER)
mc2.set_project_access(test_project_fullname, access)
# download project
mc.download_project(test_project_fullname, project_dir)
# get info about storage capacity
storage_remaining = 0
if mc.server_type() == ServerType.OLD:
user_info = mc.user_info()
storage_remaining = user_info["storage"] - user_info["disk_usage"]
else:
# This test does not make sense in newer servers as quotas are tied to workspaces, not users
return
# generate dummy data (remaining storage + extra 1024b)
dummy_data_path = project_dir + "/data.txt"
file_size = storage_remaining + 1024
_generate_big_file(dummy_data_path, file_size)
# try to upload
mc.push_project(project_dir)
# Check project content
project_info = mc.project_info(test_project_fullname)
assert len(project_info["files"]) == 1
assert project_info["disk_usage"] == file_size
# remove dummy big file from a disk
remove_folders([project_dir])
def get_project_info(mc, namespace, project_name):
"""
Returns first (and suppose to be just one) project info dict of project matching given namespace and name.
:param mc: MerginClient instance
:param namespace: project's namespace
:param project_name: project's name
:return: dict with project info
"""
projects = mc.projects_list(flag="created", namespace=namespace)
test_project_list = [p for p in projects if p["name"] == project_name and p["namespace"] == namespace]
assert len(test_project_list) == 1
return test_project_list[0]
def _generate_big_file(filepath, size):
"""
generate big binary file with the specified size in bytes
:param filepath: full filepath
:param size: the size in bytes
"""
with open(filepath, "wb") as fout:
fout.write(b"\0" * size)
def test_get_projects_by_name(mc):
"""Test server 'bulk' endpoint for projects' info"""
test_projects = {
"projectA": f"{API_USER}/projectA",
"projectB": f"{API_USER}/projectB",
}
for name, full_name in test_projects.items():
cleanup(mc, full_name, [])
mc.create_project(name)
resp = mc.get_projects_by_names(list(test_projects.values()))
assert len(resp) == len(test_projects)
for name, full_name in test_projects.items():
assert full_name in resp
assert resp[full_name]["name"] == name
assert resp[full_name]["version"] == "v0"
def test_download_versions(mc):
test_project = "test_download"
project = API_USER + "/" + test_project
project_dir = os.path.join(TMP_DIR, test_project)
# download dirs
project_dir_v1 = os.path.join(TMP_DIR, test_project + "_v1")
project_dir_v2 = os.path.join(TMP_DIR, test_project + "_v2")
project_dir_v3 = os.path.join(TMP_DIR, test_project + "_v3")
cleanup(mc, project, [project_dir, project_dir_v1, project_dir_v2, project_dir_v3])
# create remote project
shutil.copytree(TEST_DATA_DIR, project_dir)
mc.create_project_and_push(project, project_dir)
# create new version - v2
f_added = "new.txt"
with open(os.path.join(project_dir, f_added), "w") as f:
f.write("new file")
mc.push_project(project_dir)
project_info = mc.project_info(project)
assert project_info["version"] == "v2"
mc.download_project(project, project_dir_v1, "v1")
assert os.path.exists(os.path.join(project_dir_v1, "base.gpkg"))
assert not os.path.exists(os.path.join(project_dir_v2, f_added)) # added only in v2
mc.download_project(project, project_dir_v2, "v2")
assert os.path.exists(os.path.join(project_dir_v2, f_added))
assert os.path.exists(os.path.join(project_dir_v1, "base.gpkg")) # added in v1 but still present in v2
# try to download not-existing version
with pytest.raises(ClientError):
mc.download_project(project, project_dir_v3, "v3")
def test_paginated_project_list(mc):
"""Test the new endpoint for projects list with pagination, ordering etc."""
test_projects = dict()
for symb in "ABCDEF":
name = f"test_paginated_{symb}"
test_projects[name] = f"{API_USER}/{name}"
for name, full_name in test_projects.items():
cleanup(mc, full_name, [])
mc.create_project(name)
sorted_test_names = [n for n in sorted(test_projects.keys())]
resp = mc.paginated_projects_list(
flag="created",
name="test_paginated",
page=1,
per_page=10,
order_params="name_asc",
)
projects = resp["projects"]