forked from candicegjing/codalab-worksheets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_cli.py
1754 lines (1489 loc) · 62.1 KB
/
test_cli.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 -*-
"""
Tests all the CLI functionality end-to-end.
Tests will operate on temporary worksheets created during testing. In theory,
it should not mutate preexisting data on your instance, but this is not
guaranteed, and you should run this command in an unimportant CodaLab account.
For full coverage of testing, be sure to run this over a remote connection (i.e.
while connected to localhost::) in addition to local testing, in order to test
the full RPC pipeline, and also as a non-root user, to hammer out unanticipated
permission issues.
Things not tested:
- Interactive modes (cl edit, cl wedit)
- Permissions
"""
from collections import namedtuple, OrderedDict
from contextlib import contextmanager
from codalab.worker.download_util import BundleTarget
from scripts.create_sample_worksheet import SampleWorksheet
from scripts.test_util import Colorizer, run_command
import argparse
import json
import os
import random
import re
import shutil
import subprocess
import sys
import time
import traceback
global cl
# Directory where this script lives.
base_path = os.path.dirname(os.path.abspath(__file__))
crazy_name = 'crazy (ain\'t it)'
CodaLabInstance = namedtuple('CodaLabInstance', 'host home username password')
def test_path(name):
"""Return the path to the test file ``name``."""
return os.path.join(base_path, 'tests', 'files', name)
# Note: when we talk about contents, we always apply rstrip() even if it's a
# binary file. This is fine as long as we're consistent about doing rstrip()
# everywhere to test for equality.
def test_path_contents(name, binary=False):
return path_contents(test_path(name), binary=binary)
def path_contents(path, binary=False):
with open(path, "rb") as file:
if binary:
return file.read().rstrip()
return file.read().decode().rstrip()
def temp_path(suffix, tmp=True):
root = '/tmp' if tmp else base_path
return os.path.join(root, random_name() + suffix)
def random_name():
return 'temp-test-cli-' + str(random.randint(0, 1000000))
def current_worksheet():
"""
Returns the full worksheet spec of the current worksheet.
Does so by parsing the output of `cl work`:
Switched to worksheet http://localhost:2900/worksheets/0x87a7a7ffe29d4d72be9b23c745adc120 (home-codalab).
"""
m = re.search('(http.*?)/worksheets/(.*?) \((.*?)\)', _run_command([cl, 'work']))
assert m is not None
worksheet_host, worksheet_uuid, worksheet_name = m.group(1), m.group(2), m.group(3)
return worksheet_host + "::" + worksheet_name
def current_user():
"""
Return the uuid and username of the current user in a tuple
Does so by parsing the output of `cl uinfo` which by default returns the info
of the current user
"""
user_id = _run_command([cl, 'uinfo', '-f', 'id'])
user_name = _run_command([cl, 'uinfo', '-f', 'user_name'])
return user_id, user_name
def get_uuid(line):
"""
Returns the uuid from a line where the uuid is between parentheses
"""
m = re.search(".*\((0x[a-z0-9]+)\)", line)
assert m is not None
return m.group(1)
def get_info(uuid, key):
return _run_command([cl, 'info', '-f', key, uuid])
def wait_until_running(uuid, timeout_seconds=100):
start_time = time.time()
while True:
if time.time() - start_time > 100:
raise AssertionError('timeout while waiting for %s to run' % uuid)
state = get_info(uuid, 'state')
# Break when running or one of the final states
if state in {'running', 'ready', 'failed'}:
assert state == 'running', "waiting for 'running' state, but got '%s'" % state
return
time.sleep(0.5)
def wait_for_contents(uuid, substring, timeout_seconds=100):
start_time = time.time()
while True:
if time.time() - start_time > 100:
raise AssertionError('timeout while waiting for %s to run' % uuid)
try:
out = _run_command([cl, 'cat', uuid])
except AssertionError:
time.sleep(0.5)
continue
if substring in out:
return True
time.sleep(0.5)
def wait(uuid, expected_exit_code=0):
_run_command([cl, 'wait', uuid], expected_exit_code)
def check_equals(true_value, pred_value):
assert true_value == pred_value, "expected '%s', but got '%s'" % (true_value, pred_value)
return pred_value
def check_contains(true_value, pred_value):
if isinstance(true_value, list):
for v in true_value:
check_contains(v, pred_value)
else:
assert true_value in pred_value or re.search(
true_value, pred_value
), "expected something that contains '%s', but got '%s'" % (true_value, pred_value)
return pred_value
def check_num_lines(true_value, pred_value):
num_lines = len(pred_value.split('\n'))
assert num_lines == true_value, "expected %d lines, but got %s" % (true_value, num_lines)
return pred_value
def wait_until_substring(fp, substr):
"""
Block until we see substr appear in the given file fp.
"""
while True:
line = fp.readline()
if substr in line:
return
def _run_command(
args,
expected_exit_code=0,
max_output_chars=1024,
env=None,
include_stderr=False,
binary=False,
force_subprocess=False,
):
# We skip using the cli directly if force_subprocess is set to true (which forces
# us to use subprocess even for cl commands).
force_subprocess = not force_subprocess and args[0] == cl
return run_command(
args, expected_exit_code, max_output_chars, env, include_stderr, binary, force_subprocess
)
# TODO: get rid of this and set up the rest-servers outside test_cli.py and
# pass them as parameters into here. Otherwise, there are circular
# dependencies with calling codalab_service.py.
@contextmanager
def temp_instance():
"""
Usage:
with temp_instance() as remote:
run_command([cl, 'work', remote.home])
... do more stuff with new temp instance ...
"""
print('Setting up a temporary CodaLab instance')
# Dockerized instance
original_worksheet = current_worksheet()
def get_free_ports(num_ports):
import socket
socks = [socket.socket(socket.AF_INET, socket.SOCK_STREAM) for i in range(num_ports)]
ports = []
for s in socks:
s.bind(("", 0))
ports = [str(s.getsockname()[1]) for s in socks]
for s in socks:
s.close()
return ports
rest_port, http_port, mysql_port = get_free_ports(3)
temp_instance_name = random_name()
try:
subprocess.check_output(
' '.join(
[
'./codalab_service.py',
'start',
'--instance-name %s' % temp_instance_name,
'--rest-port %s' % rest_port,
'--http-port %s' % http_port,
'--mysql-port %s' % mysql_port,
'--version %s' % cl_version,
]
),
shell=True,
)
except subprocess.CalledProcessError as ex:
print("Temp instance exception: %s" % ex.output)
raise
# Switch to new host and log in to cache auth token
remote_host = 'http://localhost:%s' % rest_port
remote_worksheet = '%s::' % remote_host
_run_command([cl, 'logout', remote_worksheet[:-2]])
env = {'CODALAB_USERNAME': 'codalab', 'CODALAB_PASSWORD': 'codalab'}
_run_command([cl, 'work', remote_worksheet], env=env)
yield CodaLabInstance(
remote_host, remote_worksheet, env['CODALAB_USERNAME'], env['CODALAB_PASSWORD']
)
subprocess.check_call(
' '.join(['./codalab_service.py', 'down', '--instance-name temp-%s' % temp_instance_name]),
shell=True,
)
_run_command([cl, 'work', original_worksheet])
class ModuleContext(object):
"""ModuleContext objects manage the context of a test module.
Instances of ModuleContext are meant to be used with the Python
'with' statement (PEP 343).
For documentation on with statement context managers:
https://docs.python.org/2/reference/datamodel.html#with-statement-context-managers
"""
def __init__(self, instance):
# These are the temporary worksheets and bundles that need to be
# cleaned up at the end of the test.
self.instance = instance
self.worksheets = []
self.bundles = []
self.groups = []
self.error = None
# Allow for making REST calls
from codalab.lib.codalab_manager import CodaLabManager
manager = CodaLabManager()
self.client = manager.current_client()
def __enter__(self):
"""Prepares clean environment for test module."""
print("[*][*] SWITCHING TO TEMPORARY WORKSHEET")
self.original_environ = os.environ.copy()
self.original_worksheet = _run_command([cl, 'work', '-u'])
temp_worksheet = _run_command([cl, 'new', random_name()])
self.worksheets.append(temp_worksheet)
_run_command([cl, 'work', temp_worksheet])
print("[*][*] BEGIN TEST")
return self
def __exit__(self, exc_type, exc_value, tb):
"""Tears down temporary environment for test module."""
# Check for and handle exceptions if any
if exc_type is not None:
self.error = (exc_type, exc_value, tb)
if exc_type is AssertionError:
print(Colorizer.red("[!] ERROR: %s" % str(exc_value)))
elif exc_type is KeyboardInterrupt:
print(Colorizer.red("[!] Caught interrupt! Quitting after cleanup."))
else:
print(Colorizer.red("[!] ERROR: Test raised an exception!"))
traceback.print_exception(exc_type, exc_value, tb)
else:
print(Colorizer.green("[*] TEST PASSED"))
# Clean up and restore original worksheet
print("[*][*] CLEANING UP")
os.environ.clear()
os.environ.update(self.original_environ)
_run_command([cl, 'work', self.original_worksheet])
for worksheet in self.worksheets:
self.bundles.extend(_run_command([cl, 'ls', '-w', worksheet, '-u']).split())
_run_command([cl, 'wrm', '--force', worksheet])
# Delete all bundles (kill and dedup first)
if len(self.bundles) > 0:
for bundle in set(self.bundles):
try:
if _run_command([cl, 'info', '-f', 'state', bundle]) not in (
'ready',
'failed',
'killed',
):
_run_command([cl, 'kill', bundle])
_run_command([cl, 'wait', bundle], expected_exit_code=1)
except AssertionError:
print('CAUGHT')
pass
_run_command([cl, 'rm', '--force', bundle])
# Delete all groups (dedup first)
if len(self.groups) > 0:
_run_command([cl, 'grm'] + list(set(self.groups)))
# Reraise only KeyboardInterrupt
if exc_type is KeyboardInterrupt:
return False
else:
return True
def collect_worksheet(self, uuid):
"""Mark a worksheet for cleanup on exit."""
self.worksheets.append(uuid)
def collect_bundle(self, uuid):
"""Mark a bundle for cleanup on exit."""
self.bundles.append(uuid)
def collect_group(self, uuid):
"""Mark a group for cleanup on exit."""
self.groups.append(uuid)
class TestModule(object):
"""Instances of TestModule each encapsulate a test module and its metadata.
The class itself also maintains a registry of the existing modules, providing
a decorator to register new modules and a class method to run modules by name.
"""
modules = OrderedDict()
def __init__(self, name, func, description, default):
self.name = name
self.func = func
self.description = description
self.default = default
@classmethod
def register(cls, name, default=True):
"""Returns a decorator to register new test modules.
The decorator will add a given function as test modules to the registry
under the name provided here. The function's docstring (PEP 257) will
be used as the prose description of the test module.
:param name: name of the test module
:param default: True to include in the 'default' module set
"""
def add_module(func):
cls.modules[name] = TestModule(name, func, func.__doc__, default)
return add_module
@classmethod
def all_modules(cls):
return list(cls.modules.values())
@classmethod
def default_modules(cls):
return [m for m in cls.modules.values() if m.default]
@classmethod
def run(cls, tests, instance):
"""Run the modules named in tests againts instance.
tests should be a list of strings, each of which is either 'all',
'default', or the name of an existing test module.
instance should be a codalab instance to connect to like:
- main
- localhost
- http://server-domain:2900
"""
# Might prompt user for password
subprocess.call([cl, 'work', '%s::' % instance])
# Build list of modules to run based on tests
modules_to_run = []
for name in tests:
if name == 'all':
modules_to_run.extend(cls.all_modules())
elif name == 'default':
modules_to_run.extend(cls.default_modules())
elif name in cls.modules:
modules_to_run.append(cls.modules[name])
else:
print(Colorizer.red("[!] Could not find module %s" % name))
print(Colorizer.red("[*] Modules: all %s" % " ".join(list(cls.modules.keys()))))
sys.exit(1)
print(
(
Colorizer.yellow(
"[*][*] Running modules %s" % " ".join([m.name for m in modules_to_run])
)
)
)
# Run modules, continuing onto the next test module regardless of
# failure
failed = []
for module in modules_to_run:
print(Colorizer.yellow("[*][*] BEGIN MODULE: %s" % module.name))
if module.description is not None:
print(Colorizer.yellow("[*][*] DESCRIPTION: %s" % module.description))
with ModuleContext(instance) as ctx:
module.func(ctx)
if ctx.error:
failed.append(module.name)
# Provide a (currently very rudimentary) summary
print(Colorizer.yellow("[*][*][*] SUMMARY"))
if failed:
print(Colorizer.red("[!][!] Tests failed: %s" % ", ".join(failed)))
return False
else:
print(Colorizer.green("[*][*] All tests passed!"))
return True
############################################################
@TestModule.register('unittest')
def test(ctx):
"""Run nose unit tests (exclude this file)."""
_run_command(['nosetests', '-e', 'test_cli.py'])
@TestModule.register('gen-rest-docs')
def test(ctx):
"""Generate REST API docs."""
_run_command(['python3', os.path.join(base_path, 'scripts/gen-rest-docs.py'), '--docs', '/tmp'])
@TestModule.register('gen-cli-docs')
def test(ctx):
"""Generate CLI docs."""
_run_command(['python3', os.path.join(base_path, 'scripts/gen-cli-docs.py'), '--docs', '/tmp'])
@TestModule.register('gen-readthedocs')
def test(ctx):
"""Generate the readthedocs site."""
# Make sure there are no extraneous things.
# mkdocs doesn't return exit code 1 for some warnings.
check_num_lines(2, _run_command(['mkdocs', 'build', '-d', '/tmp/site'], include_stderr=True))
@TestModule.register('basic')
def test(ctx):
# upload
uuid = _run_command(
[cl, 'upload', test_path('a.txt'), '--description', 'hello', '--tags', 'a', 'b']
)
check_equals('a.txt', get_info(uuid, 'name'))
check_equals('hello', get_info(uuid, 'description'))
check_contains(['a', 'b'], get_info(uuid, 'tags'))
check_equals('ready', get_info(uuid, 'state'))
check_equals('ready\thello', get_info(uuid, 'state,description'))
# edit
_run_command([cl, 'edit', uuid, '--name', 'a2.txt', '--tags', 'c', 'd', 'e'])
check_equals('a2.txt', get_info(uuid, 'name'))
check_contains(['c', 'd', 'e'], get_info(uuid, 'tags'))
# cat, info
check_equals(test_path_contents('a.txt'), _run_command([cl, 'cat', uuid]))
check_contains(['bundle_type', 'uuid', 'owner', 'created'], _run_command([cl, 'info', uuid]))
check_contains('license', _run_command([cl, 'info', '--raw', uuid]))
check_contains(['host_worksheets', 'contents'], _run_command([cl, 'info', '--verbose', uuid]))
# test interpret_file_genpath
check_equals(' '.join(test_path_contents('a.txt').splitlines(False)), get_info(uuid, '/'))
# rm
_run_command([cl, 'rm', '--dry-run', uuid])
check_contains('0x', get_info(uuid, 'data_hash'))
_run_command([cl, 'rm', '--data-only', uuid])
check_equals('None', get_info(uuid, 'data_hash'))
_run_command([cl, 'rm', uuid])
# run and check the data_hash
uuid = _run_command([cl, 'run', 'echo hello'])
print('Waiting echo hello with uuid %s' % uuid)
wait(uuid)
check_contains('0x', get_info(uuid, 'data_hash'))
@TestModule.register('upload1')
def test(ctx):
# Upload contents
uuid = _run_command([cl, 'upload', '-c', 'hello'])
check_equals('hello', _run_command([cl, 'cat', uuid]))
# Upload binary file
uuid = _run_command([cl, 'upload', test_path('echo')])
check_equals(
test_path_contents('echo', binary=True), _run_command([cl, 'cat', uuid], binary=True)
)
# Upload file with crazy name
uuid = _run_command([cl, 'upload', test_path(crazy_name)])
check_equals(test_path_contents(crazy_name), _run_command([cl, 'cat', uuid]))
# Upload directory with a symlink
uuid = _run_command([cl, 'upload', test_path('')])
check_equals(' -> /etc/passwd', _run_command([cl, 'cat', uuid + '/passwd']))
# Upload symlink without following it.
uuid = _run_command([cl, 'upload', test_path('a-symlink.txt')], 1)
# Upload symlink, follow link
uuid = _run_command([cl, 'upload', test_path('a-symlink.txt'), '--follow-symlinks'])
check_equals(test_path_contents('a-symlink.txt'), _run_command([cl, 'cat', uuid]))
_run_command([cl, 'cat', uuid]) # Should have the full contents
# Upload broken symlink (should not be possible)
uuid = _run_command([cl, 'upload', test_path('broken-symlink'), '--follow-symlinks'], 1)
# Upload directory with excluded files
uuid = _run_command([cl, 'upload', test_path('dir1'), '--exclude-patterns', 'f*'])
check_num_lines(
2 + 2, _run_command([cl, 'cat', uuid])
) # 2 header lines, Only two files left after excluding and extracting.
# Upload multiple files with excluded files
uuid = _run_command(
[
cl,
'upload',
test_path('dir1'),
test_path('echo'),
test_path(crazy_name),
'--exclude-patterns',
'f*',
]
)
check_num_lines(
2 + 3, _run_command([cl, 'cat', uuid])
) # 2 header lines, 3 items at bundle target root
check_num_lines(
2 + 2, _run_command([cl, 'cat', uuid + '/dir1'])
) # 2 header lines, Only two files left after excluding and extracting.
# Upload directory with only one file, should not simplify directory structure
uuid = _run_command([cl, 'upload', test_path('dir2')])
check_num_lines(
2 + 1, _run_command([cl, 'cat', uuid])
) # Directory listing with 2 headers lines and one file
@TestModule.register('upload2')
def test(ctx):
# Upload tar.gz and zip.
for suffix in ['.tar.gz', '.zip']:
# Pack it up
archive_path = temp_path(suffix)
contents_path = test_path('dir1')
if suffix == '.tar.gz':
_run_command(
[
'tar',
'cfz',
archive_path,
'-C',
os.path.dirname(contents_path),
os.path.basename(contents_path),
]
)
else:
_run_command(
[
'bash',
'-c',
'cd %s && zip -r %s %s'
% (
os.path.dirname(contents_path),
archive_path,
os.path.basename(contents_path),
),
]
)
# Upload it and unpack
uuid = _run_command([cl, 'upload', archive_path])
check_equals(os.path.basename(archive_path).replace(suffix, ''), get_info(uuid, 'name'))
check_equals(test_path_contents('dir1/f1'), _run_command([cl, 'cat', uuid + '/f1']))
# Upload it but don't unpack
uuid = _run_command([cl, 'upload', archive_path, '--pack'])
check_equals(os.path.basename(archive_path), get_info(uuid, 'name'))
check_equals(
test_path_contents(archive_path, binary=True),
_run_command([cl, 'cat', uuid], binary=True),
)
# Force compression
uuid = _run_command([cl, 'upload', test_path('echo'), '--force-compression'])
check_equals('echo', get_info(uuid, 'name'))
check_equals(
test_path_contents('echo', binary=True), _run_command([cl, 'cat', uuid], binary=True)
)
os.unlink(archive_path)
@TestModule.register('upload3')
def test(ctx):
# Upload URL
uuid = _run_command([cl, 'upload', 'https://www.wikipedia.org'])
check_contains('<title>Wikipedia</title>', _run_command([cl, 'cat', uuid]))
# Upload URL that's an archive
uuid = _run_command([cl, 'upload', 'http://alpha.gnu.org/gnu/bc/bc-1.06.95.tar.bz2'])
check_contains(['README', 'INSTALL', 'FAQ'], _run_command([cl, 'cat', uuid]))
# Upload URL from Git
uuid = _run_command([cl, 'upload', 'https://github.com/codalab/codalab-worksheets', '--git'])
check_contains(['README.md', 'codalab', 'scripts'], _run_command([cl, 'cat', uuid]))
@TestModule.register('upload4')
def test(ctx):
# Uploads a pair of archives at the same time. Makes sure they're named correctly when unpacked.
archive_paths = [temp_path(''), temp_path('')]
archive_exts = [p + '.tar.gz' for p in archive_paths]
contents_paths = [test_path('dir1'), test_path('a.txt')]
for (archive, content) in zip(archive_exts, contents_paths):
_run_command(
['tar', 'cfz', archive, '-C', os.path.dirname(content), os.path.basename(content)]
)
uuid = _run_command([cl, 'upload'] + archive_exts)
# Make sure the names do not end with '.tar.gz' after being unpacked.
check_contains(
[os.path.basename(archive_paths[0]) + r'\s', os.path.basename(archive_paths[1]) + r'\s'],
_run_command([cl, 'cat', uuid]),
)
# Cleanup
for archive in archive_exts:
os.unlink(archive)
@TestModule.register('download')
def test(ctx):
# Upload test files directory as archive to preserve everything invariant of the upload implementation
archive_path = temp_path('.tar.gz')
contents_path = test_path('')
_run_command(
['tar', 'cfz', archive_path, '-C', os.path.dirname(contents_path), '--']
+ os.listdir(contents_path)
)
uuid = _run_command([cl, 'upload', archive_path])
# Download whole bundle
path = temp_path('')
_run_command([cl, 'download', uuid, '-o', path])
check_contains(['a.txt', 'b.txt', 'echo', crazy_name], _run_command(['ls', '-R', path]))
shutil.rmtree(path)
# Download a target inside (binary)
_run_command([cl, 'download', uuid + '/echo', '-o', path])
check_equals(test_path_contents('echo', binary=True), path_contents(path, binary=True))
os.unlink(path)
# Download a target inside (crazy name)
_run_command([cl, 'download', uuid + '/' + crazy_name, '-o', path])
check_equals(test_path_contents(crazy_name), path_contents(path))
os.unlink(path)
# Download a target inside (name starting with hyphen)
_run_command([cl, 'download', uuid + '/' + '-AmMDnVl4s8', '-o', path])
check_equals(test_path_contents('-AmMDnVl4s8'), path_contents(path))
os.unlink(path)
# Download a target inside (symlink)
_run_command([cl, 'download', uuid + '/a-symlink.txt', '-o', path], 1) # Disallow symlinks
# Download a target inside (directory)
_run_command([cl, 'download', uuid + '/dir1', '-o', path])
check_equals(test_path_contents('dir1/f1'), path_contents(path + '/f1'))
shutil.rmtree(path)
# Download something that doesn't exist
_run_command([cl, 'download', 'not-exists'], 1)
_run_command([cl, 'download', uuid + '/not-exists'], 1)
@TestModule.register('refs')
def test(ctx):
# Test references
uuid = _run_command([cl, 'upload', test_path('a.txt')])
wuuid = _run_command([cl, 'work', '-u'])
# Compound bundle references
_run_command([cl, 'info', wuuid + '/' + uuid])
# . is current worksheet
check_contains(wuuid, _run_command([cl, 'ls', '-w', '.']))
# / is home worksheet
check_contains('::home-', _run_command([cl, 'ls', '-w', '/']))
@TestModule.register('binary')
def test(ctx):
# Upload a binary file and test it
path = '/bin/ls'
uuid = _run_command([cl, 'upload', path])
check_equals(open(path, 'rb').read(), _run_command([cl, 'cat', uuid], binary=True))
_run_command([cl, 'info', '--verbose', uuid])
@TestModule.register('rm')
def test(ctx):
uuid = _run_command([cl, 'upload', test_path('a.txt')])
_run_command([cl, 'add', 'bundle', uuid]) # Duplicate
_run_command([cl, 'rm', uuid]) # Can delete even though it exists twice on the same worksheet
@TestModule.register('make')
def test(ctx):
uuid1 = _run_command([cl, 'upload', test_path('a.txt')])
uuid2 = _run_command([cl, 'upload', test_path('b.txt')])
# make
uuid3 = _run_command([cl, 'make', 'dep1:' + uuid1, 'dep2:' + uuid2])
wait(uuid3)
check_equals('ready', _run_command([cl, 'info', '-f', 'state', uuid3]))
check_contains(['dep1', uuid1, 'dep2', uuid2], _run_command([cl, 'info', uuid3]))
# anonymous make
uuid4 = _run_command([cl, 'make', uuid3, '--name', 'foo'])
wait(uuid4)
check_equals('ready', _run_command([cl, 'info', '-f', 'state', uuid4]))
check_contains([uuid3], _run_command([cl, 'info', uuid3]))
# Cleanup
_run_command([cl, 'rm', uuid1], 1) # should fail
_run_command([cl, 'rm', '--force', uuid2]) # force the deletion
_run_command([cl, 'rm', '-r', uuid1]) # delete things downstream
@TestModule.register('worksheet')
def test(ctx):
wname = random_name()
# Create new worksheet
wuuid = _run_command([cl, 'new', wname])
ctx.collect_worksheet(wuuid)
check_contains(['Switched', wname, wuuid], _run_command([cl, 'work', wuuid]))
# ls
check_equals('', _run_command([cl, 'ls', '-u']))
uuid = _run_command([cl, 'upload', test_path('a.txt')])
check_equals(uuid, _run_command([cl, 'ls', '-u']))
# create worksheet
check_contains(uuid[0:5], _run_command([cl, 'ls']))
_run_command([cl, 'add', 'text', 'testing'])
_run_command([cl, 'add', 'text', '你好世界😊'])
_run_command([cl, 'add', 'text', '% display contents / maxlines=10'])
_run_command([cl, 'add', 'bundle', uuid])
_run_command([cl, 'add', 'text', '// comment'])
_run_command([cl, 'add', 'text', '% schema foo'])
_run_command([cl, 'add', 'text', '% add uuid'])
_run_command([cl, 'add', 'text', '% add data_hash data_hash s/0x/HEAD'])
_run_command([cl, 'add', 'text', '% add CREATE created "date | [0:5]"'])
_run_command([cl, 'add', 'text', '% display table foo'])
_run_command([cl, 'add', 'bundle', uuid])
_run_command(
[cl, 'add', 'bundle', uuid, '--dest-worksheet', wuuid]
) # not testing real copying ability
_run_command([cl, 'add', 'worksheet', wuuid])
check_contains(
['Worksheet', 'testing', '你好世界😊', test_path_contents('a.txt'), uuid, 'HEAD', 'CREATE'],
_run_command([cl, 'print']),
)
_run_command([cl, 'wadd', wuuid, wuuid])
check_num_lines(8, _run_command([cl, 'ls', '-u']))
_run_command([cl, 'wedit', wuuid, '--name', wname + '2'])
_run_command(
[cl, 'wedit', wuuid, '--file', test_path('unicode-worksheet')]
) # try unicode in worksheet contents
check_contains([test_path_contents('unicode-worksheet')], _run_command([cl, 'print', '-r']))
_run_command([cl, 'wedit', wuuid, '--file', '/dev/null']) # wipe out worksheet
@TestModule.register('worksheet_search')
def test(ctx):
wname = random_name()
# Create new worksheet
wuuid = _run_command([cl, 'new', wname])
ctx.collect_worksheet(wuuid)
check_contains(['Switched', wname, wuuid], _run_command([cl, 'work', wuuid]))
uuid = _run_command([cl, 'upload', test_path('a.txt')])
_run_command([cl, 'add', 'text', '% search ' + uuid])
_run_command([cl, 'add', 'text', '% wsearch ' + wuuid])
check_contains([uuid[0:8], wuuid[0:8]], _run_command([cl, 'print']))
# Check search by group
group_wname = random_name()
group_wuuid = _run_command([cl, 'new', group_wname])
ctx.collect_worksheet(group_wuuid)
check_contains(['Switched', group_wname, group_wuuid], _run_command([cl, 'work', group_wuuid]))
user_id, user_name = current_user()
# Create new group
group_name = random_name()
group_uuid_line = _run_command([cl, 'gnew', group_name])
group_uuid = get_uuid(group_uuid_line)
ctx.collect_group(group_uuid)
# Make worksheet unavailable to public but available to the group
_run_command([cl, 'wperm', group_wuuid, 'public', 'n'])
_run_command([cl, 'wperm', group_wuuid, group_name, 'r'])
check_contains(group_wuuid[:8], _run_command([cl, 'wls', '.shared']))
check_contains(group_wuuid[:8], _run_command([cl, 'wls', 'group={}'.format(group_uuid)]))
check_contains(group_wuuid[:8], _run_command([cl, 'wls', 'group={}'.format(group_name)]))
@TestModule.register('worksheet_tags')
def test(ctx):
wname = random_name()
wuuid = _run_command([cl, 'new', wname])
ctx.collect_worksheet(wuuid)
# Add tags
tags = ['foo', 'bar', 'baz']
_run_command([cl, 'wedit', wname, '--tags'] + tags)
check_contains(['Tags: %s' % ' '.join(tags)], _run_command([cl, 'ls', '-w', wuuid]))
# Modify tags
fewer_tags = ['bar', 'foo']
_run_command([cl, 'wedit', wname, '--tags'] + fewer_tags)
check_contains(['Tags: %s' % ' '.join(fewer_tags)], _run_command([cl, 'ls', '-w', wuuid]))
# Modify to non-ascii tags
# TODO: enable with Unicode support.
non_ascii_tags = ['你好世界😊', 'fáncy ünicode']
_run_command(
[cl, 'wedit', wname, '--tags'] + non_ascii_tags, 1, force_subprocess=True
) # TODO: find a way to make this work without force_subprocess
# check_contains(non_ascii_tags, _run_command([cl, 'ls', '-w', wuuid]))
# Delete tags
_run_command([cl, 'wedit', wname, '--tags'])
check_contains(r'Tags:\s+###', _run_command([cl, 'ls', '-w', wuuid]))
@TestModule.register('freeze')
def test(ctx):
_run_command([cl, 'work', '-u'])
wname = random_name()
wuuid = _run_command([cl, 'new', wname])
ctx.collect_worksheet(wuuid)
check_contains(['Switched', wname, wuuid], _run_command([cl, 'work', wuuid]))
# Before freezing: can modify everything
uuid1 = _run_command([cl, 'upload', '-c', 'hello'])
_run_command([cl, 'add', 'text', 'message'])
_run_command([cl, 'wedit', '-t', 'new_title'])
_run_command([cl, 'wperm', wuuid, 'public', 'n'])
_run_command([cl, 'wedit', '--freeze'])
# After freezing: can only modify contents
_run_command([cl, 'detach', uuid1], 1) # would remove an item
_run_command([cl, 'rm', uuid1], 1) # would remove an item
_run_command([cl, 'add', 'text', 'message'], 1) # would add an item
_run_command([cl, 'wedit', '-t', 'new_title']) # can edit
_run_command([cl, 'wperm', wuuid, 'public', 'a']) # can edit
@TestModule.register('detach')
def test(ctx):
uuid1 = _run_command([cl, 'upload', test_path('a.txt')])
uuid2 = _run_command([cl, 'upload', test_path('b.txt')])
_run_command([cl, 'add', 'bundle', uuid1])
ctx.collect_bundle(uuid1)
_run_command([cl, 'add', 'bundle', uuid2])
ctx.collect_bundle(uuid2)
# State after the above: 1 2 1 2
_run_command([cl, 'detach', uuid1], 1) # multiple indices
_run_command([cl, 'detach', uuid1, '-n', '3'], 1) # index out of range
_run_command([cl, 'detach', uuid2, '-n', '2']) # State: 1 1 2
check_equals(get_info('^', 'uuid'), uuid2)
_run_command([cl, 'detach', uuid2]) # State: 1 1
check_equals(get_info('^', 'uuid'), uuid1)
_run_command([cl, 'detach', uuid1, '-n', '2']) # State: 1
_run_command([cl, 'detach', uuid1]) # Worksheet becomes empty
check_equals(
'', _run_command([cl, 'ls', '-u'])
) # Return string from `cl ls -u` should be empty
@TestModule.register('perm')
def test(ctx):
uuid = _run_command([cl, 'upload', test_path('a.txt')])
check_equals('all', _run_command([cl, 'info', '-v', '-f', 'permission', uuid]))
check_contains('none', _run_command([cl, 'perm', uuid, 'public', 'n']))
check_contains('read', _run_command([cl, 'perm', uuid, 'public', 'r']))
check_contains('all', _run_command([cl, 'perm', uuid, 'public', 'a']))
@TestModule.register('search')
def test(ctx):
name = random_name()
uuid1 = _run_command([cl, 'upload', test_path('a.txt'), '-n', name])
uuid2 = _run_command([cl, 'upload', test_path('b.txt'), '-n', name])
check_equals(uuid1, _run_command([cl, 'search', uuid1, '-u']))
check_equals(uuid1, _run_command([cl, 'search', 'uuid=' + uuid1, '-u']))
check_equals('', _run_command([cl, 'search', 'uuid=' + uuid1[0:8], '-u']))
check_equals(uuid1, _run_command([cl, 'search', 'uuid=' + uuid1[0:8] + '.*', '-u']))
check_equals(uuid1, _run_command([cl, 'search', 'uuid=' + uuid1[0:8] + '%', '-u']))
check_equals(uuid1, _run_command([cl, 'search', 'uuid=' + uuid1, 'name=' + name, '-u']))
check_equals(
uuid1 + '\n' + uuid2, _run_command([cl, 'search', 'name=' + name, 'id=.sort', '-u'])
)
check_equals(
uuid1 + '\n' + uuid2,
_run_command([cl, 'search', 'uuid=' + uuid1 + ',' + uuid2, 'id=.sort', '-u']),
)
check_equals(
uuid2 + '\n' + uuid1, _run_command([cl, 'search', 'name=' + name, 'id=.sort-', '-u'])
)
check_equals('2', _run_command([cl, 'search', 'name=' + name, '.count']))
size1 = float(_run_command([cl, 'info', '-f', 'data_size', uuid1]))
size2 = float(_run_command([cl, 'info', '-f', 'data_size', uuid2]))
check_equals(
size1 + size2, float(_run_command([cl, 'search', 'name=' + name, 'data_size=.sum']))
)
# Check search by group
group_bname = random_name()
group_buuid = _run_command([cl, 'run', 'echo hello', '-n', group_bname])
wait(group_buuid)
ctx.collect_bundle(group_buuid)
user_id, user_name = current_user()
# Create new group
group_name = random_name()
group_uuid_line = _run_command([cl, 'gnew', group_name])
group_uuid = get_uuid(group_uuid_line)
ctx.collect_group(group_uuid)
# Make bundle unavailable to public but available to the group
_run_command([cl, 'perm', group_buuid, 'public', 'n'])
_run_command([cl, 'perm', group_buuid, group_name, 'r'])
check_contains(group_buuid[:8], _run_command([cl, 'search', '.shared']))
check_contains(group_buuid[:8], _run_command([cl, 'search', 'group={}'.format(group_uuid)]))
check_contains(group_buuid[:8], _run_command([cl, 'search', 'group={}'.format(group_name)]))
@TestModule.register('run')
def test(ctx):
name = random_name()
uuid = _run_command([cl, 'run', 'echo hello', '-n', name])
wait(uuid)
# test search
check_contains(name, _run_command([cl, 'search', name]))
check_equals(uuid, _run_command([cl, 'search', name, '-u']))
_run_command([cl, 'search', name, '--append'])
# test download stdout
path = temp_path('')
_run_command([cl, 'download', uuid + '/stdout', '-o', path])
check_equals('hello', path_contents(path))
# get info
check_equals('ready', _run_command([cl, 'info', '-f', 'state', uuid]))
check_contains(['run "echo hello"'], _run_command([cl, 'info', '-f', 'args', uuid]))
check_equals('hello', _run_command([cl, 'cat', uuid + '/stdout']))
# block
# TODO: Uncomment this when the tail bug is figured out
# check_contains('hello', _run_command([cl, 'run', 'echo hello', '--tail']))
# invalid child path
_run_command([cl, 'run', 'not/allowed:' + uuid, 'date'], expected_exit_code=1)