File: test_rust_utils.py

package info (click to toggle)
python-cryptography 38.0.4-3%2Bdeb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 4,968 kB
  • sloc: python: 51,022; ansic: 608; java: 319; makefile: 162
file content (71 lines) | stat: -rw-r--r-- 1,693 bytes parent folder | download
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
# 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

        def destroy(c):
            events.append(("destroy", c))

        pool = FixedPool(create, destroy)
        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), ("destroy", 2)]

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

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

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

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

        def destroy(c):
            pass

        pool = FixedPool(create, destroy)

        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()