|
| 1 | +# coding: utf-8 |
| 2 | + |
| 3 | +from __future__ import absolute_import, unicode_literals |
| 4 | + |
| 5 | +import io |
| 6 | +import logging |
| 7 | + |
| 8 | +from mock import mock_open, patch, Mock |
| 9 | +import pytest |
| 10 | +from six import string_types |
| 11 | + |
| 12 | +import boxsdk.util.log |
| 13 | + |
| 14 | + |
| 15 | +_MOCK_FILEPATH = '/home/user/boxsdk.log' |
| 16 | +_MOCK_LOG_NAME = 'boxsdk' |
| 17 | + |
| 18 | + |
| 19 | +@pytest.fixture(params=[io.StringIO(), _MOCK_FILEPATH]) |
| 20 | +def stream_or_file(request): |
| 21 | + return request.param |
| 22 | + |
| 23 | + |
| 24 | +@pytest.fixture(params=[False, True]) |
| 25 | +def debug(request): |
| 26 | + return request.param |
| 27 | + |
| 28 | + |
| 29 | +@pytest.fixture |
| 30 | +def expected_log_level(debug): |
| 31 | + return logging.DEBUG if debug else logging.INFO |
| 32 | + |
| 33 | + |
| 34 | +@pytest.fixture(params=[_MOCK_LOG_NAME, None]) |
| 35 | +def name(request): |
| 36 | + return request.param |
| 37 | + |
| 38 | + |
| 39 | +@pytest.fixture |
| 40 | +def mock_logger(): |
| 41 | + return Mock(logging.Logger) |
| 42 | + |
| 43 | + |
| 44 | +def test_setup_logging(stream_or_file, debug, expected_log_level, name, mock_logger): |
| 45 | + mock_file_open = mock_open() |
| 46 | + |
| 47 | + with patch('logging.getLogger') as get_logger: |
| 48 | + with patch('logging.open', mock_file_open, create=True): |
| 49 | + get_logger.return_value = mock_logger |
| 50 | + assert boxsdk.util.log.setup_logging(stream_or_file, debug=debug, name=name) == mock_logger |
| 51 | + get_logger.assert_called_once_with(name) |
| 52 | + |
| 53 | + assert mock_logger.addHandler.call_count == 1 |
| 54 | + assert isinstance(mock_logger.addHandler.call_args[0][0], logging.Handler) |
| 55 | + mock_logger.setLevel.assert_called_once_with(expected_log_level) |
| 56 | + |
| 57 | + if isinstance(stream_or_file, string_types): |
| 58 | + assert mock_file_open.call_count == 1 |
| 59 | + assert mock_file_open.call_args[0][:2] == (stream_or_file, 'w') # Python 3 passes additional args. |
0 commit comments