【问题标题】:pytest can't see logs from function being testedpytest 看不到正在测试的函数的日志
【发布时间】:2019-05-21 13:25:35
【问题描述】:

我有一个这样的烧瓶应用程序

from flask import Flask
import logging

app = Flask(__name__)

@app.route('/')
def catch_all():
    logging.warning("I'm a warning")
    return "This is a REST API"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, debug=True)

当我运行它时,我在日志中看到了警告

WARNING:root:I'm a warning

然后我创建一个测试,像这样

import fulfillment

def test_index():
    fulfillment.app.testing = True
    client = fulfillment.app.test_client()

    r = client.get('/')
    assert r.status_code == 200
    assert 'This is a REST API' in r.data.decode('utf-8')

当我使用pytest 运行测试时,我看不到来自被测函数的日志消息。我找到了How can I see normal print output created during pytest run?,听起来很相似,但是pytest -s 选项不起作用,我认为它实际上是在谈论测试函数的输出,而不是被测函数。

如何查看被测函数的日志?

【问题讨论】:

    标签: python logging flask pytest


    【解决方案1】:

    This 可能是原因。只需使用设置创建pytest.ini

    [pytest]
    log_cli=true
    log_level=NOTSET
    

    工作正常:

    pytest test_my.py
    # ...
    -------------------------------- live log call ---------------------------------
    fulfillment.py                  37 WARNING  I'm a warning
    PASSED                                                                   [100%]
    
    =========================== 1 passed in 0.09 seconds ===========================
    

    还可以设置log_formatlog_date_format等选项。

    希望这会有所帮助。

    【讨论】:

    • 不再将日志可见性作为一项功能似乎很奇怪......但我很高兴有一种方法可以从我的测试函数中查看日志
    猜你喜欢
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 2017-10-10
    相关资源
    最近更新 更多