view tests/test_logging.py @ 18:56596902e9ae default tip

add some setup + tests
author Jeff Hammel <k0scist@gmail.com>
date Sun, 10 Dec 2017 17:57:03 -0800
parents
children
line wrap: on
line source

#!/usr/bin/env python

"""
unit-type tests for logging
"""

import json
import os
import tempfile
import unittest
from lemuriformes.log import ElasticLogger, read_logfile


class TestLogging(unittest.TestCase):
    """test various types of logging supported"""

    def test_log_line(self):
        """test logging a single JSON line"""

        message = "I was here"
        logfile = tempfile.mktemp()

        assert not os.path.exists(logfile)
        logger = ElasticLogger(logfile)
        logger(message)

        assert os.path.exists(logfile)
        with open(logfile) as f:
            data = f.read()
        assert json.loads(data)['message'] == message
        os.remove(logfile)

    def test_metadata(self):
        """test setting global + local data on a logger"""

        message = "I was here"
        logfile = tempfile.mktemp()

        assert not os.path.exists(logfile)
        logger = ElasticLogger(logfile, source='truth')
        logger(message, me="k0s")
        logger("Hi")
        logger(message, me="SomeoneElse")

        assert os.path.exists(logfile)
        log_data = read_logfile(logfile)
        os.remove(logfile)
        assert len(log_data) == 3
        assert all([line.get('source') == 'truth'
                    for line in log_data])
        assert log_data[0]['message'] == message
        assert log_data[-1]['message'] == message
        assert log_data[0]['me'] == 'k0s'
        assert log_data[-1]['me'] == 'SomeoneElse'



if __name__ == '__main__':
    unittest.main()