File: classes_test.py

package info (click to toggle)
glyphslib 3.1.4-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,152 kB
  • sloc: python: 12,750; makefile: 8
file content (1677 lines) | stat: -rwxr-xr-x 60,714 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
# coding=UTF-8
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


from __future__ import print_function, division, absolute_import, unicode_literals

import os
import sys
import datetime
import copy
import unittest
import pytest
from fontTools.misc.py23 import unicode

from glyphsLib.classes import (
    GSFont,
    GSFontMaster,
    GSInstance,
    GSCustomParameter,
    GSGlyph,
    GSLayer,
    GSAnchor,
    GSComponent,
    GSAlignmentZone,
    GSClass,
    GSFeature,
    GSAnnotation,
    GSFeaturePrefix,
    GSGuideLine,
    GSHint,
    GSNode,
    GSSmartComponentAxis,
    GSBackgroundImage,
    LayerComponentsProxy,
    LayerGuideLinesProxy,
    STEM,
    TEXT,
    ARROW,
    CIRCLE,
    PLUS,
    MINUS,
)
from glyphsLib.types import Point, Transform, Rect

TESTFILE_PATH = os.path.join(
    os.path.dirname(__file__), os.path.join("data", "GlyphsUnitTestSans.glyphs")
)


def generate_minimal_font():
    font = GSFont()
    font.appVersion = 895
    font.date = datetime.datetime.today()
    font.familyName = "MyFont"

    master = GSFontMaster()
    master.ascender = 0
    master.capHeight = 0
    master.descender = 0
    master.id = "id"
    master.xHeight = 0
    font.masters.append(master)

    font.upm = 1000
    font.versionMajor = 1
    font.versionMinor = 0

    return font


def generate_instance_from_dict(instance_dict):
    instance = GSInstance()
    instance.name = instance_dict["name"]
    for custom_parameter in instance_dict.get("customParameters", []):
        cp = GSCustomParameter()
        cp.name = custom_parameter["name"]
        cp.value = custom_parameter["value"]
        instance.customParameters.append(cp)
    return instance


def add_glyph(font, glyphname):
    glyph = GSGlyph()
    glyph.name = glyphname
    font.glyphs.append(glyph)
    layer = GSLayer()
    layer.layerId = font.masters[0].id
    layer.associatedMasterId = font.masters[0].id
    layer.width = 0
    glyph.layers.append(layer)
    return glyph


def add_anchor(font, glyphname, anchorname, x, y):
    for glyph in font.glyphs:
        if glyph.name == glyphname:
            for master in font.masters:
                layer = glyph.layers[master.id]
                layer.anchors = getattr(layer, "anchors", [])
                anchor = GSAnchor()
                anchor.name = anchorname
                anchor.position = (x, y)
                layer.anchors.append(anchor)


def add_component(font, glyphname, componentname, transform):
    for glyph in font.glyphs:
        if glyph.name == glyphname:
            for layer in glyph.layers.values():
                component = GSComponent()
                component.name = componentname
                component.transform = transform
                layer.components.append(component)


class GlyphLayersTest(unittest.TestCase):
    def test_check_master_layer(self):
        font = generate_minimal_font()
        glyph = add_glyph(font, "A")
        self.assertIsNotNone(glyph)
        master = font.masters[0]
        self.assertIsNotNone(master)
        layer = glyph.layers[master.id]
        self.assertIsNotNone(layer)

        layer = glyph.layers["XYZ123"]
        self.assertIsNone(layer)


class GSFontTest(unittest.TestCase):
    def test_init(self):
        font = GSFont()
        self.assertEqual(font.familyName, "Unnamed font")
        self.assertEqual(font.versionMajor, 1)
        self.assertEqual(font.versionMinor, 0)
        self.assertEqual(font.appVersion, "895")

        self.assertEqual(len(font.glyphs), 0)
        self.assertEqual(len(font.masters), 0)
        self.assertEqual(list(font.masters), list(()))
        self.assertEqual(len(font.instances), 0)
        self.assertEqual(font.instances, [])
        self.assertEqual(len(font.customParameters), 0)

    def test_repr(self):
        font = GSFont()
        self.assertEqual(repr(font), '<GSFont "Unnamed font">')

    def test_update_custom_parameter(self):
        font = GSFont()
        font.customParameters["Filter"] = "RemoveOverlap"
        self.assertEqual(font.customParameters["Filter"], "RemoveOverlap")
        font.customParameters["Filter"] = "AddExtremes"
        self.assertEqual(font.customParameters["Filter"], "AddExtremes")

    def test_font_master_proxy(self):
        font = GSFont()
        master = GSFontMaster()
        font.masters.append(master)
        self.assertEqual(master.font, font)


class GSObjectsTestCase(unittest.TestCase):
    def setUp(self):
        self.font = GSFont(TESTFILE_PATH)

    def assertString(self, value):
        self.assertIsInstance(value, str)
        old_value = value
        value = "eee"
        self.assertEqual(value, "eee")
        value = old_value
        self.assertEqual(value, old_value)

    def assertUnicode(self, value):
        self.assertIsInstance(value, unicode)
        old_value = value
        value = "ə"
        self.assertEqual(value, "ə")
        value = old_value
        self.assertEqual(value, old_value)

    def assertInteger(self, value):
        self.assertIsInstance(value, int)
        old_value = value
        value = 5
        self.assertEqual(value, 5)
        value = old_value
        self.assertEqual(value, old_value)

    def assertFloat(self, value):
        self.assertIsInstance(value, float)
        old_value = value
        value = 0.5
        self.assertEqual(value, 0.5)
        value = old_value
        self.assertEqual(value, old_value)

    def assertBool(self, value):
        self.assertIsInstance(value, bool)
        old_value = value
        value = not value
        self.assertEqual(value, not old_value)
        value = old_value
        self.assertEqual(value, old_value)

    def assertDict(self, dictObject):
        self.assertIsInstance(dictObject, dict)
        var1 = "abc"
        var2 = "def"
        dictObject["uniTestValue"] = var1
        self.assertEqual(dictObject["uniTestValue"], var1)
        dictObject["uniTestValue"] = var2
        self.assertEqual(dictObject["uniTestValue"], var2)


class GSFontFromFileTest(GSObjectsTestCase):
    def setUp(self):
        super(GSFontFromFileTest, self).setUp()

    @pytest.mark.skipif(
        sys.version_info < (3, 4), reason="pathlib available in >= 3.4."
    )
    def test_pathlike_path(self):
        from pathlib import Path

        font = GSFont(TESTFILE_PATH)
        self.assertEqual(font.filepath, TESTFILE_PATH)

        font = GSFont(Path(TESTFILE_PATH))
        self.assertEqual(font.filepath, TESTFILE_PATH)

    def test_masters(self):
        font = self.font
        amount = len(font.masters)
        self.assertEqual(len(list(font.masters)), 3)

        new_master = GSFontMaster()
        font.masters.append(new_master)
        self.assertEqual(new_master, font.masters[-1])
        del font.masters[-1]

        new_master1 = GSFontMaster()
        new_master2 = GSFontMaster()
        font.masters.extend([new_master1, new_master2])
        self.assertEqual(new_master1, font.masters[-2])
        self.assertEqual(new_master2, font.masters[-1])

        font.masters.remove(font.masters[-1])
        font.masters.remove(font.masters[-1])

        new_master = GSFontMaster()
        font.masters.insert(0, new_master)
        self.assertEqual(new_master, font.masters[0])
        font.masters.remove(font.masters[0])
        self.assertEqual(amount, len(font.masters))

    def test_instances(self):
        font = self.font
        amount = len(font.instances)
        self.assertEqual(len(list(font.instances)), 8)
        new_instance = GSInstance()
        font.instances.append(new_instance)
        self.assertEqual(new_instance, font.instances[-1])
        del font.instances[-1]
        new_instance1 = GSInstance()
        new_instance2 = GSInstance()
        font.instances.extend([new_instance1, new_instance2])
        self.assertEqual(new_instance1, font.instances[-2])
        self.assertEqual(new_instance2, font.instances[-1])
        font.instances.remove(font.instances[-1])
        font.instances.remove(font.instances[-1])
        new_instance = GSInstance()
        font.instances.insert(0, new_instance)
        self.assertEqual(new_instance, font.instances[0])
        font.instances.remove(font.instances[0])
        self.assertEqual(amount, len(font.instances))

    def test_glyphs(self):
        font = self.font
        self.assertGreaterEqual(len(list(font.glyphs)), 1)
        by_index = font.glyphs[3]
        by_name = font.glyphs["adieresis"]
        by_unicode_char = font.glyphs["ä"]
        by_unicode_value = font.glyphs["00E4"]
        by_unicode_value_lowercased = font.glyphs["00e4"]
        self.assertEqual(by_index, by_name)
        self.assertEqual(by_unicode_char, by_name)
        self.assertEqual(by_unicode_value, by_name)
        self.assertEqual(by_unicode_value_lowercased, by_name)

    def test_classes(self):
        font = self.font
        font.classes = []
        amount = len(font.classes)
        font.classes.append(GSClass("uppercaseLetters", "A"))
        self.assertIsNotNone(font.classes[-1].__repr__())
        self.assertEqual(len(font.classes), 1)
        self.assertIn('<GSClass "uppercaseLetters">', str(font.classes))
        self.assertIn("A", font.classes["uppercaseLetters"].code)
        del (font.classes["uppercaseLetters"])
        newClass1 = GSClass("uppercaseLetters1", "A")
        newClass2 = GSClass("uppercaseLetters2", "A")
        font.classes.extend([newClass1, newClass2])
        self.assertEqual(newClass1, font.classes[-2])
        self.assertEqual(newClass2, font.classes[-1])
        newClass = GSClass("uppercaseLetters3", "A")
        newClass = copy.copy(newClass)
        font.classes.insert(0, newClass)
        self.assertEqual(newClass, font.classes[0])
        font.classes.remove(font.classes[-1])
        font.classes.remove(font.classes[-1])
        font.classes.remove(font.classes[0])
        self.assertEqual(len(font.classes), amount)

    def test_features(self):
        font = self.font
        font.features = []
        amount = len(font.features)
        font.features.append(GSFeature("liga", "sub f i by fi;"))
        # TODO
        # self.assertIsNotNone(font.features['liga'].__repr__())
        self.assertEqual(len(font.features), 1)
        # TODO
        # self.assertIn('<GSFeature "liga">', str(font.features))
        # self.assertIn('sub f i by fi;', font.features['liga'].code)
        # del(font.features['liga'])
        del font.features[-1]
        newFeature1 = GSFeature("liga", "sub f i by fi;")
        newFeature2 = GSFeature("liga", "sub f l by fl;")
        font.features.extend([newFeature1, newFeature2])
        self.assertEqual(newFeature1, font.features[-2])
        self.assertEqual(newFeature2, font.features[-1])
        newFeature = GSFeature("liga", "sub f i by fi;")
        newFeature = copy.copy(newFeature)
        font.features.insert(0, newFeature)
        self.assertEqual(newFeature, font.features[0])
        font.features.remove(font.features[-1])
        font.features.remove(font.features[-1])
        font.features.remove(font.features[0])
        self.assertEqual(len(font.features), amount)

    def test_featurePrefixes(self):
        font = self.font
        font.featurePrefixes = []
        amount = len(font.featurePrefixes)
        font.featurePrefixes.append(
            GSFeaturePrefix("LanguageSystems", "languagesystem DFLT dflt;")
        )
        self.assertIsNotNone(font.featurePrefixes[-1].__repr__())
        self.assertEqual(len(font.featurePrefixes), 1)
        self.assertIn('<GSFeaturePrefix "LanguageSystems">', str(font.featurePrefixes))
        self.assertIn("languagesystem DFLT dflt;", font.featurePrefixes[-1].code)
        # TODO
        # del(font.featurePrefixes['LanguageSystems'])
        del font.featurePrefixes[-1]
        newFeaturePrefix1 = GSFeaturePrefix(
            "LanguageSystems1", "languagesystem DFLT dflt;"
        )
        newFeaturePrefix2 = GSFeaturePrefix(
            "LanguageSystems2", "languagesystem DFLT dflt;"
        )
        font.featurePrefixes.extend([newFeaturePrefix1, newFeaturePrefix2])
        self.assertEqual(newFeaturePrefix1, font.featurePrefixes[-2])
        self.assertEqual(newFeaturePrefix2, font.featurePrefixes[-1])
        newFeaturePrefix = GSFeaturePrefix(
            "LanguageSystems3", "languagesystem DFLT dflt;"
        )
        newFeaturePrefix = copy.copy(newFeaturePrefix)
        font.featurePrefixes.insert(0, newFeaturePrefix)
        self.assertEqual(newFeaturePrefix, font.featurePrefixes[0])
        font.featurePrefixes.remove(font.featurePrefixes[-1])
        font.featurePrefixes.remove(font.featurePrefixes[-1])
        font.featurePrefixes.remove(font.featurePrefixes[0])
        self.assertEqual(len(font.featurePrefixes), amount)

    def test_ints(self):
        attributes = ["versionMajor", "versionMajor", "upm", "grid", "gridSubDivisions"]
        font = self.font
        for attr in attributes:
            self.assertInteger(getattr(font, attr))

    def test_strings(self):
        attributes = [
            "copyright",
            "designer",
            "designerURL",
            "manufacturer",
            "manufacturerURL",
            "familyName",
        ]
        font = self.font
        for attr in attributes:
            self.assertUnicode(getattr(font, attr))

    def test_note(self):
        font = self.font
        self.assertUnicode(font.note)

    # date
    def test_date(self):
        font = self.font
        self.assertIsInstance(font.date, datetime.datetime)

    def test_kerning(self):
        font = self.font
        self.assertDict(font.kerning)

    def test_userData(self):
        font = self.font
        self.assertEqual(
            font.userData["AsteriskParameters"],
            {"253E7231-480D-4F8E-8754-50FC8575C08E": ["754", "30", 7, 51, "80", "50"]},
        )
        # self.assertIsInstance(font.userData, dict)
        # TODO
        self.assertIsNone(font.userData["TestData"])
        font.userData["TestData"] = 42
        self.assertEqual(font.userData["TestData"], 42)
        self.assertTrue("TestData" in font.userData)
        del (font.userData["TestData"])
        self.assertIsNone(font.userData["TestData"])

    def test_disableNiceNames(self):
        font = self.font
        self.assertIsInstance(font.disablesNiceNames, bool)

    def test_customParameters(self):
        font = self.font
        font.customParameters["trademark"] = "ThisFont is a trademark by MyFoundry.com"
        self.assertIn(
            font.customParameters["trademark"],
            "ThisFont is a trademark by MyFoundry.com",
        )
        amount = len(list(font.customParameters))
        newParameter = GSCustomParameter("hello1", "world1")
        font.customParameters.append(newParameter)
        self.assertEqual(newParameter, list(font.customParameters)[-1])
        del font.customParameters[-1]
        newParameter1 = GSCustomParameter("hello2", "world2")
        newParameter2 = GSCustomParameter("hello3", "world3")
        newParameter2 = copy.copy(newParameter2)
        font.customParameters.extend([newParameter1, newParameter2])
        self.assertEqual(newParameter1, list(font.customParameters)[-2])
        self.assertEqual(newParameter2, list(font.customParameters)[-1])
        font.customParameters.remove(list(font.customParameters)[-1])
        font.customParameters.remove(list(font.customParameters)[-1])
        newParameter = GSCustomParameter("hello1", "world1")
        font.customParameters.insert(0, newParameter)
        self.assertEqual(newParameter, list(font.customParameters)[0])
        font.customParameters.remove(list(font.customParameters)[0])
        self.assertEqual(amount, len(list(font.customParameters)))
        del font.customParameters["trademark"]

    # TODO: selection, selectedLayers, currentText, tabs, currentTab

    # TODO: selectedFontMaster, masterIndex

    def test_filepath(self):
        font = self.font
        self.assertIsNotNone(font.filepath)

    # TODO: tool, tools
    # TODO: save(), close()
    # TODO: setKerningForPair(), kerningForPair(), removeKerningForPair()
    # TODO: updateFeatures()
    # TODO: copy(font)


class GSFontMasterFromFileTest(GSObjectsTestCase):
    def setUp(self):
        super(GSFontMasterFromFileTest, self).setUp()
        self.font = GSFont(TESTFILE_PATH)
        self.master = self.font.masters[0]

    def test_attributes(self):
        master = self.master
        self.assertIsNotNone(master.__repr__())
        self.assertIsNotNone(master.id)
        self.assertIsNotNone(master.name)
        self.assertIsNotNone(master.weight)
        self.assertIsNotNone(master.width)
        # weightValue
        obj = master.weightValue
        old_obj = obj
        self.assertIsInstance(obj, float)
        master.weightValue = 0.5
        self.assertEqual(master.weightValue, 0.5)
        obj = old_obj
        self.assertIsInstance(master.weightValue, float)
        self.assertIsInstance(master.widthValue, float)
        self.assertIsInstance(master.customValue, float)
        self.assertIsInstance(master.ascender, float)
        self.assertIsInstance(master.capHeight, float)
        self.assertIsInstance(master.xHeight, float)
        self.assertIsInstance(master.descender, float)
        self.assertIsInstance(master.italicAngle, float)
        for attr in [
            "weightValue",
            "widthValue",
            "customValue",
            "ascender",
            "capHeight",
            "xHeight",
            "descender",
            "italicAngle",
        ]:
            value = getattr(master, attr)
            self.assertIsInstance(value, float)
            setattr(master, attr, 0.5)
            self.assertEqual(getattr(master, attr), 0.5)
            setattr(master, attr, value)
        self.assertIsInstance(master.customName, unicode)

        # verticalStems
        oldStems = master.verticalStems
        master.verticalStems = [10, 15, 20]
        self.assertEqual(len(master.verticalStems), 3)
        master.verticalStems = oldStems

        # horizontalStems
        oldStems = master.horizontalStems
        master.horizontalStems = [10, 15, 20]
        self.assertEqual(len(master.horizontalStems), 3)
        master.horizontalStems = oldStems

        # alignmentZones
        self.assertIsInstance(master.alignmentZones, list)

        # TODO blueValues
        # self.assertIsInstance(master.blueValues, list)

        # TODO otherBlues
        # self.assertIsInstance(master.otherBlues, list)

        # guides
        self.assertIsInstance(master.guides, list)
        master.guides = []
        self.assertEqual(len(master.guides), 0)
        newGuide = GSGuideLine()
        newGuide.position = Point("{100, 100}")
        newGuide.angle = -10.0
        master.guides.append(newGuide)
        self.assertIsNotNone(master.guides[0].__repr__())
        self.assertEqual(len(master.guides), 1)
        del master.guides[0]
        self.assertEqual(len(master.guides), 0)

        # guides
        self.assertIsInstance(master.guides, list)
        master.guides = []
        self.assertEqual(len(master.guides), 0)
        newGuide = GSGuideLine()
        newGuide.position = Point("{100, 100}")
        newGuide.angle = -10.0
        master.guides.append(newGuide)
        self.assertIsNotNone(master.guides[0].__repr__())
        self.assertEqual(len(master.guides), 1)
        del master.guides[0]
        self.assertEqual(len(master.guides), 0)

        # userData
        self.assertIsNotNone(master.userData)
        master.userData["TestData"] = 42
        self.assertEqual(master.userData["TestData"], 42)
        del master.userData["TestData"]
        # TODO
        # self.assertIsNone(master.userData["TestData"])

        # customParameters
        master.customParameters[
            "trademark"
        ] = "ThisFont is a trademark by MyFoundry.com"
        self.assertGreaterEqual(len(master.customParameters), 1)
        del (master.customParameters["trademark"])

        # font
        self.assertEqual(self.font, self.master.font)

    def test_name(self):
        master = self.master
        self.assertEqual("Light", master.name)

        master.width = "Condensed"
        self.assertEqual(master.name, "Condensed Light")
        master.width = ""

        master.customParameters["Master Name"] = "My custom master name"
        self.assertEqual("My custom master name", master.name)
        del (master.customParameters["Master Name"])
        self.assertEqual("Light", master.name)

        master.italicAngle = 11
        self.assertEqual("Light Italic", master.name)
        master.italicAngle = 0

        master.italicAngle = 11
        master.width = "Condensed"
        self.assertEqual("Condensed Light Italic", master.name)
        master.width = ""
        master.italicAngle = 0

        master.customName = "Rounded"
        self.assertEqual("Light Rounded", master.name)
        master.customName = "Rounded Stretched Filled Rotated"
        self.assertEqual("Light Rounded Stretched Filled Rotated", master.name)
        master.customName = ""
        self.assertEqual("Light", master.name)

        # Test the name of a master set to "Regular" in the UI dropdown
        # but with a customName
        thin = GSFontMaster()
        thin.customName = "Thin"
        self.assertEqual("Thin", thin.name)

        # Test that we don't get an extra "Regular" in the name of "Italic"
        # https://github.com/googlei18n/glyphsLib/issues/380
        master = GSFontMaster()
        master.weight = "Regular"
        master.width = "Regular"
        master.italicAngle = 10.0
        self.assertEqual("Italic", master.name)

    def test_name_assignment(self):
        test_data = [
            # <name>, <expected weight>, <expected width>, <expected custom>
            # Regular
            ("Regular", "", "", ""),
            # Weights from the dropdown
            ("Light", "Light", "", ""),
            ("SemiLight", "SemiLight", "", ""),
            ("SemiBold", "SemiBold", "", ""),
            ("Bold", "Bold", "", ""),
            # Widths from the dropdown
            ("Condensed", "", "Condensed", ""),
            ("SemiCondensed", "", "SemiCondensed", ""),
            ("SemiExtended", "", "SemiExtended", ""),
            ("Extended", "", "Extended", ""),
            # Mixed weight and width from dropdowns
            ("Light Condensed", "Light", "Condensed", ""),
            ("Bold SemiExtended", "Bold", "SemiExtended", ""),
            # With italic -- in Glyphs 1114  works like a custom part
            ("Light Italic", "Light", "", "Italic"),
            ("SemiLight Italic", "SemiLight", "", "Italic"),
            ("SemiBold Italic", "SemiBold", "", "Italic"),
            ("Bold Italic", "Bold", "", "Italic"),
            ("Condensed Italic", "", "Condensed", "Italic"),
            ("SemiCondensed Italic", "", "SemiCondensed", "Italic"),
            ("SemiExtended Italic", "", "SemiExtended", "Italic"),
            ("Extended Italic", "", "Extended", "Italic"),
            ("Light Condensed Italic", "Light", "Condensed", "Italic"),
            ("Bold SemiExtended Italic", "Bold", "SemiExtended", "Italic"),
            # With custom parts
            ("Thin", "", "", "Thin"),
            ("SemiLight Ultra Expanded", "SemiLight", "", "Ultra Expanded"),
            ("Bold Compressed", "Bold", "", "Compressed"),
            ("Fat Condensed", "", "Condensed", "Fat"),
            ("Ultra Light Extended", "Light", "Extended", "Ultra"),
            ("Hyper Light Condensed Dunhill", "Light", "Condensed", "Hyper  Dunhill"),
            ("Bold SemiExtended Rugged", "Bold", "SemiExtended", "Rugged"),
            ("Thin Italic", "", "", "Thin Italic"),
            (
                "SemiLight Ultra Expanded Italic",
                "SemiLight",
                "",
                "Ultra Expanded Italic",
            ),
            ("Bold Compressed Italic", "Bold", "", "Compressed Italic"),
            ("Fat Condensed Italic", "", "Condensed", "Fat Italic"),
            ("Ultra Light Extended Italic", "Light", "Extended", "Ultra  Italic"),
            (
                "Hyper Light Condensed Dunhill Italic",
                "Light",
                "Condensed",
                "Hyper  Dunhill Italic",
            ),
            (
                "Bold SemiExtended Rugged Italic",
                "Bold",
                "SemiExtended",
                "Rugged Italic",
            ),
            ("Green Light Red Extended Blue", "Light", "Extended", "Green Red Blue"),
            (
                "Green SemiExtended Red SemiBold Blue",
                "SemiBold",
                "SemiExtended",
                "Green Red Blue",
            ),
        ]
        master = GSFontMaster()
        for name, weight, width, custom in test_data:
            master.name = name
            self.assertEqual(master.name, name)
            self.assertEqual(master.weight, weight or "Regular")
            self.assertEqual(master.width, width or "Regular")
            self.assertEqual(master.customName, custom)

    def test_default_values(self):
        master = GSFontMaster()
        self.assertEqual(master.weightValue, 100.0)
        self.assertEqual(master.widthValue, 100.0)
        self.assertEqual(master.customValue, 0.0)
        self.assertEqual(master.customValue1, 0.0)
        self.assertEqual(master.customValue2, 0.0)
        self.assertEqual(master.customValue3, 0.0)


class GSAlignmentZoneFromFileTest(GSObjectsTestCase):
    def setUp(self):
        super(GSAlignmentZoneFromFileTest, self).setUp()
        self.master = self.font.masters[0]

    def test_attributes(self):
        master = self.master
        for i, zone in enumerate(
            [(800, 10), (700, 10), (470, 10), (0, -10), (-200, -10)]
        ):
            pos, size = zone
            self.assertEqual(master.alignmentZones[i].position, pos)
            self.assertEqual(master.alignmentZones[i].size, size)
        master.alignmentZones = []
        self.assertEqual(len(master.alignmentZones), 0)
        master.alignmentZones.append(GSAlignmentZone(100, 10))
        self.assertIsNotNone(master.alignmentZones[-1].__repr__())
        zone = copy.copy(master.alignmentZones[-1])
        self.assertEqual(len(master.alignmentZones), 1)
        self.assertEqual(master.alignmentZones[-1].position, 100)
        self.assertEqual(master.alignmentZones[-1].size, 10)
        del master.alignmentZones[-1]
        self.assertEqual(len(master.alignmentZones), 0)


class GSInstanceFromFileTest(GSObjectsTestCase):
    def setUp(self):
        super(GSInstanceFromFileTest, self).setUp()
        self.instance = self.font.instances[0]

    def test_attributes(self):
        instance = self.instance
        self.assertIsNotNone(instance.__repr__())

        # TODO: active
        # self.assertIsInstance(instance.active, bool)

        # name
        self.assertIsInstance(instance.name, unicode)

        # weight
        self.assertIsInstance(instance.weight, unicode)

        # width
        self.assertIsInstance(instance.width, unicode)

        # weightValue
        # widthValue
        # customValue
        for attr in ["weightValue", "widthValue", "customValue"]:
            value = getattr(instance, attr)
            self.assertIsInstance(value, float)
            setattr(instance, attr, 0.5)
            self.assertEqual(getattr(instance, attr), 0.5)
            setattr(instance, attr, value)
        # isItalic
        # isBold
        for attr in ["isItalic", "isBold"]:
            value = getattr(instance, attr)
            self.assertIsInstance(value, bool)
            setattr(instance, attr, not value)
            self.assertEqual(getattr(instance, attr), not value)
            setattr(instance, attr, value)

        # linkStyle
        self.assertIsInstance(instance.linkStyle, unicode)

        # familyName
        # preferredFamily
        # preferredSubfamilyName
        # windowsFamily
        # windowsStyle
        # windowsLinkedToStyle
        # fontName
        # fullName
        for attr in [
            "familyName",
            "preferredFamily",
            "preferredSubfamilyName",
            "windowsFamily",
            "windowsStyle",
            "windowsLinkedToStyle",
            "fontName",
            "fullName",
        ]:
            # self.assertIsInstance(getattr(instance, attr), unicode)
            if not hasattr(instance, attr):
                print("instance does not have %s" % attr)
                if hasattr(instance, "parent") and hasattr(instance.parent, attr):
                    value = getattr(instance.parent)
                    print(value, type(value))

        # customParameters
        instance.customParameters[
            "trademark"
        ] = "ThisFont is a trademark by MyFoundry.com"
        self.assertGreaterEqual(len(instance.customParameters), 1)
        del (instance.customParameters["trademark"])

        # instanceInterpolations
        self.assertIsInstance(dict(instance.instanceInterpolations), dict)

        # manualInterpolation
        self.assertIsInstance(instance.manualInterpolation, bool)
        value = instance.manualInterpolation
        instance.manualInterpolation = not instance.manualInterpolation
        self.assertEqual(instance.manualInterpolation, not value)
        instance.manualInterpolation = value

        # interpolatedFont
        # TODO
        # self.assertIsInstance(instance.interpolatedFont, type(Glyphs.font))

        # TODO generate()

    def test_default_values(self):
        instance = GSInstance()
        self.assertEqual(instance.weightValue, 100.0)
        self.assertEqual(instance.widthValue, 100.0)
        self.assertEqual(instance.customValue, 0.0)
        self.assertEqual(instance.customValue1, 0.0)
        self.assertEqual(instance.customValue2, 0.0)
        self.assertEqual(instance.customValue3, 0.0)


class GSGlyphFromFileTest(GSObjectsTestCase):
    def setUp(self):
        super(GSGlyphFromFileTest, self).setUp()
        self.glyph = self.font.glyphs["a"]

    # TODO duplicate
    # def test_duplicate(self):
    #     font = self.font
    #     glyph1 = self.glyph
    #     glyph2 = glyph1.duplicate()
    #     glyph3 = glyph1.duplicate('a.test')

    def test_parent(self):
        font = self.font
        glyph = self.glyph
        self.assertEqual(glyph.parent, font)

    def test_layers(self):
        glyph = self.glyph
        self.assertIsNotNone(glyph.layers)
        amount = len(glyph.layers)
        newLayer = GSLayer()
        newLayer.name = "1"
        glyph.layers.append(newLayer)
        self.assertIn('<GSLayer "1" (a)>', str(glyph.layers[-1]))
        self.assertEqual(newLayer, glyph.layers[-1])
        del glyph.layers[-1]
        newLayer1 = GSLayer()
        newLayer1.name = "2"
        newLayer2 = GSLayer()
        newLayer2.name = "3"
        glyph.layers.extend([newLayer1, newLayer2])
        self.assertEqual(newLayer1, glyph.layers[-2])
        self.assertEqual(newLayer2, glyph.layers[-1])
        newLayer = GSLayer()
        newLayer.name = "4"
        # indices here don't make sense because layer get appended using a UUID
        glyph.layers.insert(0, newLayer)
        # so the latest layer got appended at the end also
        self.assertEqual(newLayer, glyph.layers[-1])
        glyph.layers.remove(glyph.layers[-1])
        glyph.layers.remove(glyph.layers[-1])
        glyph.layers.remove(glyph.layers[-1])
        self.assertEqual(amount, len(glyph.layers))
        self.assertEqual(
            '[<GSLayer "Light" (a)>, <GSLayer "Regular" (a)>, '
            '<GSLayer "Bold" (a)>, <GSLayer "{155, 100}" (a)>]',
            repr(list(glyph.layers)),
        )
        self.assertEqual(
            '[<GSLayer "Bold" (a)>, <GSLayer "Regular" (a)>, '
            '<GSLayer "Light" (a)>, <GSLayer "{155, 100}" (a)>]',
            repr(list(glyph.layers.values())),
        )

    def test_layers_missing_master(self):
        """
        font.glyph['a'] has its layers in a different order
        than the font.masters and an extra layer.
        Adding a master but not adding it as a layer to the glyph should not
        affect glyph.layers unexpectedly.
        """
        glyph = self.glyph
        num_layers = len(glyph.layers)
        self.assertEqual(
            {l.layerId for l in glyph.layers},
            {l.layerId for l in glyph.layers.values()},
        )
        self.assertNotEqual(
            [l.layerId for l in glyph.layers],
            [l.layerId for l in glyph.layers.values()],
        )
        new_fontMaster = GSFontMaster()
        self.font.masters.insert(0, new_fontMaster)
        self.assertEqual(num_layers, len(glyph.layers))
        self.assertEqual(
            {l.layerId for l in glyph.layers},
            {l.layerId for l in glyph.layers.values()},
        )
        self.assertNotEqual(
            [l.layerId for l in glyph.layers],
            [l.layerId for l in glyph.layers.values()],
        )

    def test_name(self):
        glyph = self.glyph
        self.assertIsInstance(glyph.name, unicode)
        value = glyph.name
        glyph.name = "Ə"
        self.assertEqual(glyph.name, "Ə")
        glyph.name = value

    def test_unicode(self):
        glyph = self.glyph
        self.assertIsInstance(glyph.unicode, unicode)
        value = glyph.unicode
        # TODO:
        # glyph.unicode = "004a"
        # self.assertEqual(glyph.unicode, "004A")
        glyph.unicode = "004B"
        self.assertEqual(glyph.unicode, "004B")
        glyph.unicode = value

    def test_string(self):
        glyph = self.font.glyphs["adieresis"]
        self.assertEqual(glyph.string, "ä")

    def test_id(self):
        # TODO
        pass

    # TODO
    # category
    # storeCategory
    # subCategory
    # storeSubCategory
    # script
    # storeScript
    # productionName
    # storeProductionName
    # glyphInfo

    def test_horiz_kerningGroup(self):
        for group in ["leftKerningGroup", "rightKerningGroup"]:
            glyph = self.glyph
            self.assertIsInstance(getattr(glyph, group), unicode)
            value = getattr(glyph, group)
            setattr(glyph, group, "ä")
            self.assertEqual(getattr(glyph, group), "ä")
            setattr(glyph, group, value)

    def test_horiz_metricsKey(self):
        for group in ["leftMetricsKey", "rightMetricsKey"]:
            glyph = self.glyph
            if getattr(glyph, group) is not None:
                self.assertIsInstance(getattr(glyph, group), unicode)
            value = getattr(glyph, group)
            setattr(glyph, group, "ä")
            self.assertEqual(getattr(glyph, group), "ä")
            setattr(glyph, group, value)

    def test_export(self):
        glyph = self.glyph
        self.assertIsInstance(glyph.export, bool)
        value = glyph.export
        glyph.export = not glyph.export
        self.assertEqual(glyph.export, not value)
        glyph.export = value

    def test_color(self):
        glyph = self.glyph
        if glyph.color is not None:
            self.assertIsInstance(glyph.color, int)
        value = glyph.color
        glyph.color = 5
        self.assertEqual(glyph.color, 5)
        glyph.color = value

    def test_note(self):
        glyph = self.glyph
        if glyph.note is not None:
            self.assertIsInstance(glyph.note, unicode)
        value = glyph.note
        glyph.note = "ä"
        self.assertEqual(glyph.note, "ä")
        glyph.note = value

    # TODO
    # masterCompatible

    def test_userData(self):
        glyph = self.glyph
        # self.assertIsNone(glyph.userData)
        amount = len(glyph.userData)
        var1 = "abc"
        var2 = "def"
        glyph.userData["unitTestValue"] = var1
        self.assertEqual(glyph.userData["unitTestValue"], var1)
        glyph.userData["unitTestValue"] = var2
        self.assertEqual(glyph.userData["unitTestValue"], var2)
        del glyph.userData["unitTestValue"]
        self.assertIsNone(glyph.userData.get("unitTestValue"))
        self.assertEqual(len(glyph.userData), amount)

    def test_smart_component_axes(self):
        shoulder = self.font.glyphs["_part.shoulder"]
        axes = shoulder.smartComponentAxes
        self.assertIsNotNone(axes)
        crotch_depth, shoulder_width = axes
        self.assertIsInstance(crotch_depth, GSSmartComponentAxis)
        self.assertEqual("crotchDepth", crotch_depth.name)
        self.assertEqual(0, crotch_depth.topValue)
        self.assertEqual(-100, crotch_depth.bottomValue)
        self.assertIsInstance(shoulder_width, GSSmartComponentAxis)
        self.assertEqual("shoulderWidth", shoulder_width.name)
        self.assertEqual(100, shoulder_width.topValue)
        self.assertEqual(0, shoulder_width.bottomValue)

    # TODO
    # lastChange


class GSLayerFromFileTest(GSObjectsTestCase):
    def setUp(self):
        super(GSLayerFromFileTest, self).setUp()
        self.glyph = self.font.glyphs["a"]
        self.layer = self.glyph.layers[0]

    def test_repr(self):
        layer = self.layer
        self.assertIsNotNone(layer.__repr__())

    def test_parent(self):
        self.assertEqual(self.layer.parent, self.glyph)

    def test_name(self):
        layer = self.layer
        self.assertUnicode(layer.name)

    # TODO
    # def test_associatedMasterId(self):
    #     font = self.font
    #     layer = self.layer
    #     self.assertEqual(layer.associatedMasterId, font.masters[0].id)

    # def test_layerId(self):
    #     font = self.font
    #     layer = self.layer
    #     self.assertEqual(layer.layerId, font.masters[0].id)

    # TODO set layer color in .glyphs file
    # def test_color(self):
    #     layer = self.layer
    #     self.assertInteger(layer.color)

    def test_components(self):
        glyph = self.font.glyphs["adieresis"]
        layer = glyph.layers[0]
        self.assertIsNotNone(layer.components)
        self.assertIsInstance(layer.components, LayerComponentsProxy)
        # self.assertGreaterEqual(len(layer.components), 1)
        self.assertEqual(len(layer.components), 2)
        # for component in layer.components:
        #     self.assertIsInstance(component, GSComponent)
        #     self.assertEqual(component.parent, layer)
        amount = len(layer.components)
        component = GSComponent()
        component.name = "A"
        layer.components.append(component)
        self.assertEqual(component.parent, layer)
        self.assertEqual(len(layer.components), amount + 1)
        del layer.components[-1]
        self.assertEqual(len(layer.components), amount)
        layer.components.extend([component])
        self.assertEqual(len(layer.components), amount + 1)
        layer.components.remove(component)
        self.assertEqual(len(layer.components), amount)

    def test_guides(self):
        layer = self.layer
        self.assertIsInstance(layer.guides, LayerGuideLinesProxy)
        for guide in layer.guides:
            self.assertEqual(guide.parent, layer)
        layer.guides = []
        self.assertEqual(len(layer.guides), 0)
        newGuide = GSGuideLine()
        newGuide.position = Point("{100, 100}")
        newGuide.angle = -10.0
        amount = len(layer.guides)
        layer.guides.append(newGuide)
        self.assertEqual(newGuide.parent, layer)
        self.assertIsNotNone(layer.guides[0].__repr__())
        self.assertEqual(len(layer.guides), amount + 1)
        del layer.guides[0]
        self.assertEqual(len(layer.guides), amount)

    def test_annotations(self):
        layer = self.layer
        # self.assertEqual(layer.annotations, [])
        self.assertEqual(len(layer.annotations), 0)
        newAnnotation = GSAnnotation()
        newAnnotation.type = TEXT
        newAnnotation.text = "This curve is ugly!"
        layer.annotations.append(newAnnotation)
        # TODO position.x, position.y
        # self.assertIsNotNone(layer.annotations[0].__repr__())
        self.assertEqual(len(layer.annotations), 1)
        del layer.annotations[0]
        self.assertEqual(len(layer.annotations), 0)
        newAnnotation1 = GSAnnotation()
        newAnnotation1.type = ARROW
        newAnnotation2 = GSAnnotation()
        newAnnotation2.type = CIRCLE
        newAnnotation3 = GSAnnotation()
        newAnnotation3.type = PLUS
        layer.annotations.extend([newAnnotation1, newAnnotation2, newAnnotation3])
        self.assertEqual(layer.annotations[-3], newAnnotation1)
        self.assertEqual(layer.annotations[-2], newAnnotation2)
        self.assertEqual(layer.annotations[-1], newAnnotation3)
        newAnnotation = GSAnnotation()
        newAnnotation = copy.copy(newAnnotation)
        newAnnotation.type = MINUS
        layer.annotations.insert(0, newAnnotation)
        self.assertEqual(layer.annotations[0], newAnnotation)
        layer.annotations.remove(layer.annotations[0])
        layer.annotations.remove(layer.annotations[-1])
        layer.annotations.remove(layer.annotations[-1])
        layer.annotations.remove(layer.annotations[-1])
        self.assertEqual(len(layer.annotations), 0)

    def test_hints_from_file(self):
        glyph = self.font.glyphs["A"]
        layer = glyph.layers[1]
        self.assertEqual(2, len(layer.hints))
        first, second = layer.hints
        self.assertIsInstance(first, GSHint)
        self.assertTrue(first.horizontal)
        self.assertIsInstance(first.originNode, GSNode)
        first_origin_node = layer.paths[1].nodes[1]
        self.assertEqual(first_origin_node, first.originNode)

        self.assertIsInstance(second, GSHint)
        second_target_node = layer.paths[0].nodes[4]
        self.assertEqual(second_target_node, second.targetNode)

    def test_hints(self):
        layer = self.layer
        # layer.hints = []
        self.assertEqual(len(layer.hints), 0)
        newHint = GSHint()
        newHint = copy.copy(newHint)
        newHint.originNode = layer.paths[0].nodes[0]
        newHint.targetNode = layer.paths[0].nodes[1]
        newHint.type = STEM
        layer.hints.append(newHint)
        self.assertIsNotNone(layer.hints[0].__repr__())
        self.assertEqual(len(layer.hints), 1)
        del layer.hints[0]
        self.assertEqual(len(layer.hints), 0)
        newHint1 = GSHint()
        newHint1.originNode = layer.paths[0].nodes[0]
        newHint1.targetNode = layer.paths[0].nodes[1]
        newHint1.type = STEM
        newHint2 = GSHint()
        newHint2.originNode = layer.paths[0].nodes[0]
        newHint2.targetNode = layer.paths[0].nodes[1]
        newHint2.type = STEM
        layer.hints.extend([newHint1, newHint2])
        newHint = GSHint()
        newHint.originNode = layer.paths[0].nodes[0]
        newHint.targetNode = layer.paths[0].nodes[1]
        self.assertEqual(layer.hints[-2], newHint1)
        self.assertEqual(layer.hints[-1], newHint2)
        layer.hints.insert(0, newHint)
        self.assertEqual(layer.hints[0], newHint)
        layer.hints.remove(layer.hints[0])
        layer.hints.remove(layer.hints[-1])
        layer.hints.remove(layer.hints[-1])
        self.assertEqual(len(layer.hints), 0)

    def test_anchors(self):
        layer = self.layer
        amount = len(layer.anchors)
        self.assertEqual(len(layer.anchors), 3)
        for anchor in layer.anchors:
            self.assertEqual(anchor.parent, layer)
        if layer.anchors["top"]:
            oldPosition = layer.anchors["top"].position
        else:
            oldPosition = None
        layer.anchors["top"] = GSAnchor()
        self.assertGreaterEqual(len(layer.anchors), 1)
        self.assertIsNotNone(layer.anchors["top"].__repr__())
        layer.anchors["top"].position = Point("{100, 100}")
        # anchor = copy.copy(layer.anchors['top'])
        del layer.anchors["top"]
        layer.anchors["top"] = GSAnchor()
        self.assertEqual(amount, len(layer.anchors))
        layer.anchors["top"].position = oldPosition
        self.assertUnicode(layer.anchors["top"].name)
        newAnchor1 = GSAnchor()
        newAnchor1.name = "testPosition1"
        newAnchor2 = GSAnchor()
        newAnchor2.name = "testPosition2"
        layer.anchors.extend([newAnchor1, newAnchor2])
        self.assertEqual(layer.anchors["testPosition1"], newAnchor1)
        self.assertEqual(layer.anchors["testPosition2"], newAnchor2)
        newAnchor3 = GSAnchor()
        newAnchor3.name = "testPosition3"
        layer.anchors.append(newAnchor3)
        self.assertEqual(layer.anchors["testPosition3"], newAnchor3)
        layer.anchors.remove(layer.anchors["testPosition3"])
        layer.anchors.remove(layer.anchors["testPosition2"])
        layer.anchors.remove(layer.anchors["testPosition1"])
        self.assertEqual(amount, len(layer.anchors))

    # TODO layer.paths

    # TODO
    # selection

    # TODO
    # LSB, RSB, TSB, BSB, width

    def test_leftMetricsKey(self):
        self.assertIs(self.layer.leftMetricsKey, None)

    def test_rightMetricsKey(self):
        self.assertIs(self.layer.rightMetricsKey, None)

    def test_widthMetricsKey(self):
        self.assertIs(self.layer.widthMetricsKey, None)

    # TODO: bounds, selectionBounds

    def test_background(self):
        self.assertIn("GSBackgroundLayer", self.layer.background.__repr__())

    def test_backgroundImage(self):
        # The selected layer (0 of glyph 'a') doesn't have one
        self.assertIsNone(self.layer.backgroundImage)

        glyph = self.font.glyphs["A"]
        layer = glyph.layers[0]
        image = layer.backgroundImage
        self.assertIsInstance(image, GSBackgroundImage)
        # Values from the file
        self.assertEqual("A.jpg", image.path)
        self.assertEqual([0.0, 0.0, 489.0, 637.0], list(image.crop))
        # Default values
        self.assertEqual(50, image.alpha)
        self.assertEqual([1, 0, 0, 1, 0, 0], image.transform.value)
        self.assertEqual(False, image.locked)

        # Test documented behaviour of "alpha"
        image.alpha = 10
        self.assertEqual(10, image.alpha)
        image.alpha = 9
        self.assertEqual(50, image.alpha)
        image.alpha = 100
        self.assertEqual(100, image.alpha)
        image.alpha = 101
        self.assertEqual(50, image.alpha)

    # TODO?
    # bezierPath, openBezierPath, completeBezierPath, completeOpenBezierPath?

    def test_userData(self):
        layer = self.layer
        # self.assertDict(layer.userData)
        layer.userData["Hallo"] = "Welt"
        self.assertEqual(layer.userData["Hallo"], "Welt")
        self.assertTrue("Hallo" in layer.userData)

    def test_smartComponentPoleMapping(self):
        # http://docu.glyphsapp.com/#smartComponentPoleMapping
        # Read some data from the file
        shoulder = self.font.glyphs["_part.shoulder"]
        for layer in shoulder.layers:
            if layer.name == "NarrowShoulder":
                mapping = layer.smartComponentPoleMapping
                self.assertIsNotNone(mapping)
                # crotchDepth is at the top pole
                self.assertEqual(2, mapping["crotchDepth"])
                # shoulderWidth is at the bottom pole
                self.assertEqual(1, mapping["shoulderWidth"])

        # Exercise the getter/setter
        layer = self.layer
        self.assertDict(layer.smartComponentPoleMapping)
        self.assertFalse("crotchDepth" in layer.smartComponentPoleMapping)
        layer.smartComponentPoleMapping["crotchDepth"] = 2
        self.assertTrue("crotchDepth" in layer.smartComponentPoleMapping)
        layer.smartComponentPoleMapping = {"shoulderWidth": 1}
        self.assertFalse("crotchDepth" in layer.smartComponentPoleMapping)
        self.assertEqual(1, layer.smartComponentPoleMapping["shoulderWidth"])

    # TODO: Methods
    # copyDecomposedLayer()
    # decomposeComponents()
    # compareString()
    # connectAllOpenPaths()
    # syncMetrics()
    # correctPathDirection()
    # removeOverlap()
    # roundCoordinates()
    # addNodesAtExtremes()
    # applyTransform()
    # beginChanges()
    # endChanges()
    # cutBetweenPoints()
    # intersectionsBetweenPoints()
    # addMissingAnchors()
    # clearSelection()
    # swapForegroundWithBackground()
    # reinterpolate()
    # clear()


class GSComponentFromFileTest(GSObjectsTestCase):
    def setUp(self):
        super(GSComponentFromFileTest, self).setUp()
        self.glyph = self.font.glyphs["adieresis"]
        self.layer = self.glyph.layers[0]
        self.component = self.layer.components[0]

    def test_repr(self):
        component = self.component
        self.assertIsNotNone(component.__repr__())
        self.assertEqual(repr(component), '<GSComponent "a" x=0.0 y=0.0>')

    def test_delete_and_add(self):
        layer = self.layer
        self.assertEqual(len(layer.components), 2)
        layer.components = []
        self.assertEqual(len(layer.components), 0)
        layer.components.append(GSComponent("a"))
        self.assertIsNotNone(layer.components[0].__repr__())
        self.assertEqual(len(layer.components), 1)
        layer.components.append(GSComponent("dieresis"))
        self.assertEqual(len(layer.components), 2)
        layer.components = [GSComponent("a"), GSComponent("dieresis")]
        self.assertEqual(len(layer.components), 2)
        layer.components = []
        layer.components.extend([GSComponent("a"), GSComponent("dieresis")])
        self.assertEqual(len(layer.components), 2)
        newComponent = GSComponent("dieresis")
        layer.components.insert(0, newComponent)
        self.assertEqual(newComponent, layer.components[0])
        layer.components.remove(layer.components[0])
        self.assertEqual(len(layer.components), 2)

    def test_position(self):
        self.assertIsInstance(self.component.position, Point)

    def test_componentName(self):
        self.assertUnicode(self.component.componentName)

    def test_component(self):
        self.assertIsInstance(self.component.component, GSGlyph)

    def test_rotation(self):
        self.assertFloat(self.component.rotation)

    def test_transform(self):
        self.assertIsInstance(self.component.transform, Transform)
        self.assertEqual(len(self.component.transform.value), 6)

    def test_bounds(self):
        self.assertIsInstance(self.component.bounds, Rect)
        bounds = self.component.bounds
        self.assertEqual(bounds.origin.x, 80)
        self.assertEqual(bounds.origin.y, -10)
        self.assertEqual(bounds.size.width, 289)
        self.assertEqual(bounds.size.height, 490)

    def test_moreBounds(self):
        self.component.scale = 1.1
        bounds = self.component.bounds
        self.assertEqual(bounds.origin.x, 88)
        self.assertEqual(bounds.origin.y, -11)
        self.assertEqual(round(bounds.size.width * 10), round(317.9 * 10))
        self.assertEqual(round(bounds.size.height * 10), round(539 * 10))

    # def test_automaticAlignment(self):
    #     self.assertBool(self.component.automaticAlignment)

    def test_anchor(self):
        self.assertString(self.component.anchor)

    def test_smartComponentValues(self):
        glyph = self.font.glyphs["h"]
        stem, shoulder = glyph.layers[0].components
        self.assertEqual(100, stem.smartComponentValues["height"])
        self.assertEqual(-80.20097, shoulder.smartComponentValues["crotchDepth"])

        self.assertNotIn("shoulderWidth", shoulder.smartComponentValues)

        self.assertNotIn("somethingElse", shoulder.smartComponentValues)

    # bezierPath?
    # componentLayer()


class GSGuideLineTest(unittest.TestCase):
    def test_repr(self):
        guide = GSGuideLine()
        self.assertEqual(repr(guide), "<GSGuideLine x=0.0 y=0.0 angle=0.0>")


class GSAnchorFromFileTest(GSObjectsTestCase):
    def setUp(self):
        super(GSAnchorFromFileTest, self).setUp()
        self.glyph = self.font.glyphs["a"]
        self.layer = self.glyph.layers[0]
        self.anchor = self.layer.anchors[0]

    def test_repr(self):
        anchor = self.anchor
        self.assertEqual(anchor.__repr__(), '<GSAnchor "bottom" x=218.0 y=0.0>')

    def test_name(self):
        anchor = self.anchor
        self.assertUnicode(anchor.name)

    # TODO
    def test_position(self):
        pass


class GSPathFromFileTest(GSObjectsTestCase):
    def setUp(self):
        super(GSPathFromFileTest, self).setUp()
        self.glyph = self.font.glyphs["a"]
        self.layer = self.glyph.layers[0]
        self.path = self.layer.paths[0]

    def test_proxy(self):
        layer = self.layer
        path = self.path
        amount = len(layer.paths)
        pathCopy1 = copy.copy(path)
        layer.paths.append(pathCopy1)
        pathCopy2 = copy.copy(pathCopy1)
        layer.paths.extend([pathCopy2])
        self.assertEqual(layer.paths[-2], pathCopy1)
        self.assertEqual(layer.paths[-1], pathCopy2)
        pathCopy3 = copy.copy(pathCopy2)
        layer.paths.insert(0, pathCopy3)
        self.assertEqual(layer.paths[0], pathCopy3)
        layer.paths.remove(layer.paths[0])
        layer.paths.remove(layer.paths[-1])
        layer.paths.remove(layer.paths[-1])
        self.assertEqual(amount, len(layer.paths))

    def test_parent(self):
        path = self.path
        self.assertEqual(path.parent, self.layer)

    def test_nodes(self):
        path = self.path
        self.assertIsNotNone(path.nodes)
        self.assertEqual(len(path.nodes), 44)
        for node in path.nodes:
            self.assertEqual(node.parent, path)
        amount = len(path.nodes)
        newNode = GSNode(Point("{100, 100}"))
        path.nodes.append(newNode)
        self.assertEqual(newNode, path.nodes[-1])
        del path.nodes[-1]
        newNode = GSNode(Point("{20, 20}"))
        path.nodes.insert(0, newNode)
        self.assertEqual(newNode, path.nodes[0])
        path.nodes.remove(path.nodes[0])
        newNode1 = GSNode(Point("{10, 10}"))
        newNode2 = GSNode(Point("{20, 20}"))
        path.nodes.extend([newNode1, newNode2])
        self.assertEqual(newNode1, path.nodes[-2])
        self.assertEqual(newNode2, path.nodes[-1])
        del path.nodes[-2]
        del path.nodes[-1]
        self.assertEqual(amount, len(path.nodes))

    # TODO: GSPath.closed

    # bezierPath?

    # TODO:
    # addNodesAtExtremes()
    # applyTransform()

    def test_direction(self):
        self.assertEqual(self.path.direction, -1)

    def test_segments(self):
        oldSegments = self.path.segments
        self.assertEqual(len(self.path.segments), 20)
        self.path.reverse()
        self.assertEqual(len(self.path.segments), 20)
        self.assertEqual(oldSegments[0].nodes[0], self.path.segments[0].nodes[0])

    def test_bounds(self):
        bounds = self.path.bounds
        self.assertEqual(bounds.origin.x, 80)
        self.assertEqual(bounds.origin.y, -10)
        self.assertEqual(bounds.size.width, 289)
        self.assertEqual(bounds.size.height, 490)


class GSNodeFromFileTest(GSObjectsTestCase):
    def setUp(self):
        super(GSNodeFromFileTest, self).setUp()
        self.glyph = self.font.glyphs["a"]
        self.layer = self.glyph.layers[0]
        self.path = self.layer.paths[0]
        self.node = self.path.nodes[0]

    def test_repr(self):
        self.assertIsNotNone(self.node.__repr__())

    def test_position(self):
        self.assertIsInstance(self.node.position, Point)

    def test_type(self):
        self.assertTrue(self.node.type in [GSNode.LINE, GSNode.CURVE, GSNode.OFFCURVE])

    def test_smooth(self):
        self.assertBool(self.node.smooth)

    def test_index(self):
        self.assertInteger(self.node.index)
        self.assertEqual(self.path.nodes[0].index, 0)
        self.assertEqual(self.path.nodes[-1].index, 43)

    def test_nextNode(self):
        self.assertEqual(type(self.path.nodes[-1].nextNode), GSNode)
        self.assertEqual(self.path.nodes[-1].nextNode, self.path.nodes[0])

    def test_prevNode(self):
        self.assertEqual(type(self.path.nodes[0].prevNode), GSNode)
        self.assertEqual(self.path.nodes[0].prevNode, self.path.nodes[-1])

    def test_name(self):
        self.assertEqual(self.node.name, "Hello")

    def test_userData(self):
        self.assertEqual("1", self.node.userData["rememberToMakeCoffee"])

    def test_makeNodeFirst(self):
        oldAmount = len(self.path.nodes)
        oldSecondNode = self.path.nodes[3]
        self.path.nodes[3].makeNodeFirst()
        self.assertEqual(oldAmount, len(self.path.nodes))
        self.assertEqual(oldSecondNode, self.path.nodes[0])

    def test_toggleConnection(self):
        oldConnection = self.node.smooth
        self.node.toggleConnection()
        self.assertEqual(oldConnection, not self.node.smooth)


class GSCustomParameterTest(unittest.TestCase):
    def test_plistValue_string(self):
        test_string = "Some Value"
        param = GSCustomParameter("New Parameter", test_string)
        self.assertEqual(
            param.plistValue(), '{\nname = "New Parameter";\nvalue = "Some Value";\n}'
        )

    def test_plistValue_list(self):
        test_list = [1, 2.5, {"key1": "value1"}]
        param = GSCustomParameter("New Parameter", test_list)
        self.assertEqual(
            param.plistValue(),
            '{\nname = "New Parameter";\nvalue = (\n1,\n2.5,'
            "\n{\nkey1 = value1;\n}\n);\n}",
        )

    def test_plistValue_dict(self):
        test_dict = {"key1": "value1", "key2": "value2"}
        param = GSCustomParameter("New Parameter", test_dict)
        self.assertEqual(
            param.plistValue(),
            '{\nname = "New Parameter";\nvalue = {\nkey1 = value1;'
            "\nkey2 = value2;\n};\n}",
        )


class GSBackgroundLayerTest(unittest.TestCase):
    """Goal: forbid in glyphsLib all the GSLayer.background APIs that don't
    work in Glyphs.app, so that the code we write for glyphsLib is sure to
    work in Glyphs.app
    """

    def setUp(self):
        self.layer = GSLayer()
        self.bg = self.layer.background

    def test_get_GSLayer_background(self):
        """It should always return a GSLayer (actually a GSBackgroundLayer but
        it's a subclass of GSLayer so it's ok)
        """
        self.assertIsInstance(self.bg, GSLayer)
        bg2 = self.layer.background
        self.assertEqual(self.bg, bg2)

    def test_set_GSLayer_background(self):
        """It should raise because it behaves strangely in Glyphs.app.
        The only way to modify a background layer in glyphsLib is to get it
        from a GSLayer object.
        """
        with pytest.raises(AttributeError):
            self.layer.background = GSLayer()

    def test_get_GSLayer_foreground(self):
        """It should raise AttributeError, as in Glyphs.app"""
        with pytest.raises(AttributeError):
            self.layer.foreground

    def test_set_GSLayer_foreground(self):
        with pytest.raises(AttributeError):
            self.layer.foreground = GSLayer()

    def test_get_GSBackgroundLayer_background(self):
        """It should always return None, as in Glyphs.app"""
        self.assertIsNone(self.bg.background)

    def test_set_GSBackgroundLayer_background(self):
        """It should raise because it should not be possible."""
        with pytest.raises(AttributeError):
            self.bg.background = GSLayer()

    def test_get_GSBackgroundLayer_foreground(self):
        """It should return the foreground layer.

        WARNING: currently in Glyphs.app it is not implemented properly and it
        returns some Objective C function.
        """
        self.assertEqual(self.layer, self.bg.foreground)

    def test_set_GSBackgroundLayer_foreground(self):
        """It should raise AttributeError, because it would be too complex to
        implement properly and anyway in Glyphs.app it returns some Objective C
        function.
        """
        with pytest.raises(AttributeError):
            self.bg.foreground = GSLayer()


if __name__ == "__main__":
    unittest.main()