Will using subprocess.run() in a pytest function cause any testing problems?

Viewed 207

I have the following Python module I want to test:

import sys

def greet():
    print(f"Hello, {sys.argv[1]}!") 

I have set it up as a script entry point, such that this works:

$ greet World
Hello, World!

Now, I want to test with pytest.

It works to make a tests/test_greet.py file with the following:

import subprocess

import greet

def test_greet_cli():
    result = subprocess.run(["greet", "World"], capture_output=True)
    assert b"Hello, World!" in result.stdout

Will this cause any problems?

Are there alternative ways of testing this that I should consider?

Feel free to browse my article in which I document something similar to the above. I suggest two ways of writing the test in that article, one of which is this way. I don't want to include it if it could cause any problems.

1 Answers

Your fundamental problem is that this function

def greet():
    print(f"Hello, {sys.argv[1]}!") 

is "bad" when it comes to testability, since it relies on global variables. A much better version would be something like:

def greet(args=None):
    if args is None:
        args = sys.argv
    print(f"Hello, {args[1]}!") 

This would have the same functionality, but would be much easier to test.

Related