【问题标题】:How to mock a variable from another module in python3?如何在python3中模拟来自另一个模块的变量?
【发布时间】:2021-09-10 16:56:50
【问题描述】:

下面是我的源码

#src.py
from common.configs import MANDATORY_FIELDS

def check_mf():
   if set(MANDATORY_FIELDS).issubset(['a','b','c']):
      return True
   else:
      raise Exception("Error in mandatory fields")

这是我的测试代码

#test_src.py
from unittest import TestCase, main, mock
from src import check_mf

class TestMailSenderUtil(TestCase):
  def test_method(self):
      with mock.patch('src.MANDATORY_FIELDS') as mocked_mf:
           mocked_mf.return_value = ['a','b','c','d']
           self.assertRaises(ValidationException, check_mf)

当我运行这段代码时,测试没有通过。它会抛出一个错误,说明

AssertionError: ValidationException not raised by check_mf

为什么会出现这个错误? 仅供参考,当我在运行单元测试时尝试在 src.py 文件中打印 MANDATORY_FIELDS 时,我得到了这个

<MagicMock name='MANDATORY_FIELDS' id='139766761401144'>

为什么模拟在这里不起作用?

【问题讨论】:

    标签: python-unittest python-unittest.mock


    【解决方案1】:

    变量MANDATORY_FIELDS 没有return_value。只需将new 值作为patch() 的第二个参数传递。

    例如(Python 3.9.2)

    src.py:

    from configs import MANDATORY_FIELDS
    
    class ValidationException(Exception):
        pass
    
    def check_mf():
        print(MANDATORY_FIELDS)
        if set(MANDATORY_FIELDS).issubset(['a', 'b', 'c']):
            return True
        else:
            raise ValidationException("Error in mandatory fields")
    

    configs.py:

    MANDATORY_FIELDS=['a']
    

    test_src.py:

    from unittest import TestCase, main, mock
    from src import check_mf, ValidationException
    
    
    class TestMailSenderUtil(TestCase):
        def test_method(self):
            with mock.patch('src.MANDATORY_FIELDS', ['a', 'b', 'c', 'd']) as mocked_mf:
                self.assertRaises(ValidationException, check_mf)
    
    
    if __name__ == '__main__':
        main()
    

    单元测试结果:

    ['a', 'b', 'c', 'd']
    .
    ----------------------------------------------------------------------
    Ran 1 test in 0.000s
    
    OK
    Name                                     Stmts   Miss  Cover   Missing
    ----------------------------------------------------------------------
    src/stackoverflow/68162471/configs.py        1      0   100%
    src/stackoverflow/68162471/src.py            8      1    88%   9
    src/stackoverflow/68162471/test_src.py       8      0   100%
    ----------------------------------------------------------------------
    TOTAL                                       17      1    94%
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-20
      • 2011-04-01
      • 2021-07-06
      • 1970-01-01
      • 1970-01-01
      • 2020-12-30
      相关资源
      最近更新 更多