forked from natcap/taskgraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_task.py
More file actions
1494 lines (1285 loc) · 56.5 KB
/
test_task.py
File metadata and controls
1494 lines (1285 loc) · 56.5 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
"""Tests for taskgraph."""
import hashlib
import logging
import logging.handlers
import multiprocessing
import os
import pathlib
import pickle
import re
import shutil
import sqlite3
import subprocess
import tempfile
import time
import unittest
import retrying
import taskgraph
LOGGER = logging.getLogger(__name__)
N_TEARDOWN_RETRIES = 5
MAX_TRY_WAIT_MS = 500
def _return_value_once(value):
"""Return the value passed to it only once."""
if hasattr(_return_value_once, 'executed'):
raise RuntimeError("this function was called twice")
_return_value_once.executed = True
return value
def _noop_function(**kwargs):
"""Do nothing except allow kwargs to be passed."""
pass
def _long_running_function(delay):
"""Wait for ``delay`` seconds."""
time.sleep(delay)
def _create_two_files_on_disk(value, target_a_path, target_b_path):
"""Create two files and write ``value`` and append if possible."""
with open(target_a_path, 'a') as a_file:
a_file.write(value)
with open(target_b_path, 'a') as b_file:
b_file.write(value)
def _merge_and_append_files(base_a_path, base_b_path, target_path):
"""Merge two files and append if possible to new file."""
with open(target_path, 'a') as target_file:
for base_path in [base_a_path, base_b_path]:
with open(base_path, 'r') as base_file:
target_file.write(base_file.read())
def _create_list_on_disk(value, length, target_path=None):
"""Create a numpy array on disk filled with value of ``size``."""
target_list = [value] * length
pickle.dump(target_list, open(target_path, 'wb'))
def _call_it(target, *args):
"""Invoke ``target`` with ``args``."""
target(*args)
def _append_val(path, *val):
"""Append a ``val`` to file at ``path``."""
with open(path, 'a') as target_file:
for v in val:
target_file.write(str(v))
def _sum_lists_from_disk(list_a_path, list_b_path, target_path):
"""Read two lists, add them and save result."""
list_a = pickle.load(open(list_a_path, 'rb'))
list_b = pickle.load(open(list_b_path, 'rb'))
target_list = []
for a, b in zip(list_a, list_b):
target_list.append(a+b)
pickle.dump(target_list, open(target_path, 'wb'))
def _div_by_zero():
"""Divide by zero to raise an exception."""
return 1/0
def _create_file(target_path, content):
"""Create a file with contents."""
with open(target_path, 'w') as target_file:
target_file.write(content)
def _create_file_once(target_path, content):
"""Create a file on the first call, raise an exception on the second."""
if hasattr(_create_file_once, 'executed'):
raise RuntimeError("this function was called twice")
_create_file_once.executed = True
with open(target_path, 'w') as target_file:
target_file.write(content)
def _copy_file_once(base_path, target_path):
"""Copy base to target on the first call, raise exception on second."""
if hasattr(_copy_file_once, 'executed'):
raise RuntimeError("this function was called twice")
_copy_file_once.executed = True
shutil.copyfile(base_path, target_path)
def _copy_two_files_once(base_path, target_a_path, target_b_path):
"""Copy base to target a/b on first call, raise exception on second."""
if hasattr(_copy_two_files_once, 'executed'):
raise RuntimeError("this function was called twice")
_copy_two_files_once.executed = True
shutil.copyfile(base_path, target_a_path)
shutil.copyfile(base_path, target_b_path)
def _log_from_another_process(logger_name, log_message):
"""Write a log message to a given logger.
Args:
logger_name (string): The string logger name to which ``log_message``
will be logged.
log_message (string): The string log message to be logged (at INFO
level) to the logger at ``logger_name``.
Returns:
``None``
"""
logger = logging.getLogger(logger_name)
logger.info(log_message)
class TaskGraphTests(unittest.TestCase):
"""Tests for the taskgraph."""
def setUp(self):
"""Create temp workspace directory."""
# this lets us delete the workspace after its done no matter the
# the rest result
self.workspace_dir = tempfile.mkdtemp()
@retrying.retry(
stop_max_attempt_number=N_TEARDOWN_RETRIES,
wait_exponential_multiplier=250, wait_exponential_max=MAX_TRY_WAIT_MS)
def tearDown(self):
"""Remove temporary directory."""
try:
shutil.rmtree(self.workspace_dir)
except Exception:
LOGGER.exception('error when tearing down.')
raise
def test_version_loaded(self):
"""TaskGraph: verify we can load the version."""
try:
import taskgraph
# Verifies that there's a version attribute and it has a value.
self.assertTrue(len(taskgraph.__version__) > 0)
except Exception:
self.fail('Could not load the taskgraph version as expected.')
def test_single_task(self):
"""TaskGraph: Test a single task."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, 0, 0.1)
# forcing this one to be unicode since there shouldn't be a problem
# with that at all...
target_path = u'%s' % os.path.join(self.workspace_dir, '1000.dat')
value = 5
list_len = 1000
_ = task_graph.add_task(
func=_create_list_on_disk,
args=(value, list_len),
kwargs={
'target_path': target_path,
},
target_path_list=[target_path])
task_graph.close()
task_graph.join()
result = pickle.load(open(target_path, 'rb'))
self.assertEqual(result, [value]*list_len)
def test_task_hash_source_deleted(self):
"""TaskGraph: test if old target deleted when hashing duplicate."""
target_a_path = os.path.join(self.workspace_dir, 'a.txt')
task_graph = taskgraph.TaskGraph(self.workspace_dir, 0)
task_a = task_graph.add_task(
func=_create_file,
args=(target_a_path, 'test value'),
target_path_list=[target_a_path])
task_a.join()
target_b_path = os.path.join(self.workspace_dir, 'b.txt')
_ = task_graph.add_task(
func=_create_file,
args=(target_b_path, 'test value'),
target_path_list=[target_b_path])
task_graph.close()
task_graph.join()
del task_graph
os.remove(target_a_path)
os.remove(target_b_path)
target_c_path = os.path.join(self.workspace_dir, 'c.txt')
task_graph = taskgraph.TaskGraph(self.workspace_dir, -1)
_ = task_graph.add_task(
func=_create_file,
args=(target_c_path, 'test value'),
target_path_list=[target_c_path])
task_graph.close()
task_graph.join()
with open(target_c_path, 'r') as target_file:
result = target_file.read()
self.assertEqual(result, 'test value')
def test_task_rel_vs_absolute(self):
"""TaskGraph: test that relative path equates to absolute."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, 0)
target_a_path = os.path.relpath(os.path.join(
self.workspace_dir, 'a.txt'), start=self.workspace_dir)
target_b_path = os.path.abspath(target_a_path)
_ = task_graph.add_task(
func=_create_file,
args=(target_a_path, 'test value'),
target_path_list=[target_a_path],
task_name='task a')
_ = task_graph.add_task(
func=_create_file,
args=(target_b_path, 'test value'),
target_path_list=[target_b_path],
task_name='task b')
task_graph.close()
task_graph.join()
del task_graph
with open(target_a_path, 'r') as a_file:
m = hashlib.md5()
m.update(a_file.read().encode('utf-8'))
a_digest = m.digest()
with open(target_b_path, 'r') as b_file:
m = hashlib.md5()
m.update(b_file.read().encode('utf-8'))
b_digest = m.digest()
self.assertEqual(a_digest, b_digest)
def test_timeout_task(self):
"""TaskGraph: Test timeout functionality."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, 0)
_ = task_graph.add_task(
func=_long_running_function,
args=(5,))
task_graph.close()
timedout = not task_graph.join(0.5)
# this should timeout since function runs for 5 seconds
self.assertTrue(timedout)
def test_precomputed_task(self):
"""TaskGraph: Test that a task reuses old results."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, 0)
target_path = os.path.join(self.workspace_dir, '1000.dat')
value = 5
list_len = 1000
_ = task_graph.add_task(
func=_create_list_on_disk,
args=(value, list_len),
kwargs={
'target_path': target_path,
},
target_path_list=[target_path])
task_graph.close()
task_graph.join()
result = pickle.load(open(target_path, 'rb'))
self.assertEqual(result, [value]*list_len)
result_m_time = os.path.getmtime(target_path)
del task_graph
task_graph = taskgraph.TaskGraph(self.workspace_dir, 0)
_ = task_graph.add_task(
func=_create_list_on_disk,
args=(value, list_len),
kwargs={
'target_path': target_path,
},
target_path_list=[target_path])
task_graph.close()
task_graph.join()
del task_graph
# taskgraph shouldn't have recomputed the result
second_result_m_time = os.path.getmtime(target_path)
self.assertEqual(result_m_time, second_result_m_time)
def test_task_chain(self):
"""TaskGraph: Test a task chain."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, 0)
target_a_path = os.path.join(self.workspace_dir, 'a.dat')
target_b_path = os.path.join(self.workspace_dir, 'b.dat')
result_path = os.path.join(self.workspace_dir, 'result.dat')
result_2_path = os.path.join(self.workspace_dir, 'result2.dat')
value_a = 5
value_b = 10
list_len = 10
task_a = task_graph.add_task(
func=_create_list_on_disk,
args=(value_a, list_len),
kwargs={
'target_path': target_a_path,
},
target_path_list=[target_a_path])
task_b = task_graph.add_task(
func=_create_list_on_disk,
args=(value_b, list_len),
kwargs={
'target_path': target_b_path,
},
target_path_list=[target_b_path])
sum_task = task_graph.add_task(
func=_sum_lists_from_disk,
args=(target_a_path, target_b_path),
kwargs={
'target_path': result_path,
},
target_path_list=[result_path],
dependent_task_list=[task_a, task_b])
sum_task.join()
result = pickle.load(open(result_path, 'rb'))
self.assertEqual(result, [value_a+value_b]*list_len)
sum_2_task = task_graph.add_task(
func=_sum_lists_from_disk,
args=(target_a_path, result_path, result_2_path),
target_path_list=[result_2_path],
dependent_task_list=[task_a, sum_task])
sum_2_task.join()
result2 = pickle.load(open(result_2_path, 'rb'))
expected_result = [(value_a*2+value_b)]*list_len
self.assertEqual(result2, expected_result)
sum_3_task = task_graph.add_task(
func=_sum_lists_from_disk,
args=(target_a_path, result_path, result_2_path),
target_path_list=[result_2_path],
dependent_task_list=[task_a, sum_task])
task_graph.close()
sum_3_task.join()
result3 = pickle.load(open(result_2_path, 'rb'))
expected_result = [(value_a*2+value_b)]*list_len
self.assertEqual(result3, expected_result)
task_graph.join()
def test_task_chain_single_thread(self):
"""TaskGraph: Test a single threaded task chain."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, -1)
target_a_path = os.path.join(self.workspace_dir, 'a.dat')
target_b_path = os.path.join(self.workspace_dir, 'b.dat')
result_path = os.path.join(self.workspace_dir, 'result.dat')
result_2_path = os.path.join(self.workspace_dir, 'result2.dat')
value_a = 5
value_b = 10
list_len = 10
task_a = task_graph.add_task(
func=_create_list_on_disk,
args=(value_a, list_len),
kwargs={
'target_path': target_a_path,
},
target_path_list=[target_a_path],
task_name='task a')
task_b = task_graph.add_task(
func=_create_list_on_disk,
args=(value_b, list_len),
kwargs={
'target_path': target_b_path,
},
target_path_list=[target_b_path],
task_name='task b')
sum_task = task_graph.add_task(
func=_sum_lists_from_disk,
args=(target_a_path, target_b_path),
kwargs={
'target_path': result_path,
},
target_path_list=[result_path],
dependent_task_list=[task_a, task_b],
task_name='task c')
sum_task.join()
result = pickle.load(open(result_path, 'rb'))
self.assertEqual(result, [value_a+value_b]*list_len)
sum_2_task = task_graph.add_task(
func=_sum_lists_from_disk,
args=(target_a_path, result_path, result_2_path),
target_path_list=[result_2_path],
dependent_task_list=[task_a, sum_task],
task_name='task sum_2')
sum_2_task.join()
result2 = pickle.load(open(result_2_path, 'rb'))
expected_result = [(value_a*2+value_b)]*list_len
self.assertEqual(result2, expected_result)
sum_3_task = task_graph.add_task(
func=_sum_lists_from_disk,
args=(target_a_path, result_path, result_2_path),
target_path_list=[result_2_path],
dependent_task_list=[task_a, sum_task],
task_name='task sum_3')
task_graph.close()
sum_3_task.join()
result3 = pickle.load(open(result_2_path, 'rb'))
expected_result = [(value_a*2+value_b)]*list_len
task_graph.join()
task_graph = None
self.assertEqual(result3, expected_result)
# we should have 4 completed values in the database, 5 total but one
# was a duplicate
database_path = os.path.join(
self.workspace_dir, taskgraph._TASKGRAPH_DATABASE_FILENAME)
conn = sqlite3.connect(database_path)
with conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM taskgraph_data")
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 4)
def test_task_broken_chain(self):
"""TaskGraph: Test a multiprocess chain with exception raised."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, 4)
target_a_path = os.path.join(self.workspace_dir, 'a.dat')
target_b_path = os.path.join(self.workspace_dir, 'b.dat')
result_path = os.path.join(self.workspace_dir, 'result.dat')
value_a = 5
list_len = 10
task_a = task_graph.add_task(
func=_create_list_on_disk,
args=(value_a, list_len),
kwargs={
'target_path': target_a_path,
},
target_path_list=[target_a_path])
task_b = task_graph.add_task(
func=_div_by_zero,
dependent_task_list=[task_a])
_ = task_graph.add_task(
func=_sum_lists_from_disk,
args=(target_a_path, target_b_path),
kwargs={
'target_path': result_path,
},
target_path_list=[result_path],
dependent_task_list=[task_a, task_b])
task_graph.close()
with self.assertRaises(ZeroDivisionError):
task_graph.join()
def test_broken_task(self):
"""TaskGraph: Test that a task with an exception won't hang."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, 1)
broken_task = task_graph.add_task(
func=_div_by_zero, task_name='test_broken_task')
with self.assertRaises(ZeroDivisionError):
_ = broken_task.join()
task_graph.close()
with self.assertRaises(ZeroDivisionError):
task_graph.join()
def test_broken_task_chain(self):
"""TaskGraph: test dependent tasks fail on ancestor fail."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, 4)
target_path = os.path.join(self.workspace_dir, '1000.dat')
value = 5
list_len = 1000
for task_id in range(1):
target_path = os.path.join(
self.workspace_dir, '1000_%d.dat' % task_id)
normal_task = task_graph.add_task(
func=_create_list_on_disk,
args=(value, list_len),
kwargs={'target_path': target_path},
target_path_list=[target_path],
task_name='create list on disk %d' % task_id)
zero_div_task = task_graph.add_task(
func=_div_by_zero,
dependent_task_list=[normal_task],
task_name='test_broken_task_chain_%d' % task_id)
target_path = os.path.join(
self.workspace_dir, 'after_zerodiv_1000_%d.dat' % task_id)
_ = task_graph.add_task(
func=_create_list_on_disk,
args=(value, list_len),
kwargs={'target_path': target_path},
dependent_task_list=[zero_div_task],
target_path_list=[target_path],
task_name='create list on disk after zero div%d' % task_id)
task_graph.close()
with self.assertRaises(ZeroDivisionError):
task_graph.join()
def test_empty_task(self):
"""TaskGraph: Test an empty task."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, 0)
_ = task_graph.add_task()
task_graph.close()
task_graph.join()
# we shouldn't have anything in the database
database_path = os.path.join(
self.workspace_dir, taskgraph._TASKGRAPH_DATABASE_FILENAME)
conn = sqlite3.connect(database_path)
with conn:
cursor = conn.cursor()
cursor.executescript("SELECT * FROM taskgraph_data")
result = cursor.fetchall()
conn.close()
self.assertEqual(len(result), 0)
def test_closed_graph(self):
"""TaskGraph: Test adding to an closed task graph fails."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, 0)
task_graph.close()
target_path = os.path.join(self.workspace_dir, '1000.dat')
value = 5
list_len = 1000
with self.assertRaises(ValueError):
_ = task_graph.add_task(
func=_create_list_on_disk,
args=(value, list_len),
kwargs={'target_path': target_path},
target_path_list=[target_path])
task_graph.join()
def test_single_task_multiprocessing(self):
"""TaskGraph: Test a single task with multiprocessing."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, 1)
target_path = os.path.join(self.workspace_dir, '1000.dat')
value = 5
list_len = 1000
_ = task_graph.add_task(
func=_create_list_on_disk,
args=(value, list_len),
kwargs={
'target_path': target_path,
},
target_path_list=[target_path])
task_graph.close()
task_graph.join()
result = pickle.load(open(target_path, 'rb'))
self.assertEqual(result, [value]*list_len)
def test_get_file_stats(self):
"""TaskGraph: Test _get_file_stats subroutine."""
from taskgraph.Task import _get_file_stats
test_dir = os.path.join(self.workspace_dir, 'test_dir')
test_file = os.path.join(test_dir, 'test_file.txt')
os.mkdir(test_dir)
with open(test_file, 'w') as f:
f.write('\n')
nofile = os.path.join(self.workspace_dir, 'nofile')
base_value = [
nofile, test_dir, test_file,
10, {'a': {'b': test_file}}, {'a': {'b': test_dir, 'foo': 9}}]
ignore_dir_result = list(_get_file_stats(
base_value, 'sizetimestamp', [], True))
# should get two results if we ignore the directories because there's
# only two files
self.assertEqual(len(ignore_dir_result), 2)
dir_result = list(_get_file_stats(
base_value, 'sizetimestamp', [], False))
# should get four results if we track directories because of two files
# and two directories
self.assertEqual(len(dir_result), 4)
result = list(_get_file_stats(nofile, 'sizetimestamp', [], False))
self.assertEqual(result, [])
def test_transient_runs(self):
"""TaskGraph: ensure that transent tasks reexecute."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, -1)
target_path = os.path.join(self.workspace_dir, '1000.dat')
value = 5
list_len = 1000
_ = task_graph.add_task(
func=_create_list_on_disk,
args=(value, list_len),
kwargs={
'target_path': target_path,
})
task_graph.close()
task_graph.join()
task_graph = None
os.remove(target_path)
task_graph2 = taskgraph.TaskGraph(self.workspace_dir, -1)
_ = task_graph2.add_task(
func=_create_list_on_disk,
args=(value, list_len),
transient_run=True,
kwargs={
'target_path': target_path,
})
task_graph2.close()
task_graph2.join()
self.assertTrue(
os.path.exists(target_path),
"Expected file to exist because taskgraph should have re-run.")
def test_repeat_targeted_runs(self):
"""TaskGraph: ensure that repeated runs with targets can join."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, -1)
target_path = os.path.join(self.workspace_dir, '1000.dat')
value = 5
list_len = 1000
_ = task_graph.add_task(
func=_create_list_on_disk,
args=(value, list_len),
kwargs={
'target_path': target_path,
},
target_path_list=[target_path])
task_graph.close()
task_graph.join()
task_graph = None
task_graph2 = taskgraph.TaskGraph(self.workspace_dir, -1)
task = task_graph2.add_task(
func=_create_list_on_disk,
args=(value, list_len),
kwargs={
'target_path': target_path,
},
target_path_list=[target_path])
self.assertTrue(task.join(1.0), "join failed after 1 second")
task_graph2.close()
task_graph2.join()
def test_task_equality(self):
"""TaskGraph: test correctness of == and != for Tasks."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, -1)
target_path = os.path.join(self.workspace_dir, '1000.dat')
value = 5
list_len = 1000
task_a = task_graph.add_task(
func=_create_list_on_disk,
args=(value, list_len),
kwargs={'target_path': target_path},
target_path_list=[target_path])
task_a_same = task_graph.add_task(
func=_create_list_on_disk,
args=(value, list_len),
kwargs={'target_path': target_path},
target_path_list=[target_path])
task_b = task_graph.add_task(
func=_create_list_on_disk,
args=(value+1, list_len),
kwargs={'target_path': target_path},
target_path_list=[target_path])
self.assertTrue(task_a == task_a)
self.assertTrue(task_a == task_a_same)
self.assertTrue(task_a != task_b)
def test_async_logging(self):
"""TaskGraph: ensure async logging can execute."""
task_graph = taskgraph.TaskGraph(
self.workspace_dir, 0, reporting_interval=0.5)
_ = task_graph.add_task(
func=_long_running_function,
args=(1.0,))
task_graph.close()
task_graph.join()
timedout = not task_graph.join(5)
# this should not timeout since function runs for 1 second
self.assertFalse(timedout, "task timed out")
def test_scrub(self):
"""TaskGraph: ensure scrub is not scrubbing base types."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, 0)
target_path = os.path.join(self.workspace_dir, 'a.txt')
first_task = task_graph.add_task(
func=_append_val,
args=(target_path, 1, [1], {'x': 1}),
task_name='first append')
second_task = task_graph.add_task(
func=_append_val,
args=(target_path, 1, [1], {'x': 2}),
dependent_task_list=[first_task],
task_name='second append')
_ = task_graph.add_task(
func=_append_val,
args=(target_path, 1, [2], {'x': 1}),
dependent_task_list=[second_task],
task_name='third append')
task_graph.close()
task_graph.join()
with open(target_path, 'r') as target_file:
file_value = target_file.read()
self.assertEqual("1[1]{'x': 1}1[1]{'x': 2}1[2]{'x': 1}", file_value)
def test_target_path_order(self):
"""TaskGraph: ensure target path order doesn't matter."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, 0)
target_a_path = os.path.join(self.workspace_dir, 'a.txt')
target_b_path = os.path.join(self.workspace_dir, 'b.txt')
task_graph.add_task(
func=_create_two_files_on_disk,
args=("word", target_a_path, target_b_path),
target_path_list=[target_a_path, target_b_path])
task_graph.add_task(
func=_create_two_files_on_disk,
args=("word", target_a_path, target_b_path),
target_path_list=[target_b_path, target_a_path])
task_graph.close()
task_graph.join()
with open(target_a_path, 'r') as a_file:
a_value = a_file.read()
with open(target_b_path, 'r') as b_file:
b_value = b_file.read()
self.assertEqual(a_value, "word")
self.assertEqual(b_value, "word")
def test_task_hash_when_ready(self):
"""TaskGraph: ensure tasks don't record execution info until ready."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, 0)
target_a_path = os.path.join(self.workspace_dir, 'a.txt')
target_b_path = os.path.join(self.workspace_dir, 'b.txt')
create_files_task = task_graph.add_task(
func=_create_two_files_on_disk,
args=("word", target_a_path, target_b_path),
target_path_list=[target_a_path, target_b_path])
target_merged_path = os.path.join(self.workspace_dir, 'merged.txt')
task_graph.add_task(
func=_merge_and_append_files,
args=(target_a_path, target_b_path, target_merged_path),
target_path_list=[target_merged_path],
dependent_task_list=[create_files_task])
task_graph.join()
# this second task shouldn't execute because it's a copy of the first
task_graph.add_task(
func=_merge_and_append_files,
args=(target_a_path, target_b_path, target_merged_path),
target_path_list=[target_merged_path],
dependent_task_list=[create_files_task])
task_graph.close()
task_graph.join()
with open(target_merged_path, 'r') as target_file:
target_string = target_file.read()
self.assertEqual(target_string, "wordword")
def test_multiprocessed_logging(self):
"""TaskGraph: ensure tasks can log from multiple processes."""
logger_name = 'test.task.queuelogger'
log_message = 'This is coming from another process'
logger = logging.getLogger(logger_name)
logger.setLevel(logging.DEBUG)
file_log_path = os.path.join(
self.workspace_dir, 'test_multiprocessed_logging.log')
file_handler = logging.FileHandler(file_log_path)
file_handler.setFormatter(
logging.Formatter(fmt=':%(processName)s:%(message)s:'))
logger.addHandler(file_handler)
task_graph = taskgraph.TaskGraph(self.workspace_dir, 1)
log_task = task_graph.add_task(
func=_log_from_another_process,
args=(logger_name, log_message))
log_task.join()
file_handler.flush()
task_graph.close()
task_graph.join()
file_handler.close()
@retrying.retry(wait_exponential_multiplier=100,
wait_exponential_max=1000,
stop_max_attempt_number=5)
def get_name_and_message():
with open(file_log_path, 'r') as log_file:
message = log_file.read().rstrip()
print(message)
process_name, logged_message = re.match(
':([^:]*):([^:]*):', message).groups()
return process_name, logged_message
process_name, logged_message = get_name_and_message()
self.assertEqual(logged_message, log_message)
self.assertNotEqual(
process_name, multiprocessing.current_process().name)
def test_repeated_function(self):
"""TaskGraph: ensure no reruns if argument is a function."""
global _append_val
task_graph = taskgraph.TaskGraph(self.workspace_dir, 0)
target_path = os.path.join(self.workspace_dir, 'testfile.txt')
task_graph.add_task(
func=_call_it,
args=(_append_val, target_path, 1),
target_path_list=[target_path],
ignore_path_list=[target_path],
task_name='first _call_it')
task_graph.close()
task_graph.join()
del task_graph
# this causes the address to change
def _append_val(path, *val):
"""Append a ``val`` to file at ``path``."""
with open(path, 'a') as target_file:
for v in val:
target_file.write(str(v))
task_graph = taskgraph.TaskGraph(self.workspace_dir, 1)
target_path = os.path.join(self.workspace_dir, 'testfile.txt')
task_graph.add_task(
func=_call_it,
args=(_append_val, target_path, 1),
target_path_list=[target_path],
ignore_path_list=[target_path],
task_name='second _call_it')
task_graph.close()
task_graph.join()
with open(target_path, 'r') as target_file:
result = target_file.read()
# the second call shouldn't happen
self.assertEqual(result, '1')
def test_unix_path_repeated_function(self):
"""TaskGraph: ensure no reruns if path is unix style."""
global _append_val
_append_val = _append_val # flake8 complains if not defined
task_graph = taskgraph.TaskGraph(self.workspace_dir, -1)
target_dir = self.workspace_dir + '/foo/bar/rad/'
os.makedirs(target_dir)
target_path = target_dir + '/testfile.txt'
task_graph.add_task(
func=_call_it,
args=(_append_val, target_path, 1),
target_path_list=[target_path],
task_name='first _call_it')
task_graph.close()
task_graph.join()
del task_graph
task_graph = taskgraph.TaskGraph(self.workspace_dir, -1)
task_graph.add_task(
func=_call_it,
args=(_append_val, target_path, 1),
target_path_list=[target_path],
task_name='second _call_it')
task_graph.close()
task_graph.join()
with open(target_path, 'r') as target_file:
result = target_file.read()
# the second call shouldn't happen
self.assertEqual(result, '1')
def test_very_long_string(self):
"""TaskGraph: ensure that long strings don't case an OSError."""
from taskgraph.Task import _get_file_stats
# this is a list with two super long strings to try to trick some
# os function into thinking it's a path.
base_value = [
'c:' + r'\\\\\\\\x\\\\\\\\'*2**10 + 'foo',
'wfeji3223j8923j9' * 2**10]
self.assertEqual(
list(_get_file_stats(base_value, 'sizetimestamp', [], True)), [])
def test_duplicate_call_changed_target(self):
"""TaskGraph: test that duplicate calls copy target path."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, 0)
target_path = os.path.join(self.workspace_dir, 'testfile.txt')
if hasattr(_create_file_once, 'executed'):
del _create_file_once.executed
task_graph.add_task(
func=_create_file_once,
args=(target_path, 'test'),
target_path_list=[target_path],
hash_target_files=False,
task_name='first _create_file_once')
task_graph.close()
task_graph.join()
del task_graph
with open(target_path, 'a') as target_file:
target_file.write('updated')
task_graph = taskgraph.TaskGraph(self.workspace_dir, 0)
task_graph.add_task(
func=_create_file_once,
args=(target_path, 'test'),
target_path_list=[target_path],
hash_target_files=False,
task_name='first _create_file_once')
task_graph.close()
task_graph.join()
del task_graph
with open(target_path, 'r') as result_file:
result_contents = result_file.read()
self.assertEqual('testupdated', result_contents)
def test_duplicate_call_modify_timestamp(self):
"""TaskGraph: test that duplicate call modified stamp recompute."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, 0)
target_path = os.path.join(self.workspace_dir, 'testfile.txt')
task_graph.add_task(
func=_create_file,
args=(target_path, 'test'),
target_path_list=[target_path],
task_name='first _create_file')
task_graph.close()
task_graph.join()
del task_graph
with open(target_path, 'w') as target_file:
target_file.write('test2')
with open(target_path, 'r') as target_file:
contents = target_file.read()
self.assertEqual(contents, 'test2')
task_graph = taskgraph.TaskGraph(self.workspace_dir, 0)
task_graph.add_task(
func=_create_file,
args=(target_path, 'test'),
target_path_list=[target_path],
task_name='second _create_file')
task_graph.close()
task_graph.join()
with open(target_path, 'r') as target_file:
contents = target_file.read()
self.assertEqual(contents, 'test')
def test_different_target_path_list(self):
"""TaskGraph: duplicate calls with different targets should fail."""
task_graph = taskgraph.TaskGraph(self.workspace_dir, 0)
target_path = os.path.join(self.workspace_dir, 'testfile.txt')
task_graph.add_task(
func=_create_list_on_disk,
args=('test', 1, target_path),
target_path_list=[target_path],
task_name='first _create_list_on_disk')
with self.assertRaises(RuntimeError):
# make the same call but with different target path list