File: test_callbacks.py

package info (click to toggle)
nanobind 2.9.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,060 kB
  • sloc: cpp: 11,838; python: 5,862; ansic: 4,820; makefile: 22; sh: 15
file content (58 lines) | stat: -rw-r--r-- 1,353 bytes parent folder | download | duplicates (3)
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
import test_callbacks_ext as t
import gc


def test_callbacks():
    pub1 = t.publisher()
    pub2 = t.publisher()
    record = []

    def sub1(x):
        record.append(x + 10)

    def sub2(x):
        record.append(x + 20)

    pub1.subscribe(sub1)
    pub2.subscribe(sub2)
    for pub in (pub1, pub2):
        pub.subscribe(record.append)

    pub1.emit(1)
    assert record == [11, 1]
    del record[:]

    pub2.emit(2)
    assert record == [22, 2]
    del record[:]

    pub1_w, pub2_w = t.registry.keys()  # weakrefs to pub1, pub2
    assert pub1_w() is pub1
    assert pub2_w() is pub2
    assert t.registry[pub1_w].subscribers == {sub1, record.append}
    assert t.registry[pub2_w].subscribers == {sub2, record.append}

    # NB: this `record.append` is a different object than the one we subscribed
    # above, so we're testing the normalization logic in unsubscribe_policy
    pub1.unsubscribe(record.append)
    assert t.registry[pub1_w].subscribers == {sub1}
    pub1.emit(3)
    assert record == [13]
    del record[:]

    del pub, pub1
    gc.collect()
    gc.collect()
    assert pub1_w() is None
    assert pub2_w() is pub2
    assert t.registry.keys() == {pub2_w}

    pub2.emit(4)
    assert record == [24, 4]
    del record[:]

    del pub2
    gc.collect()
    gc.collect()
    assert pub2_w() is None
    assert not t.registry