断言可以与打印语句进行比较吗?

Can assertions compare against print statments?

断言能否与 python 中的打印语句进行比较,如下所示:

def printname(name):
    print(name)

#to not raise an error:
assert printname("Hello") == "Hello"

#to raise an error:
assert printname("Hello") == "notHello"

不,断言不能那样做。如果你想这样做,试试这个:

def printname(name):
    print(name)
    return name

#to not raise an error:
assert printname("Hello") == "Hello"

#to raise an error:
assert printname("Hello") == "notHello"

这在技术上并不能与之进行比较,但它是一个有效的解决方法。如果你真的想比较它们,请查看 StringIO.

尝试使用 mock + stringIO 来捕获 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'

此外,如果您是在测试框架内执行此操作,则您可以执行多种操作。特别是对于 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"

没有。函数 printname 没有明确的 return 语句,所以它 return 的值。所以断言将 None 与字符串进行比较,当然它会引发断言错误。