summaryrefslogtreecommitdiff
path: root/tests/test_rust_utils.py
blob: 1ee68541e7fcfaedb8b6601698c67b6704ebd6f9 (plain)
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
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.

import gc
import threading

from cryptography.hazmat.bindings._rust import FixedPool


class TestFixedPool:
    def test_basic(self):
        c = 0
        events = []

        def create():
            nonlocal c
            c += 1
            events.append(("create", c))
            return c

        pool = FixedPool(create)
        assert events == [("create", 1)]
        with pool.acquire() as c:
            assert c == 1
            assert events == [("create", 1)]

            with pool.acquire() as c:
                assert c == 2
                assert events == [("create", 1), ("create", 2)]

            assert events == [("create", 1), ("create", 2)]

        assert events == [("create", 1), ("create", 2)]

        del pool
        gc.collect()
        gc.collect()
        gc.collect()

        assert events == [
            ("create", 1),
            ("create", 2),
        ]

    def test_thread_stress(self):
        def create():
            return None

        pool = FixedPool(create)

        def thread_fn():
            with pool.acquire():
                pass

        threads = []
        for i in range(1024):
            t = threading.Thread(target=thread_fn)
            t.start()
            threads.append(t)

        for t in threads:
            t.join()