La patch finta non funziona con la classe in __init__.py
-
07-11-2019 - |
Domanda
Sto cercando di usare la patch per restituire un simulazione all'interno di un metodo. La struttura di base è la seguente:
MyCode.py
class MyClass:
def __init__(self, first_name, last_name):
self.first = first_name
self.last = last_name
def get_greeting(self):
return 'Hello {f} {l}'.format(f=self.first, l=self.last)
def get_new_greeting(first_name, last_name):
obj = MyClass(first_name, last_name)
return obj.get_greeting()
my_code_test.py
import unittest
from mock import Mock, patch
import my_code
class TestMyCode(unittest.TestCase):
def setUp(self):
pass
@patch('my_code.MyClass')
def test_get_greeting(self, MockClass):
instance = MockClass.return_value
mock_greeting = 'Hello Me'
instance.get_greeting.return_value = mock_greeting
greeting = my_code.get_new_greeting('john', 'doe')
self.assertEqual(greeting, mock_greeting)
if __name__ == '__main__':
unittest.main()
Il codice sopra funziona bene per me. Tuttavia, quando applico lo stesso modello al codice reale che sto cercando di testare, l'oggetto reale (non quello simulato) viene restituito nel metodo da testare. Non riesco a vedere differenze. L'unico pensiero che è un po 'diverso è che la vera classe è definita in a dentro.py file. Non sono sicuro che questo faccia la differenza o no? Ci ha già visto prima?
NOTA: la Lib effettiva è Twilio 3.3.5 e sto usando Python 2.6.5 e Django 1.3.1 e simulazione 0.7.2
Nessuna soluzione corretta
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow