官术网_书友最值得收藏!

Output capturing: -s and --capture

Sometimes, developers leave print statements laying around by mistake, or even on purpose, to be used later for debugging. Some applications also may write to stdout  or stderr as part of their normal operation or logging.

All that output would make understanding the test suite display much harder. For this reason, by default, pytest captures all output written to stdout and stderr automatically. 

Consider this function to compute a hash of some text given to it that has some debugging code left on it:

import hashlib

def commit_hash(contents):
size = len(contents)
print('content size', size)
hash_contents = str(size) + '\0' + contents
result = hashlib.sha1(hash_contents.encode('UTF-8')).hexdigest()
print(result)
return result[:8]

We have a very simple test for it:

def test_commit_hash():
contents = 'some text contents for commit'
assert commit_hash(contents) == '0cf85793'

When executing this test, by default, you won't see the output of the print calls:

λ pytest tests\test_digest.py
======================== test session starts ========================
...

tests\test_digest.py . [100%]

===================== 1 passed in 0.03 seconds ======================

That's nice and clean.

But those print statements are there to help you understand and debug the code, which is why pytest will show the captured output if the test fails.

Let's change the contents of the hashed text but not the hash itself. Now, pytest will show the captured output in a separate section after the error traceback:

λ pytest tests\test_digest.py
======================== test session starts ========================
...

tests\test_digest.py F [100%]

============================= FAILURES ==============================
_________________________ test_commit_hash __________________________

def test_commit_hash():
contents = 'a new text emerges!'
> assert commit_hash(contents) == '0cf85793'
E AssertionError: assert '383aa486' == '0cf85793'
E - 383aa486
E + 0cf85793

tests\test_digest.py:15: AssertionError
----------------------- Captured stdout call ------------------------
content size 19
383aa48666ab84296a573d1f798fff3b0b176ae8
===================== 1 failed in 0.05 seconds ======================

Showing the captured output on failing tests is very handy when running tests locally, and even more so when running tests on CI.

主站蜘蛛池模板: 河池市| 周宁县| 谢通门县| 霸州市| 永康市| 湘阴县| 拉孜县| 汉阴县| 大姚县| 多伦县| 乾安县| 昭平县| 金华市| 红河县| 樟树市| 观塘区| 夏邑县| 长治市| 玉溪市| 德化县| 岳普湖县| 肇庆市| 固安县| 黎川县| 周至县| 卓资县| 青阳县| 邛崃市| 邯郸市| 万盛区| 中西区| 锡林郭勒盟| 时尚| 安达市| 监利县| 会理县| 库车县| 长垣县| 泾阳县| 万全县| 永丰县|