代码之家  ›  专栏  ›  技术社区  ›  Daniel Watrous

pytest无法查看正在测试的函数的日志

  •  1
  • Daniel Watrous  · 技术社区  · 7 年前

    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 选项不起作用,我认为它实际上是指测试函数的输出,而不是被测试函数的输出。

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

    1 回复  |  直到 7 年前
        1
  •  9
  •   Danila Ganchar    7 年前

    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_format , log_date_format 以及其他选择。

    希望这有帮助。