Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

77 lines · 2.7 KiB · Python

Last changed by

Merge pull request #909 from mjpieters/issue765-json-encodingsKenneth Reitzbefore adoption28dc725

History of this file

Take it

1#!/usr/bin/env python2# -*- coding: utf-8 -*-34import codecs5import os6import sys7import unittest8import random910# Path hack.11sys.path.insert(0, os.path.abspath('..'))12import requests.utils13from requests.compat import is_py3, bytes141516if is_py3:17    unichr = chr18    byteschr = lambda c: bytes([c])19else:20    byteschr = chr212223class GuessJSONUTFTests(unittest.TestCase):24    """Tests for the JSON UTF encoding guessing code."""2526    codecs = (27        'utf-8', 'utf-8-sig',28        'utf-16', 'utf-16-le', 'utf-16-be',29        'utf-32', 'utf-32-le', 'utf-32-be'30    )3132    def test_guess_encoding(self):33        # Throw 4-character ASCII strings (encoded to a UTF encoding)34        # at the guess routine; it should correctly guess all codecs.35        guess = requests.utils.guess_json_utf36        for c in range(33, 127):  # printable only37            sample = unichr(c) * 438            for codec in self.codecs:39                res = guess(sample.encode(codec))40                self.assertEqual(res, codec)4142    def test_smoke_encoding(self):43        # Throw random 4-byte strings at the guess function.44        # Any guess for a UTF encoding is verified, a decode exception45        # is a test failure.46        guess = requests.utils.guess_json_utf47        for i in range(1000):48            sample = bytes().join(49                [byteschr(random.randrange(256)) for _ in range(4)])50            res = guess(sample)51            if res is not None:52                # This should decode without errors if this is *really*53                # something in this encoding. However, UTF-8 is a lot54                # more picky, so we expect errors there. UTF-16 surrogate55                # pairs also fail56                try:57                    sample.decode(res)58                except UnicodeDecodeError as e:59                    self.assertEqual(e.args[0].replace('-', '').lower(),60                                     res.replace('-', '').lower())61                    if res == 'utf-8':62                        self.assertTrue(e.args[-1], (63                            'invalid continuation byte',64                            'invalid start byte'))65                        continue66                    if res == 'utf-16':67                        self.assertEqual(e.args[-1], 'unexpected end of data')68                        self.assertTrue(sample[:2] in (69                            codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE))70                        # the second two bytes are in the range \ud800-\udfff71                        # if someone wants to add tests for that as well. I don't72                        # see the need; we are not testing UTF decoding here.73                        continue74                    raise7576if __name__ == '__main__':77    unittest.main()