| 1 |
import logging |
| 2 |
from pytest import fixture |
| 3 |
from unittest.mock import patch |
| 4 |
from kiwi.utils.output import DataOutput |
| 5 |
import json |
| 6 |
import unittest.mock as mock |
| 7 |
|
| 8 |
|
| 9 |
class TestDataOutput: |
| 10 |
@fixture(autouse=True) |
| 11 |
def inject_fixtures(self, caplog): |
| 12 |
self._caplog = caplog |
| 13 |
|
| 14 |
def setup(self): |
| 15 |
test_data = { |
| 16 |
'some-name': 'some-data' |
| 17 |
} |
| 18 |
self.expected_out = json.dumps( |
| 19 |
test_data, sort_keys=True, indent=4, separators=(',', ': ') |
| 20 |
) |
| 21 |
self.out = DataOutput(test_data) |
| 22 |
|
| 23 |
def setup_method(self, cls): |
| 24 |
self.setup() |
| 25 |
|
| 26 |
@patch('sys.stdout') |
| 27 |
def test_display(self, mock_stdout): |
| 28 |
self.out.display() |
| 29 |
mock_stdout.write.assert_any_call(self.expected_out) |
| 30 |
|
| 31 |
def test_display_file(self): |
| 32 |
with self._caplog.at_level(logging.INFO): |
| 33 |
with patch('builtins.open', create=True) as mock_open: |
| 34 |
file_handle = mock_open.return_value.__enter__.return_value |
| 35 |
DataOutput.display_file('some-file', 'some-message') |
| 36 |
mock_open.assert_called_once_with('some-file') |
| 37 |
file_handle.read.assert_called_once_with() |
| 38 |
|
| 39 |
@patch('sys.stdout') |
| 40 |
@patch('os.system') |
| 41 |
@patch('kiwi.utils.output.Temporary.new_file') |
| 42 |
def test_display_color(self, mock_temp, mock_system, mock_stdout): |
| 43 |
out_file = mock.Mock() |
| 44 |
out_file.name = 'tmpfile' |
| 45 |
mock_temp.return_value = out_file |
| 46 |
self.out.style = 'color' |
| 47 |
self.out.color_json = True |
| 48 |
self.out.display() |
| 49 |
mock_system.assert_called_once_with( |
| 50 |
'cat tmpfile | pjson' |
| 51 |
) |
| 52 |
|
| 53 |
@patch('sys.stdout') |
| 54 |
def test_display_color_no_pjson(self, mock_stdout): |
| 55 |
self.out.style = 'color' |
| 56 |
self.out.color_json = False |
| 57 |
with self._caplog.at_level(logging.WARNING): |
| 58 |
self.out.display() |
| 59 |
assert 'pjson for color output not installed' in self._caplog.text |
| 60 |
assert 'run: pip install pjson' in self._caplog.text |