我有一个简单的模块:
# my_module
from os.path import join
from os import environ
some_file_name = 'foo.txt'
def file_path():
join(environ['TARGET_DIRECTORY'], some_file_name)
一个简单的测试:
import os
import unittest
from os.path import join
from mock import patch
from my_module import some_file_name, file_path
class MyTest(unittest.TestCase):
def test_can_create_path(self):
some_folder = '/path/to/directory'
with patch.dict('my_module.environ', {'TARGET_DIRECTORY': some_folder}):
self.assertEqual(file_path(), join(some_folder, some_file_name))
if __name__ == '__main__':
unittest.main()
我预计对environ['TARGET_DIRECTORY']
的调用会返回'/path/to/directory'
,但会返回None
答案 0 :(得分:3)
您的函数会返回None
,因为没有明确的return
语句。添加return
:
def file_path():
return join(environ['TARGET_DIRECTORY'], some_file_name)
模拟补丁工作正常。