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'
>>>
Was Sie tun möchten, ist ein „fake“ 'file' Variable zu erstellen, die Sie in der Lage, Tests zu tun auf? –