Assert that a method was called in a Python unit test

后端 未结 5 1216
不思量自难忘°
不思量自难忘° 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:44

    Yes, I can give you the outline but my Python is a bit rusty and I'm too busy to explain in detail.

    Basically, you need to put a proxy in the method that will call the original, eg:

     class fred(object):
       def blog(self):
         print "We Blog"
    
    
     class methCallLogger(object):
       def __init__(self, meth):
         self.meth = meth
    
       def __call__(self, code=None):
         self.meth()
         # would also log the fact that it invoked the method
    
     #example
     f = fred()
     f.blog = methCallLogger(f.blog)
    

    This StackOverflow answer about callable may help you understand the above.

    In more detail:

    Although the answer was accepted, due to the interesting discussion with Glenn and having a few minutes free, I wanted to enlarge on my answer:

    # helper class defined elsewhere
    class methCallLogger(object):
       def __init__(self, meth):
         self.meth = meth
         self.was_called = False
    
       def __call__(self, code=None):
         self.meth()
         self.was_called = True
    
    #example
    class fred(object):
       def blog(self):
         print "We Blog"
    
    f = fred()
    g = fred()
    f.blog = methCallLogger(f.blog)
    g.blog = methCallLogger(g.blog)
    f.blog()
    assert(f.blog.was_called)
    assert(not g.blog.was_called)
    

提交回复
热议问题