Próbuję napisać niektóre unittests na klasie, która pochodzi z innego, ale mam pewne trudności, aby kpić z klasy klasy init metoda, której nie można, więc szukam sugestii .Makieta klasa nadrzędna __init__ metoda
Oto przykład, jak to moje zajęcia
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")
W moich unittests I chcę to sprawdzić Parent.parent_list == ["PARENT", "POCHODZONY"] podczas tworzenia obiektu z klasy pochodnej, pochodnej().
Zarówno tego rozwiązania nie działa
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 nie z
TypeError: __init__() should return None, not 'MagicMock'
test_init_002 nie z
ImportError: No module named Parent.Imported
Wszelkie ów ugryzienie?
Dlaczego dokładnie nie 'Parent .__ init__' muszą być wyśmiewany? Dlaczego po prostu nie udawaj "Importowanego"? –
Twój drugi test musi udawać "Parent.Imported". –
Wreszcie, zmodyfikowałeś 'Parent.parent_list' * w miejscu *, więc zarówno' Parent.parent_list', jak i 'Derived.parent_list' odnoszą się do tego samego obiektu. Tak więc 'Parent.parent_list' zawiera teraz" DERIVED "'. Najprawdopodobniej chcesz utworzyć kopię dla 'Derived' zamiast:' parent_list = Parent.parent_list + ["DERIVED"] '. Twoje testy mogą chcieć to sprawdzić. –