1

I have a file named

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

I am working on creating a unittest for another file which takes value of this file variable from a.py

How can I mock this variable name to any dummy file for example?

file = "/tmp/a.txt"
sam
  • 18,509
  • 24
  • 83
  • 116

3 Answers3

0

Use mock.patch:

import mock

@mock.patch('a.file', '/tmp/a.txt')
def test_a():
  assert thing_that_uses_a_file == '/tmp/a.txt'

tbm
  • 1,142
  • 12
  • 22
0

@tbm 's answer is work for me, on python 2.7

config.py

SERVICE_REQUIRED = [
  ("lrc:/etc/rc2_d/S47pppd", "legacy_run"),
  ("lrc:/etc/rc2_d/S89PRESERVE", "legacy_run"),
  ("lrc:/etc/rc2_d/S99sysinfo", "legacy_run"),
  ("lrc:/etc/rc2_d/S99tcpwindow", "legacy_run"),
  ("lrc:/etc/rc3_d/S99cpupool", "legacy_run"),
  ("lrc:/etc/rc3_d/S99logparse", "legacy_run"),
  ("lrc:/etc/rc3_d/S99nicmon", "legacy_run"),
  ("lrc:/etc/rc3_d/S99nwmond", "legacy_run")
]

file_a.py

from config import SERVICE_REQUIRED

def demo_func():
    for name, state in SERVICE_REQUIRED:
        print name, state
        ...

test_file_a.py

...
class TestFileA(unittest.TestCase):

    @mock.patch('file_a.SERVICE_REQUIRED', [
                ('svc:/system/console-login:vt2', 'online'),
                ('svc:/system/system-log:rsyslog', 'online'),
                ('svc:/network/socket-config:default', 'disabled'),
                ('dump', 'legacy_run'),
                ('firewall', 'disabled'),
                ("/'; echo hello;'", 'online')
            ])
    def test_demo_func(self):
        print SERVICE_REQUIRED

Shi-Xiaopeng
  • 1
  • 1
  • 2
-1

In your specific case, why not just import a and then a.file = "/tmp/a.txt" ?

Which version of Python are you on? Python 3.x has unittest.mock which is backported to 2.x on pypi.

Anyway, if you are trying to create a context specific mock:

>>> 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

Are you trying to mock it at import time? Based on another SO answer:

>>> import sys
>>> sys.modules['A'] = Mock(file='abc')
>>> import A
>>>
>>> A.file
'abc'
>>> mocked_a = A
>>> mocked_a.file
'abc'
>>>
Community
  • 1
  • 1
aneroid
  • 12,983
  • 3
  • 36
  • 66
  • I am using python 2.6.6 – sam Jun 24 '16 at 09:10
  • The first mock solution here merely asserts that a mock object can be tested, it does nothing to aid in testing the code which uses the file variable. Presumably the OP wants to mock the file variable to assert conditions about its use, not that it can be simply changed. – tbm May 17 '19 at 16:08