blob: 7985948041a922b8ab8b448fbe378fc7d8706574 [file] [log] [blame]
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001import enum
Ethan Furman5875d742013-10-21 20:45:55 -07002import inspect
3import pydoc
Ethan Furman6b3d64a2013-06-14 16:55:46 -07004import unittest
5from collections import OrderedDict
Ethan Furman5875d742013-10-21 20:45:55 -07006from enum import Enum, IntEnum, EnumMeta, unique
7from io import StringIO
Ethan Furman2ddb39a2014-02-06 17:28:50 -08008from pickle import dumps, loads, PicklingError, HIGHEST_PROTOCOL
Martin Panter19e69c52015-11-14 12:46:42 +00009from test import support
Ethan Furman6b3d64a2013-06-14 16:55:46 -070010
11# for pickle tests
12try:
13 class Stooges(Enum):
14 LARRY = 1
15 CURLY = 2
16 MOE = 3
17except Exception as exc:
18 Stooges = exc
19
20try:
21 class IntStooges(int, Enum):
22 LARRY = 1
23 CURLY = 2
24 MOE = 3
25except Exception as exc:
26 IntStooges = exc
27
28try:
29 class FloatStooges(float, Enum):
30 LARRY = 1.39
31 CURLY = 2.72
32 MOE = 3.142596
33except Exception as exc:
34 FloatStooges = exc
35
36# for pickle test and subclass tests
37try:
38 class StrEnum(str, Enum):
39 'accepts only string values'
40 class Name(StrEnum):
41 BDFL = 'Guido van Rossum'
42 FLUFL = 'Barry Warsaw'
43except Exception as exc:
44 Name = exc
45
46try:
47 Question = Enum('Question', 'who what when where why', module=__name__)
48except Exception as exc:
49 Question = exc
50
51try:
52 Answer = Enum('Answer', 'him this then there because')
53except Exception as exc:
54 Answer = exc
55
Ethan Furmanca1b7942014-02-08 11:36:27 -080056try:
57 Theory = Enum('Theory', 'rule law supposition', qualname='spanish_inquisition')
58except Exception as exc:
59 Theory = exc
60
Ethan Furman6b3d64a2013-06-14 16:55:46 -070061# for doctests
62try:
63 class Fruit(Enum):
64 tomato = 1
65 banana = 2
66 cherry = 3
67except Exception:
68 pass
69
Serhiy Storchakae50e7802015-03-31 16:56:49 +030070def test_pickle_dump_load(assertion, source, target=None):
Ethan Furman2ddb39a2014-02-06 17:28:50 -080071 if target is None:
72 target = source
Serhiy Storchakae50e7802015-03-31 16:56:49 +030073 for protocol in range(HIGHEST_PROTOCOL + 1):
Ethan Furman2ddb39a2014-02-06 17:28:50 -080074 assertion(loads(dumps(source, protocol=protocol)), target)
75
Serhiy Storchakae50e7802015-03-31 16:56:49 +030076def test_pickle_exception(assertion, exception, obj):
77 for protocol in range(HIGHEST_PROTOCOL + 1):
Ethan Furman2ddb39a2014-02-06 17:28:50 -080078 with assertion(exception):
79 dumps(obj, protocol=protocol)
Ethan Furman648f8602013-10-06 17:19:54 -070080
81class TestHelpers(unittest.TestCase):
82 # _is_descriptor, _is_sunder, _is_dunder
83
84 def test_is_descriptor(self):
85 class foo:
86 pass
87 for attr in ('__get__','__set__','__delete__'):
88 obj = foo()
89 self.assertFalse(enum._is_descriptor(obj))
90 setattr(obj, attr, 1)
91 self.assertTrue(enum._is_descriptor(obj))
92
93 def test_is_sunder(self):
94 for s in ('_a_', '_aa_'):
95 self.assertTrue(enum._is_sunder(s))
96
97 for s in ('a', 'a_', '_a', '__a', 'a__', '__a__', '_a__', '__a_', '_',
98 '__', '___', '____', '_____',):
99 self.assertFalse(enum._is_sunder(s))
100
101 def test_is_dunder(self):
102 for s in ('__a__', '__aa__'):
103 self.assertTrue(enum._is_dunder(s))
104 for s in ('a', 'a_', '_a', '__a', 'a__', '_a_', '_a__', '__a_', '_',
105 '__', '___', '____', '_____',):
106 self.assertFalse(enum._is_dunder(s))
107
108
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700109class TestEnum(unittest.TestCase):
Ethan Furmanca1b7942014-02-08 11:36:27 -0800110
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700111 def setUp(self):
112 class Season(Enum):
113 SPRING = 1
114 SUMMER = 2
115 AUTUMN = 3
116 WINTER = 4
117 self.Season = Season
118
Ethan Furmanec15a822013-08-31 19:17:41 -0700119 class Konstants(float, Enum):
120 E = 2.7182818
121 PI = 3.1415926
122 TAU = 2 * PI
123 self.Konstants = Konstants
124
125 class Grades(IntEnum):
126 A = 5
127 B = 4
128 C = 3
129 D = 2
130 F = 0
131 self.Grades = Grades
132
133 class Directional(str, Enum):
134 EAST = 'east'
135 WEST = 'west'
136 NORTH = 'north'
137 SOUTH = 'south'
138 self.Directional = Directional
139
140 from datetime import date
141 class Holiday(date, Enum):
142 NEW_YEAR = 2013, 1, 1
143 IDES_OF_MARCH = 2013, 3, 15
144 self.Holiday = Holiday
145
Ethan Furman388a3922013-08-12 06:51:41 -0700146 def test_dir_on_class(self):
147 Season = self.Season
148 self.assertEqual(
149 set(dir(Season)),
Ethan Furmanc850f342013-09-15 16:59:35 -0700150 set(['__class__', '__doc__', '__members__', '__module__',
Ethan Furman388a3922013-08-12 06:51:41 -0700151 'SPRING', 'SUMMER', 'AUTUMN', 'WINTER']),
152 )
153
154 def test_dir_on_item(self):
155 Season = self.Season
156 self.assertEqual(
157 set(dir(Season.WINTER)),
Ethan Furmanc850f342013-09-15 16:59:35 -0700158 set(['__class__', '__doc__', '__module__', 'name', 'value']),
Ethan Furman388a3922013-08-12 06:51:41 -0700159 )
160
Ethan Furmanc850f342013-09-15 16:59:35 -0700161 def test_dir_with_added_behavior(self):
162 class Test(Enum):
163 this = 'that'
164 these = 'those'
165 def wowser(self):
166 return ("Wowser! I'm %s!" % self.name)
167 self.assertEqual(
168 set(dir(Test)),
169 set(['__class__', '__doc__', '__members__', '__module__', 'this', 'these']),
170 )
171 self.assertEqual(
172 set(dir(Test.this)),
173 set(['__class__', '__doc__', '__module__', 'name', 'value', 'wowser']),
174 )
175
Ethan Furman0ae550b2014-10-14 08:58:32 -0700176 def test_dir_on_sub_with_behavior_on_super(self):
177 # see issue22506
178 class SuperEnum(Enum):
179 def invisible(self):
180 return "did you see me?"
181 class SubEnum(SuperEnum):
182 sample = 5
183 self.assertEqual(
184 set(dir(SubEnum.sample)),
185 set(['__class__', '__doc__', '__module__', 'name', 'value', 'invisible']),
186 )
187
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700188 def test_enum_in_enum_out(self):
189 Season = self.Season
190 self.assertIs(Season(Season.WINTER), Season.WINTER)
191
192 def test_enum_value(self):
193 Season = self.Season
194 self.assertEqual(Season.SPRING.value, 1)
195
196 def test_intenum_value(self):
197 self.assertEqual(IntStooges.CURLY.value, 2)
198
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700199 def test_enum(self):
200 Season = self.Season
201 lst = list(Season)
202 self.assertEqual(len(lst), len(Season))
203 self.assertEqual(len(Season), 4, Season)
204 self.assertEqual(
205 [Season.SPRING, Season.SUMMER, Season.AUTUMN, Season.WINTER], lst)
206
207 for i, season in enumerate('SPRING SUMMER AUTUMN WINTER'.split(), 1):
208 e = Season(i)
209 self.assertEqual(e, getattr(Season, season))
210 self.assertEqual(e.value, i)
211 self.assertNotEqual(e, i)
212 self.assertEqual(e.name, season)
213 self.assertIn(e, Season)
214 self.assertIs(type(e), Season)
215 self.assertIsInstance(e, Season)
216 self.assertEqual(str(e), 'Season.' + season)
217 self.assertEqual(
218 repr(e),
219 '<Season.{0}: {1}>'.format(season, i),
220 )
221
222 def test_value_name(self):
223 Season = self.Season
224 self.assertEqual(Season.SPRING.name, 'SPRING')
225 self.assertEqual(Season.SPRING.value, 1)
226 with self.assertRaises(AttributeError):
227 Season.SPRING.name = 'invierno'
228 with self.assertRaises(AttributeError):
229 Season.SPRING.value = 2
230
Ethan Furmanf203f2d2013-09-06 07:16:48 -0700231 def test_changing_member(self):
232 Season = self.Season
233 with self.assertRaises(AttributeError):
234 Season.WINTER = 'really cold'
235
Ethan Furman64a99722013-09-22 16:18:19 -0700236 def test_attribute_deletion(self):
237 class Season(Enum):
238 SPRING = 1
239 SUMMER = 2
240 AUTUMN = 3
241 WINTER = 4
242
243 def spam(cls):
244 pass
245
246 self.assertTrue(hasattr(Season, 'spam'))
247 del Season.spam
248 self.assertFalse(hasattr(Season, 'spam'))
249
250 with self.assertRaises(AttributeError):
251 del Season.SPRING
252 with self.assertRaises(AttributeError):
253 del Season.DRY
254 with self.assertRaises(AttributeError):
255 del Season.SPRING.name
256
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700257 def test_invalid_names(self):
258 with self.assertRaises(ValueError):
259 class Wrong(Enum):
260 mro = 9
261 with self.assertRaises(ValueError):
262 class Wrong(Enum):
263 _create_= 11
264 with self.assertRaises(ValueError):
265 class Wrong(Enum):
266 _get_mixins_ = 9
267 with self.assertRaises(ValueError):
268 class Wrong(Enum):
269 _find_new_ = 1
270 with self.assertRaises(ValueError):
271 class Wrong(Enum):
272 _any_name_ = 9
273
Ethan Furman6db1fd52015-09-17 21:49:12 -0700274 def test_bool(self):
Ethan Furman60255b62016-01-15 15:01:33 -0800275 # plain Enum members are always True
Ethan Furman6db1fd52015-09-17 21:49:12 -0700276 class Logic(Enum):
277 true = True
278 false = False
279 self.assertTrue(Logic.true)
Ethan Furman60255b62016-01-15 15:01:33 -0800280 self.assertTrue(Logic.false)
281 # unless overridden
282 class RealLogic(Enum):
283 true = True
284 false = False
285 def __bool__(self):
286 return bool(self._value_)
287 self.assertTrue(RealLogic.true)
288 self.assertFalse(RealLogic.false)
289 # mixed Enums depend on mixed-in type
290 class IntLogic(int, Enum):
291 true = 1
292 false = 0
293 self.assertTrue(IntLogic.true)
294 self.assertFalse(IntLogic.false)
Ethan Furman6db1fd52015-09-17 21:49:12 -0700295
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700296 def test_contains(self):
297 Season = self.Season
298 self.assertIn(Season.AUTUMN, Season)
299 self.assertNotIn(3, Season)
300
301 val = Season(3)
302 self.assertIn(val, Season)
303
304 class OtherEnum(Enum):
305 one = 1; two = 2
306 self.assertNotIn(OtherEnum.two, Season)
307
308 def test_comparisons(self):
309 Season = self.Season
310 with self.assertRaises(TypeError):
311 Season.SPRING < Season.WINTER
312 with self.assertRaises(TypeError):
313 Season.SPRING > 4
314
315 self.assertNotEqual(Season.SPRING, 1)
316
317 class Part(Enum):
318 SPRING = 1
319 CLIP = 2
320 BARREL = 3
321
322 self.assertNotEqual(Season.SPRING, Part.SPRING)
323 with self.assertRaises(TypeError):
324 Season.SPRING < Part.CLIP
325
326 def test_enum_duplicates(self):
327 class Season(Enum):
328 SPRING = 1
329 SUMMER = 2
330 AUTUMN = FALL = 3
331 WINTER = 4
332 ANOTHER_SPRING = 1
333 lst = list(Season)
334 self.assertEqual(
335 lst,
336 [Season.SPRING, Season.SUMMER,
337 Season.AUTUMN, Season.WINTER,
338 ])
339 self.assertIs(Season.FALL, Season.AUTUMN)
340 self.assertEqual(Season.FALL.value, 3)
341 self.assertEqual(Season.AUTUMN.value, 3)
342 self.assertIs(Season(3), Season.AUTUMN)
343 self.assertIs(Season(1), Season.SPRING)
344 self.assertEqual(Season.FALL.name, 'AUTUMN')
345 self.assertEqual(
346 [k for k,v in Season.__members__.items() if v.name != k],
347 ['FALL', 'ANOTHER_SPRING'],
348 )
349
Ethan Furman101e0742013-09-15 12:34:36 -0700350 def test_duplicate_name(self):
351 with self.assertRaises(TypeError):
352 class Color(Enum):
353 red = 1
354 green = 2
355 blue = 3
356 red = 4
357
358 with self.assertRaises(TypeError):
359 class Color(Enum):
360 red = 1
361 green = 2
362 blue = 3
363 def red(self):
364 return 'red'
365
366 with self.assertRaises(TypeError):
367 class Color(Enum):
368 @property
369 def red(self):
370 return 'redder'
371 red = 1
372 green = 2
373 blue = 3
374
375
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700376 def test_enum_with_value_name(self):
377 class Huh(Enum):
378 name = 1
379 value = 2
380 self.assertEqual(
381 list(Huh),
382 [Huh.name, Huh.value],
383 )
384 self.assertIs(type(Huh.name), Huh)
385 self.assertEqual(Huh.name.name, 'name')
386 self.assertEqual(Huh.name.value, 1)
Ethan Furmanec15a822013-08-31 19:17:41 -0700387
388 def test_format_enum(self):
389 Season = self.Season
390 self.assertEqual('{}'.format(Season.SPRING),
391 '{}'.format(str(Season.SPRING)))
392 self.assertEqual( '{:}'.format(Season.SPRING),
393 '{:}'.format(str(Season.SPRING)))
394 self.assertEqual('{:20}'.format(Season.SPRING),
395 '{:20}'.format(str(Season.SPRING)))
396 self.assertEqual('{:^20}'.format(Season.SPRING),
397 '{:^20}'.format(str(Season.SPRING)))
398 self.assertEqual('{:>20}'.format(Season.SPRING),
399 '{:>20}'.format(str(Season.SPRING)))
400 self.assertEqual('{:<20}'.format(Season.SPRING),
401 '{:<20}'.format(str(Season.SPRING)))
402
403 def test_format_enum_custom(self):
404 class TestFloat(float, Enum):
405 one = 1.0
406 two = 2.0
407 def __format__(self, spec):
408 return 'TestFloat success!'
409 self.assertEqual('{}'.format(TestFloat.one), 'TestFloat success!')
410
411 def assertFormatIsValue(self, spec, member):
412 self.assertEqual(spec.format(member), spec.format(member.value))
413
414 def test_format_enum_date(self):
415 Holiday = self.Holiday
416 self.assertFormatIsValue('{}', Holiday.IDES_OF_MARCH)
417 self.assertFormatIsValue('{:}', Holiday.IDES_OF_MARCH)
418 self.assertFormatIsValue('{:20}', Holiday.IDES_OF_MARCH)
419 self.assertFormatIsValue('{:^20}', Holiday.IDES_OF_MARCH)
420 self.assertFormatIsValue('{:>20}', Holiday.IDES_OF_MARCH)
421 self.assertFormatIsValue('{:<20}', Holiday.IDES_OF_MARCH)
422 self.assertFormatIsValue('{:%Y %m}', Holiday.IDES_OF_MARCH)
423 self.assertFormatIsValue('{:%Y %m %M:00}', Holiday.IDES_OF_MARCH)
424
425 def test_format_enum_float(self):
426 Konstants = self.Konstants
427 self.assertFormatIsValue('{}', Konstants.TAU)
428 self.assertFormatIsValue('{:}', Konstants.TAU)
429 self.assertFormatIsValue('{:20}', Konstants.TAU)
430 self.assertFormatIsValue('{:^20}', Konstants.TAU)
431 self.assertFormatIsValue('{:>20}', Konstants.TAU)
432 self.assertFormatIsValue('{:<20}', Konstants.TAU)
433 self.assertFormatIsValue('{:n}', Konstants.TAU)
434 self.assertFormatIsValue('{:5.2}', Konstants.TAU)
435 self.assertFormatIsValue('{:f}', Konstants.TAU)
436
437 def test_format_enum_int(self):
438 Grades = self.Grades
439 self.assertFormatIsValue('{}', Grades.C)
440 self.assertFormatIsValue('{:}', Grades.C)
441 self.assertFormatIsValue('{:20}', Grades.C)
442 self.assertFormatIsValue('{:^20}', Grades.C)
443 self.assertFormatIsValue('{:>20}', Grades.C)
444 self.assertFormatIsValue('{:<20}', Grades.C)
445 self.assertFormatIsValue('{:+}', Grades.C)
446 self.assertFormatIsValue('{:08X}', Grades.C)
447 self.assertFormatIsValue('{:b}', Grades.C)
448
449 def test_format_enum_str(self):
450 Directional = self.Directional
451 self.assertFormatIsValue('{}', Directional.WEST)
452 self.assertFormatIsValue('{:}', Directional.WEST)
453 self.assertFormatIsValue('{:20}', Directional.WEST)
454 self.assertFormatIsValue('{:^20}', Directional.WEST)
455 self.assertFormatIsValue('{:>20}', Directional.WEST)
456 self.assertFormatIsValue('{:<20}', Directional.WEST)
457
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700458 def test_hash(self):
459 Season = self.Season
460 dates = {}
461 dates[Season.WINTER] = '1225'
462 dates[Season.SPRING] = '0315'
463 dates[Season.SUMMER] = '0704'
464 dates[Season.AUTUMN] = '1031'
465 self.assertEqual(dates[Season.AUTUMN], '1031')
466
467 def test_intenum_from_scratch(self):
468 class phy(int, Enum):
469 pi = 3
470 tau = 2 * pi
471 self.assertTrue(phy.pi < phy.tau)
472
473 def test_intenum_inherited(self):
474 class IntEnum(int, Enum):
475 pass
476 class phy(IntEnum):
477 pi = 3
478 tau = 2 * pi
479 self.assertTrue(phy.pi < phy.tau)
480
481 def test_floatenum_from_scratch(self):
482 class phy(float, Enum):
Ethan Furmanec15a822013-08-31 19:17:41 -0700483 pi = 3.1415926
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700484 tau = 2 * pi
485 self.assertTrue(phy.pi < phy.tau)
486
487 def test_floatenum_inherited(self):
488 class FloatEnum(float, Enum):
489 pass
490 class phy(FloatEnum):
Ethan Furmanec15a822013-08-31 19:17:41 -0700491 pi = 3.1415926
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700492 tau = 2 * pi
493 self.assertTrue(phy.pi < phy.tau)
494
495 def test_strenum_from_scratch(self):
496 class phy(str, Enum):
497 pi = 'Pi'
498 tau = 'Tau'
499 self.assertTrue(phy.pi < phy.tau)
500
501 def test_strenum_inherited(self):
502 class StrEnum(str, Enum):
503 pass
504 class phy(StrEnum):
505 pi = 'Pi'
506 tau = 'Tau'
507 self.assertTrue(phy.pi < phy.tau)
508
509
510 def test_intenum(self):
511 class WeekDay(IntEnum):
512 SUNDAY = 1
513 MONDAY = 2
514 TUESDAY = 3
515 WEDNESDAY = 4
516 THURSDAY = 5
517 FRIDAY = 6
518 SATURDAY = 7
519
520 self.assertEqual(['a', 'b', 'c'][WeekDay.MONDAY], 'c')
521 self.assertEqual([i for i in range(WeekDay.TUESDAY)], [0, 1, 2])
522
523 lst = list(WeekDay)
524 self.assertEqual(len(lst), len(WeekDay))
525 self.assertEqual(len(WeekDay), 7)
526 target = 'SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY'
527 target = target.split()
528 for i, weekday in enumerate(target, 1):
529 e = WeekDay(i)
530 self.assertEqual(e, i)
531 self.assertEqual(int(e), i)
532 self.assertEqual(e.name, weekday)
533 self.assertIn(e, WeekDay)
534 self.assertEqual(lst.index(e)+1, i)
535 self.assertTrue(0 < e < 8)
536 self.assertIs(type(e), WeekDay)
537 self.assertIsInstance(e, int)
538 self.assertIsInstance(e, Enum)
539
540 def test_intenum_duplicates(self):
541 class WeekDay(IntEnum):
542 SUNDAY = 1
543 MONDAY = 2
544 TUESDAY = TEUSDAY = 3
545 WEDNESDAY = 4
546 THURSDAY = 5
547 FRIDAY = 6
548 SATURDAY = 7
549 self.assertIs(WeekDay.TEUSDAY, WeekDay.TUESDAY)
550 self.assertEqual(WeekDay(3).name, 'TUESDAY')
551 self.assertEqual([k for k,v in WeekDay.__members__.items()
552 if v.name != k], ['TEUSDAY', ])
553
554 def test_pickle_enum(self):
555 if isinstance(Stooges, Exception):
556 raise Stooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800557 test_pickle_dump_load(self.assertIs, Stooges.CURLY)
558 test_pickle_dump_load(self.assertIs, Stooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700559
560 def test_pickle_int(self):
561 if isinstance(IntStooges, Exception):
562 raise IntStooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800563 test_pickle_dump_load(self.assertIs, IntStooges.CURLY)
564 test_pickle_dump_load(self.assertIs, IntStooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700565
566 def test_pickle_float(self):
567 if isinstance(FloatStooges, Exception):
568 raise FloatStooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800569 test_pickle_dump_load(self.assertIs, FloatStooges.CURLY)
570 test_pickle_dump_load(self.assertIs, FloatStooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700571
572 def test_pickle_enum_function(self):
573 if isinstance(Answer, Exception):
574 raise Answer
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800575 test_pickle_dump_load(self.assertIs, Answer.him)
576 test_pickle_dump_load(self.assertIs, Answer)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700577
578 def test_pickle_enum_function_with_module(self):
579 if isinstance(Question, Exception):
580 raise Question
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800581 test_pickle_dump_load(self.assertIs, Question.who)
582 test_pickle_dump_load(self.assertIs, Question)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700583
Ethan Furmanca1b7942014-02-08 11:36:27 -0800584 def test_enum_function_with_qualname(self):
585 if isinstance(Theory, Exception):
586 raise Theory
587 self.assertEqual(Theory.__qualname__, 'spanish_inquisition')
588
589 def test_class_nested_enum_and_pickle_protocol_four(self):
590 # would normally just have this directly in the class namespace
591 class NestedEnum(Enum):
592 twigs = 'common'
593 shiny = 'rare'
594
595 self.__class__.NestedEnum = NestedEnum
596 self.NestedEnum.__qualname__ = '%s.NestedEnum' % self.__class__.__name__
Serhiy Storchakae50e7802015-03-31 16:56:49 +0300597 test_pickle_dump_load(self.assertIs, self.NestedEnum.twigs)
Ethan Furmanca1b7942014-02-08 11:36:27 -0800598
Ethan Furman24e837f2015-03-18 17:27:57 -0700599 def test_pickle_by_name(self):
600 class ReplaceGlobalInt(IntEnum):
601 ONE = 1
602 TWO = 2
603 ReplaceGlobalInt.__reduce_ex__ = enum._reduce_ex_by_name
604 for proto in range(HIGHEST_PROTOCOL):
605 self.assertEqual(ReplaceGlobalInt.TWO.__reduce_ex__(proto), 'TWO')
606
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700607 def test_exploding_pickle(self):
Ethan Furmanca1b7942014-02-08 11:36:27 -0800608 BadPickle = Enum(
609 'BadPickle', 'dill sweet bread-n-butter', module=__name__)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700610 globals()['BadPickle'] = BadPickle
Ethan Furmanca1b7942014-02-08 11:36:27 -0800611 # now break BadPickle to test exception raising
612 enum._make_class_unpicklable(BadPickle)
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800613 test_pickle_exception(self.assertRaises, TypeError, BadPickle.dill)
614 test_pickle_exception(self.assertRaises, PicklingError, BadPickle)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700615
616 def test_string_enum(self):
617 class SkillLevel(str, Enum):
618 master = 'what is the sound of one hand clapping?'
619 journeyman = 'why did the chicken cross the road?'
620 apprentice = 'knock, knock!'
621 self.assertEqual(SkillLevel.apprentice, 'knock, knock!')
622
623 def test_getattr_getitem(self):
624 class Period(Enum):
625 morning = 1
626 noon = 2
627 evening = 3
628 night = 4
629 self.assertIs(Period(2), Period.noon)
630 self.assertIs(getattr(Period, 'night'), Period.night)
631 self.assertIs(Period['morning'], Period.morning)
632
633 def test_getattr_dunder(self):
634 Season = self.Season
635 self.assertTrue(getattr(Season, '__eq__'))
636
637 def test_iteration_order(self):
638 class Season(Enum):
639 SUMMER = 2
640 WINTER = 4
641 AUTUMN = 3
642 SPRING = 1
643 self.assertEqual(
644 list(Season),
645 [Season.SUMMER, Season.WINTER, Season.AUTUMN, Season.SPRING],
646 )
647
Ethan Furman2131a4a2013-09-14 18:11:24 -0700648 def test_reversed_iteration_order(self):
649 self.assertEqual(
650 list(reversed(self.Season)),
651 [self.Season.WINTER, self.Season.AUTUMN, self.Season.SUMMER,
652 self.Season.SPRING]
653 )
654
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700655 def test_programatic_function_string(self):
656 SummerMonth = Enum('SummerMonth', 'june july august')
657 lst = list(SummerMonth)
658 self.assertEqual(len(lst), len(SummerMonth))
659 self.assertEqual(len(SummerMonth), 3, SummerMonth)
660 self.assertEqual(
661 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
662 lst,
663 )
664 for i, month in enumerate('june july august'.split(), 1):
665 e = SummerMonth(i)
666 self.assertEqual(int(e.value), i)
667 self.assertNotEqual(e, i)
668 self.assertEqual(e.name, month)
669 self.assertIn(e, SummerMonth)
670 self.assertIs(type(e), SummerMonth)
671
Ethan Furmand9925a12014-09-16 20:35:55 -0700672 def test_programatic_function_string_with_start(self):
673 SummerMonth = Enum('SummerMonth', 'june july august', start=10)
674 lst = list(SummerMonth)
675 self.assertEqual(len(lst), len(SummerMonth))
676 self.assertEqual(len(SummerMonth), 3, SummerMonth)
677 self.assertEqual(
678 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
679 lst,
680 )
681 for i, month in enumerate('june july august'.split(), 10):
682 e = SummerMonth(i)
683 self.assertEqual(int(e.value), i)
684 self.assertNotEqual(e, i)
685 self.assertEqual(e.name, month)
686 self.assertIn(e, SummerMonth)
687 self.assertIs(type(e), SummerMonth)
688
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700689 def test_programatic_function_string_list(self):
690 SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'])
691 lst = list(SummerMonth)
692 self.assertEqual(len(lst), len(SummerMonth))
693 self.assertEqual(len(SummerMonth), 3, SummerMonth)
694 self.assertEqual(
695 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
696 lst,
697 )
698 for i, month in enumerate('june july august'.split(), 1):
699 e = SummerMonth(i)
700 self.assertEqual(int(e.value), i)
701 self.assertNotEqual(e, i)
702 self.assertEqual(e.name, month)
703 self.assertIn(e, SummerMonth)
704 self.assertIs(type(e), SummerMonth)
705
Ethan Furmand9925a12014-09-16 20:35:55 -0700706 def test_programatic_function_string_list_with_start(self):
707 SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'], start=20)
708 lst = list(SummerMonth)
709 self.assertEqual(len(lst), len(SummerMonth))
710 self.assertEqual(len(SummerMonth), 3, SummerMonth)
711 self.assertEqual(
712 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
713 lst,
714 )
715 for i, month in enumerate('june july august'.split(), 20):
716 e = SummerMonth(i)
717 self.assertEqual(int(e.value), i)
718 self.assertNotEqual(e, i)
719 self.assertEqual(e.name, month)
720 self.assertIn(e, SummerMonth)
721 self.assertIs(type(e), SummerMonth)
722
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700723 def test_programatic_function_iterable(self):
724 SummerMonth = Enum(
725 'SummerMonth',
726 (('june', 1), ('july', 2), ('august', 3))
727 )
728 lst = list(SummerMonth)
729 self.assertEqual(len(lst), len(SummerMonth))
730 self.assertEqual(len(SummerMonth), 3, SummerMonth)
731 self.assertEqual(
732 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
733 lst,
734 )
735 for i, month in enumerate('june july august'.split(), 1):
736 e = SummerMonth(i)
737 self.assertEqual(int(e.value), i)
738 self.assertNotEqual(e, i)
739 self.assertEqual(e.name, month)
740 self.assertIn(e, SummerMonth)
741 self.assertIs(type(e), SummerMonth)
742
743 def test_programatic_function_from_dict(self):
744 SummerMonth = Enum(
745 'SummerMonth',
746 OrderedDict((('june', 1), ('july', 2), ('august', 3)))
747 )
748 lst = list(SummerMonth)
749 self.assertEqual(len(lst), len(SummerMonth))
750 self.assertEqual(len(SummerMonth), 3, SummerMonth)
751 self.assertEqual(
752 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
753 lst,
754 )
755 for i, month in enumerate('june july august'.split(), 1):
756 e = SummerMonth(i)
757 self.assertEqual(int(e.value), i)
758 self.assertNotEqual(e, i)
759 self.assertEqual(e.name, month)
760 self.assertIn(e, SummerMonth)
761 self.assertIs(type(e), SummerMonth)
762
763 def test_programatic_function_type(self):
764 SummerMonth = Enum('SummerMonth', 'june july august', type=int)
765 lst = list(SummerMonth)
766 self.assertEqual(len(lst), len(SummerMonth))
767 self.assertEqual(len(SummerMonth), 3, SummerMonth)
768 self.assertEqual(
769 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
770 lst,
771 )
772 for i, month in enumerate('june july august'.split(), 1):
773 e = SummerMonth(i)
774 self.assertEqual(e, i)
775 self.assertEqual(e.name, month)
776 self.assertIn(e, SummerMonth)
777 self.assertIs(type(e), SummerMonth)
778
Ethan Furmand9925a12014-09-16 20:35:55 -0700779 def test_programatic_function_type_with_start(self):
780 SummerMonth = Enum('SummerMonth', 'june july august', type=int, start=30)
781 lst = list(SummerMonth)
782 self.assertEqual(len(lst), len(SummerMonth))
783 self.assertEqual(len(SummerMonth), 3, SummerMonth)
784 self.assertEqual(
785 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
786 lst,
787 )
788 for i, month in enumerate('june july august'.split(), 30):
789 e = SummerMonth(i)
790 self.assertEqual(e, i)
791 self.assertEqual(e.name, month)
792 self.assertIn(e, SummerMonth)
793 self.assertIs(type(e), SummerMonth)
794
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700795 def test_programatic_function_type_from_subclass(self):
796 SummerMonth = IntEnum('SummerMonth', 'june july august')
797 lst = list(SummerMonth)
798 self.assertEqual(len(lst), len(SummerMonth))
799 self.assertEqual(len(SummerMonth), 3, SummerMonth)
800 self.assertEqual(
801 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
802 lst,
803 )
804 for i, month in enumerate('june july august'.split(), 1):
805 e = SummerMonth(i)
806 self.assertEqual(e, i)
807 self.assertEqual(e.name, month)
808 self.assertIn(e, SummerMonth)
809 self.assertIs(type(e), SummerMonth)
810
Ethan Furmand9925a12014-09-16 20:35:55 -0700811 def test_programatic_function_type_from_subclass_with_start(self):
812 SummerMonth = IntEnum('SummerMonth', 'june july august', start=40)
813 lst = list(SummerMonth)
814 self.assertEqual(len(lst), len(SummerMonth))
815 self.assertEqual(len(SummerMonth), 3, SummerMonth)
816 self.assertEqual(
817 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
818 lst,
819 )
820 for i, month in enumerate('june july august'.split(), 40):
821 e = SummerMonth(i)
822 self.assertEqual(e, i)
823 self.assertEqual(e.name, month)
824 self.assertIn(e, SummerMonth)
825 self.assertIs(type(e), SummerMonth)
826
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700827 def test_subclassing(self):
828 if isinstance(Name, Exception):
829 raise Name
830 self.assertEqual(Name.BDFL, 'Guido van Rossum')
831 self.assertTrue(Name.BDFL, Name('Guido van Rossum'))
832 self.assertIs(Name.BDFL, getattr(Name, 'BDFL'))
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800833 test_pickle_dump_load(self.assertIs, Name.BDFL)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700834
835 def test_extending(self):
836 class Color(Enum):
837 red = 1
838 green = 2
839 blue = 3
840 with self.assertRaises(TypeError):
841 class MoreColor(Color):
842 cyan = 4
843 magenta = 5
844 yellow = 6
845
846 def test_exclude_methods(self):
847 class whatever(Enum):
848 this = 'that'
849 these = 'those'
850 def really(self):
851 return 'no, not %s' % self.value
852 self.assertIsNot(type(whatever.really), whatever)
853 self.assertEqual(whatever.this.really(), 'no, not that')
854
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700855 def test_wrong_inheritance_order(self):
856 with self.assertRaises(TypeError):
857 class Wrong(Enum, str):
858 NotHere = 'error before this point'
859
860 def test_intenum_transitivity(self):
861 class number(IntEnum):
862 one = 1
863 two = 2
864 three = 3
865 class numero(IntEnum):
866 uno = 1
867 dos = 2
868 tres = 3
869 self.assertEqual(number.one, numero.uno)
870 self.assertEqual(number.two, numero.dos)
871 self.assertEqual(number.three, numero.tres)
872
873 def test_wrong_enum_in_call(self):
874 class Monochrome(Enum):
875 black = 0
876 white = 1
877 class Gender(Enum):
878 male = 0
879 female = 1
880 self.assertRaises(ValueError, Monochrome, Gender.male)
881
882 def test_wrong_enum_in_mixed_call(self):
883 class Monochrome(IntEnum):
884 black = 0
885 white = 1
886 class Gender(Enum):
887 male = 0
888 female = 1
889 self.assertRaises(ValueError, Monochrome, Gender.male)
890
891 def test_mixed_enum_in_call_1(self):
892 class Monochrome(IntEnum):
893 black = 0
894 white = 1
895 class Gender(IntEnum):
896 male = 0
897 female = 1
898 self.assertIs(Monochrome(Gender.female), Monochrome.white)
899
900 def test_mixed_enum_in_call_2(self):
901 class Monochrome(Enum):
902 black = 0
903 white = 1
904 class Gender(IntEnum):
905 male = 0
906 female = 1
907 self.assertIs(Monochrome(Gender.male), Monochrome.black)
908
909 def test_flufl_enum(self):
910 class Fluflnum(Enum):
911 def __int__(self):
912 return int(self.value)
913 class MailManOptions(Fluflnum):
914 option1 = 1
915 option2 = 2
916 option3 = 3
917 self.assertEqual(int(MailManOptions.option1), 1)
918
Ethan Furman5e5a8232013-08-04 08:42:23 -0700919 def test_introspection(self):
920 class Number(IntEnum):
921 one = 100
922 two = 200
923 self.assertIs(Number.one._member_type_, int)
924 self.assertIs(Number._member_type_, int)
925 class String(str, Enum):
926 yarn = 'soft'
927 rope = 'rough'
928 wire = 'hard'
929 self.assertIs(String.yarn._member_type_, str)
930 self.assertIs(String._member_type_, str)
931 class Plain(Enum):
932 vanilla = 'white'
933 one = 1
934 self.assertIs(Plain.vanilla._member_type_, object)
935 self.assertIs(Plain._member_type_, object)
936
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700937 def test_no_such_enum_member(self):
938 class Color(Enum):
939 red = 1
940 green = 2
941 blue = 3
942 with self.assertRaises(ValueError):
943 Color(4)
944 with self.assertRaises(KeyError):
945 Color['chartreuse']
946
947 def test_new_repr(self):
948 class Color(Enum):
949 red = 1
950 green = 2
951 blue = 3
952 def __repr__(self):
953 return "don't you just love shades of %s?" % self.name
954 self.assertEqual(
955 repr(Color.blue),
956 "don't you just love shades of blue?",
957 )
958
959 def test_inherited_repr(self):
960 class MyEnum(Enum):
961 def __repr__(self):
962 return "My name is %s." % self.name
963 class MyIntEnum(int, MyEnum):
964 this = 1
965 that = 2
966 theother = 3
967 self.assertEqual(repr(MyIntEnum.that), "My name is that.")
968
969 def test_multiple_mixin_mro(self):
970 class auto_enum(type(Enum)):
971 def __new__(metacls, cls, bases, classdict):
972 temp = type(classdict)()
973 names = set(classdict._member_names)
974 i = 0
975 for k in classdict._member_names:
976 v = classdict[k]
977 if v is Ellipsis:
978 v = i
979 else:
980 i = v
981 i += 1
982 temp[k] = v
983 for k, v in classdict.items():
984 if k not in names:
985 temp[k] = v
986 return super(auto_enum, metacls).__new__(
987 metacls, cls, bases, temp)
988
989 class AutoNumberedEnum(Enum, metaclass=auto_enum):
990 pass
991
992 class AutoIntEnum(IntEnum, metaclass=auto_enum):
993 pass
994
995 class TestAutoNumber(AutoNumberedEnum):
996 a = ...
997 b = 3
998 c = ...
999
1000 class TestAutoInt(AutoIntEnum):
1001 a = ...
1002 b = 3
1003 c = ...
1004
1005 def test_subclasses_with_getnewargs(self):
1006 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001007 __qualname__ = 'NamedInt' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001008 def __new__(cls, *args):
1009 _args = args
1010 name, *args = args
1011 if len(args) == 0:
1012 raise TypeError("name and value must be specified")
1013 self = int.__new__(cls, *args)
1014 self._intname = name
1015 self._args = _args
1016 return self
1017 def __getnewargs__(self):
1018 return self._args
1019 @property
1020 def __name__(self):
1021 return self._intname
1022 def __repr__(self):
1023 # repr() is updated to include the name and type info
1024 return "{}({!r}, {})".format(type(self).__name__,
1025 self.__name__,
1026 int.__repr__(self))
1027 def __str__(self):
1028 # str() is unchanged, even if it relies on the repr() fallback
1029 base = int
1030 base_str = base.__str__
1031 if base_str.__objclass__ is object:
1032 return base.__repr__(self)
1033 return base_str(self)
1034 # for simplicity, we only define one operator that
1035 # propagates expressions
1036 def __add__(self, other):
1037 temp = int(self) + int( other)
1038 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1039 return NamedInt(
1040 '({0} + {1})'.format(self.__name__, other.__name__),
1041 temp )
1042 else:
1043 return temp
1044
1045 class NEI(NamedInt, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001046 __qualname__ = 'NEI' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001047 x = ('the-x', 1)
1048 y = ('the-y', 2)
1049
Ethan Furman2aa27322013-07-19 19:35:56 -07001050
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001051 self.assertIs(NEI.__new__, Enum.__new__)
1052 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1053 globals()['NamedInt'] = NamedInt
1054 globals()['NEI'] = NEI
1055 NI5 = NamedInt('test', 5)
1056 self.assertEqual(NI5, 5)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001057 test_pickle_dump_load(self.assertEqual, NI5, 5)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001058 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001059 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001060 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001061
Ethan Furmanca1b7942014-02-08 11:36:27 -08001062 def test_subclasses_with_getnewargs_ex(self):
1063 class NamedInt(int):
1064 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1065 def __new__(cls, *args):
1066 _args = args
1067 name, *args = args
1068 if len(args) == 0:
1069 raise TypeError("name and value must be specified")
1070 self = int.__new__(cls, *args)
1071 self._intname = name
1072 self._args = _args
1073 return self
1074 def __getnewargs_ex__(self):
1075 return self._args, {}
1076 @property
1077 def __name__(self):
1078 return self._intname
1079 def __repr__(self):
1080 # repr() is updated to include the name and type info
1081 return "{}({!r}, {})".format(type(self).__name__,
1082 self.__name__,
1083 int.__repr__(self))
1084 def __str__(self):
1085 # str() is unchanged, even if it relies on the repr() fallback
1086 base = int
1087 base_str = base.__str__
1088 if base_str.__objclass__ is object:
1089 return base.__repr__(self)
1090 return base_str(self)
1091 # for simplicity, we only define one operator that
1092 # propagates expressions
1093 def __add__(self, other):
1094 temp = int(self) + int( other)
1095 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1096 return NamedInt(
1097 '({0} + {1})'.format(self.__name__, other.__name__),
1098 temp )
1099 else:
1100 return temp
1101
1102 class NEI(NamedInt, Enum):
1103 __qualname__ = 'NEI' # needed for pickle protocol 4
1104 x = ('the-x', 1)
1105 y = ('the-y', 2)
1106
1107
1108 self.assertIs(NEI.__new__, Enum.__new__)
1109 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1110 globals()['NamedInt'] = NamedInt
1111 globals()['NEI'] = NEI
1112 NI5 = NamedInt('test', 5)
1113 self.assertEqual(NI5, 5)
Serhiy Storchakae50e7802015-03-31 16:56:49 +03001114 test_pickle_dump_load(self.assertEqual, NI5, 5)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001115 self.assertEqual(NEI.y.value, 2)
Serhiy Storchakae50e7802015-03-31 16:56:49 +03001116 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001117 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001118
1119 def test_subclasses_with_reduce(self):
1120 class NamedInt(int):
1121 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1122 def __new__(cls, *args):
1123 _args = args
1124 name, *args = args
1125 if len(args) == 0:
1126 raise TypeError("name and value must be specified")
1127 self = int.__new__(cls, *args)
1128 self._intname = name
1129 self._args = _args
1130 return self
1131 def __reduce__(self):
1132 return self.__class__, self._args
1133 @property
1134 def __name__(self):
1135 return self._intname
1136 def __repr__(self):
1137 # repr() is updated to include the name and type info
1138 return "{}({!r}, {})".format(type(self).__name__,
1139 self.__name__,
1140 int.__repr__(self))
1141 def __str__(self):
1142 # str() is unchanged, even if it relies on the repr() fallback
1143 base = int
1144 base_str = base.__str__
1145 if base_str.__objclass__ is object:
1146 return base.__repr__(self)
1147 return base_str(self)
1148 # for simplicity, we only define one operator that
1149 # propagates expressions
1150 def __add__(self, other):
1151 temp = int(self) + int( other)
1152 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1153 return NamedInt(
1154 '({0} + {1})'.format(self.__name__, other.__name__),
1155 temp )
1156 else:
1157 return temp
1158
1159 class NEI(NamedInt, Enum):
1160 __qualname__ = 'NEI' # needed for pickle protocol 4
1161 x = ('the-x', 1)
1162 y = ('the-y', 2)
1163
1164
1165 self.assertIs(NEI.__new__, Enum.__new__)
1166 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1167 globals()['NamedInt'] = NamedInt
1168 globals()['NEI'] = NEI
1169 NI5 = NamedInt('test', 5)
1170 self.assertEqual(NI5, 5)
1171 test_pickle_dump_load(self.assertEqual, NI5, 5)
1172 self.assertEqual(NEI.y.value, 2)
1173 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001174 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001175
1176 def test_subclasses_with_reduce_ex(self):
1177 class NamedInt(int):
1178 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1179 def __new__(cls, *args):
1180 _args = args
1181 name, *args = args
1182 if len(args) == 0:
1183 raise TypeError("name and value must be specified")
1184 self = int.__new__(cls, *args)
1185 self._intname = name
1186 self._args = _args
1187 return self
1188 def __reduce_ex__(self, proto):
1189 return self.__class__, self._args
1190 @property
1191 def __name__(self):
1192 return self._intname
1193 def __repr__(self):
1194 # repr() is updated to include the name and type info
1195 return "{}({!r}, {})".format(type(self).__name__,
1196 self.__name__,
1197 int.__repr__(self))
1198 def __str__(self):
1199 # str() is unchanged, even if it relies on the repr() fallback
1200 base = int
1201 base_str = base.__str__
1202 if base_str.__objclass__ is object:
1203 return base.__repr__(self)
1204 return base_str(self)
1205 # for simplicity, we only define one operator that
1206 # propagates expressions
1207 def __add__(self, other):
1208 temp = int(self) + int( other)
1209 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1210 return NamedInt(
1211 '({0} + {1})'.format(self.__name__, other.__name__),
1212 temp )
1213 else:
1214 return temp
1215
1216 class NEI(NamedInt, Enum):
1217 __qualname__ = 'NEI' # needed for pickle protocol 4
1218 x = ('the-x', 1)
1219 y = ('the-y', 2)
1220
1221
1222 self.assertIs(NEI.__new__, Enum.__new__)
1223 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1224 globals()['NamedInt'] = NamedInt
1225 globals()['NEI'] = NEI
1226 NI5 = NamedInt('test', 5)
1227 self.assertEqual(NI5, 5)
1228 test_pickle_dump_load(self.assertEqual, NI5, 5)
1229 self.assertEqual(NEI.y.value, 2)
1230 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001231 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001232
Ethan Furmandc870522014-02-18 12:37:12 -08001233 def test_subclasses_without_direct_pickle_support(self):
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001234 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001235 __qualname__ = 'NamedInt'
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001236 def __new__(cls, *args):
1237 _args = args
1238 name, *args = args
1239 if len(args) == 0:
1240 raise TypeError("name and value must be specified")
1241 self = int.__new__(cls, *args)
1242 self._intname = name
1243 self._args = _args
1244 return self
1245 @property
1246 def __name__(self):
1247 return self._intname
1248 def __repr__(self):
1249 # repr() is updated to include the name and type info
1250 return "{}({!r}, {})".format(type(self).__name__,
1251 self.__name__,
1252 int.__repr__(self))
1253 def __str__(self):
1254 # str() is unchanged, even if it relies on the repr() fallback
1255 base = int
1256 base_str = base.__str__
1257 if base_str.__objclass__ is object:
1258 return base.__repr__(self)
1259 return base_str(self)
1260 # for simplicity, we only define one operator that
1261 # propagates expressions
1262 def __add__(self, other):
1263 temp = int(self) + int( other)
1264 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1265 return NamedInt(
1266 '({0} + {1})'.format(self.__name__, other.__name__),
1267 temp )
1268 else:
1269 return temp
1270
1271 class NEI(NamedInt, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001272 __qualname__ = 'NEI'
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001273 x = ('the-x', 1)
1274 y = ('the-y', 2)
1275
1276 self.assertIs(NEI.__new__, Enum.__new__)
1277 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1278 globals()['NamedInt'] = NamedInt
1279 globals()['NEI'] = NEI
1280 NI5 = NamedInt('test', 5)
1281 self.assertEqual(NI5, 5)
1282 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001283 test_pickle_exception(self.assertRaises, TypeError, NEI.x)
1284 test_pickle_exception(self.assertRaises, PicklingError, NEI)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001285
Ethan Furmandc870522014-02-18 12:37:12 -08001286 def test_subclasses_without_direct_pickle_support_using_name(self):
1287 class NamedInt(int):
1288 __qualname__ = 'NamedInt'
1289 def __new__(cls, *args):
1290 _args = args
1291 name, *args = args
1292 if len(args) == 0:
1293 raise TypeError("name and value must be specified")
1294 self = int.__new__(cls, *args)
1295 self._intname = name
1296 self._args = _args
1297 return self
1298 @property
1299 def __name__(self):
1300 return self._intname
1301 def __repr__(self):
1302 # repr() is updated to include the name and type info
1303 return "{}({!r}, {})".format(type(self).__name__,
1304 self.__name__,
1305 int.__repr__(self))
1306 def __str__(self):
1307 # str() is unchanged, even if it relies on the repr() fallback
1308 base = int
1309 base_str = base.__str__
1310 if base_str.__objclass__ is object:
1311 return base.__repr__(self)
1312 return base_str(self)
1313 # for simplicity, we only define one operator that
1314 # propagates expressions
1315 def __add__(self, other):
1316 temp = int(self) + int( other)
1317 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1318 return NamedInt(
1319 '({0} + {1})'.format(self.__name__, other.__name__),
1320 temp )
1321 else:
1322 return temp
1323
1324 class NEI(NamedInt, Enum):
1325 __qualname__ = 'NEI'
1326 x = ('the-x', 1)
1327 y = ('the-y', 2)
1328 def __reduce_ex__(self, proto):
1329 return getattr, (self.__class__, self._name_)
1330
1331 self.assertIs(NEI.__new__, Enum.__new__)
1332 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1333 globals()['NamedInt'] = NamedInt
1334 globals()['NEI'] = NEI
1335 NI5 = NamedInt('test', 5)
1336 self.assertEqual(NI5, 5)
1337 self.assertEqual(NEI.y.value, 2)
1338 test_pickle_dump_load(self.assertIs, NEI.y)
1339 test_pickle_dump_load(self.assertIs, NEI)
1340
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001341 def test_tuple_subclass(self):
1342 class SomeTuple(tuple, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001343 __qualname__ = 'SomeTuple' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001344 first = (1, 'for the money')
1345 second = (2, 'for the show')
1346 third = (3, 'for the music')
1347 self.assertIs(type(SomeTuple.first), SomeTuple)
1348 self.assertIsInstance(SomeTuple.second, tuple)
1349 self.assertEqual(SomeTuple.third, (3, 'for the music'))
1350 globals()['SomeTuple'] = SomeTuple
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001351 test_pickle_dump_load(self.assertIs, SomeTuple.first)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001352
1353 def test_duplicate_values_give_unique_enum_items(self):
1354 class AutoNumber(Enum):
1355 first = ()
1356 second = ()
1357 third = ()
1358 def __new__(cls):
1359 value = len(cls.__members__) + 1
1360 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001361 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001362 return obj
1363 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001364 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001365 self.assertEqual(
1366 list(AutoNumber),
1367 [AutoNumber.first, AutoNumber.second, AutoNumber.third],
1368 )
1369 self.assertEqual(int(AutoNumber.second), 2)
Ethan Furman2aa27322013-07-19 19:35:56 -07001370 self.assertEqual(AutoNumber.third.value, 3)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001371 self.assertIs(AutoNumber(1), AutoNumber.first)
1372
1373 def test_inherited_new_from_enhanced_enum(self):
1374 class AutoNumber(Enum):
1375 def __new__(cls):
1376 value = len(cls.__members__) + 1
1377 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001378 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001379 return obj
1380 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001381 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001382 class Color(AutoNumber):
1383 red = ()
1384 green = ()
1385 blue = ()
1386 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1387 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1388
1389 def test_inherited_new_from_mixed_enum(self):
1390 class AutoNumber(IntEnum):
1391 def __new__(cls):
1392 value = len(cls.__members__) + 1
1393 obj = int.__new__(cls, value)
Ethan Furman520ad572013-07-19 19:47:21 -07001394 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001395 return obj
1396 class Color(AutoNumber):
1397 red = ()
1398 green = ()
1399 blue = ()
1400 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1401 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1402
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001403 def test_equality(self):
1404 class AlwaysEqual:
1405 def __eq__(self, other):
1406 return True
1407 class OrdinaryEnum(Enum):
1408 a = 1
1409 self.assertEqual(AlwaysEqual(), OrdinaryEnum.a)
1410 self.assertEqual(OrdinaryEnum.a, AlwaysEqual())
1411
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001412 def test_ordered_mixin(self):
1413 class OrderedEnum(Enum):
1414 def __ge__(self, other):
1415 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001416 return self._value_ >= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001417 return NotImplemented
1418 def __gt__(self, other):
1419 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001420 return self._value_ > other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001421 return NotImplemented
1422 def __le__(self, other):
1423 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001424 return self._value_ <= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001425 return NotImplemented
1426 def __lt__(self, other):
1427 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001428 return self._value_ < other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001429 return NotImplemented
1430 class Grade(OrderedEnum):
1431 A = 5
1432 B = 4
1433 C = 3
1434 D = 2
1435 F = 1
1436 self.assertGreater(Grade.A, Grade.B)
1437 self.assertLessEqual(Grade.F, Grade.C)
1438 self.assertLess(Grade.D, Grade.A)
1439 self.assertGreaterEqual(Grade.B, Grade.B)
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001440 self.assertEqual(Grade.B, Grade.B)
1441 self.assertNotEqual(Grade.C, Grade.D)
Ethan Furman520ad572013-07-19 19:47:21 -07001442
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001443 def test_extending2(self):
1444 class Shade(Enum):
1445 def shade(self):
1446 print(self.name)
1447 class Color(Shade):
1448 red = 1
1449 green = 2
1450 blue = 3
1451 with self.assertRaises(TypeError):
1452 class MoreColor(Color):
1453 cyan = 4
1454 magenta = 5
1455 yellow = 6
1456
1457 def test_extending3(self):
1458 class Shade(Enum):
1459 def shade(self):
1460 return self.name
1461 class Color(Shade):
1462 def hex(self):
1463 return '%s hexlified!' % self.value
1464 class MoreColor(Color):
1465 cyan = 4
1466 magenta = 5
1467 yellow = 6
1468 self.assertEqual(MoreColor.magenta.hex(), '5 hexlified!')
1469
1470
1471 def test_no_duplicates(self):
1472 class UniqueEnum(Enum):
1473 def __init__(self, *args):
1474 cls = self.__class__
1475 if any(self.value == e.value for e in cls):
1476 a = self.name
1477 e = cls(self.value).name
1478 raise ValueError(
1479 "aliases not allowed in UniqueEnum: %r --> %r"
1480 % (a, e)
1481 )
1482 class Color(UniqueEnum):
1483 red = 1
1484 green = 2
1485 blue = 3
1486 with self.assertRaises(ValueError):
1487 class Color(UniqueEnum):
1488 red = 1
1489 green = 2
1490 blue = 3
1491 grene = 2
1492
1493 def test_init(self):
1494 class Planet(Enum):
1495 MERCURY = (3.303e+23, 2.4397e6)
1496 VENUS = (4.869e+24, 6.0518e6)
1497 EARTH = (5.976e+24, 6.37814e6)
1498 MARS = (6.421e+23, 3.3972e6)
1499 JUPITER = (1.9e+27, 7.1492e7)
1500 SATURN = (5.688e+26, 6.0268e7)
1501 URANUS = (8.686e+25, 2.5559e7)
1502 NEPTUNE = (1.024e+26, 2.4746e7)
1503 def __init__(self, mass, radius):
1504 self.mass = mass # in kilograms
1505 self.radius = radius # in meters
1506 @property
1507 def surface_gravity(self):
1508 # universal gravitational constant (m3 kg-1 s-2)
1509 G = 6.67300E-11
1510 return G * self.mass / (self.radius * self.radius)
1511 self.assertEqual(round(Planet.EARTH.surface_gravity, 2), 9.80)
1512 self.assertEqual(Planet.EARTH.value, (5.976e+24, 6.37814e6))
1513
Ethan Furman2aa27322013-07-19 19:35:56 -07001514 def test_nonhash_value(self):
1515 class AutoNumberInAList(Enum):
1516 def __new__(cls):
1517 value = [len(cls.__members__) + 1]
1518 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001519 obj._value_ = value
Ethan Furman2aa27322013-07-19 19:35:56 -07001520 return obj
1521 class ColorInAList(AutoNumberInAList):
1522 red = ()
1523 green = ()
1524 blue = ()
1525 self.assertEqual(list(ColorInAList), [ColorInAList.red, ColorInAList.green, ColorInAList.blue])
Ethan Furman1a162882013-10-16 19:09:31 -07001526 for enum, value in zip(ColorInAList, range(3)):
1527 value += 1
1528 self.assertEqual(enum.value, [value])
1529 self.assertIs(ColorInAList([value]), enum)
Ethan Furman2aa27322013-07-19 19:35:56 -07001530
Ethan Furmanb41803e2013-07-25 13:50:45 -07001531 def test_conflicting_types_resolved_in_new(self):
1532 class LabelledIntEnum(int, Enum):
1533 def __new__(cls, *args):
1534 value, label = args
1535 obj = int.__new__(cls, value)
1536 obj.label = label
1537 obj._value_ = value
1538 return obj
1539
1540 class LabelledList(LabelledIntEnum):
1541 unprocessed = (1, "Unprocessed")
1542 payment_complete = (2, "Payment Complete")
1543
1544 self.assertEqual(list(LabelledList), [LabelledList.unprocessed, LabelledList.payment_complete])
1545 self.assertEqual(LabelledList.unprocessed, 1)
1546 self.assertEqual(LabelledList(1), LabelledList.unprocessed)
Ethan Furman2aa27322013-07-19 19:35:56 -07001547
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001548
Ethan Furmanf24bb352013-07-18 17:05:39 -07001549class TestUnique(unittest.TestCase):
1550
1551 def test_unique_clean(self):
1552 @unique
1553 class Clean(Enum):
1554 one = 1
1555 two = 'dos'
1556 tres = 4.0
1557 @unique
1558 class Cleaner(IntEnum):
1559 single = 1
1560 double = 2
1561 triple = 3
1562
1563 def test_unique_dirty(self):
1564 with self.assertRaisesRegex(ValueError, 'tres.*one'):
1565 @unique
1566 class Dirty(Enum):
1567 one = 1
1568 two = 'dos'
1569 tres = 1
1570 with self.assertRaisesRegex(
1571 ValueError,
1572 'double.*single.*turkey.*triple',
1573 ):
1574 @unique
1575 class Dirtier(IntEnum):
1576 single = 1
1577 double = 1
1578 triple = 3
1579 turkey = 3
1580
1581
Ethan Furman3323da92015-04-11 09:39:59 -07001582expected_help_output_with_docs = """\
Ethan Furman5875d742013-10-21 20:45:55 -07001583Help on class Color in module %s:
1584
1585class Color(enum.Enum)
Ethan Furman48a724f2015-04-11 23:23:06 -07001586 | An enumeration.
Serhiy Storchakab599ca82015-04-04 12:48:04 +03001587 |\x20\x20
Ethan Furman5875d742013-10-21 20:45:55 -07001588 | Method resolution order:
1589 | Color
1590 | enum.Enum
1591 | builtins.object
1592 |\x20\x20
1593 | Data and other attributes defined here:
1594 |\x20\x20
1595 | blue = <Color.blue: 3>
1596 |\x20\x20
1597 | green = <Color.green: 2>
1598 |\x20\x20
1599 | red = <Color.red: 1>
1600 |\x20\x20
1601 | ----------------------------------------------------------------------
1602 | Data descriptors inherited from enum.Enum:
1603 |\x20\x20
1604 | name
1605 | The name of the Enum member.
1606 |\x20\x20
1607 | value
1608 | The value of the Enum member.
1609 |\x20\x20
1610 | ----------------------------------------------------------------------
1611 | Data descriptors inherited from enum.EnumMeta:
1612 |\x20\x20
1613 | __members__
1614 | Returns a mapping of member name->value.
1615 |\x20\x20\x20\x20\x20\x20
1616 | This mapping lists all enum members, including aliases. Note that this
Ethan Furman3323da92015-04-11 09:39:59 -07001617 | is a read-only view of the internal mapping."""
1618
1619expected_help_output_without_docs = """\
1620Help on class Color in module %s:
1621
1622class Color(enum.Enum)
1623 | Method resolution order:
1624 | Color
1625 | enum.Enum
1626 | builtins.object
1627 |\x20\x20
1628 | Data and other attributes defined here:
1629 |\x20\x20
1630 | blue = <Color.blue: 3>
1631 |\x20\x20
1632 | green = <Color.green: 2>
1633 |\x20\x20
1634 | red = <Color.red: 1>
1635 |\x20\x20
1636 | ----------------------------------------------------------------------
1637 | Data descriptors inherited from enum.Enum:
1638 |\x20\x20
1639 | name
1640 |\x20\x20
1641 | value
1642 |\x20\x20
1643 | ----------------------------------------------------------------------
1644 | Data descriptors inherited from enum.EnumMeta:
1645 |\x20\x20
1646 | __members__"""
Ethan Furman5875d742013-10-21 20:45:55 -07001647
1648class TestStdLib(unittest.TestCase):
1649
Ethan Furman48a724f2015-04-11 23:23:06 -07001650 maxDiff = None
1651
Ethan Furman5875d742013-10-21 20:45:55 -07001652 class Color(Enum):
1653 red = 1
1654 green = 2
1655 blue = 3
1656
1657 def test_pydoc(self):
1658 # indirectly test __objclass__
Ethan Furman3323da92015-04-11 09:39:59 -07001659 if StrEnum.__doc__ is None:
1660 expected_text = expected_help_output_without_docs % __name__
1661 else:
1662 expected_text = expected_help_output_with_docs % __name__
Ethan Furman5875d742013-10-21 20:45:55 -07001663 output = StringIO()
1664 helper = pydoc.Helper(output=output)
1665 helper(self.Color)
1666 result = output.getvalue().strip()
Victor Stinner4b0432d2014-06-16 22:48:43 +02001667 self.assertEqual(result, expected_text)
Ethan Furman5875d742013-10-21 20:45:55 -07001668
1669 def test_inspect_getmembers(self):
1670 values = dict((
1671 ('__class__', EnumMeta),
Ethan Furman48a724f2015-04-11 23:23:06 -07001672 ('__doc__', 'An enumeration.'),
Ethan Furman5875d742013-10-21 20:45:55 -07001673 ('__members__', self.Color.__members__),
1674 ('__module__', __name__),
1675 ('blue', self.Color.blue),
1676 ('green', self.Color.green),
1677 ('name', Enum.__dict__['name']),
1678 ('red', self.Color.red),
1679 ('value', Enum.__dict__['value']),
1680 ))
1681 result = dict(inspect.getmembers(self.Color))
1682 self.assertEqual(values.keys(), result.keys())
1683 failed = False
1684 for k in values.keys():
1685 if result[k] != values[k]:
1686 print()
1687 print('\n%s\n key: %s\n result: %s\nexpected: %s\n%s\n' %
1688 ('=' * 75, k, result[k], values[k], '=' * 75), sep='')
1689 failed = True
1690 if failed:
1691 self.fail("result does not equal expected, see print above")
1692
1693 def test_inspect_classify_class_attrs(self):
1694 # indirectly test __objclass__
1695 from inspect import Attribute
1696 values = [
1697 Attribute(name='__class__', kind='data',
1698 defining_class=object, object=EnumMeta),
1699 Attribute(name='__doc__', kind='data',
Ethan Furman48a724f2015-04-11 23:23:06 -07001700 defining_class=self.Color, object='An enumeration.'),
Ethan Furman5875d742013-10-21 20:45:55 -07001701 Attribute(name='__members__', kind='property',
1702 defining_class=EnumMeta, object=EnumMeta.__members__),
1703 Attribute(name='__module__', kind='data',
1704 defining_class=self.Color, object=__name__),
1705 Attribute(name='blue', kind='data',
1706 defining_class=self.Color, object=self.Color.blue),
1707 Attribute(name='green', kind='data',
1708 defining_class=self.Color, object=self.Color.green),
1709 Attribute(name='red', kind='data',
1710 defining_class=self.Color, object=self.Color.red),
1711 Attribute(name='name', kind='data',
1712 defining_class=Enum, object=Enum.__dict__['name']),
1713 Attribute(name='value', kind='data',
1714 defining_class=Enum, object=Enum.__dict__['value']),
1715 ]
1716 values.sort(key=lambda item: item.name)
1717 result = list(inspect.classify_class_attrs(self.Color))
1718 result.sort(key=lambda item: item.name)
1719 failed = False
1720 for v, r in zip(values, result):
1721 if r != v:
1722 print('\n%s\n%s\n%s\n%s\n' % ('=' * 75, r, v, '=' * 75), sep='')
1723 failed = True
1724 if failed:
1725 self.fail("result does not equal expected, see print above")
1726
Martin Panter19e69c52015-11-14 12:46:42 +00001727
1728class MiscTestCase(unittest.TestCase):
1729 def test__all__(self):
1730 support.check__all__(self, enum)
1731
1732
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001733if __name__ == '__main__':
1734 unittest.main()