I have a program that takes 2 ints as arguments and everything works as expected in the command line. I want to be able to create a tester python file that imports this first program, calls program.main(), and pass along two ints as arguments for main. Is this possible?
Asked
Active
Viewed 176 times
0
-
2Does this answer your question? [How do you write tests for the argparse portion of a python module?](https://stackoverflow.com/questions/18160078/how-do-you-write-tests-for-the-argparse-portion-of-a-python-module) – Michael Delgado Sep 14 '22 at 22:41
-
Unfortunately no since I cannot edit the first program and argparse is called through program.main() – JackaJacka Sep 14 '22 at 22:53
-
You can assign to `sys.argv` before calling `program.main()` – Barmar Sep 14 '22 at 22:56
-
It's inelegant, but could you just set a new value for `sys.argv` ? – sj95126 Sep 14 '22 at 22:58
-
`argparse` unittest tests both methods - passing an argv argument, and tweaking the sys.argv list. – hpaulj Sep 14 '22 at 23:08
1 Answers
0
Assign to sys.argv
before calling program.main()
import sys
import program
sys.argv = ["program.py", "1", "2"]
program.main()

Barmar
- 741,623
- 53
- 500
- 612
-
I think the program name is typically the firs argument of `argv` isn't it – Alexander Sep 14 '22 at 22:58
-
`sys.argv[1:= ['1','two']` would be better. But look at `sys.argv` first just to safe. – hpaulj Sep 14 '22 at 23:06
-
@hpaulj That's wrong because we want to emulate what would happen when you run `program.py`. The current `sys.argv` contains the name of the testing script. – Barmar Sep 14 '22 at 23:07
-
-
@hpaulj Although uncommon, the application can examine `sys.argv[0]` and change its behavior depending on it. In any case, there's no reason for it to be different from what it would be if you ran executed the script normally. – Barmar Sep 15 '22 at 14:47