|
| 1 | +"""Unit tests for the pysnow module.""" |
| 2 | + |
| 3 | +import warnings |
| 4 | +from unittest.mock import MagicMock, mock_open, patch |
| 5 | + |
| 6 | +from nautobot.core.testing import TestCase |
| 7 | + |
| 8 | +from nautobot_ssot.integrations.servicenow.third_party.pysnow.attachment import Attachment |
| 9 | + |
| 10 | + |
| 11 | +class TestAttachmentUploadContentType(TestCase): |
| 12 | + """Test that the upload method sets Content-Type based on HAS_MAGIC.""" |
| 13 | + |
| 14 | + def setUp(self): |
| 15 | + """Set up a minimal Attachment instance with a mocked resource.""" |
| 16 | + self.resource = MagicMock() |
| 17 | + self.attachment = Attachment(resource=self.resource, table_name="incident") |
| 18 | + |
| 19 | + @patch("nautobot_ssot.integrations.servicenow.third_party.pysnow.attachment.HAS_MAGIC", True) |
| 20 | + @patch("nautobot_ssot.integrations.servicenow.third_party.pysnow.attachment.magic", create=True) |
| 21 | + @patch("builtins.open", mock_open(read_data=b"file content")) |
| 22 | + def test_upload_uses_magic_when_available(self, mock_magic): |
| 23 | + """When python-magic is available, Content-Type should be determined by magic.""" |
| 24 | + file_path = "/tmp/test.pdf" |
| 25 | + mock_magic.from_file.return_value = "application/pdf" |
| 26 | + |
| 27 | + self.attachment.upload(sys_id="abc123", file_path=file_path) |
| 28 | + |
| 29 | + mock_magic.from_file.assert_called_once_with(file_path, mime=True) |
| 30 | + call_kwargs = self.resource.request.call_args[1] |
| 31 | + self.assertEqual(call_kwargs["headers"]["Content-Type"], "application/pdf") |
| 32 | + |
| 33 | + @patch("nautobot_ssot.integrations.servicenow.third_party.pysnow.attachment.HAS_MAGIC", False) |
| 34 | + @patch("builtins.open", mock_open(read_data=b"file content")) |
| 35 | + def test_upload_falls_back_to_text_plain_without_magic(self): |
| 36 | + """When python-magic is missing, Content-Type should fall back to text/plain with a warning.""" |
| 37 | + with warnings.catch_warnings(record=True) as caught_warnings: |
| 38 | + warnings.simplefilter("always") |
| 39 | + self.attachment.upload(sys_id="abc123", file_path="/tmp/test.txt") |
| 40 | + |
| 41 | + self.assertEqual(len(caught_warnings), 1) |
| 42 | + self.assertIn("python-magic", str(caught_warnings[0].message)) |
| 43 | + |
| 44 | + call_kwargs = self.resource.request.call_args[1] |
| 45 | + self.assertEqual(call_kwargs["headers"]["Content-Type"], "text/plain") |
0 commit comments