2013-11-28 14 views
14

Provo a testare alcuni codici che non restituiscono nulla ma salvano il risultato nel DB. Deridendo il metodo Save, desidero verificare se le cose sono stati trattati correttamente:Come chiamare self in un metodo fittizio di un oggetto in Python?

def mock_save(self): 
    assert(self.attr, 'dest_val') 
with mock.patch.object(Item, "save", create=True) as save: 
    save.side_effect = mock_save 
    func_to_call() //in func_to_call, I call item.save() 

Tuttavia, sembra che questo non è permesso. Dice che il numero di argomenti non corrispondenti.

Se faccio def mock_save(), non funzionerà.

Come posso avere un riferimento all'oggetto su cui agisce anche il metodo di simulazione? (L'ho visto in un altro thread che è applicabile a init metodo che può essere chiamato direttamente dalla classe)

risposta

14

È necessario autospec=True

def mock_save(self): 
    assert self.attr == 'dest_val' 
with mock.patch.object(Item, "save", autospec=True) as save: 
    save.side_effect = mock_save 
    func_to_call() 
0

A volte si desidera solo per verificare che un metodo è stato chiamato , ma non hai il controllo su dove viene istanziata la sua classe o sul metodo chiamato. Ecco un approccio che potrebbe far risparmiare tempo a chiunque si imbattesse in questo modello:

# first get a reference to the original unbound method we want to mock 
original_save = Item.save 
# then create a wrapper whose main purpose is to record a reference to `self` 
# when it will be passed, then delegates the actual work to the unbound method 
def side_fx(self, *a, **kw): 
    side_fx.self = self 
    return original_save(self, *a, **kw) 
# you're now ready to play 
with patch.object(Item, 'save', autospec=True, side_effect=side_fx) as mock_save: 
    data = "the data" 
    # your "system under test" 
    instance = SomeClass() 
    # the method where your mock is used 
    instance.some_method(data) 

    # you now want to check if it was indeed called with all the proper arguments 
    mock_save.assert_called_once_with(side_fx.self, data) 
Problemi correlati