Debian Codegraph @

ansible_collections/community/general/tests/unit/plugins/module_utils/test__ocapi_utils.py

raw
1 # Copyright (c) Ansible project
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 from __future__ import annotations
6
7 import os
8 import re
9 import shutil
10 import tempfile
11 import unittest
12
13 from ansible_collections.community.general.plugins.module_utils._ocapi_utils import OcapiUtils
14
15
16 class TestOcapiUtils(unittest.TestCase):
17 def setUp(self):
18 self.tempdir = tempfile.mkdtemp()
19 self.utils = OcapiUtils(
20 creds={"user": "a_user", "pswd": "a_password"},
21 base_uri="fakeUri",
22 proxy_slot_number=None,
23 timeout=30,
24 module=None,
25 )
26
27 def tearDown(self):
28 shutil.rmtree(self.tempdir)
29
30 def test_prepare_multipart_firmware_upload(self):
31 # Generate a binary file and save it
32 filename = "fake_firmware.bin"
33 filepath = os.path.join(self.tempdir, filename)
34 file_contents = b"\x00\x01\x02\x03\x04"
35 with open(filepath, "wb+") as f:
36 f.write(file_contents)
37
38 # Call prepare_mutipart_firmware_upload
39 content_type, b_form_data = self.utils.prepare_multipart_firmware_upload(filepath)
40
41 # Check the returned content-type
42 content_type_pattern = r"multipart/form-data; boundary=(.*)"
43 m = re.match(content_type_pattern, content_type)
44 self.assertIsNotNone(m)
45
46 # Check the returned binary data
47 boundary = m.group(1)
48 expected_content_text = f"--{boundary}\r\n"
49 expected_content_text += f'Content-Disposition: form-data; name="FirmwareFile"; filename="{filename}"\r\n'
50 expected_content_text += "Content-Type: application/octet-stream\r\n\r\n"
51 expected_content_bytes = bytearray(expected_content_text, "utf-8")
52 expected_content_bytes += file_contents
53 expected_content_bytes += bytearray(f"\r\n--{boundary}--", "utf-8")
54 self.assertEqual(expected_content_bytes, b_form_data)