-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtest_fixture_capsys.py
52 lines (40 loc) · 1.48 KB
/
test_fixture_capsys.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def test_capsys(capsys):
"""
使用 capsys.readouterr() 捕获所有标准输出, 写入captured对象.
"""
print("hello")
captured = capsys.readouterr()
stdout, stderr = captured.out, captured.err
assert stdout == "hello\n"
assert stderr == ''
def test_capsys_rewrite(capsys):
"""
使用 capsys.readouterr() 捕获所有标准输出, 写入captured对象.
然后再使用 sys.stdout.write 在次写入到标准输出, 此时的输出就没有被捕获.
"""
import sys
print("good")
captured = capsys.readouterr()
stdout, stderr = captured.out, captured.err
sys.stdout.write(stdout)
def test_capsys_stderr(capsys):
"""
使用 capsys.readouterr() 捕获所有标准输出, 写入captured对象.
然后再使用 sys.stdout.write 在次写入到标准输出, 此时的输出就没有被捕获.
"""
import sys
print("bad", file=sys.stderr)
captured = capsys.readouterr()
stdout, stderr = captured.out, captured.err
sys.stdout.write(stderr)
"""
输出结果
============================= test session starts ==============================
collecting ... collected 3 items
test_fixture_capsys.py::test_capsys PASSED [ 33%]
test_fixture_capsys.py::test_capsys_rewrite PASSED [ 66%]
good
test_fixture_capsys.py::test_capsys_stderr PASSED [100%]
bad
============================== 3 passed in 0.04s ===============================
"""