Reputation: 5913
I have a test that is calling a script using subprocess.check_call. I have assertions inside the script checking the validity of the arguments and I want to check the error cases. So I've done this:
try:
self.assertRaises(subprocess.CalledProcessError, subprocess.check_call, ['myscript.py', 'myBadArgument'])
except AssertionError:
pass
The test actually passes since the correct assertion gets raised, but I want to keep the assertion messages and associated stack dump from getting printed to the screen.
How do I do this? Thanks!
Upvotes: 1
Views: 784
Reputation: 5913
The problem here was that I was overusing the assert()
statement. I was using assert
to check for things such as whether the user gave me files that existed, or values that made sense in the script.
This was a misunderstanding on my part. I now see that the correct approach is to check the data and raise the appropriate exceptions in my library elements, then catch those exceptions in my user-facing scripts and provide a call-stack free message.
Once I cleaned this up my test passed with the correct exceptions and with no unneeded messages.
Upvotes: 1
Reputation: 281476
To suppress the subprocess's error messages, redirect its stderr:
from subprocess import DEVNULL
with self.assertRaises(subprocess.CalledProcessError):
subprocess.run(['myscript.py', 'myBadArgument'], stdout=DEVNULL, stderr=DEVNULL)
Also, don't catch AssertionError
. That doesn't do anything to suppress the subprocess's error messages; it only causes your test to incorrectly pass even if the subprocess doesn't raise an error.
Upvotes: 3