2016-06-24 9 views
0

Ich habe eine Datei mit dem Nameneine Variable innerhalb einer Datei spöttischen

a.py 
file = "/home/test/abc.txt" 

ich auf die Schaffung eines Unittest für eine andere Datei arbeite, die von a.py

Wert dieser Datei Variable nimmt Wie kann ich spotten dieser Variablenname zu einer Dummy-Datei zum Beispiel?

file = "/tmp/a.txt" 
+0

Was Sie tun möchten, ist ein „fake“ 'file' Variable zu erstellen, die Sie in der Lage, Tests zu tun auf? –

Antwort

0

In Ihrem speziellen Fall, warum nicht nur import a und dann a.file = "/tmp/a.txt"?

In welcher Version von Python sind Sie? Python 3.x hat unittest.mock, die backported to 2.x on pypi ist.

Wie auch immer, wenn Sie eine kontextspezifische mock versuchen, zu erstellen:

>>> from mock import Mock 
>>> 
>>> # applies to module imports but doing it as a class here 
... class A(object): 
...  file = 'xyz' 
... 
>>> some_a = Mock(file='abc') 
>>> some_a.file 
'abc' 
>>> 
>>> actual_a = A() 
>>> actual_a.file 
'xyz' 
>>> 
>>> 
>>> def some_test(): 
... A = Mock(file='abc') 
... assert A.file == 'abc' 
... assert A.file != 'xyz' 
... 
>>> some_test() 
>>> # no assertion error 

Versuchen Sie es beim Import zu verspotten? Basierend auf another SO answer:

>>> import sys 
>>> sys.modules['A'] = Mock(file='abc') 
>>> import A 
>>> 
>>> A.file 
'abc' 
>>> mocked_a = A 
>>> mocked_a.file 
'abc' 
>>> 
+0

Ich benutze Python 2.6.6 – sam