Assert that a method was called in a Python unit test

后端 未结 5 1203
不思量自难忘°
不思量自难忘° 2020-12-04 15:14

Suppose I have the following code in a Python unit test:

aw = aps.Request(\"nv1\")
aw2 = aps.Request(\"nv2\", aw)

Is there an easy way to a

5条回答
  •  离开以前
    2020-12-04 15:32

    I'm not aware of anything built-in. It's pretty simple to implement:

    class assertMethodIsCalled(object):
        def __init__(self, obj, method):
            self.obj = obj
            self.method = method
    
        def called(self, *args, **kwargs):
            self.method_called = True
            self.orig_method(*args, **kwargs)
    
        def __enter__(self):
            self.orig_method = getattr(self.obj, self.method)
            setattr(self.obj, self.method, self.called)
            self.method_called = False
    
        def __exit__(self, exc_type, exc_value, traceback):
            assert getattr(self.obj, self.method) == self.called,
                "method %s was modified during assertMethodIsCalled" % self.method
    
            setattr(self.obj, self.method, self.orig_method)
    
            # If an exception was thrown within the block, we've already failed.
            if traceback is None:
                assert self.method_called,
                    "method %s of %s was not called" % (self.method, self.obj)
    
    class test(object):
        def a(self):
            print "test"
        def b(self):
            self.a()
    
    obj = test()
    with assertMethodIsCalled(obj, "a"):
        obj.b()
    

    This requires that the object itself won't modify self.b, which is almost always true.

提交回复
热议问题