-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathonce_test.py
1400 lines (1149 loc) · 48.2 KB
/
once_test.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
"""Unit tests for once decorators."""
# pylint: disable=missing-function-docstring
import asyncio
import collections.abc
import concurrent.futures
import functools
import gc
import inspect
import math
import sys
import threading
import unittest
import uuid
import weakref
import once
if sys.version_info.minor < 10:
print(f"Redefining anext for python 3.{sys.version_info.minor}")
async def anext(iter, default=StopAsyncIteration):
if default != StopAsyncIteration:
try:
return await iter.__anext__()
except StopAsyncIteration:
return default
return await iter.__anext__()
# This is a "large" number of workers to schedule function calls in parallel.
_N_WORKERS = 32
class WrappedException:
def __init__(self, exception):
self.exception = exception
def parallel_map(
test: unittest.TestCase,
func: collections.abc.Callable,
# would be collections.abc.Iterable[tuple] | None on py >= 3.10
call_args=None,
n_threads: int = _N_WORKERS,
timeout: float = 60.0,
) -> list:
"""Run a function multiple times in parallel.
We ensure that N parallel tasks are all launched at the "same time", which
means all have parallel threads which are released to the GIL to execute at
the same time.
Why?
We can't rely on the thread pool excector to always spin up the full list of _N_WORKERS.
In pypy, we have observed that even with blocked tasks, the same thread executes multiple
function calls. This lets us handle the scheduling in a predictable way for testing.
"""
if call_args is None:
call_args = (tuple() for _ in range(n_threads))
batches = [[] for i in range(n_threads)] # type: list[list[tuple[int, tuple]]]
for i, call_args in enumerate(call_args):
if not isinstance(call_args, tuple):
raise TypeError("call arguments must be a tuple")
batches[i % n_threads].append((i, call_args))
n_calls = i + 1 # len(call_args), but it is now an exhuasted iterator.
unset = object()
results_lock = threading.Lock()
results = [unset for _ in range(n_calls)]
# This barrier is used to ensure that all calls release together, after this function has
# completed its setup of creating them.
start_barrier = threading.Barrier(min(n_threads, n_calls))
def wrapped_fn(batch):
start_barrier.wait()
for index, args in batch:
try:
result = func(*args)
except Exception as e:
result = WrappedException(e)
with results_lock:
results[index] = result
# We manually set thread names for easier debugging.
invocation_id = str(uuid.uuid4())
threads = [
threading.Thread(target=wrapped_fn, args=[batch], name=f"{test.id()}-{i}-{invocation_id}")
for i, batch in enumerate(batches)
]
for t in threads:
t.start()
for t in threads:
t.join(timeout=timeout)
for i, result in enumerate(results):
if result is unset:
test.fail(f"Call {i} did not complete succesfully")
elif isinstance(result, WrappedException):
raise result.exception
return results
class Counter:
"""Holding object for a counter.
If we return an integer directly, it will simply return a copy and
will not update as the number of calls increases.
The counter can also be paused by clearing its ready attribute, which will be convenient to
start multiple runs to execute concurrently.
"""
def __init__(self) -> None:
self.value = 0
self.ready = threading.Event()
self.ready.set()
def get_incremented(self) -> int:
self.ready.wait()
self.value += 1
return self.value
def execute_with_barrier(*args, n_workers=None, is_async=False):
"""Decorator to ensure function calls do not begin until at least n_workers have started.
This ensures that our parallel tests actually test concurrency. Without this, it is possible
that function calls execute as they are being scheduled, and do not truly execute in parallel.
The decorated function should receive an integer multiple of n_workers invokations.
Please note that calling this decorator outside of our once call will generally not change the
semantic meaning. However, it does increase the likelihood that once executions occur in
parallel, to increase the chance of races and therefore the chances that our tests catch a race
condition, although this is still non-deterministic. Calling this decorator **inside** the once
decorator however is deterministic.
"""
# Trick to make the decorator accept an arugment. The first call only gets the n_workers
# parameter, and then returns a new function with it set that then accepts the function.
if n_workers is None:
raise ValueError("n_workers not set")
if len(args) == 0:
return functools.partial(execute_with_barrier, n_workers=n_workers, is_async=is_async)
if len(args) > 1:
raise ValueError("Up to one argument expected.")
func = args[0]
barrier = threading.Barrier(n_workers)
if is_async:
async def wrapped(*args, **kwargs):
barrier.wait() # yes I know
return await func(*args, **kwargs)
else:
def wrapped(*args, **kwargs):
barrier.wait()
return func(*args, **kwargs)
functools.update_wrapper(wrapped, func)
return wrapped
def ensure_started(executor, func, *args, **kwargs):
"""Submit an execution to the executor and ensure it starts."""
event = threading.Event()
def run():
event.set()
return func(*args, **kwargs)
future = executor.submit(run)
event.wait()
return future
def generate_once_counter_fn():
"""Generates a once.once decorated function which counts its calls."""
counter = Counter()
@once.once
def counting_fn(*args) -> int:
"""Returns the call count, which should always be 1."""
nonlocal counter
del args
return counter.get_incremented()
return counting_fn, counter
class TestFunctionInspection(unittest.TestCase):
"""Unit tests for function inspection"""
def sample_sync_method(self, _):
return 1
def test_sync_method(self):
self.assertEqual(
once._wrapped_function_type(TestFunctionInspection.sample_sync_method),
once._WrappedFunctionType.SYNC_FUNCTION,
)
self.assertEqual(
once._wrapped_function_type(
functools.partial(TestFunctionInspection.sample_sync_method, 1)
),
once._WrappedFunctionType.SYNC_FUNCTION,
)
def test_sync_function(self):
def sample_sync_fn(_1, _2):
return 1
self.assertEqual(
once._wrapped_function_type(sample_sync_fn), once._WrappedFunctionType.SYNC_FUNCTION
)
self.assertEqual(
once._wrapped_function_type(once.once(sample_sync_fn)),
once._WrappedFunctionType.SYNC_FUNCTION,
)
self.assertEqual(
once._wrapped_function_type(functools.partial(sample_sync_fn, 1)),
once._WrappedFunctionType.SYNC_FUNCTION,
)
self.assertEqual(
once._wrapped_function_type(functools.partial(functools.partial(sample_sync_fn, 1), 2)),
once._WrappedFunctionType.SYNC_FUNCTION,
)
self.assertEqual(
once._wrapped_function_type(lambda x: x + 1), once._WrappedFunctionType.SYNC_FUNCTION
)
async def sample_async_method(self, _):
return 1
def test_async_method(self):
self.assertEqual(
once._wrapped_function_type(TestFunctionInspection.sample_async_method),
once._WrappedFunctionType.ASYNC_FUNCTION,
)
self.assertEqual(
once._wrapped_function_type(
functools.partial(TestFunctionInspection.sample_async_method, 1)
),
once._WrappedFunctionType.ASYNC_FUNCTION,
)
def test_async_function(self):
async def sample_async_fn(_1, _2):
return 1
self.assertEqual(
once._wrapped_function_type(sample_async_fn), once._WrappedFunctionType.ASYNC_FUNCTION
)
self.assertEqual(
once._wrapped_function_type(once.once(sample_async_fn)),
once._WrappedFunctionType.ASYNC_FUNCTION,
)
self.assertEqual(
once._wrapped_function_type(functools.partial(sample_async_fn, 1)),
once._WrappedFunctionType.ASYNC_FUNCTION,
)
self.assertEqual(
once._wrapped_function_type(
functools.partial(functools.partial(sample_async_fn, 1), 2)
),
once._WrappedFunctionType.ASYNC_FUNCTION,
)
def sample_sync_generator_method(self, _):
yield 1
def test_sync_generator_method(self):
self.assertEqual(
once._wrapped_function_type(TestFunctionInspection.sample_sync_generator_method),
once._WrappedFunctionType.SYNC_GENERATOR,
)
self.assertEqual(
once._wrapped_function_type(
functools.partial(TestFunctionInspection.sample_sync_generator_method, 1)
),
once._WrappedFunctionType.SYNC_GENERATOR,
)
def test_sync_generator_function(self):
def sample_sync_generator_fn(_1, _2):
yield 1
self.assertEqual(
once._wrapped_function_type(sample_sync_generator_fn),
once._WrappedFunctionType.SYNC_GENERATOR,
)
self.assertEqual(
once._wrapped_function_type(once.once(sample_sync_generator_fn)),
once._WrappedFunctionType.SYNC_GENERATOR,
)
self.assertEqual(
once._wrapped_function_type(functools.partial(sample_sync_generator_fn, 1)),
once._WrappedFunctionType.SYNC_GENERATOR,
)
self.assertEqual(
once._wrapped_function_type(
functools.partial(functools.partial(sample_sync_generator_fn, 1), 2)
),
once._WrappedFunctionType.SYNC_GENERATOR,
)
# The output of a sync generator is not a wrappable.
with self.assertRaises(SyntaxError):
once._wrapped_function_type(sample_sync_generator_fn(1, 2))
async def sample_async_generator_method(self, _):
yield 1
def test_async_generator_method(self):
self.assertEqual(
once._wrapped_function_type(TestFunctionInspection.sample_async_generator_method),
once._WrappedFunctionType.ASYNC_GENERATOR,
)
self.assertEqual(
once._wrapped_function_type(
functools.partial(TestFunctionInspection.sample_async_generator_method, 1)
),
once._WrappedFunctionType.ASYNC_GENERATOR,
)
def test_async_generator_function(self):
async def sample_async_generator_fn(_1, _2):
yield 1
self.assertEqual(
once._wrapped_function_type(sample_async_generator_fn),
once._WrappedFunctionType.ASYNC_GENERATOR,
)
self.assertEqual(
once._wrapped_function_type(once.once(sample_async_generator_fn)),
once._WrappedFunctionType.ASYNC_GENERATOR,
)
self.assertEqual(
once._wrapped_function_type(functools.partial(sample_async_generator_fn, 1)),
once._WrappedFunctionType.ASYNC_GENERATOR,
)
self.assertEqual(
once._wrapped_function_type(
functools.partial(functools.partial(sample_async_generator_fn, 1))
),
once._WrappedFunctionType.ASYNC_GENERATOR,
)
# The output of an async generator is not a wrappable.
with self.assertRaises(SyntaxError):
once._wrapped_function_type(sample_async_generator_fn(1, 2))
class TestOnce(unittest.TestCase):
"""Unit tests for once decorators."""
def test_inspect_iterator(self):
@once.once
def yielding_iterator():
for i in range(3):
yield i
self.assertTrue(inspect.isgeneratorfunction(yielding_iterator))
def test_counter_works(self):
"""Ensure the counter text fixture works."""
counter = Counter()
self.assertEqual(counter.value, 0)
self.assertEqual(counter.get_incremented(), 1)
self.assertEqual(counter.value, 1)
self.assertEqual(counter.get_incremented(), 2)
self.assertEqual(counter.value, 2)
def test_different_args_same_result(self):
counting_fn, counter = generate_once_counter_fn()
self.assertEqual(counting_fn(1), 1)
self.assertEqual(counter.value, 1)
# Should return the same result as the first call.
self.assertEqual(counting_fn(2), 1)
self.assertEqual(counter.value, 1)
def test_partial(self):
counter = Counter()
func = once.once(functools.partial(lambda _: counter.get_incremented(), None))
self.assertEqual(func(), 1)
self.assertEqual(func(), 1)
def test_reset(self):
counter = Counter()
@once.once(allow_reset=True)
def counting_fn():
return counter.get_incremented()
self.assertEqual(counting_fn(), 1)
counting_fn.reset()
self.assertEqual(counting_fn(), 2)
counting_fn.reset()
counting_fn.reset()
self.assertEqual(counting_fn(), 3)
def test_reset_not_allowed(self):
counting_fn, counter = generate_once_counter_fn()
self.assertEqual(counting_fn(None), 1)
with self.assertRaises(RuntimeError):
counting_fn.reset()
def test_failing_function(self):
counter = Counter()
@once.once
def sample_failing_fn():
if counter.get_incremented() < 4:
raise ValueError("expected failure")
return 1
with self.assertRaises(ValueError):
sample_failing_fn()
self.assertEqual(counter.get_incremented(), 2)
with self.assertRaises(ValueError):
sample_failing_fn()
self.assertEqual(counter.get_incremented(), 3, "Function call incremented the counter")
def test_failing_function_retry_exceptions(self):
counter = Counter()
@once.once(retry_exceptions=True)
def sample_failing_fn():
if counter.get_incremented() < 4:
raise ValueError("expected failure")
return 1
with self.assertRaises(ValueError):
sample_failing_fn()
self.assertEqual(counter.get_incremented(), 2)
with self.assertRaises(ValueError):
sample_failing_fn()
# This ensures that this was a new function call, not a cached result.
self.assertEqual(counter.get_incremented(), 4)
self.assertEqual(sample_failing_fn(), 1)
def test_iterator(self):
counter = Counter()
@once.once
def yielding_iterator():
nonlocal counter
for _ in range(3):
yield counter.get_incremented()
self.assertEqual(list(yielding_iterator()), [1, 2, 3])
self.assertEqual(list(yielding_iterator()), [1, 2, 3])
def test_iterator_reset(self):
counter = Counter()
@once.once(allow_reset=True)
def yielding_iterator():
nonlocal counter
for _ in range(3):
yield counter.get_incremented()
self.assertEqual(list(yielding_iterator()), [1, 2, 3])
yielding_iterator.reset()
self.assertEqual(list(yielding_iterator()), [4, 5, 6])
def test_iterator_reset_not_allowed(self):
counter = Counter()
@once.once
def yielding_iterator():
nonlocal counter
for _ in range(3):
yield counter.get_incremented()
self.assertEqual(list(yielding_iterator()), [1, 2, 3])
with self.assertRaises(RuntimeError):
yielding_iterator.reset()
def test_failing_generator(self):
counter = Counter()
@once.once
def sample_failing_fn():
yield counter.get_incremented()
result = counter.get_incremented()
yield result
if result == 2:
raise ValueError("expected failure after 2.")
# Both of these calls should return the same results.
call1 = sample_failing_fn()
call2 = sample_failing_fn()
self.assertEqual(next(call1), 1)
self.assertEqual(next(call2), 1)
self.assertEqual(next(call1), 2)
self.assertEqual(next(call2), 2)
with self.assertRaises(ValueError):
next(call1)
with self.assertRaises(ValueError):
next(call2)
# These next 2 calls should also fail.
call3 = sample_failing_fn()
call4 = sample_failing_fn()
self.assertEqual(next(call3), 1)
self.assertEqual(next(call4), 1)
self.assertEqual(next(call3), 2)
self.assertEqual(next(call4), 2)
with self.assertRaises(ValueError):
next(call3)
with self.assertRaises(ValueError):
next(call4)
def test_failing_generator_retry_exceptions(self):
counter = Counter()
@once.once(retry_exceptions=True)
def sample_failing_fn():
yield counter.get_incremented()
result = counter.get_incremented()
yield result
if result == 2:
raise ValueError("expected failure after 2.")
# Both of these calls should return the same results.
call1 = sample_failing_fn()
call2 = sample_failing_fn()
self.assertEqual(next(call1), 1)
self.assertEqual(next(call2), 1)
self.assertEqual(next(call1), 2)
self.assertEqual(next(call2), 2)
with self.assertRaises(ValueError):
next(call1)
with self.assertRaises(ValueError):
next(call2)
# These next 2 calls should succeed.
call3 = sample_failing_fn()
call4 = sample_failing_fn()
self.assertEqual(list(call3), [3, 4])
self.assertEqual(list(call4), [3, 4])
# Subsequent calls should return the original value.
self.assertEqual(list(sample_failing_fn()), [3, 4])
self.assertEqual(list(sample_failing_fn()), [3, 4])
def test_iterator_parallel_execution(self):
counter = Counter()
@once.once
def yielding_iterator():
nonlocal counter
for _ in range(3):
yield counter.get_incremented()
results = parallel_map(
self,
lambda: list(yielding_iterator()),
(tuple() for _ in range(_N_WORKERS * 2)),
)
for result in results:
self.assertEqual(result, [1, 2, 3])
def test_iterator_lock_not_held_during_evaluation(self):
counter = Counter()
@once.once
def yielding_iterator():
nonlocal counter
for _ in range(3):
yield counter.get_incremented()
gen1 = yielding_iterator()
gen2 = yielding_iterator()
self.assertEqual(next(gen1), 1)
counter.ready.clear()
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
# By using ensure_started and self.assertFalse(updater.done()), we can ensure it is
# definitively still running.
gen1_updater = ensure_started(executor, next, gen1)
self.assertFalse(gen1_updater.done())
self.assertEqual(next(gen2), 1)
gen2_updater = ensure_started(executor, next, gen2)
self.assertFalse(gen1_updater.done())
self.assertFalse(gen2_updater.done())
counter.ready.set()
self.assertEqual(gen1_updater.result(), 2)
self.assertEqual(gen2_updater.result(), 2)
def test_threaded_single_function(self):
counting_fn, counter = generate_once_counter_fn()
results = parallel_map(self, counting_fn)
self.assertEqual(len(results), _N_WORKERS)
for r in results:
self.assertEqual(r, 1)
self.assertEqual(counter.value, 1)
def test_once_per_thread(self):
counter = Counter()
@once.once(per_thread=True)
@execute_with_barrier(n_workers=_N_WORKERS)
def counting_fn(*args) -> int:
"""Returns the call count, which should always be 1."""
nonlocal counter
del args
return counter.get_incremented()
results = parallel_map(self, counting_fn, (tuple() for _ in range(_N_WORKERS * 4)))
self.assertEqual(min(results), 1)
self.assertEqual(max(results), _N_WORKERS)
def test_threaded_multiple_functions(self):
counters = []
fns = []
for _ in range(4):
cfn, counter = generate_once_counter_fn()
counters.append(counter)
fns.append(cfn)
def call_all_functions(i):
for j in range(i, i + 4):
self.assertEqual(fns[j % 4](), 1)
parallel_map(self, call_all_functions, ((i,) for i in range(_N_WORKERS)))
for counter in counters:
self.assertEqual(counter.value, 1)
def test_different_fn_do_not_deadlock(self):
"""Ensure different functions use different locks to avoid deadlock."""
fn1_called = threading.Event()
fn2_called = threading.Event()
# If fn1 is called first, these functions will deadlock unless they can
# run in parallel.
@once.once
def fn1():
fn1_called.set()
if not fn2_called.wait(5.0):
self.fail("Function fn1 deadlocked for 5 seconds.")
@once.once
def fn2():
fn2_called.set()
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
fn1_promise = ensure_started(executor, fn1)
fn1_called.wait()
fn2()
fn1_promise.result()
def test_closure_gc(self):
"""Tests that closure function is not cached indefinitely"""
class EphemeralObject:
"""Object which should get GC'ed"""
def create_closure():
ephemeral = EphemeralObject()
ephemeral_ref = weakref.ref(ephemeral)
@once.once
def closure():
return ephemeral
return closure, ephemeral_ref
closure, ephemeral_ref = create_closure()
# Cannot yet be garbage collected because kept alive in the closure.
self.assertIsNotNone(ephemeral_ref())
self.assertIsInstance(closure(), EphemeralObject)
self.assertIsNotNone(ephemeral_ref())
self.assertIsInstance(closure(), EphemeralObject)
del closure
# Can now be garbage collected.
# In CPython this call technically should not be needed, because
# garbage collection should have happened automatically. However, that
# is an implementation detail which does not hold on all platforms,
# such as for example pypy. Therefore, we manually trigger a garbage
# collection cycle.
gc.collect()
self.assertIsNone(ephemeral_ref())
def test_function_signature_preserved(self):
def type_annotated_fn(arg: float) -> int:
"""Very descriptive docstring."""
del arg
return 1
decorated_function = once.once(type_annotated_fn)
original_sig = inspect.signature(type_annotated_fn)
decorated_sig = inspect.signature(decorated_function)
self.assertIs(original_sig.parameters["arg"].annotation, float)
self.assertIs(decorated_sig.parameters["arg"].annotation, float)
self.assertIs(original_sig.return_annotation, int)
self.assertIs(decorated_sig.return_annotation, int)
self.assertEqual(inspect.getdoc(type_annotated_fn), inspect.getdoc(decorated_function))
if sys.flags.optimize >= 2:
self.skipTest("docstrings get stripped with -OO")
self.assertEqual(inspect.getdoc(type_annotated_fn), "Very descriptive docstring.")
def test_once_per_class(self):
class _CallOnceClass(Counter):
@once.once_per_class
def once_fn(self):
return self.get_incremented()
a = _CallOnceClass() # pylint: disable=invalid-name
b = _CallOnceClass() # pylint: disable=invalid-name
self.assertEqual(a.once_fn(), 1)
self.assertEqual(a.once_fn(), 1)
self.assertEqual(b.once_fn(), 1)
self.assertEqual(b.once_fn(), 1)
def test_once_per_class_parallel(self):
class _CallOnceClass(Counter):
@once.once_per_class
def once_fn(self):
return self.get_incremented()
once_obj = _CallOnceClass()
def execute():
return once_obj.once_fn()
results = parallel_map(self, execute, (tuple() for _ in range(_N_WORKERS * 4)))
self.assertEqual(min(results), 1)
self.assertEqual(max(results), 1)
def test_once_per_class_per_thread(self):
class _CallOnceClass(Counter):
@once.once_per_class.with_options(per_thread=True)
@execute_with_barrier(n_workers=_N_WORKERS)
def once_fn(self):
return self.get_incremented()
once_obj = _CallOnceClass()
def execute():
return once_obj.once_fn()
results = parallel_map(self, execute, (tuple() for _ in range(_N_WORKERS * 4)))
self.assertEqual(min(results), 1)
self.assertEqual(max(results), _N_WORKERS)
def test_once_not_allowed_on_method(self):
with self.assertRaises(SyntaxError):
class _InvalidClass: # pylint: disable=unused-variable
@once.once
def once_method(self):
pass
def test_once_per_instance_not_allowed_on_function(self):
with self.assertRaises(SyntaxError):
@once.once_per_instance
def once_fn():
pass
def test_once_per_class_not_allowed_on_classmethod(self):
with self.assertRaises(SyntaxError):
class _InvalidClass: # pylint: disable=unused-variable
@once.once_per_instance
@classmethod
def once_method(cls):
pass
def test_once_per_class_not_allowed_on_staticmethod(self):
with self.assertRaises(SyntaxError):
class _InvalidClass: # pylint: disable=unused-variable
@once.once_per_instance
@staticmethod
def once_method():
pass
def test_once_per_instance(self):
class _CallOnceClass:
def __init__(self, value: str, test: unittest.TestCase):
self._value = value
self.called = False
self.test = test
@once.once_per_instance
def value(self): # pylint: disable=inconsistent-return-statements
if not self.called:
self.called = True
return self._value
if self.called:
self.test.fail(f"Method on {self.value} called a second time.")
a = _CallOnceClass("a", self) # pylint: disable=invalid-name
b = _CallOnceClass("b", self) # pylint: disable=invalid-name
def call_and_check_both(i: int):
# Run in different order based on the call
if i % 4 == 0:
self.assertEqual(a.value(), "a")
self.assertEqual(a.value(), "a")
self.assertEqual(b.value(), "b")
self.assertEqual(b.value(), "b")
elif i % 4 == 1:
self.assertEqual(a.value(), "a")
self.assertEqual(b.value(), "b")
self.assertEqual(a.value(), "a")
self.assertEqual(b.value(), "b")
elif i % 4 == 2:
self.assertEqual(b.value(), "b")
self.assertEqual(a.value(), "a")
self.assertEqual(b.value(), "b")
self.assertEqual(a.value(), "a")
else:
self.assertEqual(b.value(), "b")
self.assertEqual(b.value(), "b")
self.assertEqual(a.value(), "a")
self.assertEqual(a.value(), "a")
parallel_map(self, call_and_check_both, ((i,) for i in range(_N_WORKERS)))
def test_once_per_instance_do_not_block_each_other(self):
class _BlockableClass:
def __init__(self, test: unittest.TestCase):
self.test = test
self.started = threading.Event()
self.counter = Counter()
@once.once_per_instance
def run(self) -> int:
self.started.set()
return self.counter.get_incremented()
a = _BlockableClass(self)
a.counter.ready.clear()
b = _BlockableClass(self)
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
a_job = executor.submit(a.run)
a.started.wait()
# At this point, the A job has started. However, it cannot
# complete while paused. Despite this, we want to ensure
# that B can still run.
b_job = executor.submit(b.run)
# The b_job will deadlock and this will fail if different
# object executions block each other.
self.assertEqual(b_job.result(timeout=5), 1)
a.counter.ready.set()
self.assertEqual(a_job.result(timeout=5), 1)
def test_once_per_instance_parallel(self):
class _CallOnceClass(Counter):
@once.once_per_instance
@execute_with_barrier(n_workers=4)
def once_fn(self):
return self.get_incremented()
once_objs = [_CallOnceClass(), _CallOnceClass(), _CallOnceClass(), _CallOnceClass()]
def execute(i):
return once_objs[i % 4].once_fn()
results = parallel_map(self, execute, ((i,) for i in range(_N_WORKERS * 4)))
self.assertEqual(min(results), 1)
self.assertEqual(max(results), 1)
def test_once_per_instance_per_thread(self):
class _CallOnceClass(Counter):
@once.once_per_instance.with_options(per_thread=True)
@execute_with_barrier(n_workers=_N_WORKERS)
def once_fn(self):
return self.get_incremented()
once_objs = [_CallOnceClass(), _CallOnceClass(), _CallOnceClass(), _CallOnceClass()]
def execute(i):
return once_objs[i % 4].once_fn()
results = parallel_map(self, execute, ((i,) for i in range(_N_WORKERS)))
self.assertEqual(min(results), 1)
self.assertEqual(max(results), math.ceil(_N_WORKERS / 4))
def test_once_per_instance_property(self):
counter = Counter()
class _CallOnceClass:
@once.once_per_instance
@property
def value(self):
nonlocal counter
return counter.get_incremented()
a = _CallOnceClass()
b = _CallOnceClass()
self.assertEqual(a.value, 1)
self.assertEqual(b.value, 2)
self.assertEqual(a.value, 1)
self.assertEqual(b.value, 2)
self.assertEqual(_CallOnceClass().value, 3)
self.assertEqual(_CallOnceClass().value, 4)
def test_once_per_class_classmethod(self):
counter = Counter()
class _CallOnceClass:
@once.once_per_class
@classmethod
def value(cls):
nonlocal counter
return counter.get_incremented()
self.assertEqual(_CallOnceClass.value(), 1)
self.assertEqual(_CallOnceClass.value(), 1)
def test_once_per_class_staticmethod(self):
counter = Counter()
class _CallOnceClass:
@once.once_per_class
@staticmethod
def value():
nonlocal counter
return counter.get_incremented()
self.assertEqual(_CallOnceClass.value(), 1)
self.assertEqual(_CallOnceClass.value(), 1)
def test_receiving_iterator(self):
@once.once
def receiving_iterator():
next = yield 0
while next is not None:
next = yield next
gen_1 = receiving_iterator()
gen_2 = receiving_iterator()
self.assertEqual(gen_1.send(None), 0)
self.assertEqual(gen_1.send(1), 1)
self.assertEqual(gen_1.send(2), 2)
self.assertEqual(gen_2.send(None), 0)
self.assertEqual(gen_2.send(-1), 1)
self.assertEqual(gen_2.send(-1), 2)
self.assertEqual(gen_2.send(5), 5)
self.assertEqual(next(gen_2, None), None)
self.assertEqual(gen_1.send(None), 5)
self.assertEqual(next(gen_1, None), None)
self.assertEqual(list(receiving_iterator()), [0, 1, 2, 5])
def test_receiving_iterator_parallel_execution(self):
@once.once
def receiving_iterator():
next = yield 0
while next is not None:
next = yield next
barrier = threading.Barrier(_N_WORKERS)
def call_iterator():
gen = receiving_iterator()
result = []
barrier.wait()
result.append(gen.send(None))
for i in range(1, _N_WORKERS * 4):
result.append(gen.send(i))
return result
results = parallel_map(self, call_iterator)
for result in results:
self.assertEqual(result, list(range(_N_WORKERS * 4)))
def test_receiving_iterator_parallel_execution_halting(self):
@once.once
def receiving_iterator():
next = yield 0
while next is not None:
next = yield next
barrier = threading.Barrier(_N_WORKERS)
def call_iterator(n):
"""Call the iterator but end early"""
gen = receiving_iterator()
result = []
barrier.wait()
result.append(gen.send(None))
for i in range(1, n):
result.append(gen.send(i))
return result
# Unlike the previous test, each execution should yield lists of different lengths.
# This ensures that the iterator does not hang, even if not exhausted
results = parallel_map(self, call_iterator, ((i,) for i in range(1, _N_WORKERS + 1)))
for i, result in enumerate(results):
self.assertEqual(result, list(range(i + 1)))
class TestOnceAsync(unittest.IsolatedAsyncioTestCase):
async def test_fn_called_once(self):