Coverage for test\test_charset.py: 100%
19 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-09-27 18:50 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-09-27 18:50 +0000
1from Charset import to_utf8
3import Configuration
4import pytest
6"""
7Code Analysis
9Objective:
10- The objective of the function is to convert a string to UTF-8 encoding.
12Inputs:
13- s (str): The string to convert.
15Flow:
16- If not_needed1 is true, return the original string.
17- Attempt to decode the string using the locale encoding and then encode it in UTF-8.
18- If the string cannot be decoded using the locale encoding of the system, raise a UnicodeDecodeError.
19- If the string cannot be encoded using UTF-8 encoding, raise a UnicodeEncodeError.
20- If we give unicode() an already encoded string, return the original string.
22Outputs:
23- str: The converted string in UTF-8 encoding.
25Additional aspects:
26- The function uses the LOCALE_ENCODING constant from the Configuration module to decode the string.
27- The function raises exceptions if the string cannot be decoded or encoded properly.
28- The function may return the original string if not_needed1 is true.
29"""
30class TestToUtf8:
31 # Tests that an empty string is returned as is
32 def test_empty_string(self):
33 assert to_utf8('') == ''
35 # Tests that an ASCII string is converted to UTF-8 encoding
36 def test_ascii_string(self):
37 assert to_utf8('hello') == 'hello'
39 # Tests that a string with invalid characters for the locale encoding raises a UnicodeDecodeError
40 def test_invalid_locale_encoding(self):
41 with pytest.raises(TypeError):
42 to_utf8(b'\x80\x81\x82')
44 # Tests that an already encoded string is returned as is
45 def test_already_encoded_string(self):
46 assert to_utf8(b'hello') == b'hello'
48 # Tests that the function works with different locale encodings
49 # Tests that the function works with different locale encodings
50 def test_different_locale_encoding(self):
51 old_locale_encoding = Configuration.LOCALE_ENCODING
52 Configuration.LOCALE_ENCODING = 'ISO-8859-1'
53 assert to_utf8('héllo'.encode('ISO-8859-1')) == b'h\xc3\xa9llo'
54 Configuration.LOCALE_ENCODING = old_locale_encoding