1

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.

2
  • try changing return {'msg':'ok'} to print({'msg':'ok'}) Commented Feb 12, 2019 at 6:00
  • @itzMEonTV that still won't work- it'll get the string rep of {'msg':'ok'} and compare that to expected_output's dictionary: {'msg':'ok'}. Commented Feb 12, 2019 at 6:05

2 Answers 2

2

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() 
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.