如何从导入的包中获取 python 单元测试覆盖变量

how to get python unit test overwrite variable from imported package

试图找出如何在单元测试期间覆盖变量:

#mainscript.py
import json

org_file = 'unitfile.json'

def load_json (file_name):
    with open ('{0}'.format(org_file)) as f:
       json_object =  json.load(f)
    return json_object

new_file = load_json(org_file)

def print_me():
    return (new_file['text'])

def main():
    print_me()

if __name__ == '__main__':
    main()

单元测试:

#test_mainscript.py
import json
import mainscript
import unittest
from  unittest.mock import patch

class Testmainscript(unittest.TestCase):
    # def setUp(self):
        # Not needed when using mock
    @patch('mainscript.org_file','unitfile2.json')
    def test_print_me(self):
        self.assertEqual(mainscript.org_file, 'unitfile2.json') # Correctly overwrites file
        self.assertEqual(mainscript.print_me(),'Bye World') #does not pass, still reading unitfile.json instead of unitfile2.json
if __name__ == '__main__':
    unittest.main()

这个测试应该会失败,因为我用 unitestfile2.json(包含 {'text':'Bye World'})而不是 unittestfile.json(包含 {'text':'Hello World'})覆盖 org_file )

但它目前通过了,因为变量没有被覆盖

您要查找的内容名为“mocking”,您的案例示例:

import json
import mainscript
import unittest
from unittest.mock import patch

class Testmainscript(unittest.TestCase):
    # def setUp(self):
        # Not needed when using mock
 
    @patch('mainscript.org_file', 'unitfile2.json')
    def test_print_me(self):
        self.assertEqual(mainscript.print_me(),'Hello World')

if __name__ == '__main__':
    unittest.main()

我发现问题是我按预期覆盖了文件,但是当我调用测试时我没有使用模拟文件。包装函数似乎有效:

#mainscript.py
import json


org_file = 'unitfile.json'
def load_json (json_file):
    with open ('{0}'.format(org_file)) as f:
       json_object =  json.load(f)
    return json_object


def print_me(df_file):
    return (df_file['text'])

def main():
    print_me()

if __name__ == '__main__':
    main()

这里我使用了包装好的补丁作为输入

#test_mainscript.py
import json
import mainscript
import unittest
from  unittest.mock import patch

class Testmainscript(unittest.TestCase):
    @patch('mainscript.org_file','unitfile2.json')
    def test_print_me(self):
        self.assertEqual(mainscript.org_file, 'unitfile2.json')
        self.assertEqual(mainscript.print_me(mainscript.load_json(mainscript.org_file)),'Bye World')

if __name__ == '__main__':
    unittest.main()

测试现在有效:

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK