【问题标题】:Mocking decorator which is outside of python class but class using this模拟装饰器,它在 python 类之外,但使用它的类
【发布时间】:2021-03-15 11:32:26
【问题描述】:

我尝试在 StackOverflow 上查找答案,但我找不到解决方案 - 大多数答案是旧的或不适合我的。 我有这样的代码:

#file app.py
#structure of directory
#-words
#--x
#---y
#----z
#------app.py
#-test
#--test.py

def is_connected(f):
    def is_con(self):
        if self.connection:
           print("not work")
        else:
             return False
        f()
        return True
   return is_con

class A():
    /*another code */
    
    @is_connected
    def get_element(self):
        return True

这是我的代码的基本逻辑,现在我想用 unittest 来测试一下。


def lol():
   print(123)

from unittest.mock import patch
from words.x.y.z.app import A
class TestUnit:
    @patch('words.x.y.z.app.is_connected)
    def test_get(self, mocked):
       mocked.return_value = 23
       mocked.side_effect = lol
       a = A()
       assert a.get_element()

但是当我运行测试时,我会在控制台中看到

not work

所以我猜,这个装饰器没有被嘲笑。我怎样才能正确地做到这一点?

我尝试过的stackoverflow解决方案对我来说很有意义。: Mock authentication decorator in unittesting , Can I patch a Python decorator before it wraps a function?

【问题讨论】:

    标签: python unit-testing python-3.7 python-unittest python-decorators


    【解决方案1】:

    我找到了解决方案:我从 functools import wraps 添加到我的装饰器 @wraps(f)

    def is_connected(f):
        def is_con(self):
            if self.connection:
               print("not work")
            else:
                 return False
            f()
            return True
       return is_con
    

    当我想用这个测试任何方法时,我只是这样做:

    from unittest.mock import patch
    from words.x.y.z.app import A
    class TestUnit:
    
        def test_get(self, ):
           a = A()
           assert a.get_element.__wrapped__(a)
    

    但我不知道在这种情况下我应该如何使用它:

        @is_connected
        def get_element(self, element):
            return element
    

    应该像这样工作:

           assert a.get_element(1).__wrapped__(a)
    

    但没有

    【讨论】:

      猜你喜欢
      • 2014-03-02
      • 2022-12-09
      • 2018-12-04
      • 2022-01-03
      • 2021-07-16
      • 1970-01-01
      • 2010-09-23
      • 2010-09-25
      相关资源
      最近更新 更多