-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest.py
More file actions
1636 lines (1377 loc) · 43.1 KB
/
test.py
File metadata and controls
1636 lines (1377 loc) · 43.1 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
# -*- coding: utf-8 -*-
from contextlib import contextmanager
import gc
import multiprocessing
import os
import random
import signal
import sys
import time
import weakref
import gevent
from gevent import Greenlet, GreenletExit, Timeout
from gevent.event import AsyncResult, Event
from gevent.lock import Semaphore
from gevent.pool import Group
from gevent.queue import Channel, Full
import pytest
from six.moves import range
import lets
from lets.quietlet import quiet
@contextmanager
def takes(seconds, tolerance=0.1):
t = time.time()
yield
e = time.time() - t
if not (seconds - tolerance <= e <= seconds + tolerance):
raise AssertionError('%r seconds expected but %r '
'seconds taken' % (seconds, e))
@contextmanager
def killing(obj, exception=GreenletExit, block=True, timeout=None):
try:
yield obj
finally:
obj.kill(exception, block, timeout)
def return_args(*args, **kwargs):
return args, kwargs
def kill_itself():
os.kill(os.getpid(), signal.SIGKILL)
def busy_waiting(seconds=0.1):
t = time.time()
while time.time() - t < seconds:
pass
return seconds
def divide_by_zero():
1989 / 12 / 12 / 0
def throw(exception):
raise exception
def spawn_again(f, *args, **kwargs):
return gevent.spawn(lambda: gevent.spawn(f, *args, **kwargs).get())
class Killed(BaseException):
pass
class ExpectedError(BaseException):
pass
class Error1(Exception):
pass
class Error2(Exception):
pass
def notify_entry(hole, f, *args, **kwargs):
g = lets.Quietlet.spawn(f, *args, **kwargs)
g.join(0)
try:
hole.put(True)
return g.get()
except BaseException as exc:
g.kill(exc)
return g.get()
def raise_when_killed(exception=Killed):
try:
while True:
gevent.sleep(0)
except BaseException as exc:
if exception is None:
raise exc
else:
raise exception
def get_pid_anyway(*args, **kwargs):
# ProcessGroup.map may don't spawn enough processlets when calling too fast
# function.
gevent.sleep(0.1)
return os.getpid()
def test_processlet_spawn_child_process():
job = lets.Processlet.spawn(os.getppid)
assert job.exit_code is None
assert job.pid != os.getpid()
assert job.get() == os.getpid()
assert job.exit_code == 0
def test_processlet_join_zero():
job = lets.Processlet.spawn(busy_waiting)
assert job.pid is None
job.join(0)
assert job.pid is not None
job.join()
@pytest.mark.flaky(reruns=10)
def test_processlet_parallel_execution():
# NOTE: Here's a potential hang.
cpu_count = multiprocessing.cpu_count()
if cpu_count < 2:
pytest.skip('CPU not enough')
t = time.time()
jobs = [gevent.spawn(busy_waiting) for x in range(5)]
gevent.joinall(jobs)
delay = time.time() - t
assert delay > 0.5
for job in jobs:
assert job.get() == 0.1
t = time.time()
jobs = [lets.Processlet.spawn(busy_waiting) for x in range(5)]
gevent.joinall(jobs)
delay = time.time() - t
assert delay < 0.1 * cpu_count
for job in jobs:
assert job.get() == 0.1
def test_processlet_exception():
job = lets.Processlet.spawn(divide_by_zero)
with pytest.raises(ZeroDivisionError):
job.get()
assert job.exit_code == 1
def test_processlet_args():
args = (1, 2)
kwargs = {'x': 3, 'y': 4}
job = lets.Processlet.spawn(return_args, *args, **kwargs)
assert job.get() == (args, kwargs)
# def test_processlet_pipe_arg():
# with gipc.pipe() as (r, w):
# job = lets.Processlet.spawn(type(w).put, w, 1)
# assert r.get() == 1
# job.join()
def test_processlet_without_start():
job = lets.Processlet(os.getppid)
assert job.exit_code is None
assert job.pid is None
with pytest.raises(gevent.Timeout), gevent.Timeout(0.1):
job.join()
with pytest.raises(gevent.Timeout):
job.get(timeout=0.1)
def test_processlet_unref(count_greenlets):
job = lets.Processlet.spawn(os.getppid)
assert count_greenlets() == 1
job.join()
assert count_greenlets() == 0
def test_processlet_start_twice():
job = lets.Processlet(random.random)
job.start()
r1 = job.get()
job.start()
r2 = job.get()
assert r1 == r2
# def f_for_test_processlet_callback():
# gevent.sleep(0.5)
# 0 / 0
# def test_processlet_callback():
# pool = lets.ProcessPool(2)
# r = []
# with killing(pool):
# for x in range(10):
# job = pool.spawn(f_for_test_processlet_callback)
# job.link(lambda j: (j.join(), r.append(1)))
# pool.join()
# assert len(r) == 10
def test_kill_processlet_before_starting(proc):
job = lets.Processlet.spawn(raise_when_killed)
assert len(proc.children()) == 0
job.kill()
assert isinstance(job.get(), GreenletExit)
assert len(proc.children()) == 0
def test_kill_processlet_after_starting(proc, pipe):
p, c = pipe
job = lets.Processlet.spawn(notify_entry, c, raise_when_killed)
assert len(proc.children()) == 0
assert p.get() is True
assert len(proc.children()) == 1
job.kill()
assert len(proc.children()) == 0
with pytest.raises(Killed):
job.get()
assert job.exit_code == 1
def test_kill_processlet(proc):
job = lets.Processlet.spawn(raise_when_killed)
job.join(0)
assert len(proc.children()) == 1
job.kill()
assert len(proc.children()) == 0
with pytest.raises(Killed):
job.get()
assert job.exit_code == 1
def test_kill_processlet_busy(proc):
job = lets.Processlet.spawn(busy_waiting, 60)
job.join(0)
assert len(proc.children()) == 1
with pytest.raises(gevent.Timeout), gevent.Timeout(0.5):
job.kill()
assert len(proc.children()) == 1
job.send(signal.SIGKILL)
job.join()
assert len(proc.children()) == 0
def test_kill_processlet_busy_with_kill_signo(proc):
job = lets.Processlet.spawn(signal.SIGUSR1, busy_waiting, 60)
job.join(0)
assert len(proc.children()) == 1
job.kill(Killed)
assert len(proc.children()) == 0
with pytest.raises(Killed):
job.get()
assert job.exit_code == 1
def test_kill_processlet_after_join_another_processlet(proc):
job1 = lets.Processlet.spawn(gevent.sleep, 1)
job2 = lets.Processlet.spawn(gevent.sleep, 3)
job1.join(0.1)
with gevent.Timeout(5, AssertionError('job2.kill() timed out')):
job2.kill()
assert job2.ready()
job1.join()
assert job1.ready()
def test_kill_processlet_nonblock(proc):
job = lets.Processlet.spawn(raise_when_killed)
job.join(0)
assert len(proc.children()) == 1
job.kill(block=False)
assert len(proc.children()) == 1
with pytest.raises(Killed):
job.get()
assert len(proc.children()) == 0
assert job.exit_code == 1
def test_kill_processlet_group(proc):
group = Group()
group.greenlet_class = lets.Processlet
group.spawn(raise_when_killed)
group.spawn(raise_when_killed)
group.spawn(raise_when_killed)
group.join(0)
assert len(proc.children()) == 3
group.kill()
assert len(proc.children()) == 0
for job in group:
with pytest.raises(Killed):
job.get()
assert job.exit_code == 1
@pytest.mark.flaky(reruns=10)
def test_joinall_processlets():
p1 = lets.Processlet.spawn(lambda: gevent.sleep(1))
p2 = lets.Processlet.spawn(lambda: 0 / 0)
with pytest.raises(ZeroDivisionError):
gevent.joinall([p1, p2], raise_error=True)
assert not p1.ready()
assert p2.ready()
with takes(1):
assert p1.get() is None
def test_process_pool_recycles_child_process(proc):
assert len(proc.children()) == 0
pool = lets.ProcessPool(1)
with killing(pool):
pids = set()
for x in range(10):
pids.add(pool.spawn(os.getpid).get())
assert len(pids) == 1
assert next(iter(pids)) != os.getpid()
assert len(proc.children()) == 1
assert len(proc.children()) == 0
def test_process_pool_size_limited(proc):
assert len(proc.children()) == 0
pool = lets.ProcessPool(2)
with killing(pool):
pool.spawn(busy_waiting, 0.1)
pool.spawn(busy_waiting, 0.2)
pool.spawn(busy_waiting, 0.1)
pool.spawn(busy_waiting, 0.2)
pool.spawn(busy_waiting, 0.1)
pool.join(0)
assert len(proc.children()) == 2
pool.join()
assert len(proc.children()) == 0
def test_process_pool_waits_worker_available(proc):
assert len(proc.children()) == 0
pool = lets.ProcessPool(2)
with killing(pool):
with Timeout(0.1):
pool.spawn(busy_waiting, 0.5)
pool.spawn(busy_waiting, 0.5)
with pytest.raises(Timeout):
with Timeout(0.1):
pool.spawn(busy_waiting, 0.5)
pool.join()
assert len(proc.children()) == 2
assert len(proc.children()) == 0
@pytest.mark.flaky(reruns=10)
def test_process_pool_apply(proc):
assert len(proc.children()) == 0
pool = lets.ProcessPool(2)
with killing(pool):
pool.apply_async(busy_waiting, (0.2,))
pool.apply_async(busy_waiting, (0.2,))
pool.apply_async(busy_waiting, (0.2,))
with Timeout(3):
pool.join()
assert len(proc.children()) == 2
assert len(proc.children()) == 0
def test_process_pool_map(proc):
assert len(proc.children()) == 0
pool = lets.ProcessPool(3)
with killing(pool):
assert pool.map(busy_waiting, [0.1] * 5) == [0.1] * 5
assert len(set(pool.map(get_pid_anyway, range(10)))) == 3
assert len(proc.children()) == 3
assert len(proc.children()) == 0
def test_process_pool_unlimited(proc):
assert len(proc.children()) == 0
pool = lets.ProcessPool()
with killing(pool):
for x in range(5):
pids = pool.map(get_pid_anyway, range(x + 1))
assert len(pids) == x + 1
assert len(proc.children()) == x + 1
for x in reversed(range(5)):
pids = pool.map(get_pid_anyway, range(x + 1))
assert len(pids) == x + 1
assert len(proc.children()) == 5
assert len(proc.children()) == 0
def test_process_pool_respawns_worker(proc):
assert len(proc.children()) == 0
pool = lets.ProcessPool(2)
with killing(pool):
pids1 = pool.map(get_pid_anyway, range(2))
pool.kill()
pids2 = pool.map(get_pid_anyway, range(2))
assert not set(pids1).intersection(pids2)
assert len(proc.children()) == 0
def test_process_pool_raises(proc):
assert len(proc.children()) == 0
pool = lets.ProcessPool(1)
with killing(pool):
pid1 = pool.spawn(os.getpid).get()
g = pool.spawn(divide_by_zero)
with pytest.raises(ZeroDivisionError):
g.get()
pid2 = pool.spawn(os.getpid).get()
assert pid1 == pid2
assert len(proc.children()) == 0
@contextmanager
def raises_from(exc_type, code_name):
try:
yield
except exc_type:
__, __, tb = sys.exc_info()
while tb.tb_next is not None:
tb = tb.tb_next
assert tb.tb_frame.f_code.co_name == code_name
else:
raise AssertionError('Expected error not raised')
def test_quietlet():
job = lets.Quietlet.spawn(divide_by_zero)
with raises_from(ZeroDivisionError, 'divide_by_zero'):
job.get()
def test_quietlet_doesnt_print_exception(capsys):
job = lets.Quietlet.spawn(divide_by_zero)
job.join()
out, err = capsys.readouterr()
assert not out
assert not err
@pytest.mark.skipif(gevent.__version__ == '1.1a2',
reason='Killed greenlet of gevent-1.1a2 raises nothing')
def test_kill_quietlet():
job = lets.Quietlet.spawn(divide_by_zero)
job.kill()
assert isinstance(job.get(), GreenletExit)
job = lets.Quietlet.spawn(divide_by_zero)
job.kill(RuntimeError)
with pytest.raises(RuntimeError):
job.get()
@pytest.fixture
def ref_count():
# try:
# # CPython
# return sys.getrefcount
# except AttributeError:
# PyPy
def count_referrers(x):
gc.collect()
refs = gc.get_referrers(x)
refs = reduce(lambda refs, r: refs.append(r) or refs
if r not in refs else refs, refs, [])
return len(refs)
return count_referrers
def _test_quietlet_no_leak(ref_count):
ref = weakref.ref(lets.Quietlet.spawn(divide_by_zero))
gc.collect()
assert isinstance(ref(), lets.Quietlet)
gevent.wait()
gc.collect()
assert ref() is None
job = lets.Quietlet(divide_by_zero)
assert ref_count(job) == 2 # variable 'job' (1) + argument (1)
job.start()
assert ref_count(job) == 3 # + hub (1)
job.join()
assert ref_count(job) == 6 # + gevent (3)
gevent.sleep(0)
assert ref_count(job) == 2 # - gevent (3) - hub (1)
ref = weakref.ref(job)
del job
gc.collect()
assert ref() is None
def test_quiet_group():
from gevent.pool import Group
group = Group()
group.spawn(divide_by_zero)
group.spawn(divide_by_zero)
with raises_from(ZeroDivisionError, 'divide_by_zero'):
group.join(raise_error=True)
def test_greenlet_exit(group):
g = group.spawn(gevent.sleep, 1)
g.kill()
assert g.ready()
assert g.successful()
assert isinstance(g.get(), GreenletExit)
def test_task_kills_group(proc, group):
def f1():
gevent.sleep(0.1)
raise Error1
def f2():
try:
gevent.sleep(100)
except Error1:
raise Error2
def f3():
gevent.sleep(100)
g1 = group.spawn(f1)
g1.link_exception(lambda g: group.kill(g.exception))
g2 = group.spawn(f2)
g3 = group.spawn(f3)
with pytest.raises((Error1, Error2)):
group.join(raise_error=True)
assert len(proc.children()) == 0
assert not group.greenlets
assert g1.ready()
assert g2.ready()
assert g3.ready()
assert not g1.successful()
assert not g2.successful()
assert not g3.successful()
assert isinstance(g1.exception, Error1)
assert isinstance(g2.exception, Error2)
assert isinstance(g3.exception, Error1)
def _test_quiet_context(capsys):
# Print the exception.
gevent.spawn(divide_by_zero).join()
out, err = capsys.readouterr()
assert 'ZeroDivisionError' in err
# Don't print.
with quiet():
gevent.spawn(divide_by_zero).join()
out, err = capsys.readouterr()
assert not err
# Don't print also.
# gevent.spawn(divide_by_zero)
# with quiet():
# gevent.wait()
# out, err = capsys.readouterr()
# assert not err
# quiet() context in a greenlet doesn't print also.
def f():
with quiet():
gevent.spawn(divide_by_zero).join()
gevent.spawn(f).join()
out, err = capsys.readouterr()
assert not err
# Out of quiet() context in a greenlet prints.
def f():
with quiet():
gevent.spawn(divide_by_zero).join()
0 / 0
gevent.spawn(f).join()
out, err = capsys.readouterr()
assert 'ZeroDivisionError' in err
# quiet() context with a greenlet doesn't print.
g = gevent.spawn(divide_by_zero)
with quiet(g):
g.join()
out, err = capsys.readouterr()
assert not err
# Remaining greenlet.
with quiet():
g = gevent.spawn(gevent.sleep, 0.1)
gevent.sleep(1)
def test_greenlet_system_exit():
gevent.spawn(sys.exit)
with pytest.raises(SystemExit):
gevent.spawn(gevent.sleep, 0.1).join()
def test_processlet_system_exit(pipe):
job = lets.Processlet.spawn(kill_itself)
gevent.spawn(gevent.sleep, 0.1).join()
with pytest.raises(lets.ProcessExit) as e:
job.get()
assert e.value.code == -signal.SIGKILL
assert job.exit_code == -signal.SIGKILL
gevent.sleep(1)
job = lets.Processlet.spawn(busy_waiting, 10)
job.join(0)
os.kill(job.pid, signal.SIGTERM)
with pytest.raises(lets.ProcessExit) as e:
job.get()
assert e.value.code == -signal.SIGTERM
assert job.exit_code == -signal.SIGTERM
p, c = pipe
job = lets.Processlet.spawn(notify_entry, c, raise_when_killed,
SystemExit(42))
p.get()
job.kill()
with pytest.raises(lets.ProcessExit) as e:
job.get()
assert e.value.code == 42
assert job.exit_code == 42
def test_processlet_exits_by_sigint():
job = lets.Processlet.spawn(busy_waiting, 10)
job.send(signal.SIGINT)
job.join()
assert isinstance(job.get(), gevent.GreenletExit)
def test_processlet_pause_and_resume(pipe):
p, c = pipe
job = lets.Processlet.spawn(notify_entry, c, lambda: gevent.sleep(2) or 42)
p.get()
os.kill(job.pid, signal.SIGSTOP)
gevent.sleep(1)
with pytest.raises(gevent.Timeout), gevent.Timeout(3):
job.join()
os.kill(job.pid, signal.SIGCONT)
assert job.get() == 42
def test_processlet_kill_kill():
job = lets.Processlet.spawn(raise_when_killed, exception=None)
job.join(0)
job.kill(Error1, block=False)
job.kill(Error2, block=False)
with pytest.raises(Error1):
job.get()
@pytest.mark.parametrize('greenlet_class, exception_class', [
(Greenlet, SystemExit), (lets.Processlet, lets.ProcessExit)
])
def test_exit_in_greenlet(greenlet_class, exception_class):
code = random.randrange(1, 65)
def f():
raise SystemExit(code)
g = greenlet_class.spawn(f)
with pytest.raises(exception_class) as excinfo:
g.get()
assert excinfo.type is exception_class
assert excinfo.value.args == (code,)
# def test_exit_from_nested_greenlet_in_processlet_after_greenlet_exit():
# def f(x):
# def ff():
# raise SystemExit(x)
# gevent.spawn(ff).get()
# # by Processlet - ok
# g = lets.Processlet.spawn(f, 1)
# with pytest.raises(lets.ProcessExit) as excinfo:
# g.get()
# assert excinfo.value.args == (1,)
# # by Greenlet - ok
# g = Greenlet.spawn(f, 2)
# with pytest.raises(SystemExit) as excinfo:
# g.get()
# assert excinfo.value.args == (2,)
# # by Greenlet - ok
# g = Greenlet.spawn(f, 3)
# with pytest.raises(SystemExit) as excinfo:
# g.get()
# assert excinfo.value.args == (3,)
# # by Processlet - fail with SystemExit(2) not ProcessExit(3).
# g = lets.Processlet.spawn(f, 4)
# with pytest.raises(BaseException) as excinfo:
# g.get()
# assert excinfo.value.args == (4,)
# assert excinfo.type is lets.ProcessExit
@pytest.mark.parametrize('greenlet_class, exception_class', [
(Greenlet, SystemExit), (lets.Processlet, lets.ProcessExit)
])
def test_exit_recovery_from_nested_greenlet(greenlet_class, exception_class):
code = random.randrange(1, 65)
def f():
def ff():
raise SystemExit(code)
try:
gevent.spawn(ff).get()
except SystemExit:
# Not working.
return 'caught'
except:
return 'some error'
else:
return 'no error'
g = greenlet_class.spawn(f)
with pytest.raises(exception_class) as excinfo:
g.get()
assert excinfo.type is exception_class
assert excinfo.value.args == (code,)
def test_quietlet_system_exit():
job = lets.Quietlet.spawn(sys.exit)
gevent.spawn(gevent.sleep, 0.1).join()
job.join()
assert job.ready()
assert not job.successful()
assert isinstance(job.exception, SystemExit)
def test_object_pool():
# getting object blocks
pool = lets.ObjectPool(2, object)
assert pool.available()
assert pool.count() == 0
o1 = pool.get()
assert pool.available()
assert pool.count() == 1
o2 = pool.get()
assert not pool.available()
with pytest.raises(gevent.Timeout):
pool.get(timeout=0.1)
assert o1 is not o2
assert pool.count() == 2
# release and get again
pool.release(o1)
assert pool.available()
o3 = pool.get()
assert not pool.available()
assert o1 is o3
assert pool.count() == 2
# discard
pool.discard(o2)
o4 = pool.get()
assert not pool.available()
assert o2 is not o4
pool.discard(o4)
assert pool.available()
def test_object_pool_unlimited():
# getting object blocks
pool = lets.ObjectPool(None, object)
assert pool.available()
o1 = pool.get()
assert pool.available()
o2 = pool.get()
assert pool.available()
assert o1 is not o2
assert pool.count() == 2
# release and get again
pool.release(o1)
o3 = pool.get()
assert o1 is o3
o4 = pool.get()
assert o4 is not o1
assert o4 is not o2
assert pool.count() == 3
# discard
pool.discard(o2)
o5 = pool.get()
assert o2 is not o5
def test_object_pool_context():
pool = lets.ObjectPool(1, object)
assert pool.available()
with pool.reserve() as o:
assert type(o) is object
assert not pool.available()
assert pool.available()
def test_object_pool_wait_available():
pool = lets.ObjectPool(1, object)
o = pool.get()
waiting_avaiable = gevent.spawn(pool.wait_available)
waiting_avaiable.join(0.1)
assert not waiting_avaiable.ready()
pool.release(o)
waiting_avaiable.join(0.1)
assert waiting_avaiable.ready()
def test_object_pool_rotation():
counter = [0]
def f():
counter[0] += 1
return counter[0]
pool = lets.ObjectPool(3, f)
assert pool.get() == 1
assert pool.get() == 2
assert pool.get() == 3
pool.release(1)
pool.release(2)
pool.release(3)
assert pool.get() == 1
pool.discard(2)
assert pool.get() == 3
assert pool.get() == 4
pool.discard(1)
pool.release(1)
assert pool.get() == 5
assert not pool.available()
def test_object_pool_with_slow_behaviors():
def slow():
gevent.sleep(0.1)
return object()
pool = lets.ObjectPool(2, slow)
def consume_obj_from_pool():
with pool.reserve():
gevent.sleep(0.1)
gevent.joinall([gevent.spawn(consume_obj_from_pool) for x in range(10)])
assert pool.count() == 2
def test_object_pool_clear():
events = []
pool = lets.ObjectPool(2, lambda: events.pop(), lambda e: e.set())
# clear all
_events = [Event(), Event()]
events.extend(_events)
with pool.reserve():
with pool.reserve():
pass
assert pool.count() == 2
assert [e.is_set() for e in _events] == [False, False]
pool.clear()
assert pool.count() == 0
assert [e.is_set() for e in _events] == [True, True]
# clear only available
_events = [Event(), Event()]
events.extend(_events)
with pool.reserve():
with pool.reserve():
pass
assert pool.count() == 2
assert [e.is_set() for e in _events] == [False, False]
pool.clear()
assert pool.count() == 1
assert [e.is_set() for e in _events] == [True, False]
pool.clear()
assert [e.is_set() for e in _events] == [True, False]
pool.clear()
assert pool.count() == 0
assert [e.is_set() for e in _events] == [True, True]
def test_object_pool_discard_later():
pool = lets.ObjectPool(1, object, discard_later=0.1)
with pool.reserve() as a:
pass
with pool.reserve() as b:
pass
assert a is b
assert pool.count() == 1
gevent.sleep(0.2)
assert pool.count() == 0
with pool.reserve() as c:
pass
assert a is not c
gevent.sleep(0.05) # try to discard soon
with pool.reserve() as d:
gevent.sleep(0.2) # but busy
assert c is d
def test_object_pool_discard_later_with_destroy():
objects = set()
def factory():
obj = object()
objects.add(obj)
return obj
def destroy(obj):
objects.remove(obj)
pool = lets.ObjectPool(1, factory, destroy, discard_later=0.1)
with pool.reserve() as a:
pass
with pool.reserve() as b:
pass
assert a is b
assert a in objects
assert pool.count() == 1
gevent.sleep(0.2)
assert pool.count() == 0
assert a not in objects
with pool.reserve() as c:
pass
assert a is not c
assert a not in objects
assert c in objects
gevent.sleep(0.05) # try to discard soon
with pool.reserve() as d:
gevent.sleep(0.2) # but busy
assert c is d
assert c in objects
assert len(objects) == 1
def test_object_pool_discard_immediately():
pool = lets.ObjectPool(None, object, discard_later=0)
assert pool.count() == 0
x = pool.get()
assert pool.count() == 1
pool.release(x)
assert pool.count() == 0
def test_object_pool_as_just_factory():
objects = set()
def factory():
obj = object()
objects.add(obj)
return obj
def destroy(obj):
objects.remove(obj)
# Actually, ObjectPool with (size=None, discard_later=0) is not useful as
# a pool. get() always succeeds, release() always destroys the object.
# The pool just looks like an object factory.
pool = lets.ObjectPool(None, factory, destroy, discard_later=0)
with pool.reserve() as a:
assert a in objects
with pool.reserve() as b:
assert a in objects
assert b in objects
assert a is not b
with pool.reserve() as c:
assert a in objects
assert b in objects
assert c in objects
assert a is not b
assert a is not c
assert b is not c
assert a in objects
assert b in objects
assert c not in objects
assert a in objects
assert b not in objects
assert c not in objects
assert a not in objects
assert b not in objects
assert c not in objects
def test_object_pool_discard_later_with_slow_destroy():
destroy_started = Event()
destroy_ended = Event()
def slow_destroy(obj):
destroy_started.set()
gevent.sleep(10)
destroy_ended.set()
pool = lets.ObjectPool(1, object, slow_destroy, discard_later=0.1)
with pool.reserve() as a:
pass