【问题标题】:Python Mock Patch Two Functions that are similarPython Mock Patch 两个相似的函数
【发布时间】:2021-09-05 13:57:28
【问题描述】:

假设我有一个函数,它有两个相似的函数调用:

def foo():
  test = one_func("SELECT * from Users;")
  test1 = one_func("SELECT * from Addresses;")
  return test, test1

如何修补这些功能内容?这是我的尝试:

@patch('one_func')
def test_foo(self, mock_one_func):
     mock_one_func.return_value = one_func("SELECT * from TestUsers;")
     mock_one_func.return_value = one_func("SELECT * from TestAddresses;")

但我认为这种方法将 one_func 作为一个整体修补每个函数。结果:

def foo():
  test = one_func("SELECT * from TestUsers;")
  test1 = one_func("SELECT * from TestUsers;")
  return test, test1

然后在下一行

def foo():
  test = one_func("SELECT * from TestAddresses;")
  test1 = one_func("SELECT * from TestAddresses;")
  return test, test1

我希望在修补函数中发生的事情是。

def foo():
  test = one_func("SELECT * from TestUsers;")
  test1 = one_func("SELECT * from TestAddresses;")
  return test, test1

【问题讨论】:

    标签: sqlalchemy python-unittest python-unittest.mock


    【解决方案1】:

    实现您需要的方法是使用side_effect 而不是return_valueside_effect 可以是很多东西。如果它是Exception 类或对象,则只要调用修补方法,它就会引发该异常。如果它是一个值列表,将为每个方法调用按顺序返回每个值。如果它是一个函数,将使用每个模拟方法调用的参数执行该函数。

    这是一个工作示例,我将向您展示如何在 side_effectside_effect 函数上使用值列表。使用函数的好处在于您可以根据修补方法调用的参数使其返回特定值。

    from mock import patch
    
    import unittest
    
    class MyClass(object):
        def one_func(self, query):
            return ''
    
        def foo(self):
            test = self.one_func("SELECT * from Users;")
            test1 = self.one_func("SELECT * from Addresses;")
            return test, test1
    
    class Test(unittest.TestCase):
        @patch.object(MyClass, 'one_func')
        def test_foo(self, one_func_mock):
            # side_effect can be a list of responses that will be returned in
            # subsequent calls
            one_func_mock.side_effect = ['users', 'addresses']
            self.assertEqual(('users', 'addresses'), MyClass().foo())
    
            # side_effect can also be a method which will return different mock
            # responses depending on args:
            def side_effect(args):
                if args == "SELECT * from Users;":
                    return 'other users'
    
                if args == "SELECT * from Addresses;":
                    return 'other addresses'
            
            one_func_mock.side_effect = side_effect
            self.assertEqual(('other users', 'other addresses'), MyClass().foo())
    
    unittest.main()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-23
      • 2015-10-13
      • 1970-01-01
      • 2014-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-01
      相关资源
      最近更新 更多