我有一个测试用例,希望能够运行带有参数的python文件。
我有2个文件。 app.py
def process_data(arg1,arg2,arg3):
return {'msg':'ok'}
if __name__ == "__main__":
arg1 = sys.argv[1]
arg2 = sys.argv[2]
arg3 = sys.argv[3]
process_data(arg1,arg2,arg3)
test_cases.py
class TestCase(unittest.TestCase):
def test_case1(self):
expected_output = {'msg':'ok'}
with os.popen("echo python app.py arg1 arg2 arg3") as o:
output = o.read()
output = output.strip()
self.assertEqual(output, expected_output)
if __name__ == "__main__":
unittest.main()
预期结果为{'msg':'ok'},但是变量输出不返回任何内容。
答案 0 :(得分:2)
您无需使用os.popen()来调用该函数,您可以将其直接导入到test_cases.py中并调用它(强烈建议使用),请参见以下示例:
from app import process_data
class TestCase(unittest.TestCase):
def test_case1(self):
expected_output = {'msg':'ok'}
output = process_data('arg1', 'arg2', 'arg3')
self.assertEqual(output, expected_output)
if __name__ == "__main__":
unittest.main()
答案 1 :(得分:0)
您忘记的一件事是进程输出将以字符串形式返回,但是您正在与dict进行比较,因此expected_output = "{'msg': 'ok'}"
中的变化很小
import os
import unittest
class TestCase(unittest.TestCase):
def test_case1(self):
expected_output = "{'msg': 'ok'}"
output = os.popen('python3 app.py arg1 arg2 arg3').read().strip()
print('=============>', output)
self.assertEqual(output, expected_output)
if __name__ == "__main__":
unittest.main()
app.py
import sys
def process_data(arg1, arg2, arg3):
print({'msg': 'ok'})
# return pass
if __name__ == "__main__":
arg1 = sys.argv[1]
arg2 = sys.argv[2]
arg3 = sys.argv[3]
process_data(arg1, arg2, arg3)
输出:
Ran 1 test in 0.025s
OK
=============> {'msg': 'ok'}