模拟父类__init__方法

时间:2015-09-02 09:47:04

标签: python python-2.7 unit-testing mocking

我正在尝试在一个派生自另一个类的类上编写一些单元测试,但是我在模拟父类 init 方法时遇到了一些困难,但是你不能这样做,所以我正在寻找建议

这是我的课程

的示例

Imported.py

class Imported():
    def __init__(self, a="I am Imported"):
        print("a:{}".format(a))

Parent.py

from Imported import Imported

class Parent(object):

    parent_list = ["PARENT"]

    def __init__(self, a="I am Parent"):
        imported = Imported(a)

Derived.py

from Parent import Parent

class Derived(Parent):

    Parent.parent_list.append("DERIVED")

在我的单元测试中,当我从Derived类Derived()实例化一个对象时,我想验证Parent.parent_list == [“PARENT”,“DERIVED”]。

这两个解决方案都不起作用

test_Derived.py

import unittest
from mock import patch

from Derived import Derived


class test_Derived(unittest.TestCase):

    @patch("Derived.Parent.__init__")
    def test_init_001(self, mock_parent_init):
        a = Derived("I am Derived")
        mock_parent_init.assert_called_with("I am Derived")
        self.assertEquals(a.parent_list, ["PARENT", "DERIVED"])

    @patch("Derived.Imported.Imported")
    def test_init_002(self, mock_parent_init):
        a = Derived("I am Derived")
        mock_parent_init.assert_called_with("I am Derived")
        self.assertEquals(a.parent_list, ["PARENT", "DERIVED"])

test_init_001以

失败
TypeError: __init__() should return None, not 'MagicMock'

test_init_002失败,

ImportError: No module named Parent.Imported

有什么建议吗?

1 个答案:

答案 0 :(得分:20)

对于第一个解决方案,请将None方法的返回值更改为@patch("Derived.Parent.__init__") def test_init_001(self, mock_parent_init): mock_parent_init.return_value = None # <--- a = Derived("I am Derived") mock_parent_init.assert_called_with("I am Derived") self.assertEquals(a.parent_list, ["PARENT", "DERIVED"])

Parent.Imported

对于第二个解决方案,修补程序@patch("Parent.Imported") # <--- def test_init_002(self, mock_parent_init): a = Derived("I am Derived") mock_parent_init.assert_called_with("I am Derived") self.assertEquals(a.parent_list, ["PARENT", "DERIVED"])

import re
str= "ERTYHGFYUUHGFREDFYAAAAAAAAAA"
endings = ['AAAAA', 'AAAAAA', 'AAAAAAA', 'AAAAAAAA', 'AAAAAAAAA']

print max([i for i in endings if re.findall(i+r"$",str)],key=len)