Skip to content
Myr

Fix the smoke test in the face of UTF-16 surrogate pairs.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

If the random data starts with a UTF-16 BOM *and* the next two bytes are for a character in the `\ud800`-`\udfff` range decoding would fail. Small chance, but still possible. Extend it to check the UTF-8 error as well. The goal is to test that the guesser was *mostly* correct, and to verify the cases where it wasn't that it was to be expected. Most of all that the function doesn't buckle under wildly unexpected data.

authored by Martijn Pieters · committed by Martijn Pieters · parent be01a35 · Browse files · 1 file+24 added−5 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+24 added−5 removed

  • tests:+24 added−5 removed

1 file+24 added−5 removed

modified:tests/test_utils.py+24 added-5 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34import codecs5import os6import sys7import unittest8import random
38 unmodified lines
47 for i in range(1000):48 sample = bytes().join(49 [byteschr(random.randrange(256)) for _ in range(4)])50 res = guess(sample)50 if res is not None and res != 'utf-8':51 if res is not None:52 # This should decode without errors if this is *really*52 # something in this encoding. Skip UTF-8, it is more53 # picky about valid data.54 sample.decode(res)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 raise755676if __name__ == '__main__':77 unittest.main()