-1

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"
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Shibainu
  • 3
  • 2
  • 3
    What happened when you tried it? – John Kugelman May 14 '20 at 22:52
  • 1
    Not exactly a duplicate, but highly relevant: [Function returns None without return statement](https://stackoverflow.com/questions/7053652/function-returns-none-without-return-statement). Also, what if you try `assert print('hello') == None` and see what happens? – G. Anderson May 14 '20 at 23:02
  • Are you trying to test that it actually printed what was intended? – Barmar May 14 '20 at 23:06

3 Answers3

0

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.

xilpex
  • 3,097
  • 2
  • 14
  • 45
0

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"
Cireo
  • 4,197
  • 1
  • 19
  • 24
0

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.

angeldeluz777
  • 319
  • 3
  • 4