xref: /aosp_15_r20/external/fonttools/Tests/afmLib/afmLib_test.py (revision e1fe3e4ad2793916b15cccdc4a7da52a7e1dd0e9)
1import unittest
2import os
3from fontTools import afmLib
4
5
6CWD = os.path.abspath(os.path.dirname(__file__))
7DATADIR = os.path.join(CWD, "data")
8AFM = os.path.join(DATADIR, "TestAFM.afm")
9
10
11class AFMTest(unittest.TestCase):
12    def test_read_afm(self):
13        afm = afmLib.AFM(AFM)
14        self.assertEqual(
15            sorted(afm.kernpairs()),
16            sorted(
17                [("V", "A"), ("T", "comma"), ("V", "d"), ("T", "c"), ("T", "period")]
18            ),
19        )
20        self.assertEqual(afm["V", "A"], -60)
21        self.assertEqual(afm["V", "d"], 30)
22        self.assertEqual(afm["A"], (65, 668, (8, -25, 660, 666)))
23
24    def test_write_afm(self):
25        afm = afmLib.AFM(AFM)
26        newAfm, afmData = self.write(afm)
27        self.assertEqual(afm.kernpairs(), newAfm.kernpairs())
28        self.assertEqual(afm.chars(), newAfm.chars())
29        self.assertEqual(
30            afm.comments(), newAfm.comments()[1:]
31        )  # skip the "generated by afmLib" comment
32        for pair in afm.kernpairs():
33            self.assertEqual(afm[pair], newAfm[pair])
34        for char in afm.chars():
35            self.assertEqual(afm[char], newAfm[char])
36        with open(AFM, "r") as f:
37            originalLines = f.read().splitlines()
38        newLines = afmData.splitlines()
39        del newLines[1]  # remove the "generated by afmLib" comment
40        self.assertEqual(originalLines, newLines)
41
42    @staticmethod
43    def write(afm, sep="\r"):
44        temp = os.path.join(DATADIR, "temp.afm")
45        try:
46            afm.write(temp, sep)
47            with open(temp, "r") as f:
48                afmData = f.read()
49            afm = afmLib.AFM(temp)
50        finally:
51            if os.path.exists(temp):
52                os.remove(temp)
53        return afm, afmData
54
55
56if __name__ == "__main__":
57    import sys
58
59    sys.exit(unittest.main())
60