Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(195604)

Side by Side Diff: Lib/test/test_enum.py

Issue 17947: Code, test, and doc review for PEP-0435 Enum
Patch Set: Created 6 years, 6 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
View unified diff | Download patch
« Lib/enum.py ('K') | « Lib/enum.py ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 import enum
2 import sys
Zach Ware 2013/05/17 15:37:11 Turns out sys isn't used here, either.
stoneleaf 2013/05/17 17:40:14 Done.
3 import unittest
4 from collections import OrderedDict
5 from pickle import dumps, loads, PicklingError
6 from enum import Enum, IntEnum
7
8
9 # for pickle tests
10 try:
11 class Stooges(Enum):
12 LARRY = 1
13 CURLY = 2
14 MOE = 3
15 except Exception as exc:
16 Stooges = exc
17
18 try:
19 class IntStooges(int, Enum):
20 LARRY = 1
21 CURLY = 2
22 MOE = 3
23 except Exception as exc:
24 IntStooges = exc
25
26 try:
27 class FloatStooges(float, Enum):
28 LARRY = 1.39
29 CURLY = 2.72
30 MOE = 3.142596
31 except Exception as exc:
32 FloatStooges = exc
33
34 # for pickle test and subclass tests
35 try:
36 class StrEnum(str, Enum):
37 'accepts only string values'
38 class Name(StrEnum):
39 BDFL = 'Guido van Rossum'
40 FLUFL = 'Barry Warsaw'
41 except Exception as exc:
42 Name = exc
43
44 try:
45 Question = Enum('Question', 'who what when where why', module=__name__)
46 except Exception as exc:
47 Question = exc
48
49 try:
50 Answer = Enum('Answer', 'him this then there because')
51 except Exception as exc:
52 Answer = exc
53
54 class TestEnum(unittest.TestCase):
55 def setUp(self):
56 class Season(Enum):
57 SPRING = 1
58 SUMMER = 2
59 AUTUMN = 3
60 WINTER = 4
61 self.Season = Season
62
63 def test_enum_in_enum_out(self):
64 Season = self.Season
65 self.assertIs(Season(Season.WINTER), Season.WINTER)
66
67 def test_enum_value(self):
68 Season = self.Season
69 self.assertEqual(Season.SPRING.value, 1)
70
71 def test_intenum_value(self):
72 self.assertEqual(IntStooges.CURLY.value, 2)
73
74 def test_dir_on_class(self):
75 Season = self.Season
76 self.assertEqual(
77 set(dir(Season)),
78 set(['__class__', '__doc__', '__members__',
79 'SPRING', 'SUMMER', 'AUTUMN', 'WINTER']),
80 )
81
82 def test_dir_on_item(self):
83 Season = self.Season
84 self.assertEqual(
85 set(dir(Season.WINTER)),
86 set(['__class__', '__doc__', 'name', 'value']),
87 )
88
89 def test_enum(self):
90 Season = self.Season
91 lst = list(Season)
92 self.assertEqual(len(lst), len(Season))
93 self.assertEqual(len(Season), 4, Season)
94 self.assertEqual(
95 [Season.SPRING, Season.SUMMER, Season.AUTUMN, Season.WINTER], lst)
96
97 for i, season in enumerate('SPRING SUMMER AUTUMN WINTER'.split(), 1):
98 e = Season(i)
99 self.assertEqual(e, getattr(Season, season))
100 self.assertEqual(e.value, i)
101 self.assertNotEqual(e, i)
102 self.assertEqual(e.name, season)
103 self.assertIn(e, Season)
104 self.assertIs(type(e), Season)
105 self.assertIsInstance(e, Season)
106 self.assertEqual(str(e), 'Season.' + season)
107 self.assertEqual(
108 repr(e),
109 '<Season.{0}: {1}>'.format(season, i),
110 )
111
112 def test_value_name(self):
113 Season = self.Season
114 self.assertEqual(Season.SPRING.name, 'SPRING')
115 self.assertEqual(Season.SPRING.value, 1)
116 with self.assertRaises(AttributeError):
117 Season.SPRING.name = 'invierno'
118 with self.assertRaises(AttributeError):
119 Season.SPRING.value = 2
120
121 def test_invalid_names(self):
122 with self.assertRaises(ValueError):
123 class Wrong(Enum):
124 mro = 9
125 with self.assertRaises(ValueError):
126 class Wrong(Enum):
127 _create= 11
128 with self.assertRaises(ValueError):
129 class Wrong(Enum):
130 _get_mixins = 9
131 with self.assertRaises(ValueError):
132 class Wrong(Enum):
133 _find_new = 1
134
135
136 def test_contains(self):
137 Season = self.Season
138 self.assertIn(Season.AUTUMN, Season)
139 self.assertNotIn(3, Season)
140
141 val = Season(3)
142 self.assertIn(val, Season)
143
144 class OtherEnum(Enum):
145 one = 1; two = 2
146 self.assertNotIn(OtherEnum.two, Season)
147
148 def test_comparisons(self):
149 Season = self.Season
150 with self.assertRaises(TypeError):
151 Season.SPRING < Season.WINTER
152 with self.assertRaises(TypeError):
153 Season.SPRING > 4
154
155 self.assertNotEqual(Season.SPRING, 1)
156
157 class Part(Enum):
158 SPRING = 1
159 CLIP = 2
160 BARREL = 3
161
162 self.assertNotEqual(Season.SPRING, Part.SPRING)
163 with self.assertRaises(TypeError):
164 Season.SPRING < Part.CLIP
165
166 def test_enum_duplicates(self):
167 class Season(Enum):
168 SPRING = 1
169 SUMMER = 2
170 AUTUMN = FALL = 3
171 WINTER = 4
172 ANOTHER_SPRING = 1
173 lst = list(Season)
174 self.assertEqual(
175 lst,
176 [Season.SPRING, Season.SUMMER,
177 Season.AUTUMN, Season.WINTER,
178 ])
179 self.assertIs(Season.FALL, Season.AUTUMN)
180 self.assertEqual(Season.FALL.value, 3)
181 self.assertEqual(Season.AUTUMN.value, 3)
182 self.assertIs(Season(3), Season.AUTUMN)
183 self.assertIs(Season(1), Season.SPRING)
184 self.assertEqual(Season.FALL.name, 'AUTUMN')
185 self.assertEqual(
186 [k for k,v in Season.__members__.items() if v.name != k],
187 ['FALL', 'ANOTHER_SPRING'],
188 )
189
190 def test_enum_with_value_name(self):
191 class Huh(Enum):
192 name = 1
193 value = 2
194 self.assertEqual(
195 list(Huh),
196 [Huh.name, Huh.value],
197 )
198 self.assertIs(type(Huh.name), Huh)
199 self.assertEqual(Huh.name.name, 'name')
200 self.assertEqual(Huh.name.value, 1)
201
202 def test_intenum(self):
203 class WeekDay(IntEnum):
204 SUNDAY = 1
205 MONDAY = 2
206 TUESDAY = 3
207 WEDNESDAY = 4
208 THURSDAY = 5
209 FRIDAY = 6
210 SATURDAY = 7
211
212 self.assertEqual(['a', 'b', 'c'][WeekDay.MONDAY], 'c')
213 self.assertEqual([i for i in range(WeekDay.TUESDAY)], [0, 1, 2])
214
215 lst = list(WeekDay)
216 self.assertEqual(len(lst), len(WeekDay))
217 self.assertEqual(len(WeekDay), 7)
218 target = 'SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY'
219 target = target.split()
220 for i, weekday in enumerate(target, 1):
221 e = WeekDay(i)
222 self.assertEqual(e, i)
223 self.assertEqual(int(e), i)
224 self.assertEqual(e.name, weekday)
225 self.assertIn(e, WeekDay)
226 self.assertEqual(lst.index(e)+1, i)
227 self.assertTrue(0 < e < 8)
228 self.assertIs(type(e), WeekDay)
229 self.assertIsInstance(e, int)
230 self.assertIsInstance(e, Enum)
231
232 def test_intenum_duplicates(self):
233 class WeekDay(IntEnum):
234 SUNDAY = 1
235 MONDAY = 2
236 TUESDAY = TEUSDAY = 3
237 WEDNESDAY = 4
238 THURSDAY = 5
239 FRIDAY = 6
240 SATURDAY = 7
241 self.assertIs(WeekDay.TEUSDAY, WeekDay.TUESDAY)
242 self.assertEqual(WeekDay(3).name, 'TUESDAY')
243 self.assertEqual([k for k,v in WeekDay.__members__.items()
244 if v.name != k], ['TEUSDAY', ])
245
246 def test_pickle_enum(self):
247 if isinstance(Stooges, Exception):
248 raise Stooges
249 self.assertIs(Stooges.CURLY, loads(dumps(Stooges.CURLY)))
250 self.assertIs(Stooges, loads(dumps(Stooges)))
251
252 def test_pickle_int(self):
253 if isinstance(IntStooges, Exception):
254 raise IntStooges
255 self.assertIs(IntStooges.CURLY, loads(dumps(IntStooges.CURLY)))
256 self.assertIs(IntStooges, loads(dumps(IntStooges)))
257
258 def test_pickle_float(self):
259 if isinstance(FloatStooges, Exception):
260 raise FloatStooges
261 self.assertIs(FloatStooges.CURLY, loads(dumps(FloatStooges.CURLY)))
262 self.assertIs(FloatStooges, loads(dumps(FloatStooges)))
263
264 def test_pickle_enum_function(self):
265 if isinstance(Answer, Exception):
266 raise Answer
267 self.assertIs(Answer.him, loads(dumps(Answer.him)))
268 self.assertIs(Answer, loads(dumps(Answer)))
269
270 def test_pickle_enum_function_with_module(self):
271 if isinstance(Question, Exception):
272 raise Question
273 self.assertIs(Question.who, loads(dumps(Question.who)))
274 self.assertIs(Question, loads(dumps(Question)))
275
276 def test_exploding_pickle(self):
277 BadPickle = Enum('BadPickle', 'dill sweet bread-n-butter')
278 BadPickle.__module__ = 'uh uh'
279 BadPickle.__reduce__ = enum.break_noisily_on_pickle
280 globals()['BadPickle'] = BadPickle
281 with self.assertRaises(TypeError):
282 dumps(BadPickle.dill)
283 with self.assertRaises(PicklingError):
284 dumps(BadPickle)
285
286 def test_string_enum(self):
287 class SkillLevel(str, Enum):
288 master = 'what is the sound of one hand clapping?'
289 journeyman = 'why did the chicken cross the road?'
290 apprentice = 'knock, knock!'
291 self.assertEqual(SkillLevel.apprentice, 'knock, knock!')
292
293 def test_getattr_getitem(self):
294 class Period(Enum):
295 morning = 1
296 noon = 2
297 evening = 3
298 night = 4
299 self.assertIs(Period(2), Period.noon)
300 self.assertIs(getattr(Period, 'night'), Period.night)
301 self.assertIs(Period['morning'], Period.morning)
302
303 def test_getattr_dunder(self):
304 Season = self.Season
305 self.assertTrue(getattr(Season, '__eq__'))
306
307 def test_iteration_order(self):
308 class Season(Enum):
309 SUMMER = 2
310 WINTER = 4
311 AUTUMN = 3
312 SPRING = 1
313 self.assertEqual(
314 list(Season),
315 [Season.SUMMER, Season.WINTER, Season.AUTUMN, Season.SPRING],
316 )
317
318 def test_programatic_function_string(self):
319 SummerMonth = Enum('SummerMonth', 'june july august')
320 lst = list(SummerMonth)
321 self.assertEqual(len(lst), len(SummerMonth))
322 self.assertEqual(len(SummerMonth), 3, SummerMonth)
323 self.assertEqual(
324 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
325 lst,
326 )
327 for i, month in enumerate('june july august'.split(), 1):
328 e = SummerMonth(i)
329 self.assertEqual(int(e.value), i)
330 self.assertNotEqual(e, i)
331 self.assertEqual(e.name, month)
332 self.assertIn(e, SummerMonth)
333 self.assertIs(type(e), SummerMonth)
334
335 def test_programatic_function_string_list(self):
336 SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'])
337 lst = list(SummerMonth)
338 self.assertEqual(len(lst), len(SummerMonth))
339 self.assertEqual(len(SummerMonth), 3, SummerMonth)
340 self.assertEqual(
341 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
342 lst,
343 )
344 for i, month in enumerate('june july august'.split(), 1):
345 e = SummerMonth(i)
346 self.assertEqual(int(e.value), i)
347 self.assertNotEqual(e, i)
348 self.assertEqual(e.name, month)
349 self.assertIn(e, SummerMonth)
350 self.assertIs(type(e), SummerMonth)
351
352 def test_programatic_function_iterable(self):
353 SummerMonth = Enum(
354 'SummerMonth',
355 (('june', 1), ('july', 2), ('august', 3))
356 )
357 lst = list(SummerMonth)
358 self.assertEqual(len(lst), len(SummerMonth))
359 self.assertEqual(len(SummerMonth), 3, SummerMonth)
360 self.assertEqual(
361 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
362 lst,
363 )
364 for i, month in enumerate('june july august'.split(), 1):
365 e = SummerMonth(i)
366 self.assertEqual(int(e.value), i)
367 self.assertNotEqual(e, i)
368 self.assertEqual(e.name, month)
369 self.assertIn(e, SummerMonth)
370 self.assertIs(type(e), SummerMonth)
371
372 def test_programatic_function_from_dict(self):
373 SummerMonth = Enum(
374 'SummerMonth',
375 OrderedDict((('june', 1), ('july', 2), ('august', 3)))
376 )
377 lst = list(SummerMonth)
378 self.assertEqual(len(lst), len(SummerMonth))
379 self.assertEqual(len(SummerMonth), 3, SummerMonth)
380 self.assertEqual(
381 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
382 lst,
383 )
384 for i, month in enumerate('june july august'.split(), 1):
385 e = SummerMonth(i)
386 self.assertEqual(int(e.value), i)
387 self.assertNotEqual(e, i)
388 self.assertEqual(e.name, month)
389 self.assertIn(e, SummerMonth)
390 self.assertIs(type(e), SummerMonth)
391
392 def test_programatic_function_type(self):
393 SummerMonth = Enum('SummerMonth', 'june july august', type=int)
394 lst = list(SummerMonth)
395 self.assertEqual(len(lst), len(SummerMonth))
396 self.assertEqual(len(SummerMonth), 3, SummerMonth)
397 self.assertEqual(
398 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
399 lst,
400 )
401 for i, month in enumerate('june july august'.split(), 1):
402 e = SummerMonth(i)
403 self.assertEqual(e, i)
404 self.assertEqual(e.name, month)
405 self.assertIn(e, SummerMonth)
406 self.assertIs(type(e), SummerMonth)
407
408 def test_programatic_function_type_from_subclass(self):
409 SummerMonth = IntEnum('SummerMonth', 'june july august')
410 lst = list(SummerMonth)
411 self.assertEqual(len(lst), len(SummerMonth))
412 self.assertEqual(len(SummerMonth), 3, SummerMonth)
413 self.assertEqual(
414 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
415 lst,
416 )
417 for i, month in enumerate('june july august'.split(), 1):
418 e = SummerMonth(i)
419 self.assertEqual(e, i)
420 self.assertEqual(e.name, month)
421 self.assertIn(e, SummerMonth)
422 self.assertIs(type(e), SummerMonth)
423
424 def test_subclassing(self):
425 if isinstance(Name, Exception):
426 raise Name
427 self.assertEqual(Name.BDFL, 'Guido van Rossum')
428 self.assertTrue(Name.BDFL, Name('Guido van Rossum'))
429 self.assertIs(Name.BDFL, getattr(Name, 'BDFL'))
430 self.assertIs(Name.BDFL, loads(dumps(Name.BDFL)))
431
432 def test_extending(self):
433 class Color(Enum):
434 red = 1
435 green = 2
436 blue = 3
437 with self.assertRaises(TypeError):
438 class MoreColor(Color):
439 cyan = 4
440 magenta = 5
441 yellow = 6
442
443 def test_exclude_methods(self):
444 class whatever(Enum):
445 this = 'that'
446 these = 'those'
447 def really(self):
448 return 'no, not %s' % self.value
449 self.assertIsNot(type(whatever.really), whatever)
450 self.assertEqual(whatever.this.really(), 'no, not that')
451
452 def test_overwrite_enums(self):
453 class Why(Enum):
454 question = 1
455 answer = 2
456 propisition = 3
457 def question(self):
458 print(42)
459 self.assertIsNot(type(Why.question), Why)
460 self.assertNotIn(Why.question, Why._enum_names)
461 self.assertNotIn(Why.question, Why)
462
463 def test_wrong_inheritance_order(self):
464 with self.assertRaises(TypeError):
465 class Wrong(Enum, str):
466 NotHere = 'error before this point'
467
468 def test_wrong_enum_in_call(self):
469 class Monochrome(Enum):
470 black = 0
471 white = 1
472 class Gender(Enum):
473 male = 0
474 female = 1
475 self.assertRaises(ValueError, Monochrome, Gender.male)
476
477 def test_wrong_enum_in_mixed_call(self):
478 class Monochrome(IntEnum):
479 black = 0
480 white = 1
481 class Gender(Enum):
482 male = 0
483 female = 1
484 self.assertRaises(ValueError, Monochrome, Gender.male)
485
486 def test_mixed_enum_in_call_1(self):
487 class Monochrome(IntEnum):
488 black = 0
489 white = 1
490 class Gender(IntEnum):
491 male = 0
492 female = 1
493 self.assertIs(Monochrome(Gender.female), Monochrome.white)
494
495 def test_mixed_enum_in_call_2(self):
496 class Monochrome(Enum):
497 black = 0
498 white = 1
499 class Gender(IntEnum):
500 male = 0
501 female = 1
502 self.assertIs(Monochrome(Gender.male), Monochrome.black)
503
504 def test_flufl_enum(self):
505 class Fluflnum(Enum):
506 def __int__(self):
507 return int(self.value)
508 class MailManOptions(Fluflnum):
509 option1 = 1
510 option2 = 2
511 option3 = 3
512 self.assertEqual(int(MailManOptions.option1), 1)
513
514 def test_no_such_enum_member(self):
515 class Color(Enum):
516 red = 1
517 green = 2
518 blue = 3
519 with self.assertRaises(ValueError):
520 Color(4)
521 with self.assertRaises(KeyError):
522 Color['chartreuse']
523
524 def test_new_repr(self):
525 class Color(Enum):
526 red = 1
527 green = 2
528 blue = 3
529 def __repr__(self):
530 return "don't you just love shades of %s?" % self.name
531 self.assertEqual(
532 repr(Color.blue),
533 "don't you just love shades of blue?",
534 )
535
536 def test_inherited_repr(self):
537 class MyEnum(Enum):
538 def __repr__(self):
539 return "My name is %s." % self.name
540 class MyIntEnum(int, MyEnum):
541 this = 1
542 that = 2
543 theother = 3
544 self.assertEqual(repr(MyIntEnum.that), "My name is that.")
545
546 def test_multiple_mixin_mro(self):
547 class auto_enum(type(Enum)):
548 def __new__(metacls, cls, bases, classdict):
549 temp = type(classdict)()
550 names = set(classdict._enum_names)
551 i = 0
552 for k in classdict._enum_names:
553 v = classdict[k]
554 if v is Ellipsis:
555 v = i
556 else:
557 i = v
558 i += 1
559 temp[k] = v
560 for k, v in classdict.items():
561 if k not in names:
562 temp[k] = v
563 return super(auto_enum, metacls).__new__(
564 metacls, cls, bases, temp)
565
566 class AutoNumberedEnum(Enum, metaclass=auto_enum):
567 pass
568
569 class AutoIntEnum(IntEnum, metaclass=auto_enum):
570 pass
571
572 class TestAutoNumber(AutoNumberedEnum):
573 a = ...
574 b = 3
575 c = ...
576
577 class TestAutoInt(AutoIntEnum):
578 a = ...
579 b = 3
580 c = ...
581
582 def test_subclasses_with_getnewargs(self):
583 class NamedInt(int):
584 def __new__(cls, *args):
585 _args = args
586 name, *args = args
587 if len(args) == 0:
588 raise TypeError("name and value must be specified")
589 self = int.__new__(cls, *args)
590 self._intname = name
591 self._args = _args
592 return self
593 def __getnewargs__(self):
594 return self._args
595 @property
596 def __name__(self):
597 return self._intname
598 def __repr__(self):
599 # repr() is updated to include the name and type info
600 return "{}({!r}, {})".format(type(self).__name__,
601 self.__name__,
602 int.__repr__(self))
603 def __str__(self):
604 # str() is unchanged, even if it relies on the repr() fallback
605 base = int
606 base_str = base.__str__
607 if base_str.__objclass__ is object:
608 return base.__repr__(self)
609 return base_str(self)
610 # for simplicity, we only define one operator that
611 # propagates expressions
612 def __add__(self, other):
613 temp = int(self) + int( other)
614 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
615 return NamedInt(
616 '({0} + {1})'.format(self.__name__, other.__name__),
617 temp )
618 else:
619 return temp
620
621 class NEI(NamedInt, Enum):
622 x = ('the-x', 1)
623 y = ('the-y', 2)
624
625 self.assertIs(NEI.__new__, Enum.__new__)
626 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
627 globals()['NamedInt'] = NamedInt
628 globals()['NEI'] = NEI
629 NI5 = NamedInt('test', 5)
630 self.assertEqual(NI5, 5)
631 self.assertEqual(loads(dumps(NI5)), 5)
632 self.assertEqual(NEI.y.value, 2)
633 self.assertIs(loads(dumps(NEI.y)), NEI.y)
634
635 def test_subclasses_without_getnewargs(self):
636 class NamedInt(int):
637 def __new__(cls, *args):
638 _args = args
639 name, *args = args
640 if len(args) == 0:
641 raise TypeError("name and value must be specified")
642 self = int.__new__(cls, *args)
643 self._intname = name
644 self._args = _args
645 return self
646 @property
647 def __name__(self):
648 return self._intname
649 def __repr__(self):
650 # repr() is updated to include the name and type info
651 return "{}({!r}, {})".format(type(self).__name__,
652 self.__name__,
653 int.__repr__(self))
654 def __str__(self):
655 # str() is unchanged, even if it relies on the repr() fallback
656 base = int
657 base_str = base.__str__
658 if base_str.__objclass__ is object:
659 return base.__repr__(self)
660 return base_str(self)
661 # for simplicity, we only define one operator that
662 # propagates expressions
663 def __add__(self, other):
664 temp = int(self) + int( other)
665 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
666 return NamedInt(
667 '({0} + {1})'.format(self.__name__, other.__name__),
668 temp )
669 else:
670 return temp
671
672 class NEI(NamedInt, Enum):
673 x = ('the-x', 1)
674 y = ('the-y', 2)
675
676 self.assertIs(NEI.__new__, Enum.__new__)
677 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
678 globals()['NamedInt'] = NamedInt
679 globals()['NEI'] = NEI
680 NI5 = NamedInt('test', 5)
681 self.assertEqual(NI5, 5)
682 self.assertEqual(NEI.y.value, 2)
683 with self.assertRaises(TypeError):
684 dumps(NEI.x)
685 with self.assertRaises(PicklingError):
686 dumps(NEI)
687
688 def test_tuple_subclass(self):
689 class SomeTuple(tuple, Enum):
690 first = (1, 'for the money')
691 second = (2, 'for the show')
692 third = (3, 'for the music')
693 self.assertIs(type(SomeTuple.first), SomeTuple)
694 self.assertIsInstance(SomeTuple.second, tuple)
695 self.assertEqual(SomeTuple.third, (3, 'for the music'))
696 globals()['SomeTuple'] = SomeTuple
697 self.assertIs(loads(dumps(SomeTuple.first)), SomeTuple.first)
698
699 def test_duplicate_values_give_unique_enum_items(self):
700 class AutoNumber(Enum):
701 first = ()
702 second = ()
703 third = ()
704 def __new__(cls):
705 value = len(cls.__members__) + 1
706 obj = object.__new__(cls)
707 obj._value = value
708 return obj
709 def __int__(self):
710 return int(self._value)
711 self.assertEqual(
712 list(AutoNumber),
713 [AutoNumber.first, AutoNumber.second, AutoNumber.third],
714 )
715 self.assertEqual(int(AutoNumber.second), 2)
716 self.assertIs(AutoNumber(1), AutoNumber.first)
717
718 def test_inherited_new_from_enhanced_enum(self):
719 class AutoNumber(Enum):
720 def __new__(cls):
721 value = len(cls.__members__) + 1
722 obj = object.__new__(cls)
723 obj._value = value
724 return obj
725 def __int__(self):
726 return int(self._value)
727 class Color(AutoNumber):
728 red = ()
729 green = ()
730 blue = ()
731 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
732 self.assertEqual(list(map(int, Color)), [1, 2, 3])
733
734 def test_inherited_new_from_mixed_enum(self):
735 class AutoNumber(IntEnum):
736 def __new__(cls):
737 value = len(cls.__members__) + 1
738 obj = int.__new__(cls, value)
739 obj._value = value
740 return obj
741 class Color(AutoNumber):
742 red = ()
743 green = ()
744 blue = ()
745 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
746 self.assertEqual(list(map(int, Color)), [1, 2, 3])
747
748 def test_ordered_mixin(self):
749 class OrderedEnum(Enum):
750 def __ge__(self, other):
751 if self.__class__ is other.__class__:
752 return self._value >= other._value
753 return NotImplemented
754 def __gt__(self, other):
755 if self.__class__ is other.__class__:
756 return self._value > other._value
757 return NotImplemented
758 def __le__(self, other):
759 if self.__class__ is other.__class__:
760 return self._value <= other._value
761 return NotImplemented
762 def __lt__(self, other):
763 if self.__class__ is other.__class__:
764 return self._value < other._value
765 return NotImplemented
766 class Grade(OrderedEnum):
767 A = 5
768 B = 4
769 C = 3
770 D = 2
771 F = 1
772 self.assertGreater(Grade.A, Grade.B)
773 self.assertLessEqual(Grade.F, Grade.C)
774 self.assertLess(Grade.D, Grade.A)
775 self.assertGreaterEqual(Grade.B, Grade.B)
776
777
778 if __name__ == '__main__':
779 unittest.main()
OLDNEW
« Lib/enum.py ('K') | « Lib/enum.py ('k') | no next file » | no next file with comments »

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+