test_normalization.py 2.46 KB
Newer Older
1 2
from test.test_support import (verbose, TestFailed, TestSkipped, verify,
                               open_urlresource)
3
import sys
4
import os
5
from unicodedata import normalize
6

7 8
TESTDATAFILE = "NormalizationTest" + os.extsep + "txt"
TESTDATAURL = "http://www.unicode.org/Public/4.1.0/ucd/" + TESTDATAFILE
9

10
class RangeError(Exception):
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
    pass

def NFC(str):
    return normalize("NFC", str)

def NFKC(str):
    return normalize("NFKC", str)

def NFD(str):
    return normalize("NFD", str)

def NFKD(str):
    return normalize("NFKD", str)

def unistr(data):
    data = [int(x, 16) for x in data.split(" ")]
    for x in data:
        if x > sys.maxunicode:
            raise RangeError
    return u"".join([unichr(x) for x in data])

32 33
def test_main():
    part1_data = {}
34
    for line in open_urlresource(TESTDATAURL):
35 36 37 38 39 40
        if '#' in line:
            line = line.split('#')[0]
        line = line.strip()
        if not line:
            continue
        if line.startswith("@Part"):
41 42 43 44
            part = line.split()[0]
            continue
        if part == "@Part3":
            # XXX we don't support PRI #29 yet, so skip these tests for now
45 46 47 48
            continue
        try:
            c1,c2,c3,c4,c5 = [unistr(x) for x in line.split(';')[:-1]]
        except RangeError:
Tim Peters's avatar
Tim Peters committed
49
            # Skip unsupported characters;
50 51
            # try atleast adding c1 if we are in part1
            if part == "@Part1":
Tim Peters's avatar
Tim Peters committed
52
                try:
53 54 55 56 57
                    c1=unistr(line.split(';')[0])
                except RangeError:
                    pass
                else:
                    part1_data[c1] = 1
58 59 60 61
            continue

        if verbose:
            print line
62

63 64 65 66 67 68 69 70 71
        # Perform tests
        verify(c2 ==  NFC(c1) ==  NFC(c2) ==  NFC(c3), line)
        verify(c4 ==  NFC(c4) ==  NFC(c5), line)
        verify(c3 ==  NFD(c1) ==  NFD(c2) ==  NFD(c3), line)
        verify(c5 ==  NFD(c4) ==  NFD(c5), line)
        verify(c4 == NFKC(c1) == NFKC(c2) == NFKC(c3) == NFKC(c4) == NFKC(c5),
               line)
        verify(c5 == NFKD(c1) == NFKD(c2) == NFKD(c3) == NFKD(c4) == NFKD(c5),
               line)
Tim Peters's avatar
Tim Peters committed
72

73 74 75
        # Record part 1 data
        if part == "@Part1":
            part1_data[c1] = 1
76

77 78 79 80 81 82
    # Perform tests for all other data
    for c in range(sys.maxunicode+1):
        X = unichr(c)
        if X in part1_data:
            continue
        assert X == NFC(X) == NFD(X) == NFKC(X) == NFKD(X), c
83

84 85 86
    # Check for bug 834676
    normalize('NFC',u'\ud55c\uae00')

87 88
if __name__ == "__main__":
    test_main()