Can assertions compare against print statements in python like this:
def printname(name):
print(name)
#to not raise an error:
assert printname("Hello") == "Hello"
#to raise an error:
assert printname("Hello") == "notHello"
Can assertions compare against print statements in python like this:
def printname(name):
print(name)
#to not raise an error:
assert printname("Hello") == "Hello"
#to raise an error:
assert printname("Hello") == "notHello"
No, assertions can't do that. If you want to do that try this:
def printname(name):
print(name)
return name
#to not raise an error:
assert printname("Hello") == "Hello"
#to raise an error:
assert printname("Hello") == "notHello"
This technically doesn't compare it, but its a valid workaround. If you really want to compare them take a look into StringIO
.
Try using mock + stringIO to capture stdout/err:
from mock import patch
from StringIO import StringIO
def test_foobar():
out, err = StringIO(), StringIO()
with patch.multiple(sys, stdout=out, stderr=err):
do_stuff()
assert out.getvalue() == 'foo'
assert err.getvalue() == 'bar'
Also if you are doing this within a test framework, you may be able to do a variety of things. In particular for pytest:
def test_myoutput(capsys): # or use "capfd" for fd-level
print("hello")
sys.stderr.write("world\n")
captured = capsys.readouterr()
assert captured.out == "hello\n"
assert captured.err == "world\n"
print("next")
captured = capsys.readouterr()
assert captured.out == "next\n"
No. The function printname doesn't have an explicit return statement, so it return the value . So the assert compares None against a string and of course it raise an assertion error.