LoginSignup
9
13

More than 5 years have passed since last update.

pythonでログ出力を単体テストする

Posted at

こんにちはsekitakaです。

普段何気なくログを出力していますが、ログが確かに出力されていることをテストしたいことがたまにあります。
この記事では「ログが出力されている」ことをテストする方法を紹介します。

テスト方法

testfixtures

ログが出力されていることをテストするにはtestfixturesというパッケージを利用します。

pip install testfixtures

使用例

次の例ではput_logという関数がINFOレベルでfooというログを出力することをテストしています。

# coding=utf-8
from testfixtures import LogCapture
import logging
from unittest import TestCase
import unittest

logger = logging.getLogger()
def put_log(message):
    logger.info(message)

class Test(TestCase):
    def test_put_log(self):
        with LogCapture() as l:
            put_log("foo")
            l.check(
                ("root","INFO","foo")
            )

if __name__ == '__main__':
    unittest.main

応用

LogCapture()の引数によってloggerの名前や、キャプチャするログレベルのフィルタリングなどができます。
また log_str = str(l) とすることで、以下のような形式のログの全文を文字列として取得できるので、正規表現マッチングなどのアサーションによってテストするのも良いかもしれません。

root INFO
  foo

しかしどこまでテストするのかいつも悩ましい

9
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
13