blob: e4e6c2b51af23d6206561cb08eb88d39c8991e05 [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):
275 class Logic(Enum):
276 true = True
277 false = False
278 self.assertTrue(Logic.true)
279 self.assertFalse(Logic.false)
280
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700281 def test_contains(self):
282 Season = self.Season
283 self.assertIn(Season.AUTUMN, Season)
284 self.assertNotIn(3, Season)
285
286 val = Season(3)
287 self.assertIn(val, Season)
288
289 class OtherEnum(Enum):
290 one = 1; two = 2
291 self.assertNotIn(OtherEnum.two, Season)
292
293 def test_comparisons(self):
294 Season = self.Season
295 with self.assertRaises(TypeError):
296 Season.SPRING < Season.WINTER
297 with self.assertRaises(TypeError):
298 Season.SPRING > 4
299
300 self.assertNotEqual(Season.SPRING, 1)
301
302 class Part(Enum):
303 SPRING = 1
304 CLIP = 2
305 BARREL = 3
306
307 self.assertNotEqual(Season.SPRING, Part.SPRING)
308 with self.assertRaises(TypeError):
309 Season.SPRING < Part.CLIP
310
311 def test_enum_duplicates(self):
312 class Season(Enum):
313 SPRING = 1
314 SUMMER = 2
315 AUTUMN = FALL = 3
316 WINTER = 4
317 ANOTHER_SPRING = 1
318 lst = list(Season)
319 self.assertEqual(
320 lst,
321 [Season.SPRING, Season.SUMMER,
322 Season.AUTUMN, Season.WINTER,
323 ])
324 self.assertIs(Season.FALL, Season.AUTUMN)
325 self.assertEqual(Season.FALL.value, 3)
326 self.assertEqual(Season.AUTUMN.value, 3)
327 self.assertIs(Season(3), Season.AUTUMN)
328 self.assertIs(Season(1), Season.SPRING)
329 self.assertEqual(Season.FALL.name, 'AUTUMN')
330 self.assertEqual(
331 [k for k,v in Season.__members__.items() if v.name != k],
332 ['FALL', 'ANOTHER_SPRING'],
333 )
334
Ethan Furman101e0742013-09-15 12:34:36 -0700335 def test_duplicate_name(self):
336 with self.assertRaises(TypeError):
337 class Color(Enum):
338 red = 1
339 green = 2
340 blue = 3
341 red = 4
342
343 with self.assertRaises(TypeError):
344 class Color(Enum):
345 red = 1
346 green = 2
347 blue = 3
348 def red(self):
349 return 'red'
350
351 with self.assertRaises(TypeError):
352 class Color(Enum):
353 @property
354 def red(self):
355 return 'redder'
356 red = 1
357 green = 2
358 blue = 3
359
360
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700361 def test_enum_with_value_name(self):
362 class Huh(Enum):
363 name = 1
364 value = 2
365 self.assertEqual(
366 list(Huh),
367 [Huh.name, Huh.value],
368 )
369 self.assertIs(type(Huh.name), Huh)
370 self.assertEqual(Huh.name.name, 'name')
371 self.assertEqual(Huh.name.value, 1)
Ethan Furmanec15a822013-08-31 19:17:41 -0700372
373 def test_format_enum(self):
374 Season = self.Season
375 self.assertEqual('{}'.format(Season.SPRING),
376 '{}'.format(str(Season.SPRING)))
377 self.assertEqual( '{:}'.format(Season.SPRING),
378 '{:}'.format(str(Season.SPRING)))
379 self.assertEqual('{:20}'.format(Season.SPRING),
380 '{:20}'.format(str(Season.SPRING)))
381 self.assertEqual('{:^20}'.format(Season.SPRING),
382 '{:^20}'.format(str(Season.SPRING)))
383 self.assertEqual('{:>20}'.format(Season.SPRING),
384 '{:>20}'.format(str(Season.SPRING)))
385 self.assertEqual('{:<20}'.format(Season.SPRING),
386 '{:<20}'.format(str(Season.SPRING)))
387
388 def test_format_enum_custom(self):
389 class TestFloat(float, Enum):
390 one = 1.0
391 two = 2.0
392 def __format__(self, spec):
393 return 'TestFloat success!'
394 self.assertEqual('{}'.format(TestFloat.one), 'TestFloat success!')
395
396 def assertFormatIsValue(self, spec, member):
397 self.assertEqual(spec.format(member), spec.format(member.value))
398
399 def test_format_enum_date(self):
400 Holiday = self.Holiday
401 self.assertFormatIsValue('{}', Holiday.IDES_OF_MARCH)
402 self.assertFormatIsValue('{:}', Holiday.IDES_OF_MARCH)
403 self.assertFormatIsValue('{:20}', Holiday.IDES_OF_MARCH)
404 self.assertFormatIsValue('{:^20}', Holiday.IDES_OF_MARCH)
405 self.assertFormatIsValue('{:>20}', Holiday.IDES_OF_MARCH)
406 self.assertFormatIsValue('{:<20}', Holiday.IDES_OF_MARCH)
407 self.assertFormatIsValue('{:%Y %m}', Holiday.IDES_OF_MARCH)
408 self.assertFormatIsValue('{:%Y %m %M:00}', Holiday.IDES_OF_MARCH)
409
410 def test_format_enum_float(self):
411 Konstants = self.Konstants
412 self.assertFormatIsValue('{}', Konstants.TAU)
413 self.assertFormatIsValue('{:}', Konstants.TAU)
414 self.assertFormatIsValue('{:20}', Konstants.TAU)
415 self.assertFormatIsValue('{:^20}', Konstants.TAU)
416 self.assertFormatIsValue('{:>20}', Konstants.TAU)
417 self.assertFormatIsValue('{:<20}', Konstants.TAU)
418 self.assertFormatIsValue('{:n}', Konstants.TAU)
419 self.assertFormatIsValue('{:5.2}', Konstants.TAU)
420 self.assertFormatIsValue('{:f}', Konstants.TAU)
421
422 def test_format_enum_int(self):
423 Grades = self.Grades
424 self.assertFormatIsValue('{}', Grades.C)
425 self.assertFormatIsValue('{:}', Grades.C)
426 self.assertFormatIsValue('{:20}', Grades.C)
427 self.assertFormatIsValue('{:^20}', Grades.C)
428 self.assertFormatIsValue('{:>20}', Grades.C)
429 self.assertFormatIsValue('{:<20}', Grades.C)
430 self.assertFormatIsValue('{:+}', Grades.C)
431 self.assertFormatIsValue('{:08X}', Grades.C)
432 self.assertFormatIsValue('{:b}', Grades.C)
433
434 def test_format_enum_str(self):
435 Directional = self.Directional
436 self.assertFormatIsValue('{}', Directional.WEST)
437 self.assertFormatIsValue('{:}', Directional.WEST)
438 self.assertFormatIsValue('{:20}', Directional.WEST)
439 self.assertFormatIsValue('{:^20}', Directional.WEST)
440 self.assertFormatIsValue('{:>20}', Directional.WEST)
441 self.assertFormatIsValue('{:<20}', Directional.WEST)
442
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700443 def test_hash(self):
444 Season = self.Season
445 dates = {}
446 dates[Season.WINTER] = '1225'
447 dates[Season.SPRING] = '0315'
448 dates[Season.SUMMER] = '0704'
449 dates[Season.AUTUMN] = '1031'
450 self.assertEqual(dates[Season.AUTUMN], '1031')
451
452 def test_intenum_from_scratch(self):
453 class phy(int, Enum):
454 pi = 3
455 tau = 2 * pi
456 self.assertTrue(phy.pi < phy.tau)
457
458 def test_intenum_inherited(self):
459 class IntEnum(int, Enum):
460 pass
461 class phy(IntEnum):
462 pi = 3
463 tau = 2 * pi
464 self.assertTrue(phy.pi < phy.tau)
465
466 def test_floatenum_from_scratch(self):
467 class phy(float, Enum):
Ethan Furmanec15a822013-08-31 19:17:41 -0700468 pi = 3.1415926
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700469 tau = 2 * pi
470 self.assertTrue(phy.pi < phy.tau)
471
472 def test_floatenum_inherited(self):
473 class FloatEnum(float, Enum):
474 pass
475 class phy(FloatEnum):
Ethan Furmanec15a822013-08-31 19:17:41 -0700476 pi = 3.1415926
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700477 tau = 2 * pi
478 self.assertTrue(phy.pi < phy.tau)
479
480 def test_strenum_from_scratch(self):
481 class phy(str, Enum):
482 pi = 'Pi'
483 tau = 'Tau'
484 self.assertTrue(phy.pi < phy.tau)
485
486 def test_strenum_inherited(self):
487 class StrEnum(str, Enum):
488 pass
489 class phy(StrEnum):
490 pi = 'Pi'
491 tau = 'Tau'
492 self.assertTrue(phy.pi < phy.tau)
493
494
495 def test_intenum(self):
496 class WeekDay(IntEnum):
497 SUNDAY = 1
498 MONDAY = 2
499 TUESDAY = 3
500 WEDNESDAY = 4
501 THURSDAY = 5
502 FRIDAY = 6
503 SATURDAY = 7
504
505 self.assertEqual(['a', 'b', 'c'][WeekDay.MONDAY], 'c')
506 self.assertEqual([i for i in range(WeekDay.TUESDAY)], [0, 1, 2])
507
508 lst = list(WeekDay)
509 self.assertEqual(len(lst), len(WeekDay))
510 self.assertEqual(len(WeekDay), 7)
511 target = 'SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY'
512 target = target.split()
513 for i, weekday in enumerate(target, 1):
514 e = WeekDay(i)
515 self.assertEqual(e, i)
516 self.assertEqual(int(e), i)
517 self.assertEqual(e.name, weekday)
518 self.assertIn(e, WeekDay)
519 self.assertEqual(lst.index(e)+1, i)
520 self.assertTrue(0 < e < 8)
521 self.assertIs(type(e), WeekDay)
522 self.assertIsInstance(e, int)
523 self.assertIsInstance(e, Enum)
524
525 def test_intenum_duplicates(self):
526 class WeekDay(IntEnum):
527 SUNDAY = 1
528 MONDAY = 2
529 TUESDAY = TEUSDAY = 3
530 WEDNESDAY = 4
531 THURSDAY = 5
532 FRIDAY = 6
533 SATURDAY = 7
534 self.assertIs(WeekDay.TEUSDAY, WeekDay.TUESDAY)
535 self.assertEqual(WeekDay(3).name, 'TUESDAY')
536 self.assertEqual([k for k,v in WeekDay.__members__.items()
537 if v.name != k], ['TEUSDAY', ])
538
539 def test_pickle_enum(self):
540 if isinstance(Stooges, Exception):
541 raise Stooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800542 test_pickle_dump_load(self.assertIs, Stooges.CURLY)
543 test_pickle_dump_load(self.assertIs, Stooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700544
545 def test_pickle_int(self):
546 if isinstance(IntStooges, Exception):
547 raise IntStooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800548 test_pickle_dump_load(self.assertIs, IntStooges.CURLY)
549 test_pickle_dump_load(self.assertIs, IntStooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700550
551 def test_pickle_float(self):
552 if isinstance(FloatStooges, Exception):
553 raise FloatStooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800554 test_pickle_dump_load(self.assertIs, FloatStooges.CURLY)
555 test_pickle_dump_load(self.assertIs, FloatStooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700556
557 def test_pickle_enum_function(self):
558 if isinstance(Answer, Exception):
559 raise Answer
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800560 test_pickle_dump_load(self.assertIs, Answer.him)
561 test_pickle_dump_load(self.assertIs, Answer)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700562
563 def test_pickle_enum_function_with_module(self):
564 if isinstance(Question, Exception):
565 raise Question
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800566 test_pickle_dump_load(self.assertIs, Question.who)
567 test_pickle_dump_load(self.assertIs, Question)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700568
Ethan Furmanca1b7942014-02-08 11:36:27 -0800569 def test_enum_function_with_qualname(self):
570 if isinstance(Theory, Exception):
571 raise Theory
572 self.assertEqual(Theory.__qualname__, 'spanish_inquisition')
573
574 def test_class_nested_enum_and_pickle_protocol_four(self):
575 # would normally just have this directly in the class namespace
576 class NestedEnum(Enum):
577 twigs = 'common'
578 shiny = 'rare'
579
580 self.__class__.NestedEnum = NestedEnum
581 self.NestedEnum.__qualname__ = '%s.NestedEnum' % self.__class__.__name__
Serhiy Storchakae50e7802015-03-31 16:56:49 +0300582 test_pickle_dump_load(self.assertIs, self.NestedEnum.twigs)
Ethan Furmanca1b7942014-02-08 11:36:27 -0800583
Ethan Furman24e837f2015-03-18 17:27:57 -0700584 def test_pickle_by_name(self):
585 class ReplaceGlobalInt(IntEnum):
586 ONE = 1
587 TWO = 2
588 ReplaceGlobalInt.__reduce_ex__ = enum._reduce_ex_by_name
589 for proto in range(HIGHEST_PROTOCOL):
590 self.assertEqual(ReplaceGlobalInt.TWO.__reduce_ex__(proto), 'TWO')
591
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700592 def test_exploding_pickle(self):
Ethan Furmanca1b7942014-02-08 11:36:27 -0800593 BadPickle = Enum(
594 'BadPickle', 'dill sweet bread-n-butter', module=__name__)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700595 globals()['BadPickle'] = BadPickle
Ethan Furmanca1b7942014-02-08 11:36:27 -0800596 # now break BadPickle to test exception raising
597 enum._make_class_unpicklable(BadPickle)
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800598 test_pickle_exception(self.assertRaises, TypeError, BadPickle.dill)
599 test_pickle_exception(self.assertRaises, PicklingError, BadPickle)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700600
601 def test_string_enum(self):
602 class SkillLevel(str, Enum):
603 master = 'what is the sound of one hand clapping?'
604 journeyman = 'why did the chicken cross the road?'
605 apprentice = 'knock, knock!'
606 self.assertEqual(SkillLevel.apprentice, 'knock, knock!')
607
608 def test_getattr_getitem(self):
609 class Period(Enum):
610 morning = 1
611 noon = 2
612 evening = 3
613 night = 4
614 self.assertIs(Period(2), Period.noon)
615 self.assertIs(getattr(Period, 'night'), Period.night)
616 self.assertIs(Period['morning'], Period.morning)
617
618 def test_getattr_dunder(self):
619 Season = self.Season
620 self.assertTrue(getattr(Season, '__eq__'))
621
622 def test_iteration_order(self):
623 class Season(Enum):
624 SUMMER = 2
625 WINTER = 4
626 AUTUMN = 3
627 SPRING = 1
628 self.assertEqual(
629 list(Season),
630 [Season.SUMMER, Season.WINTER, Season.AUTUMN, Season.SPRING],
631 )
632
Ethan Furman2131a4a2013-09-14 18:11:24 -0700633 def test_reversed_iteration_order(self):
634 self.assertEqual(
635 list(reversed(self.Season)),
636 [self.Season.WINTER, self.Season.AUTUMN, self.Season.SUMMER,
637 self.Season.SPRING]
638 )
639
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700640 def test_programatic_function_string(self):
641 SummerMonth = Enum('SummerMonth', 'june july august')
642 lst = list(SummerMonth)
643 self.assertEqual(len(lst), len(SummerMonth))
644 self.assertEqual(len(SummerMonth), 3, SummerMonth)
645 self.assertEqual(
646 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
647 lst,
648 )
649 for i, month in enumerate('june july august'.split(), 1):
650 e = SummerMonth(i)
651 self.assertEqual(int(e.value), i)
652 self.assertNotEqual(e, i)
653 self.assertEqual(e.name, month)
654 self.assertIn(e, SummerMonth)
655 self.assertIs(type(e), SummerMonth)
656
Ethan Furmand9925a12014-09-16 20:35:55 -0700657 def test_programatic_function_string_with_start(self):
658 SummerMonth = Enum('SummerMonth', 'june july august', start=10)
659 lst = list(SummerMonth)
660 self.assertEqual(len(lst), len(SummerMonth))
661 self.assertEqual(len(SummerMonth), 3, SummerMonth)
662 self.assertEqual(
663 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
664 lst,
665 )
666 for i, month in enumerate('june july august'.split(), 10):
667 e = SummerMonth(i)
668 self.assertEqual(int(e.value), i)
669 self.assertNotEqual(e, i)
670 self.assertEqual(e.name, month)
671 self.assertIn(e, SummerMonth)
672 self.assertIs(type(e), SummerMonth)
673
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700674 def test_programatic_function_string_list(self):
675 SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'])
676 lst = list(SummerMonth)
677 self.assertEqual(len(lst), len(SummerMonth))
678 self.assertEqual(len(SummerMonth), 3, SummerMonth)
679 self.assertEqual(
680 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
681 lst,
682 )
683 for i, month in enumerate('june july august'.split(), 1):
684 e = SummerMonth(i)
685 self.assertEqual(int(e.value), i)
686 self.assertNotEqual(e, i)
687 self.assertEqual(e.name, month)
688 self.assertIn(e, SummerMonth)
689 self.assertIs(type(e), SummerMonth)
690
Ethan Furmand9925a12014-09-16 20:35:55 -0700691 def test_programatic_function_string_list_with_start(self):
692 SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'], start=20)
693 lst = list(SummerMonth)
694 self.assertEqual(len(lst), len(SummerMonth))
695 self.assertEqual(len(SummerMonth), 3, SummerMonth)
696 self.assertEqual(
697 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
698 lst,
699 )
700 for i, month in enumerate('june july august'.split(), 20):
701 e = SummerMonth(i)
702 self.assertEqual(int(e.value), i)
703 self.assertNotEqual(e, i)
704 self.assertEqual(e.name, month)
705 self.assertIn(e, SummerMonth)
706 self.assertIs(type(e), SummerMonth)
707
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700708 def test_programatic_function_iterable(self):
709 SummerMonth = Enum(
710 'SummerMonth',
711 (('june', 1), ('july', 2), ('august', 3))
712 )
713 lst = list(SummerMonth)
714 self.assertEqual(len(lst), len(SummerMonth))
715 self.assertEqual(len(SummerMonth), 3, SummerMonth)
716 self.assertEqual(
717 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
718 lst,
719 )
720 for i, month in enumerate('june july august'.split(), 1):
721 e = SummerMonth(i)
722 self.assertEqual(int(e.value), i)
723 self.assertNotEqual(e, i)
724 self.assertEqual(e.name, month)
725 self.assertIn(e, SummerMonth)
726 self.assertIs(type(e), SummerMonth)
727
728 def test_programatic_function_from_dict(self):
729 SummerMonth = Enum(
730 'SummerMonth',
731 OrderedDict((('june', 1), ('july', 2), ('august', 3)))
732 )
733 lst = list(SummerMonth)
734 self.assertEqual(len(lst), len(SummerMonth))
735 self.assertEqual(len(SummerMonth), 3, SummerMonth)
736 self.assertEqual(
737 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
738 lst,
739 )
740 for i, month in enumerate('june july august'.split(), 1):
741 e = SummerMonth(i)
742 self.assertEqual(int(e.value), i)
743 self.assertNotEqual(e, i)
744 self.assertEqual(e.name, month)
745 self.assertIn(e, SummerMonth)
746 self.assertIs(type(e), SummerMonth)
747
748 def test_programatic_function_type(self):
749 SummerMonth = Enum('SummerMonth', 'june july august', type=int)
750 lst = list(SummerMonth)
751 self.assertEqual(len(lst), len(SummerMonth))
752 self.assertEqual(len(SummerMonth), 3, SummerMonth)
753 self.assertEqual(
754 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
755 lst,
756 )
757 for i, month in enumerate('june july august'.split(), 1):
758 e = SummerMonth(i)
759 self.assertEqual(e, i)
760 self.assertEqual(e.name, month)
761 self.assertIn(e, SummerMonth)
762 self.assertIs(type(e), SummerMonth)
763
Ethan Furmand9925a12014-09-16 20:35:55 -0700764 def test_programatic_function_type_with_start(self):
765 SummerMonth = Enum('SummerMonth', 'june july august', type=int, start=30)
766 lst = list(SummerMonth)
767 self.assertEqual(len(lst), len(SummerMonth))
768 self.assertEqual(len(SummerMonth), 3, SummerMonth)
769 self.assertEqual(
770 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
771 lst,
772 )
773 for i, month in enumerate('june july august'.split(), 30):
774 e = SummerMonth(i)
775 self.assertEqual(e, i)
776 self.assertEqual(e.name, month)
777 self.assertIn(e, SummerMonth)
778 self.assertIs(type(e), SummerMonth)
779
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700780 def test_programatic_function_type_from_subclass(self):
781 SummerMonth = IntEnum('SummerMonth', 'june july august')
782 lst = list(SummerMonth)
783 self.assertEqual(len(lst), len(SummerMonth))
784 self.assertEqual(len(SummerMonth), 3, SummerMonth)
785 self.assertEqual(
786 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
787 lst,
788 )
789 for i, month in enumerate('june july august'.split(), 1):
790 e = SummerMonth(i)
791 self.assertEqual(e, i)
792 self.assertEqual(e.name, month)
793 self.assertIn(e, SummerMonth)
794 self.assertIs(type(e), SummerMonth)
795
Ethan Furmand9925a12014-09-16 20:35:55 -0700796 def test_programatic_function_type_from_subclass_with_start(self):
797 SummerMonth = IntEnum('SummerMonth', 'june july august', start=40)
798 lst = list(SummerMonth)
799 self.assertEqual(len(lst), len(SummerMonth))
800 self.assertEqual(len(SummerMonth), 3, SummerMonth)
801 self.assertEqual(
802 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
803 lst,
804 )
805 for i, month in enumerate('june july august'.split(), 40):
806 e = SummerMonth(i)
807 self.assertEqual(e, i)
808 self.assertEqual(e.name, month)
809 self.assertIn(e, SummerMonth)
810 self.assertIs(type(e), SummerMonth)
811
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700812 def test_subclassing(self):
813 if isinstance(Name, Exception):
814 raise Name
815 self.assertEqual(Name.BDFL, 'Guido van Rossum')
816 self.assertTrue(Name.BDFL, Name('Guido van Rossum'))
817 self.assertIs(Name.BDFL, getattr(Name, 'BDFL'))
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800818 test_pickle_dump_load(self.assertIs, Name.BDFL)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700819
820 def test_extending(self):
821 class Color(Enum):
822 red = 1
823 green = 2
824 blue = 3
825 with self.assertRaises(TypeError):
826 class MoreColor(Color):
827 cyan = 4
828 magenta = 5
829 yellow = 6
830
831 def test_exclude_methods(self):
832 class whatever(Enum):
833 this = 'that'
834 these = 'those'
835 def really(self):
836 return 'no, not %s' % self.value
837 self.assertIsNot(type(whatever.really), whatever)
838 self.assertEqual(whatever.this.really(), 'no, not that')
839
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700840 def test_wrong_inheritance_order(self):
841 with self.assertRaises(TypeError):
842 class Wrong(Enum, str):
843 NotHere = 'error before this point'
844
845 def test_intenum_transitivity(self):
846 class number(IntEnum):
847 one = 1
848 two = 2
849 three = 3
850 class numero(IntEnum):
851 uno = 1
852 dos = 2
853 tres = 3
854 self.assertEqual(number.one, numero.uno)
855 self.assertEqual(number.two, numero.dos)
856 self.assertEqual(number.three, numero.tres)
857
858 def test_wrong_enum_in_call(self):
859 class Monochrome(Enum):
860 black = 0
861 white = 1
862 class Gender(Enum):
863 male = 0
864 female = 1
865 self.assertRaises(ValueError, Monochrome, Gender.male)
866
867 def test_wrong_enum_in_mixed_call(self):
868 class Monochrome(IntEnum):
869 black = 0
870 white = 1
871 class Gender(Enum):
872 male = 0
873 female = 1
874 self.assertRaises(ValueError, Monochrome, Gender.male)
875
876 def test_mixed_enum_in_call_1(self):
877 class Monochrome(IntEnum):
878 black = 0
879 white = 1
880 class Gender(IntEnum):
881 male = 0
882 female = 1
883 self.assertIs(Monochrome(Gender.female), Monochrome.white)
884
885 def test_mixed_enum_in_call_2(self):
886 class Monochrome(Enum):
887 black = 0
888 white = 1
889 class Gender(IntEnum):
890 male = 0
891 female = 1
892 self.assertIs(Monochrome(Gender.male), Monochrome.black)
893
894 def test_flufl_enum(self):
895 class Fluflnum(Enum):
896 def __int__(self):
897 return int(self.value)
898 class MailManOptions(Fluflnum):
899 option1 = 1
900 option2 = 2
901 option3 = 3
902 self.assertEqual(int(MailManOptions.option1), 1)
903
Ethan Furman5e5a8232013-08-04 08:42:23 -0700904 def test_introspection(self):
905 class Number(IntEnum):
906 one = 100
907 two = 200
908 self.assertIs(Number.one._member_type_, int)
909 self.assertIs(Number._member_type_, int)
910 class String(str, Enum):
911 yarn = 'soft'
912 rope = 'rough'
913 wire = 'hard'
914 self.assertIs(String.yarn._member_type_, str)
915 self.assertIs(String._member_type_, str)
916 class Plain(Enum):
917 vanilla = 'white'
918 one = 1
919 self.assertIs(Plain.vanilla._member_type_, object)
920 self.assertIs(Plain._member_type_, object)
921
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700922 def test_no_such_enum_member(self):
923 class Color(Enum):
924 red = 1
925 green = 2
926 blue = 3
927 with self.assertRaises(ValueError):
928 Color(4)
929 with self.assertRaises(KeyError):
930 Color['chartreuse']
931
932 def test_new_repr(self):
933 class Color(Enum):
934 red = 1
935 green = 2
936 blue = 3
937 def __repr__(self):
938 return "don't you just love shades of %s?" % self.name
939 self.assertEqual(
940 repr(Color.blue),
941 "don't you just love shades of blue?",
942 )
943
944 def test_inherited_repr(self):
945 class MyEnum(Enum):
946 def __repr__(self):
947 return "My name is %s." % self.name
948 class MyIntEnum(int, MyEnum):
949 this = 1
950 that = 2
951 theother = 3
952 self.assertEqual(repr(MyIntEnum.that), "My name is that.")
953
954 def test_multiple_mixin_mro(self):
955 class auto_enum(type(Enum)):
956 def __new__(metacls, cls, bases, classdict):
957 temp = type(classdict)()
958 names = set(classdict._member_names)
959 i = 0
960 for k in classdict._member_names:
961 v = classdict[k]
962 if v is Ellipsis:
963 v = i
964 else:
965 i = v
966 i += 1
967 temp[k] = v
968 for k, v in classdict.items():
969 if k not in names:
970 temp[k] = v
971 return super(auto_enum, metacls).__new__(
972 metacls, cls, bases, temp)
973
974 class AutoNumberedEnum(Enum, metaclass=auto_enum):
975 pass
976
977 class AutoIntEnum(IntEnum, metaclass=auto_enum):
978 pass
979
980 class TestAutoNumber(AutoNumberedEnum):
981 a = ...
982 b = 3
983 c = ...
984
985 class TestAutoInt(AutoIntEnum):
986 a = ...
987 b = 3
988 c = ...
989
990 def test_subclasses_with_getnewargs(self):
991 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800992 __qualname__ = 'NamedInt' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700993 def __new__(cls, *args):
994 _args = args
995 name, *args = args
996 if len(args) == 0:
997 raise TypeError("name and value must be specified")
998 self = int.__new__(cls, *args)
999 self._intname = name
1000 self._args = _args
1001 return self
1002 def __getnewargs__(self):
1003 return self._args
1004 @property
1005 def __name__(self):
1006 return self._intname
1007 def __repr__(self):
1008 # repr() is updated to include the name and type info
1009 return "{}({!r}, {})".format(type(self).__name__,
1010 self.__name__,
1011 int.__repr__(self))
1012 def __str__(self):
1013 # str() is unchanged, even if it relies on the repr() fallback
1014 base = int
1015 base_str = base.__str__
1016 if base_str.__objclass__ is object:
1017 return base.__repr__(self)
1018 return base_str(self)
1019 # for simplicity, we only define one operator that
1020 # propagates expressions
1021 def __add__(self, other):
1022 temp = int(self) + int( other)
1023 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1024 return NamedInt(
1025 '({0} + {1})'.format(self.__name__, other.__name__),
1026 temp )
1027 else:
1028 return temp
1029
1030 class NEI(NamedInt, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001031 __qualname__ = 'NEI' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001032 x = ('the-x', 1)
1033 y = ('the-y', 2)
1034
Ethan Furman2aa27322013-07-19 19:35:56 -07001035
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001036 self.assertIs(NEI.__new__, Enum.__new__)
1037 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1038 globals()['NamedInt'] = NamedInt
1039 globals()['NEI'] = NEI
1040 NI5 = NamedInt('test', 5)
1041 self.assertEqual(NI5, 5)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001042 test_pickle_dump_load(self.assertEqual, NI5, 5)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001043 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001044 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001045 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001046
Ethan Furmanca1b7942014-02-08 11:36:27 -08001047 def test_subclasses_with_getnewargs_ex(self):
1048 class NamedInt(int):
1049 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1050 def __new__(cls, *args):
1051 _args = args
1052 name, *args = args
1053 if len(args) == 0:
1054 raise TypeError("name and value must be specified")
1055 self = int.__new__(cls, *args)
1056 self._intname = name
1057 self._args = _args
1058 return self
1059 def __getnewargs_ex__(self):
1060 return self._args, {}
1061 @property
1062 def __name__(self):
1063 return self._intname
1064 def __repr__(self):
1065 # repr() is updated to include the name and type info
1066 return "{}({!r}, {})".format(type(self).__name__,
1067 self.__name__,
1068 int.__repr__(self))
1069 def __str__(self):
1070 # str() is unchanged, even if it relies on the repr() fallback
1071 base = int
1072 base_str = base.__str__
1073 if base_str.__objclass__ is object:
1074 return base.__repr__(self)
1075 return base_str(self)
1076 # for simplicity, we only define one operator that
1077 # propagates expressions
1078 def __add__(self, other):
1079 temp = int(self) + int( other)
1080 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1081 return NamedInt(
1082 '({0} + {1})'.format(self.__name__, other.__name__),
1083 temp )
1084 else:
1085 return temp
1086
1087 class NEI(NamedInt, Enum):
1088 __qualname__ = 'NEI' # needed for pickle protocol 4
1089 x = ('the-x', 1)
1090 y = ('the-y', 2)
1091
1092
1093 self.assertIs(NEI.__new__, Enum.__new__)
1094 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1095 globals()['NamedInt'] = NamedInt
1096 globals()['NEI'] = NEI
1097 NI5 = NamedInt('test', 5)
1098 self.assertEqual(NI5, 5)
Serhiy Storchakae50e7802015-03-31 16:56:49 +03001099 test_pickle_dump_load(self.assertEqual, NI5, 5)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001100 self.assertEqual(NEI.y.value, 2)
Serhiy Storchakae50e7802015-03-31 16:56:49 +03001101 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001102 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001103
1104 def test_subclasses_with_reduce(self):
1105 class NamedInt(int):
1106 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1107 def __new__(cls, *args):
1108 _args = args
1109 name, *args = args
1110 if len(args) == 0:
1111 raise TypeError("name and value must be specified")
1112 self = int.__new__(cls, *args)
1113 self._intname = name
1114 self._args = _args
1115 return self
1116 def __reduce__(self):
1117 return self.__class__, self._args
1118 @property
1119 def __name__(self):
1120 return self._intname
1121 def __repr__(self):
1122 # repr() is updated to include the name and type info
1123 return "{}({!r}, {})".format(type(self).__name__,
1124 self.__name__,
1125 int.__repr__(self))
1126 def __str__(self):
1127 # str() is unchanged, even if it relies on the repr() fallback
1128 base = int
1129 base_str = base.__str__
1130 if base_str.__objclass__ is object:
1131 return base.__repr__(self)
1132 return base_str(self)
1133 # for simplicity, we only define one operator that
1134 # propagates expressions
1135 def __add__(self, other):
1136 temp = int(self) + int( other)
1137 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1138 return NamedInt(
1139 '({0} + {1})'.format(self.__name__, other.__name__),
1140 temp )
1141 else:
1142 return temp
1143
1144 class NEI(NamedInt, Enum):
1145 __qualname__ = 'NEI' # needed for pickle protocol 4
1146 x = ('the-x', 1)
1147 y = ('the-y', 2)
1148
1149
1150 self.assertIs(NEI.__new__, Enum.__new__)
1151 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1152 globals()['NamedInt'] = NamedInt
1153 globals()['NEI'] = NEI
1154 NI5 = NamedInt('test', 5)
1155 self.assertEqual(NI5, 5)
1156 test_pickle_dump_load(self.assertEqual, NI5, 5)
1157 self.assertEqual(NEI.y.value, 2)
1158 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001159 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001160
1161 def test_subclasses_with_reduce_ex(self):
1162 class NamedInt(int):
1163 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1164 def __new__(cls, *args):
1165 _args = args
1166 name, *args = args
1167 if len(args) == 0:
1168 raise TypeError("name and value must be specified")
1169 self = int.__new__(cls, *args)
1170 self._intname = name
1171 self._args = _args
1172 return self
1173 def __reduce_ex__(self, proto):
1174 return self.__class__, self._args
1175 @property
1176 def __name__(self):
1177 return self._intname
1178 def __repr__(self):
1179 # repr() is updated to include the name and type info
1180 return "{}({!r}, {})".format(type(self).__name__,
1181 self.__name__,
1182 int.__repr__(self))
1183 def __str__(self):
1184 # str() is unchanged, even if it relies on the repr() fallback
1185 base = int
1186 base_str = base.__str__
1187 if base_str.__objclass__ is object:
1188 return base.__repr__(self)
1189 return base_str(self)
1190 # for simplicity, we only define one operator that
1191 # propagates expressions
1192 def __add__(self, other):
1193 temp = int(self) + int( other)
1194 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1195 return NamedInt(
1196 '({0} + {1})'.format(self.__name__, other.__name__),
1197 temp )
1198 else:
1199 return temp
1200
1201 class NEI(NamedInt, Enum):
1202 __qualname__ = 'NEI' # needed for pickle protocol 4
1203 x = ('the-x', 1)
1204 y = ('the-y', 2)
1205
1206
1207 self.assertIs(NEI.__new__, Enum.__new__)
1208 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1209 globals()['NamedInt'] = NamedInt
1210 globals()['NEI'] = NEI
1211 NI5 = NamedInt('test', 5)
1212 self.assertEqual(NI5, 5)
1213 test_pickle_dump_load(self.assertEqual, NI5, 5)
1214 self.assertEqual(NEI.y.value, 2)
1215 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001216 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001217
Ethan Furmandc870522014-02-18 12:37:12 -08001218 def test_subclasses_without_direct_pickle_support(self):
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001219 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001220 __qualname__ = 'NamedInt'
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001221 def __new__(cls, *args):
1222 _args = args
1223 name, *args = args
1224 if len(args) == 0:
1225 raise TypeError("name and value must be specified")
1226 self = int.__new__(cls, *args)
1227 self._intname = name
1228 self._args = _args
1229 return self
1230 @property
1231 def __name__(self):
1232 return self._intname
1233 def __repr__(self):
1234 # repr() is updated to include the name and type info
1235 return "{}({!r}, {})".format(type(self).__name__,
1236 self.__name__,
1237 int.__repr__(self))
1238 def __str__(self):
1239 # str() is unchanged, even if it relies on the repr() fallback
1240 base = int
1241 base_str = base.__str__
1242 if base_str.__objclass__ is object:
1243 return base.__repr__(self)
1244 return base_str(self)
1245 # for simplicity, we only define one operator that
1246 # propagates expressions
1247 def __add__(self, other):
1248 temp = int(self) + int( other)
1249 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1250 return NamedInt(
1251 '({0} + {1})'.format(self.__name__, other.__name__),
1252 temp )
1253 else:
1254 return temp
1255
1256 class NEI(NamedInt, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001257 __qualname__ = 'NEI'
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001258 x = ('the-x', 1)
1259 y = ('the-y', 2)
1260
1261 self.assertIs(NEI.__new__, Enum.__new__)
1262 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1263 globals()['NamedInt'] = NamedInt
1264 globals()['NEI'] = NEI
1265 NI5 = NamedInt('test', 5)
1266 self.assertEqual(NI5, 5)
1267 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001268 test_pickle_exception(self.assertRaises, TypeError, NEI.x)
1269 test_pickle_exception(self.assertRaises, PicklingError, NEI)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001270
Ethan Furmandc870522014-02-18 12:37:12 -08001271 def test_subclasses_without_direct_pickle_support_using_name(self):
1272 class NamedInt(int):
1273 __qualname__ = 'NamedInt'
1274 def __new__(cls, *args):
1275 _args = args
1276 name, *args = args
1277 if len(args) == 0:
1278 raise TypeError("name and value must be specified")
1279 self = int.__new__(cls, *args)
1280 self._intname = name
1281 self._args = _args
1282 return self
1283 @property
1284 def __name__(self):
1285 return self._intname
1286 def __repr__(self):
1287 # repr() is updated to include the name and type info
1288 return "{}({!r}, {})".format(type(self).__name__,
1289 self.__name__,
1290 int.__repr__(self))
1291 def __str__(self):
1292 # str() is unchanged, even if it relies on the repr() fallback
1293 base = int
1294 base_str = base.__str__
1295 if base_str.__objclass__ is object:
1296 return base.__repr__(self)
1297 return base_str(self)
1298 # for simplicity, we only define one operator that
1299 # propagates expressions
1300 def __add__(self, other):
1301 temp = int(self) + int( other)
1302 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1303 return NamedInt(
1304 '({0} + {1})'.format(self.__name__, other.__name__),
1305 temp )
1306 else:
1307 return temp
1308
1309 class NEI(NamedInt, Enum):
1310 __qualname__ = 'NEI'
1311 x = ('the-x', 1)
1312 y = ('the-y', 2)
1313 def __reduce_ex__(self, proto):
1314 return getattr, (self.__class__, self._name_)
1315
1316 self.assertIs(NEI.__new__, Enum.__new__)
1317 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1318 globals()['NamedInt'] = NamedInt
1319 globals()['NEI'] = NEI
1320 NI5 = NamedInt('test', 5)
1321 self.assertEqual(NI5, 5)
1322 self.assertEqual(NEI.y.value, 2)
1323 test_pickle_dump_load(self.assertIs, NEI.y)
1324 test_pickle_dump_load(self.assertIs, NEI)
1325
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001326 def test_tuple_subclass(self):
1327 class SomeTuple(tuple, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001328 __qualname__ = 'SomeTuple' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001329 first = (1, 'for the money')
1330 second = (2, 'for the show')
1331 third = (3, 'for the music')
1332 self.assertIs(type(SomeTuple.first), SomeTuple)
1333 self.assertIsInstance(SomeTuple.second, tuple)
1334 self.assertEqual(SomeTuple.third, (3, 'for the music'))
1335 globals()['SomeTuple'] = SomeTuple
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001336 test_pickle_dump_load(self.assertIs, SomeTuple.first)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001337
1338 def test_duplicate_values_give_unique_enum_items(self):
1339 class AutoNumber(Enum):
1340 first = ()
1341 second = ()
1342 third = ()
1343 def __new__(cls):
1344 value = len(cls.__members__) + 1
1345 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001346 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001347 return obj
1348 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001349 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001350 self.assertEqual(
1351 list(AutoNumber),
1352 [AutoNumber.first, AutoNumber.second, AutoNumber.third],
1353 )
1354 self.assertEqual(int(AutoNumber.second), 2)
Ethan Furman2aa27322013-07-19 19:35:56 -07001355 self.assertEqual(AutoNumber.third.value, 3)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001356 self.assertIs(AutoNumber(1), AutoNumber.first)
1357
1358 def test_inherited_new_from_enhanced_enum(self):
1359 class AutoNumber(Enum):
1360 def __new__(cls):
1361 value = len(cls.__members__) + 1
1362 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001363 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001364 return obj
1365 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001366 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001367 class Color(AutoNumber):
1368 red = ()
1369 green = ()
1370 blue = ()
1371 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1372 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1373
1374 def test_inherited_new_from_mixed_enum(self):
1375 class AutoNumber(IntEnum):
1376 def __new__(cls):
1377 value = len(cls.__members__) + 1
1378 obj = int.__new__(cls, value)
Ethan Furman520ad572013-07-19 19:47:21 -07001379 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001380 return obj
1381 class Color(AutoNumber):
1382 red = ()
1383 green = ()
1384 blue = ()
1385 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1386 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1387
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001388 def test_equality(self):
1389 class AlwaysEqual:
1390 def __eq__(self, other):
1391 return True
1392 class OrdinaryEnum(Enum):
1393 a = 1
1394 self.assertEqual(AlwaysEqual(), OrdinaryEnum.a)
1395 self.assertEqual(OrdinaryEnum.a, AlwaysEqual())
1396
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001397 def test_ordered_mixin(self):
1398 class OrderedEnum(Enum):
1399 def __ge__(self, other):
1400 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001401 return self._value_ >= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001402 return NotImplemented
1403 def __gt__(self, other):
1404 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001405 return self._value_ > other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001406 return NotImplemented
1407 def __le__(self, other):
1408 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001409 return self._value_ <= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001410 return NotImplemented
1411 def __lt__(self, other):
1412 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001413 return self._value_ < other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001414 return NotImplemented
1415 class Grade(OrderedEnum):
1416 A = 5
1417 B = 4
1418 C = 3
1419 D = 2
1420 F = 1
1421 self.assertGreater(Grade.A, Grade.B)
1422 self.assertLessEqual(Grade.F, Grade.C)
1423 self.assertLess(Grade.D, Grade.A)
1424 self.assertGreaterEqual(Grade.B, Grade.B)
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001425 self.assertEqual(Grade.B, Grade.B)
1426 self.assertNotEqual(Grade.C, Grade.D)
Ethan Furman520ad572013-07-19 19:47:21 -07001427
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001428 def test_extending2(self):
1429 class Shade(Enum):
1430 def shade(self):
1431 print(self.name)
1432 class Color(Shade):
1433 red = 1
1434 green = 2
1435 blue = 3
1436 with self.assertRaises(TypeError):
1437 class MoreColor(Color):
1438 cyan = 4
1439 magenta = 5
1440 yellow = 6
1441
1442 def test_extending3(self):
1443 class Shade(Enum):
1444 def shade(self):
1445 return self.name
1446 class Color(Shade):
1447 def hex(self):
1448 return '%s hexlified!' % self.value
1449 class MoreColor(Color):
1450 cyan = 4
1451 magenta = 5
1452 yellow = 6
1453 self.assertEqual(MoreColor.magenta.hex(), '5 hexlified!')
1454
1455
1456 def test_no_duplicates(self):
1457 class UniqueEnum(Enum):
1458 def __init__(self, *args):
1459 cls = self.__class__
1460 if any(self.value == e.value for e in cls):
1461 a = self.name
1462 e = cls(self.value).name
1463 raise ValueError(
1464 "aliases not allowed in UniqueEnum: %r --> %r"
1465 % (a, e)
1466 )
1467 class Color(UniqueEnum):
1468 red = 1
1469 green = 2
1470 blue = 3
1471 with self.assertRaises(ValueError):
1472 class Color(UniqueEnum):
1473 red = 1
1474 green = 2
1475 blue = 3
1476 grene = 2
1477
1478 def test_init(self):
1479 class Planet(Enum):
1480 MERCURY = (3.303e+23, 2.4397e6)
1481 VENUS = (4.869e+24, 6.0518e6)
1482 EARTH = (5.976e+24, 6.37814e6)
1483 MARS = (6.421e+23, 3.3972e6)
1484 JUPITER = (1.9e+27, 7.1492e7)
1485 SATURN = (5.688e+26, 6.0268e7)
1486 URANUS = (8.686e+25, 2.5559e7)
1487 NEPTUNE = (1.024e+26, 2.4746e7)
1488 def __init__(self, mass, radius):
1489 self.mass = mass # in kilograms
1490 self.radius = radius # in meters
1491 @property
1492 def surface_gravity(self):
1493 # universal gravitational constant (m3 kg-1 s-2)
1494 G = 6.67300E-11
1495 return G * self.mass / (self.radius * self.radius)
1496 self.assertEqual(round(Planet.EARTH.surface_gravity, 2), 9.80)
1497 self.assertEqual(Planet.EARTH.value, (5.976e+24, 6.37814e6))
1498
Ethan Furman2aa27322013-07-19 19:35:56 -07001499 def test_nonhash_value(self):
1500 class AutoNumberInAList(Enum):
1501 def __new__(cls):
1502 value = [len(cls.__members__) + 1]
1503 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001504 obj._value_ = value
Ethan Furman2aa27322013-07-19 19:35:56 -07001505 return obj
1506 class ColorInAList(AutoNumberInAList):
1507 red = ()
1508 green = ()
1509 blue = ()
1510 self.assertEqual(list(ColorInAList), [ColorInAList.red, ColorInAList.green, ColorInAList.blue])
Ethan Furman1a162882013-10-16 19:09:31 -07001511 for enum, value in zip(ColorInAList, range(3)):
1512 value += 1
1513 self.assertEqual(enum.value, [value])
1514 self.assertIs(ColorInAList([value]), enum)
Ethan Furman2aa27322013-07-19 19:35:56 -07001515
Ethan Furmanb41803e2013-07-25 13:50:45 -07001516 def test_conflicting_types_resolved_in_new(self):
1517 class LabelledIntEnum(int, Enum):
1518 def __new__(cls, *args):
1519 value, label = args
1520 obj = int.__new__(cls, value)
1521 obj.label = label
1522 obj._value_ = value
1523 return obj
1524
1525 class LabelledList(LabelledIntEnum):
1526 unprocessed = (1, "Unprocessed")
1527 payment_complete = (2, "Payment Complete")
1528
1529 self.assertEqual(list(LabelledList), [LabelledList.unprocessed, LabelledList.payment_complete])
1530 self.assertEqual(LabelledList.unprocessed, 1)
1531 self.assertEqual(LabelledList(1), LabelledList.unprocessed)
Ethan Furman2aa27322013-07-19 19:35:56 -07001532
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001533
Ethan Furmanf24bb352013-07-18 17:05:39 -07001534class TestUnique(unittest.TestCase):
1535
1536 def test_unique_clean(self):
1537 @unique
1538 class Clean(Enum):
1539 one = 1
1540 two = 'dos'
1541 tres = 4.0
1542 @unique
1543 class Cleaner(IntEnum):
1544 single = 1
1545 double = 2
1546 triple = 3
1547
1548 def test_unique_dirty(self):
1549 with self.assertRaisesRegex(ValueError, 'tres.*one'):
1550 @unique
1551 class Dirty(Enum):
1552 one = 1
1553 two = 'dos'
1554 tres = 1
1555 with self.assertRaisesRegex(
1556 ValueError,
1557 'double.*single.*turkey.*triple',
1558 ):
1559 @unique
1560 class Dirtier(IntEnum):
1561 single = 1
1562 double = 1
1563 triple = 3
1564 turkey = 3
1565
1566
Ethan Furman3323da92015-04-11 09:39:59 -07001567expected_help_output_with_docs = """\
Ethan Furman5875d742013-10-21 20:45:55 -07001568Help on class Color in module %s:
1569
1570class Color(enum.Enum)
Ethan Furman48a724f2015-04-11 23:23:06 -07001571 | An enumeration.
Serhiy Storchakab599ca82015-04-04 12:48:04 +03001572 |\x20\x20
Ethan Furman5875d742013-10-21 20:45:55 -07001573 | Method resolution order:
1574 | Color
1575 | enum.Enum
1576 | builtins.object
1577 |\x20\x20
1578 | Data and other attributes defined here:
1579 |\x20\x20
1580 | blue = <Color.blue: 3>
1581 |\x20\x20
1582 | green = <Color.green: 2>
1583 |\x20\x20
1584 | red = <Color.red: 1>
1585 |\x20\x20
1586 | ----------------------------------------------------------------------
1587 | Data descriptors inherited from enum.Enum:
1588 |\x20\x20
1589 | name
1590 | The name of the Enum member.
1591 |\x20\x20
1592 | value
1593 | The value of the Enum member.
1594 |\x20\x20
1595 | ----------------------------------------------------------------------
1596 | Data descriptors inherited from enum.EnumMeta:
1597 |\x20\x20
1598 | __members__
1599 | Returns a mapping of member name->value.
1600 |\x20\x20\x20\x20\x20\x20
1601 | This mapping lists all enum members, including aliases. Note that this
Ethan Furman3323da92015-04-11 09:39:59 -07001602 | is a read-only view of the internal mapping."""
1603
1604expected_help_output_without_docs = """\
1605Help on class Color in module %s:
1606
1607class Color(enum.Enum)
1608 | Method resolution order:
1609 | Color
1610 | enum.Enum
1611 | builtins.object
1612 |\x20\x20
1613 | Data and other attributes defined here:
1614 |\x20\x20
1615 | blue = <Color.blue: 3>
1616 |\x20\x20
1617 | green = <Color.green: 2>
1618 |\x20\x20
1619 | red = <Color.red: 1>
1620 |\x20\x20
1621 | ----------------------------------------------------------------------
1622 | Data descriptors inherited from enum.Enum:
1623 |\x20\x20
1624 | name
1625 |\x20\x20
1626 | value
1627 |\x20\x20
1628 | ----------------------------------------------------------------------
1629 | Data descriptors inherited from enum.EnumMeta:
1630 |\x20\x20
1631 | __members__"""
Ethan Furman5875d742013-10-21 20:45:55 -07001632
1633class TestStdLib(unittest.TestCase):
1634
Ethan Furman48a724f2015-04-11 23:23:06 -07001635 maxDiff = None
1636
Ethan Furman5875d742013-10-21 20:45:55 -07001637 class Color(Enum):
1638 red = 1
1639 green = 2
1640 blue = 3
1641
1642 def test_pydoc(self):
1643 # indirectly test __objclass__
Ethan Furman3323da92015-04-11 09:39:59 -07001644 if StrEnum.__doc__ is None:
1645 expected_text = expected_help_output_without_docs % __name__
1646 else:
1647 expected_text = expected_help_output_with_docs % __name__
Ethan Furman5875d742013-10-21 20:45:55 -07001648 output = StringIO()
1649 helper = pydoc.Helper(output=output)
1650 helper(self.Color)
1651 result = output.getvalue().strip()
Victor Stinner4b0432d2014-06-16 22:48:43 +02001652 self.assertEqual(result, expected_text)
Ethan Furman5875d742013-10-21 20:45:55 -07001653
1654 def test_inspect_getmembers(self):
1655 values = dict((
1656 ('__class__', EnumMeta),
Ethan Furman48a724f2015-04-11 23:23:06 -07001657 ('__doc__', 'An enumeration.'),
Ethan Furman5875d742013-10-21 20:45:55 -07001658 ('__members__', self.Color.__members__),
1659 ('__module__', __name__),
1660 ('blue', self.Color.blue),
1661 ('green', self.Color.green),
1662 ('name', Enum.__dict__['name']),
1663 ('red', self.Color.red),
1664 ('value', Enum.__dict__['value']),
1665 ))
1666 result = dict(inspect.getmembers(self.Color))
1667 self.assertEqual(values.keys(), result.keys())
1668 failed = False
1669 for k in values.keys():
1670 if result[k] != values[k]:
1671 print()
1672 print('\n%s\n key: %s\n result: %s\nexpected: %s\n%s\n' %
1673 ('=' * 75, k, result[k], values[k], '=' * 75), sep='')
1674 failed = True
1675 if failed:
1676 self.fail("result does not equal expected, see print above")
1677
1678 def test_inspect_classify_class_attrs(self):
1679 # indirectly test __objclass__
1680 from inspect import Attribute
1681 values = [
1682 Attribute(name='__class__', kind='data',
1683 defining_class=object, object=EnumMeta),
1684 Attribute(name='__doc__', kind='data',
Ethan Furman48a724f2015-04-11 23:23:06 -07001685 defining_class=self.Color, object='An enumeration.'),
Ethan Furman5875d742013-10-21 20:45:55 -07001686 Attribute(name='__members__', kind='property',
1687 defining_class=EnumMeta, object=EnumMeta.__members__),
1688 Attribute(name='__module__', kind='data',
1689 defining_class=self.Color, object=__name__),
1690 Attribute(name='blue', kind='data',
1691 defining_class=self.Color, object=self.Color.blue),
1692 Attribute(name='green', kind='data',
1693 defining_class=self.Color, object=self.Color.green),
1694 Attribute(name='red', kind='data',
1695 defining_class=self.Color, object=self.Color.red),
1696 Attribute(name='name', kind='data',
1697 defining_class=Enum, object=Enum.__dict__['name']),
1698 Attribute(name='value', kind='data',
1699 defining_class=Enum, object=Enum.__dict__['value']),
1700 ]
1701 values.sort(key=lambda item: item.name)
1702 result = list(inspect.classify_class_attrs(self.Color))
1703 result.sort(key=lambda item: item.name)
1704 failed = False
1705 for v, r in zip(values, result):
1706 if r != v:
1707 print('\n%s\n%s\n%s\n%s\n' % ('=' * 75, r, v, '=' * 75), sep='')
1708 failed = True
1709 if failed:
1710 self.fail("result does not equal expected, see print above")
1711
Martin Panter19e69c52015-11-14 12:46:42 +00001712
1713class MiscTestCase(unittest.TestCase):
1714 def test__all__(self):
1715 support.check__all__(self, enum)
1716
1717
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001718if __name__ == '__main__':
1719 unittest.main()