python 使用外部库方法调用的修补程序方法

nlejzf6q  于 2023-05-21  发布在  Python
关注(0)|答案(1)|浏览(128)

foo类将外部库链接到一个属性,这样我就可以使用self.external_class. externalClassMethod。但是为了进行测试,我需要修补这个方法调用,以便可以继续测试该方法的其余部分。我已经尝试了@patch decorator中的所有功能,但没有任何效果:(

import os
from unittest import TestCase
from unittest.mock import patch

class Foo(object):
    def __init__(self):
        self.os_handle = os
        self.string = None
    def path(self):
        try:
            print(self.os_handle.getNothing())
        except Exception:
            raise Exception
        self.string = "circumvented the faulty os_handle method call"
    
class TestFoo(TestCase):
    def testClass(self):
        self.assertEqual(1,1)
    def testLibraryCall(self):
        with self.assertRaises(Exception) as cm:
            foo = Foo()
            foo.path()
        self.assertEqual(cm.exception.__class__, Exception)
    # @patch('os', 'getNothing', ...)  # WHAT DO I PATCH?????
    def testLibraryCallNoException(self):
        foo = Foo()
        foo.path()
        self.assertEqual(foo.string, "circumvented the faulty os_handle method call")

将上述代码保存在my_class.py中,并使用$ python -m unittest my_class运行上述代码

dxpyg8gm

dxpyg8gm1#

尝试以下修改:

import os
from unittest import TestCase
from unittest.mock import patch

class Foo(object):
    def __init__(self):
        self.os_handle = os
        self.string = None
    def path(self):
        try:
            print(self.os_handle.getNothing())
        except Exception:
            raise Exception
        self.string = "circumvented the faulty os_handle method call"
    
class TestFoo(TestCase):
    def testClass(self):
        self.assertEqual(1,1)
    def testLibraryCall(self):
        with self.assertRaises(Exception) as cm:
            foo = Foo()
            foo.path()
        self.assertEqual(cm.exception.__class__, Exception)
    
    def testLibraryCallNoException(self):
        foo = Foo()
        with patch.object(foo, "os_handle") as mock_os_handle: 
            foo.path()
            self.assertEqual(foo.string, "circumvented the faulty os_handle method call")

我只修改了testLibraryCallNoException()方法:

  • 使用patch.object()代替patch():以这种方式,属性self.os_handle被模拟对象mock_os_handle替代。这种替换的效果是,在您的生产代码中,指令self.os_handle.getNothing()不会按照您的要求执行任何操作(我在解释中省略了一些细节!)
  • 我将self.添加到assertEqual(foo.string, "circumvented the faulty os_handle method call")中,以解决测试代码中的另一个错误。

相关问题