File: test_weakmethod.py

package info (click to toggle)
python-enaml 0.19.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,284 kB
  • sloc: python: 31,443; cpp: 4,499; makefile: 140; javascript: 68; lisp: 53; sh: 20
file content (62 lines) | stat: -rw-r--r-- 1,584 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
#------------------------------------------------------------------------------
# Copyright (c) 2020-2024, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
#------------------------------------------------------------------------------
import gc

import pytest

from enaml.weakmethod import WeakMethod

class CObj:
    def __init__(self):
        self.counter = 0
        self.last_args = ()
        self.last_kwargs = {}

    def meth(self, *args, **kwargs):
        self.counter += 1
        self.last_args = args
        self.last_kwargs = kwargs
        return 1


def test_weakmethod_lifetime():
    """Test WeakMethod lifetime.

    """
    obj = CObj()
    wm = WeakMethod(obj.meth)
    assert wm is WeakMethod(obj.meth)
    assert wm(1, 2, a=2, b=3) == 1
    assert obj.counter == 1
    assert obj.last_args == (1, 2)
    assert obj.last_kwargs == dict(a=2, b=3)

    del obj
    gc.collect()
    assert wm() is None


def test_handling_bad_arguments():
    """Test handling bad arguments to WeakMethod.

    """
    with pytest.raises(TypeError) as exc:
        WeakMethod(a=1)
    assert "keyword" in exc.value.args[0]

    with pytest.raises(TypeError) as exc:
        WeakMethod(1, 2)
    assert "1 argument" in exc.value.args[0]

    with pytest.raises(TypeError) as exc:
        WeakMethod()
    assert "1 argument" in exc.value.args[0]

    with pytest.raises(TypeError) as exc:
        WeakMethod(CObj.meth)
    assert "MethodType" in exc.value.args[0]