|
| 1 | +import io |
| 2 | +import json |
| 3 | +import os |
| 4 | +import sys |
| 5 | +import tempfile |
| 6 | +import unittest |
| 7 | +from unittest.mock import patch |
| 8 | + |
| 9 | +from tools.private.toml2json import toml2json |
| 10 | + |
| 11 | +class Toml2JsonTest(unittest.TestCase): |
| 12 | + |
| 13 | + def setUp(self): |
| 14 | + self.temp_dir = tempfile.TemporaryDirectory() |
| 15 | + self.addCleanup(self.temp_dir.cleanup) |
| 16 | + |
| 17 | + def _create_temp_toml_file(self, content): |
| 18 | + fd, path = tempfile.mkstemp(suffix=".toml", dir=self.temp_dir.name) |
| 19 | + with os.fdopen(fd, "wb") as f: |
| 20 | + f.write(content) |
| 21 | + return path |
| 22 | + |
| 23 | + def test_basic_conversion(self): |
| 24 | + toml_content = b""" |
| 25 | +[owner] |
| 26 | +name = "Tom Preston-Werner" |
| 27 | +dob = 1979-05-27T07:32:00-08:00 |
| 28 | +""" |
| 29 | + expected_json = { |
| 30 | + "owner": { |
| 31 | + "name": "Tom Preston-Werner", |
| 32 | + "dob": "1979-05-27T07:32:00-08:00" |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + toml_file_path = self._create_temp_toml_file(toml_content) |
| 37 | + |
| 38 | + with patch('sys.stdout', new=io.StringIO()) as mock_stdout: |
| 39 | + with patch('sys.argv', ['toml2json.py', toml_file_path]): |
| 40 | + toml2json.main() |
| 41 | + actual_json = json.loads(mock_stdout.getvalue()) |
| 42 | + self.assertEqual(actual_json, expected_json) |
| 43 | + |
| 44 | + def test_invalid_toml(self): |
| 45 | + toml_content = b""" |
| 46 | +[owner |
| 47 | +name = "Tom Preston-Werner" |
| 48 | +""" |
| 49 | + |
| 50 | + toml_file_path = self._create_temp_toml_file(toml_content) |
| 51 | + |
| 52 | + with patch('sys.stderr', new=io.StringIO()) as mock_stderr: |
| 53 | + with patch('sys.stdout', new=io.StringIO()): # We don't expect stdout for errors |
| 54 | + with patch('sys.exit') as mock_exit: |
| 55 | + with patch('sys.argv', ['toml2json.py', toml_file_path]): |
| 56 | + toml2json.main() |
| 57 | + mock_exit.assert_called_with(1) |
| 58 | + self.assertIn("Error decoding TOML", mock_stderr.getvalue()) |
| 59 | + |
| 60 | + |
| 61 | +if __name__ == '__main__': |
| 62 | + unittest.main() |
0 commit comments