summaryrefslogtreecommitdiff
path: root/src/zope/schema/tests/test_vocabulary.py
blob: eef246b6c6964adee18d5132330c535835d8ac22 (plain)
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
##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Test of the Vocabulary and related support APIs.
"""
import unittest


class SimpleTermTests(unittest.TestCase):

    def _getTargetClass(self):
        from zope.schema.vocabulary import SimpleTerm
        return SimpleTerm

    def _makeOne(self, *args, **kw):
        return self._getTargetClass()(*args, **kw)

    def test_class_conforms_to_ITokenizedTerm(self):
        from zope.interface.verify import verifyClass
        from zope.schema.interfaces import ITokenizedTerm
        verifyClass(ITokenizedTerm, self._getTargetClass())

    def test_instance_conforms_to_ITokenizedTerm(self):
        from zope.interface.verify import verifyObject
        from zope.schema.interfaces import ITokenizedTerm
        verifyObject(ITokenizedTerm, self._makeOne('VALUE'))

    def test_ctor_defaults(self):
        from zope.schema.interfaces import ITitledTokenizedTerm
        term = self._makeOne('VALUE')
        self.assertEqual(term.value, 'VALUE')
        self.assertEqual(term.token, 'VALUE')
        self.assertEqual(term.title, None)
        self.assertFalse(ITitledTokenizedTerm.providedBy(term))

    def test_ctor_explicit(self):
        from zope.schema.interfaces import ITitledTokenizedTerm
        term = self._makeOne('TERM', 'TOKEN', 'TITLE')
        self.assertEqual(term.value, 'TERM')
        self.assertEqual(term.token, 'TOKEN')
        self.assertEqual(term.title, 'TITLE')
        self.assertTrue(ITitledTokenizedTerm.providedBy(term))

    def test_bytes_value(self):
        from zope.schema.interfaces import ITitledTokenizedTerm
        term = self._makeOne(b'term')
        self.assertEqual(term.value, b'term')
        self.assertEqual(term.token, 'term')
        self.assertFalse(ITitledTokenizedTerm.providedBy(term))

    def test_bytes_non_ascii_value(self):
        from zope.schema.interfaces import ITitledTokenizedTerm
        term = self._makeOne(b'Snowman \xe2\x98\x83')
        self.assertEqual(term.value, b'Snowman \xe2\x98\x83')
        self.assertEqual(term.token, 'Snowman \\xe2\\x98\\x83')
        self.assertFalse(ITitledTokenizedTerm.providedBy(term))

    def test_unicode_non_ascii_value(self):
        from zope.schema.interfaces import ITitledTokenizedTerm
        term = self._makeOne(u'Snowman \u2603')
        self.assertEqual(term.value, u'Snowman \u2603')
        self.assertEqual(term.token, 'Snowman \\u2603')
        self.assertFalse(ITitledTokenizedTerm.providedBy(term))

    def test__eq__and__hash__(self):
        term = self._makeOne('value')
        # Equal to itself
        self.assertEqual(term, term)
        # Not equal to a different class
        self.assertNotEqual(term, object())
        self.assertNotEqual(object(), term)

        term2 = self._makeOne('value')
        # Equal to another with the same value
        self.assertEqual(term, term2)
        # equal objects hash the same
        self.assertEqual(hash(term), hash(term2))

        # Providing tokens or titles that differ
        # changes equality
        term = self._makeOne('value', 'token')
        self.assertNotEqual(term, term2)
        self.assertNotEqual(hash(term), hash(term2))

        term2 = self._makeOne('value', 'token')
        self.assertEqual(term, term2)
        self.assertEqual(hash(term), hash(term2))

        term = self._makeOne('value', 'token', 'title')
        self.assertNotEqual(term, term2)
        self.assertNotEqual(hash(term), hash(term2))

        term2 = self._makeOne('value', 'token', 'title')
        self.assertEqual(term, term2)
        self.assertEqual(hash(term), hash(term2))


class SimpleVocabularyTests(unittest.TestCase):

    def _getTargetClass(self):
        from zope.schema.vocabulary import SimpleVocabulary
        return SimpleVocabulary

    def _makeOne(self, *args, **kw):
        return self._getTargetClass()(*args, **kw)

    def test_class_conforms_to_IVocabularyTokenized(self):
        from zope.interface.verify import verifyClass
        from zope.schema.interfaces import IVocabularyTokenized
        verifyClass(IVocabularyTokenized, self._getTargetClass())

    def test_instance_conforms_to_IVocabularyTokenized(self):
        from zope.interface.verify import verifyObject
        from zope.schema.interfaces import IVocabularyTokenized
        verifyObject(IVocabularyTokenized, self._makeOne(()))

    def test_ctor_additional_interfaces(self):
        from zope.interface import Interface
        from zope.schema.vocabulary import SimpleTerm

        class IStupid(Interface):
            pass

        VALUES = [1, 4, 2, 9]
        vocabulary = self._makeOne([SimpleTerm(x) for x in VALUES], IStupid)
        self.assertTrue(IStupid.providedBy(vocabulary))
        self.assertEqual(len(vocabulary), len(VALUES))
        for value, term in zip(VALUES, vocabulary):
            self.assertEqual(term.value, value)
        for value in VALUES:
            self.assertTrue(value in vocabulary)
        self.assertFalse('ABC' in vocabulary)
        for term in vocabulary:
            self.assertIs(vocabulary.getTerm(term.value), term)
            self.assertIs(vocabulary.getTermByToken(term.token), term)

    def test_fromValues(self):
        from zope.interface import Interface
        from zope.schema.interfaces import ITokenizedTerm

        class IStupid(Interface):
            pass

        VALUES = [1, 4, 2, 9]
        vocabulary = self._getTargetClass().fromValues(VALUES)
        self.assertEqual(len(vocabulary), len(VALUES))
        for value, term in zip(VALUES, vocabulary):
            self.assertTrue(ITokenizedTerm.providedBy(term))
            self.assertEqual(term.value, value)
        for value in VALUES:
            self.assertIn(value, vocabulary)

    def test_fromItems(self):
        from zope.interface import Interface
        from zope.schema.interfaces import ITokenizedTerm

        class IStupid(Interface):
            pass

        ITEMS = [('one', 1), ('two', 2), ('three', 3), ('fore!', 4)]
        vocabulary = self._getTargetClass().fromItems(ITEMS)
        self.assertEqual(len(vocabulary), len(ITEMS))
        for item, term in zip(ITEMS, vocabulary):
            self.assertTrue(ITokenizedTerm.providedBy(term))
            self.assertEqual(term.token, item[0])
            self.assertEqual(term.value, item[1])
        for item in ITEMS:
            self.assertIn(item[1], vocabulary)

    def test_fromItems_triples(self):
        from zope.interface import Interface
        from zope.schema.interfaces import ITitledTokenizedTerm

        class IStupid(Interface):
            pass

        ITEMS = [
            ('one', 1, 'title 1'),
            ('two', 2, 'title 2'),
            ('three', 3, 'title 3'),
            ('fore!', 4, 'title four')
        ]
        vocabulary = self._getTargetClass().fromItems(ITEMS)
        self.assertEqual(len(vocabulary), len(ITEMS))
        for item, term in zip(ITEMS, vocabulary):
            self.assertTrue(ITitledTokenizedTerm.providedBy(term))
            self.assertEqual(term.token, item[0])
            self.assertEqual(term.value, item[1])
            self.assertEqual(term.title, item[2])
        for item in ITEMS:
            self.assertIn(item[1], vocabulary)

    def test_createTerm(self):
        from zope.schema.vocabulary import SimpleTerm
        VALUES = [1, 4, 2, 9]
        for value in VALUES:
            term = self._getTargetClass().createTerm(value)
            self.assertTrue(isinstance(term, SimpleTerm))
            self.assertEqual(term.value, value)
            self.assertEqual(term.token, str(value))

    def test_getTerm_miss(self):
        vocabulary = self._makeOne(())
        self.assertRaises(LookupError, vocabulary.getTerm, 'nonesuch')

    def test_getTermByToken_miss(self):
        vocabulary = self._makeOne(())
        self.assertRaises(LookupError, vocabulary.getTermByToken, 'nonesuch')

    def test_nonunique_tokens(self):
        klass = self._getTargetClass()
        self.assertRaises(ValueError, klass.fromValues, [2, '2'])
        self.assertRaises(
            ValueError,
            klass.fromItems,
            [(1, 'one'), ('1', 'another one')]
        )
        self.assertRaises(
            ValueError,
            klass.fromItems,
            [(0, 'one'), (1, 'one')]
        )

    def test_nonunique_tokens_swallow(self):
        klass = self._getTargetClass()
        items = [(0, 'one'), (1, 'one')]
        terms = [klass.createTerm(value, token) for (token, value) in items]
        vocab = self._getTargetClass()(terms, swallow_duplicates=True)
        self.assertEqual(vocab.getTerm('one').token, '1')

    def test_nonunique_token_message(self):
        try:
            self._getTargetClass().fromValues([2, '2'])
        except ValueError as e:
            self.assertEqual(str(e), "term tokens must be unique: '2'")

    def test_nonunique_token_messages(self):
        try:
            self._getTargetClass().fromItems([(0, 'one'), (1, 'one')])
        except ValueError as e:
            self.assertEqual(str(e), "term values must be unique: 'one'")

    def test_overriding_createTerm(self):
        class MyTerm(object):
            def __init__(self, value):
                self.value = value
                self.token = repr(value)
                self.nextvalue = value + 1

        class MyVocabulary(self._getTargetClass()):
            def createTerm(cls, value):
                return MyTerm(value)
            createTerm = classmethod(createTerm)

        vocab = MyVocabulary.fromValues([1, 2, 3])
        for term in vocab:
            self.assertEqual(term.value + 1, term.nextvalue)

    def test__eq__and__hash__(self):
        from zope import interface

        values = [1, 4, 2, 9]
        vocabulary = self._getTargetClass().fromValues(values)

        # Equal to itself
        self.assertEqual(vocabulary, vocabulary)
        # Not to other classes
        self.assertNotEqual(vocabulary, object())
        self.assertNotEqual(object(), vocabulary)

        # Equal to another object with the same values
        vocabulary2 = self._getTargetClass().fromValues(values)
        self.assertEqual(vocabulary, vocabulary2)
        self.assertEqual(hash(vocabulary), hash(vocabulary2))

        # Changing the values or the interfaces changes
        # equality
        class IFoo(interface.Interface):
            "an interface"

        vocabulary = self._getTargetClass().fromValues(values, IFoo)
        self.assertNotEqual(vocabulary, vocabulary2)
        # Interfaces are not taken into account in the hash; that's
        # OK: equal hashes do not imply equal objects
        self.assertEqual(hash(vocabulary), hash(vocabulary2))

        vocabulary2 = self._getTargetClass().fromValues(values, IFoo)
        self.assertEqual(vocabulary, vocabulary2)
        self.assertEqual(hash(vocabulary), hash(vocabulary2))


# Test _createTermTree via TreeVocabulary.fromDict


class TreeVocabularyTests(unittest.TestCase):

    def _getTargetClass(self):
        from zope.schema.vocabulary import TreeVocabulary
        return TreeVocabulary

    def tree_vocab_2(self):
        region_tree = {
            ('regions', 'Regions'): {
                ('aut', 'Austria'): {
                    ('tyr', 'Tyrol'): {
                        ('auss', 'Ausserfern'): {},
                    }
                },
                ('ger', 'Germany'): {
                    ('bav', 'Bavaria'): {}
                },
            }
        }
        return self._getTargetClass().fromDict(region_tree)

    def business_tree(self):
        return {
            ('services', 'services', 'Services'): {
                ('reservations', 'reservations', 'Reservations'): {
                    ('res_host', 'res_host', 'Res Host'): {},
                    ('res_gui', 'res_gui', 'Res GUI'): {},
                },
                ('check_in', 'check_in', 'Check-in'): {
                    ('dcs_host', 'dcs_host', 'DCS Host'): {},
                },
            },
            ('infrastructure', 'infrastructure', 'Infrastructure'): {
                ('communication_network', 'communication_network',
                 'Communication/Network'): {
                    ('messaging', 'messaging', 'Messaging'): {},
                },
                ('data_transaction', 'data_transaction',
                 'Data/Transaction'): {
                    ('database', 'database', 'Database'): {},
                },
                ('security', 'security', 'Security'): {},
            },
        }

    def tree_vocab_3(self):
        return self._getTargetClass().fromDict(self.business_tree())

    def test_only_titled_if_triples(self):
        from zope.schema.interfaces import ITitledTokenizedTerm
        no_titles = self.tree_vocab_2()
        for term in no_titles:
            self.assertIsNone(term.title)
            self.assertFalse(ITitledTokenizedTerm.providedBy(term))

        all_titles = self.tree_vocab_3()
        for term in all_titles:
            self.assertIsNotNone(term.title)
            self.assertTrue(ITitledTokenizedTerm.providedBy(term))

    def test_implementation(self):
        from zope.interface.verify import verifyObject
        from zope.interface.common.mapping import IEnumerableMapping
        from zope.schema.interfaces import ITreeVocabulary
        from zope.schema.interfaces import IVocabulary
        from zope.schema.interfaces import IVocabularyTokenized
        for v in [self.tree_vocab_2(), self.tree_vocab_3()]:
            self.assertTrue(verifyObject(IEnumerableMapping, v))
            self.assertTrue(verifyObject(IVocabulary, v))
            self.assertTrue(verifyObject(IVocabularyTokenized, v))
            self.assertTrue(verifyObject(ITreeVocabulary, v))

    def test_additional_interfaces(self):
        from zope.interface import Interface

        class IStupid(Interface):
            pass

        v = self._getTargetClass().fromDict({('one', '1'): {}}, IStupid)
        self.assertTrue(IStupid.providedBy(v))

    def test_ordering(self):
        # The TreeVocabulary makes use of an OrderedDict to store its
        # internal tree representation.
        #
        # Check that the keys are indeed ordered.
        from collections import OrderedDict

        d = {
            (1, 'new_york', 'New York'): {
                (2, 'ny_albany', 'Albany'): {},
                (3, 'ny_new_york', 'New York'): {},
            },
            (4, 'california', 'California'): {
                (5, 'ca_los_angeles', 'Los Angeles'): {},
                (6, 'ca_san_francisco', 'San Francisco'): {},
            },
            (7, 'texas', 'Texas'): {},
            (8, 'florida', 'Florida'): {},
            (9, 'utah', 'Utah'): {},
        }
        dict_ = OrderedDict(sorted(d.items(), key=lambda t: t[0]))
        vocab = self._getTargetClass().fromDict(dict_)
        # Test keys
        self.assertEqual(
            [k.token for k in vocab.keys()],
            ['1', '4', '7', '8', '9']
        )
        # Test __iter__
        self.assertEqual(
            [k.token for k in vocab],
            ['1', '4', '7', '8', '9']
        )

        self.assertEqual(
            [k.token for k in vocab[[k for k in vocab.keys()][0]].keys()],
            ['2', '3']
        )
        self.assertEqual(
            [k.token for k in vocab[[k for k in vocab.keys()][1]].keys()],
            ['5', '6']
        )

    def test_indexes(self):
        # TreeVocabulary creates three indexes for quick lookups,
        # term_by_value, term_by_value and path_by_value.
        tv2 = self.tree_vocab_2()
        self.assertEqual(
            [k for k in sorted(tv2.term_by_value.keys())],
            ['Ausserfern', 'Austria', 'Bavaria', 'Germany', 'Regions', 'Tyrol']
        )

        self.assertEqual(
            [k for k in sorted(tv2.term_by_token.keys())],
            ['auss', 'aut', 'bav', 'ger', 'regions', 'tyr']
        )

        self.assertEqual(
            [k for k in sorted(tv2.path_by_value.keys())],
            ['Ausserfern', 'Austria', 'Bavaria', 'Germany', 'Regions', 'Tyrol']
        )

        self.assertEqual(
            [k for k in sorted(tv2.path_by_value.values())],
            [
                ['Regions'],
                ['Regions', 'Austria'],
                ['Regions', 'Austria', 'Tyrol'],
                ['Regions', 'Austria', 'Tyrol', 'Ausserfern'],
                ['Regions', 'Germany'],
                ['Regions', 'Germany', 'Bavaria'],
            ]
        )

        self.assertEqual(
            [k for k in sorted(self.tree_vocab_3().term_by_value.keys())],
            [
                'check_in',
                'communication_network',
                'data_transaction',
                'database',
                'dcs_host',
                'infrastructure',
                'messaging',
                'res_gui',
                'res_host',
                'reservations',
                'security',
                'services',
            ]
        )

        self.assertEqual(
            [k for k in sorted(self.tree_vocab_3().term_by_token.keys())],
            [
                'check_in',
                'communication_network',
                'data_transaction',
                'database',
                'dcs_host',
                'infrastructure',
                'messaging',
                'res_gui',
                'res_host',
                'reservations',
                'security',
                'services',
            ]
        )

        self.assertEqual(
            [k for k in sorted(self.tree_vocab_3().path_by_value.values())],
            [
                ['infrastructure'],
                ['infrastructure', 'communication_network'],
                ['infrastructure', 'communication_network', 'messaging'],
                ['infrastructure', 'data_transaction'],
                ['infrastructure', 'data_transaction', 'database'],
                ['infrastructure', 'security'],
                ['services'],
                ['services', 'check_in'],
                ['services', 'check_in', 'dcs_host'],
                ['services', 'reservations'],
                ['services', 'reservations', 'res_gui'],
                ['services', 'reservations', 'res_host'],
            ]
        )

    def test_termpath(self):
        tv2 = self.tree_vocab_2()
        tv3 = self.tree_vocab_3()
        self.assertEqual(
            tv2.getTermPath('Bavaria'),
            ['Regions', 'Germany', 'Bavaria']
        )
        self.assertEqual(
            tv2.getTermPath('Austria'),
            ['Regions', 'Austria']
        )
        self.assertEqual(
            tv2.getTermPath('Ausserfern'),
            ['Regions', 'Austria', 'Tyrol', 'Ausserfern']
        )
        self.assertEqual(
            tv2.getTermPath('Non-existent'),
            []
        )
        self.assertEqual(
            tv3.getTermPath('database'),
            ["infrastructure", "data_transaction", "database"]
        )

    def test_len(self):
        # len returns the number of all nodes in the dict
        self.assertEqual(len(self.tree_vocab_2()), 1)
        self.assertEqual(len(self.tree_vocab_3()), 2)

    def test_contains(self):
        tv2 = self.tree_vocab_2()
        self.assertTrue('Regions' in tv2 and
                        'Austria' in tv2 and
                        'Bavaria' in tv2)

        self.assertTrue('bav' not in tv2)
        self.assertTrue('foo' not in tv2)
        self.assertTrue({} not in tv2)  # not hashable

        tv3 = self.tree_vocab_3()
        self.assertTrue('database' in tv3 and
                        'security' in tv3 and
                        'services' in tv3)

        self.assertTrue('Services' not in tv3)
        self.assertTrue('Database' not in tv3)
        self.assertTrue({} not in tv3)  # not hashable

    def test_values_and_items(self):
        for v in (self.tree_vocab_2(), self.tree_vocab_3()):
            for term in v:
                self.assertEqual([i for i in v.values()],
                                 [i for i in v._terms.values()])
                self.assertEqual([i for i in v.items()],
                                 [i for i in v._terms.items()])

    def test_get(self):
        for v in [self.tree_vocab_2(), self.tree_vocab_3()]:
            for key, value in v.items():
                self.assertEqual(v.get(key), value)
                self.assertEqual(v[key], value)

    def test_get_term(self):
        for v in (self.tree_vocab_2(), self.tree_vocab_3()):
            for term in v:
                self.assertTrue(v.getTerm(term.value) is term)
                self.assertTrue(v.getTermByToken(term.token) is term)
            self.assertRaises(LookupError, v.getTerm, 'non-present-value')
            self.assertRaises(LookupError,
                              v.getTermByToken, 'non-present-token')

    def test_nonunique_values_and_tokens(self):
        # Since we do term and value lookups, all terms' values and tokens
        # must be unique. This rule applies recursively.
        self.assertRaises(
            ValueError, self._getTargetClass().fromDict,
            {
                ('one', '1'): {},
                ('two', '1'): {},
            })
        self.assertRaises(
            ValueError, self._getTargetClass().fromDict,
            {
                ('one', '1'): {},
                ('one', '2'): {},
            })
        # Even nested tokens must be unique.
        self.assertRaises(
            ValueError, self._getTargetClass().fromDict,
            {
                ('new_york', 'New York'): {
                    ('albany', 'Albany'): {},
                    ('new_york', 'New York'): {},
                },
            })
        # The same applies to nested values.
        self.assertRaises(
            ValueError, self._getTargetClass().fromDict,
            {
                ('1', 'new_york'): {
                    ('2', 'albany'): {},
                    ('3', 'new_york'): {},
                },
            })
        # The title attribute does however not have to be unique.
        self._getTargetClass().fromDict({
            ('1', 'new_york', 'New York'): {
                ('2', 'ny_albany', 'Albany'): {},
                ('3', 'ny_new_york', 'New York'): {},
            },
        })
        self._getTargetClass().fromDict({
            ('one', '1', 'One'): {},
            ('two', '2', 'One'): {},
        })

    def test_nonunique_value_message(self):
        try:
            self._getTargetClass().fromDict({
                ('one', '1'): {},
                ('two', '1'): {},
            })
        except ValueError as e:
            self.assertEqual(str(e), "Term values must be unique: '1'")

    def test_nonunique_token_message(self):
        try:
            self._getTargetClass().fromDict({
                ('one', '1'): {},
                ('one', '2'): {},
            })
        except ValueError as e:
            self.assertEqual(str(e), "Term tokens must be unique: 'one'")

    def test_recursive_methods(self):
        # Test the _createTermTree and _getPathToTreeNode methods
        from zope.schema.vocabulary import _createTermTree
        tree = _createTermTree({}, self.business_tree())
        vocab = self._getTargetClass().fromDict(self.business_tree())

        term_path = vocab._getPathToTreeNode(tree, "infrastructure")
        vocab_path = vocab._getPathToTreeNode(vocab, "infrastructure")
        self.assertEqual(term_path, vocab_path)
        self.assertEqual(term_path, ["infrastructure"])

        term_path = vocab._getPathToTreeNode(tree, "security")
        vocab_path = vocab._getPathToTreeNode(vocab, "security")
        self.assertEqual(term_path, vocab_path)
        self.assertEqual(term_path, ["infrastructure", "security"])

        term_path = vocab._getPathToTreeNode(tree, "database")
        vocab_path = vocab._getPathToTreeNode(vocab, "database")
        self.assertEqual(term_path, vocab_path)
        self.assertEqual(term_path,
                         ["infrastructure", "data_transaction", "database"])

        term_path = vocab._getPathToTreeNode(tree, "dcs_host")
        vocab_path = vocab._getPathToTreeNode(vocab, "dcs_host")
        self.assertEqual(term_path, vocab_path)
        self.assertEqual(term_path, ["services", "check_in", "dcs_host"])

        term_path = vocab._getPathToTreeNode(tree, "dummy")
        vocab_path = vocab._getPathToTreeNode(vocab, "dummy")
        self.assertEqual(term_path, vocab_path)
        self.assertEqual(term_path, [])


class RegistryTests(unittest.TestCase):
    # Tests of the simple vocabulary and presentation registries.

    def setUp(self):
        from zope.schema.vocabulary import _clear
        _clear()

    def tearDown(self):
        from zope.schema.vocabulary import _clear
        _clear()

    def test_setVocabularyRegistry(self):
        from zope.schema.vocabulary import setVocabularyRegistry
        from zope.schema.vocabulary import getVocabularyRegistry
        r = _makeDummyRegistry()
        setVocabularyRegistry(r)
        self.assertTrue(getVocabularyRegistry() is r)

    def test_getVocabularyRegistry(self):
        from zope.schema.interfaces import IVocabularyRegistry
        from zope.schema.vocabulary import getVocabularyRegistry
        r = getVocabularyRegistry()
        self.assertTrue(IVocabularyRegistry.providedBy(r))

    # TODO: still need to test the default implementation


def _makeSampleVocabulary():
    from zope.interface import implementer
    from zope.schema.interfaces import IVocabulary

    class SampleTerm(object):
        pass

    @implementer(IVocabulary)
    class SampleVocabulary(object):

        def __iter__(self):
            raise AssertionError("Not called")

        def __contains__(self, value):
            return 0 <= value < 10

        def __len__(self):  # pragma: no cover
            return 10

        def getTerm(self, value):
            raise AssertionError("Not called.")

    return SampleVocabulary()


def _makeDummyRegistry():
    from zope.schema.vocabulary import VocabularyRegistry

    class DummyRegistry(VocabularyRegistry):
        def get(self, object, name):
            raise AssertionError("Not called")
    return DummyRegistry()