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

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.

主站蜘蛛池模板: 颍上县| 建宁县| 娄底市| 富蕴县| 托克托县| 开鲁县| 高唐县| 双城市| 称多县| 东莞市| 秀山| 奉新县| 磐石市| 阳泉市| 樟树市| 仪征市| 阿克| 辉县市| 即墨市| 克拉玛依市| 吉水县| 临江市| 通道| 许昌县| 古蔺县| 雅江县| 金湖县| 大方县| 西藏| 长葛市| 富蕴县| 双江| 三亚市| 阳高县| 彭泽县| 新密市| 沂南县| 大田县| 子洲县| 隆化县| 博白县|