pytest执行case时不显示引用文件内的log, 排查了好半天总算是找到方案了, 记录一下

问题

pytest测试case中引用了的一些test class之外的类, 其中的log并不会显示到pytest的执行log中,即使是使用的logger.

查了很久到底是为什么, 现在粗略的理解是 pytest自身会捕获所有log, 但是不管设置的log_level如何,都只会捕获本身case里写的日志. pytest-How to manage logging

解决

后来搜到了stackoverflow上的相关提问,算是有了解答 stackoverflow-how to see normal print output created during pytest run

总结就是, 在pytest.ini中加addopts = -rA等可解决.
直接-s或者--capture=no也可以,但是不优雅(pytest不劫持log输出了,各种print都会输出,不好).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
-rP(显示passed的case的log,不附带时间戳)
-rp(显示passed的case的log,附带时间戳)
-rA(显示所有的日志)


pytest --help中提示文案
  -r chars              Show extra test summary info as specified by chars: (f)ailed, (E)rror,
                        (s)kipped, (x)failed, (X)passed, (p)assed, (P)assed with output, (a)ll
                        except passed (p/P), or (A)ll. (w)arnings are enabled by default (see
                        --disable-warnings), 'N' can be used to reset the list. (default: 'fE').

个人方案是直接在pytest.ini上加addopts = -rA

1
2
3
4
5
6
7
8
# pytest.init内容

log_cli = 1
log_cli_level = DEBUG
log_file = test.log
log_file_level = DEBUG
...
add_opts = -rA

参考

https://docs.pytest.org/en/stable/reference/customize.html https://docs.pytest.org/en/stable/how-to/logging.html https://stackoverflow.com/questions/14405063/how-to-see-normal-print-output-created-during-pytest-run/59156707#59156707