Reputation: 41
I have a test case where I'd like to be able to run a python file with arguments.
I have 2 files. 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()
expected result is {'msg':'ok'} however the variable output returns nothing.
Upvotes: 1
Views: 948
Reputation: 5324
There is one thing you are forgetting is process output will return as string, but you are comparing with dict, so little change in 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)
output:
Ran 1 test in 0.025s
OK
=============> {'msg': 'ok'}
Upvotes: 2
Reputation: 3346
you don't need to call that function using os.popen() you can directly import that function in your test_cases.py and call it(highly recommended ) see below example:
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()
Upvotes: 2