Python在指定参数时模拟方法

2024-05-29 11:02:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python方法,比如

import external_object

from external_lib1 import ExternalClass1
from external_lib2 import Hook

class MyClass(self):

    def my_method(self):
        ExternalClass.get('arg1') #should be mocked and return a specific value with this arg1
        ExternalClass.get('arg2') #should be mocked and return a specific value with this arg2

    def get_hook(self):
        return Hook() # return a mock object with mocked method on it

    def my_method(self):
        object_1 = external_object.instance_type_1('args') # those are two different object instanciate from the same lib.
        object_2 = external_object.instance_type_2('args')

        object_1.method_1('arg') # should return what I want when object_1 mocked
        object_2.method_2 ('arg') # should return what I want when object_2 mocked

在我的测试中,我想知道我在评论中写了什么

我本可以做到的,但每次都变得一团糟。 我曾经为一些东西调用flexmock(例如ExternalClass.get('arg1')将使用flexmock(ExternalClass).should_return('arg').with_args('arg') # etc...进行模拟),但是我厌倦了使用不同的测试库进行模拟

我只想使用mock库,但我很难找到一种一致的方法


Tags: fromimportselfgetreturnobjectdefwith
1条回答
网友
1楼 · 发布于 2024-05-29 11:02:47

我喜欢使用python的unittest库。具体来说,unittest.mock是一个很好的库,可以自定义单元测试函数中的side effectsreturn value

它们可以如下使用:

class Some(object):
  """
    You want to test this class
    external_lib is an external component we cannot test
  """
  def __init__(self, external_lib):
    self.lib = external_lib

  def create_index(self, unique_index):
    """
      Create an index.
    """
    try:
      self.lib.create(index=unique_index) # mock this
      return True
    except MyException as e:
      self.logger.error(e.__dict__, color="red")
      return False

class MockLib():
   pass

class TestSome(unittest.TestCase):
  def setUp(self):
    self.lib = MockLib()
    self.some = Some(self.lib)

  def test_create_index(self):
    # This will test the method returns True if everything went fine

    self.some.create_index = MagicMock(return_value={})
    self.assertTrue(self.some.create_index("test-index"))

  def test_create_index_fail(self):
    # This will test the exception is handled and return False

    self.some.create_index = MagicMock(side_effect=MyException("error create"))
    self.assertFalse(self.some.create_index("test-index"))

TestSome()类文件放在your-codebase-path/tests这样的位置并运行:

python -m unittest -v

我希望它有用

相关问题 更多 >

    热门问题