I am trying to write some unittests on a class which is derived from another, but I have some difficulties to mock the parent class init method, which afaik you cannot, so I am looking for suggestion.
Here an example of how are my classes
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")
In my unittests I want to verify that Parent.parent_list == ["PARENT", "DERIVED"] when I instantiate an object from the Derived class, Derived().
Both of this solution doesn't work
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 fails with
TypeError: __init__() should return None, not 'MagicMock'
test_init_002 fails with
ImportError: No module named Parent.Imported
Any suggestion?
Aucun commentaire:
Enregistrer un commentaire