blob: a59a04943407b143a1d8134e7f6200860a5403bc [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
Ethan Furman6b3d64a2013-06-14 16:55:46 -07009
10# for pickle tests
11try:
12 class Stooges(Enum):
13 LARRY = 1
14 CURLY = 2
15 MOE = 3
16except Exception as exc:
17 Stooges = exc
18
19try:
20 class IntStooges(int, Enum):
21 LARRY = 1
22 CURLY = 2
23 MOE = 3
24except Exception as exc:
25 IntStooges = exc
26
27try:
28 class FloatStooges(float, Enum):
29 LARRY = 1.39
30 CURLY = 2.72
31 MOE = 3.142596
32except Exception as exc:
33 FloatStooges = exc
34
35# for pickle test and subclass tests
36try:
37 class StrEnum(str, Enum):
38 'accepts only string values'
39 class Name(StrEnum):
40 BDFL = 'Guido van Rossum'
41 FLUFL = 'Barry Warsaw'
42except Exception as exc:
43 Name = exc
44
45try:
46 Question = Enum('Question', 'who what when where why', module=__name__)
47except Exception as exc:
48 Question = exc
49
50try:
51 Answer = Enum('Answer', 'him this then there because')
52except Exception as exc:
53 Answer = exc
54
Ethan Furmanca1b7942014-02-08 11:36:27 -080055try:
56 Theory = Enum('Theory', 'rule law supposition', qualname='spanish_inquisition')
57except Exception as exc:
58 Theory = exc
59
Ethan Furman6b3d64a2013-06-14 16:55:46 -070060# for doctests
61try:
62 class Fruit(Enum):
63 tomato = 1
64 banana = 2
65 cherry = 3
66except Exception:
67 pass
68
Serhiy Storchakae50e7802015-03-31 16:56:49 +030069def test_pickle_dump_load(assertion, source, target=None):
Ethan Furman2ddb39a2014-02-06 17:28:50 -080070 if target is None:
71 target = source
Serhiy Storchakae50e7802015-03-31 16:56:49 +030072 for protocol in range(HIGHEST_PROTOCOL + 1):
Ethan Furman2ddb39a2014-02-06 17:28:50 -080073 assertion(loads(dumps(source, protocol=protocol)), target)
74
Serhiy Storchakae50e7802015-03-31 16:56:49 +030075def test_pickle_exception(assertion, exception, obj):
76 for protocol in range(HIGHEST_PROTOCOL + 1):
Ethan Furman2ddb39a2014-02-06 17:28:50 -080077 with assertion(exception):
78 dumps(obj, protocol=protocol)
Ethan Furman648f8602013-10-06 17:19:54 -070079
80class TestHelpers(unittest.TestCase):
81 # _is_descriptor, _is_sunder, _is_dunder
82
83 def test_is_descriptor(self):
84 class foo:
85 pass
86 for attr in ('__get__','__set__','__delete__'):
87 obj = foo()
88 self.assertFalse(enum._is_descriptor(obj))
89 setattr(obj, attr, 1)
90 self.assertTrue(enum._is_descriptor(obj))
91
92 def test_is_sunder(self):
93 for s in ('_a_', '_aa_'):
94 self.assertTrue(enum._is_sunder(s))
95
96 for s in ('a', 'a_', '_a', '__a', 'a__', '__a__', '_a__', '__a_', '_',
97 '__', '___', '____', '_____',):
98 self.assertFalse(enum._is_sunder(s))
99
100 def test_is_dunder(self):
101 for s in ('__a__', '__aa__'):
102 self.assertTrue(enum._is_dunder(s))
103 for s in ('a', 'a_', '_a', '__a', 'a__', '_a_', '_a__', '__a_', '_',
104 '__', '___', '____', '_____',):
105 self.assertFalse(enum._is_dunder(s))
106
107
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700108class TestEnum(unittest.TestCase):
Ethan Furmanca1b7942014-02-08 11:36:27 -0800109
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700110 def setUp(self):
111 class Season(Enum):
112 SPRING = 1
113 SUMMER = 2
114 AUTUMN = 3
115 WINTER = 4
116 self.Season = Season
117
Ethan Furmanec15a822013-08-31 19:17:41 -0700118 class Konstants(float, Enum):
119 E = 2.7182818
120 PI = 3.1415926
121 TAU = 2 * PI
122 self.Konstants = Konstants
123
124 class Grades(IntEnum):
125 A = 5
126 B = 4
127 C = 3
128 D = 2
129 F = 0
130 self.Grades = Grades
131
132 class Directional(str, Enum):
133 EAST = 'east'
134 WEST = 'west'
135 NORTH = 'north'
136 SOUTH = 'south'
137 self.Directional = Directional
138
139 from datetime import date
140 class Holiday(date, Enum):
141 NEW_YEAR = 2013, 1, 1
142 IDES_OF_MARCH = 2013, 3, 15
143 self.Holiday = Holiday
144
Ethan Furman388a3922013-08-12 06:51:41 -0700145 def test_dir_on_class(self):
146 Season = self.Season
147 self.assertEqual(
148 set(dir(Season)),
Ethan Furmanc850f342013-09-15 16:59:35 -0700149 set(['__class__', '__doc__', '__members__', '__module__',
Ethan Furman388a3922013-08-12 06:51:41 -0700150 'SPRING', 'SUMMER', 'AUTUMN', 'WINTER']),
151 )
152
153 def test_dir_on_item(self):
154 Season = self.Season
155 self.assertEqual(
156 set(dir(Season.WINTER)),
Ethan Furmanc850f342013-09-15 16:59:35 -0700157 set(['__class__', '__doc__', '__module__', 'name', 'value']),
Ethan Furman388a3922013-08-12 06:51:41 -0700158 )
159
Ethan Furmanc850f342013-09-15 16:59:35 -0700160 def test_dir_with_added_behavior(self):
161 class Test(Enum):
162 this = 'that'
163 these = 'those'
164 def wowser(self):
165 return ("Wowser! I'm %s!" % self.name)
166 self.assertEqual(
167 set(dir(Test)),
168 set(['__class__', '__doc__', '__members__', '__module__', 'this', 'these']),
169 )
170 self.assertEqual(
171 set(dir(Test.this)),
172 set(['__class__', '__doc__', '__module__', 'name', 'value', 'wowser']),
173 )
174
Ethan Furman0ae550b2014-10-14 08:58:32 -0700175 def test_dir_on_sub_with_behavior_on_super(self):
176 # see issue22506
177 class SuperEnum(Enum):
178 def invisible(self):
179 return "did you see me?"
180 class SubEnum(SuperEnum):
181 sample = 5
182 self.assertEqual(
183 set(dir(SubEnum.sample)),
184 set(['__class__', '__doc__', '__module__', 'name', 'value', 'invisible']),
185 )
186
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700187 def test_enum_in_enum_out(self):
188 Season = self.Season
189 self.assertIs(Season(Season.WINTER), Season.WINTER)
190
191 def test_enum_value(self):
192 Season = self.Season
193 self.assertEqual(Season.SPRING.value, 1)
194
195 def test_intenum_value(self):
196 self.assertEqual(IntStooges.CURLY.value, 2)
197
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700198 def test_enum(self):
199 Season = self.Season
200 lst = list(Season)
201 self.assertEqual(len(lst), len(Season))
202 self.assertEqual(len(Season), 4, Season)
203 self.assertEqual(
204 [Season.SPRING, Season.SUMMER, Season.AUTUMN, Season.WINTER], lst)
205
206 for i, season in enumerate('SPRING SUMMER AUTUMN WINTER'.split(), 1):
207 e = Season(i)
208 self.assertEqual(e, getattr(Season, season))
209 self.assertEqual(e.value, i)
210 self.assertNotEqual(e, i)
211 self.assertEqual(e.name, season)
212 self.assertIn(e, Season)
213 self.assertIs(type(e), Season)
214 self.assertIsInstance(e, Season)
215 self.assertEqual(str(e), 'Season.' + season)
216 self.assertEqual(
217 repr(e),
218 '<Season.{0}: {1}>'.format(season, i),
219 )
220
221 def test_value_name(self):
222 Season = self.Season
223 self.assertEqual(Season.SPRING.name, 'SPRING')
224 self.assertEqual(Season.SPRING.value, 1)
225 with self.assertRaises(AttributeError):
226 Season.SPRING.name = 'invierno'
227 with self.assertRaises(AttributeError):
228 Season.SPRING.value = 2
229
Ethan Furmanf203f2d2013-09-06 07:16:48 -0700230 def test_changing_member(self):
231 Season = self.Season
232 with self.assertRaises(AttributeError):
233 Season.WINTER = 'really cold'
234
Ethan Furman64a99722013-09-22 16:18:19 -0700235 def test_attribute_deletion(self):
236 class Season(Enum):
237 SPRING = 1
238 SUMMER = 2
239 AUTUMN = 3
240 WINTER = 4
241
242 def spam(cls):
243 pass
244
245 self.assertTrue(hasattr(Season, 'spam'))
246 del Season.spam
247 self.assertFalse(hasattr(Season, 'spam'))
248
249 with self.assertRaises(AttributeError):
250 del Season.SPRING
251 with self.assertRaises(AttributeError):
252 del Season.DRY
253 with self.assertRaises(AttributeError):
254 del Season.SPRING.name
255
Ethan Furman5de67b12016-04-13 23:52:09 -0700256 def test_bool_of_class(self):
257 class Empty(Enum):
258 pass
259 self.assertTrue(bool(Empty))
260
261 def test_bool_of_member(self):
262 class Count(Enum):
263 zero = 0
264 one = 1
265 two = 2
266 for member in Count:
267 self.assertTrue(bool(member))
268
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700269 def test_invalid_names(self):
270 with self.assertRaises(ValueError):
271 class Wrong(Enum):
272 mro = 9
273 with self.assertRaises(ValueError):
274 class Wrong(Enum):
275 _create_= 11
276 with self.assertRaises(ValueError):
277 class Wrong(Enum):
278 _get_mixins_ = 9
279 with self.assertRaises(ValueError):
280 class Wrong(Enum):
281 _find_new_ = 1
282 with self.assertRaises(ValueError):
283 class Wrong(Enum):
284 _any_name_ = 9
285
286 def test_contains(self):
287 Season = self.Season
288 self.assertIn(Season.AUTUMN, Season)
289 self.assertNotIn(3, Season)
290
291 val = Season(3)
292 self.assertIn(val, Season)
293
294 class OtherEnum(Enum):
295 one = 1; two = 2
296 self.assertNotIn(OtherEnum.two, Season)
297
298 def test_comparisons(self):
299 Season = self.Season
300 with self.assertRaises(TypeError):
301 Season.SPRING < Season.WINTER
302 with self.assertRaises(TypeError):
303 Season.SPRING > 4
304
305 self.assertNotEqual(Season.SPRING, 1)
306
307 class Part(Enum):
308 SPRING = 1
309 CLIP = 2
310 BARREL = 3
311
312 self.assertNotEqual(Season.SPRING, Part.SPRING)
313 with self.assertRaises(TypeError):
314 Season.SPRING < Part.CLIP
315
316 def test_enum_duplicates(self):
317 class Season(Enum):
318 SPRING = 1
319 SUMMER = 2
320 AUTUMN = FALL = 3
321 WINTER = 4
322 ANOTHER_SPRING = 1
323 lst = list(Season)
324 self.assertEqual(
325 lst,
326 [Season.SPRING, Season.SUMMER,
327 Season.AUTUMN, Season.WINTER,
328 ])
329 self.assertIs(Season.FALL, Season.AUTUMN)
330 self.assertEqual(Season.FALL.value, 3)
331 self.assertEqual(Season.AUTUMN.value, 3)
332 self.assertIs(Season(3), Season.AUTUMN)
333 self.assertIs(Season(1), Season.SPRING)
334 self.assertEqual(Season.FALL.name, 'AUTUMN')
335 self.assertEqual(
336 [k for k,v in Season.__members__.items() if v.name != k],
337 ['FALL', 'ANOTHER_SPRING'],
338 )
339
Ethan Furman101e0742013-09-15 12:34:36 -0700340 def test_duplicate_name(self):
341 with self.assertRaises(TypeError):
342 class Color(Enum):
343 red = 1
344 green = 2
345 blue = 3
346 red = 4
347
348 with self.assertRaises(TypeError):
349 class Color(Enum):
350 red = 1
351 green = 2
352 blue = 3
353 def red(self):
354 return 'red'
355
356 with self.assertRaises(TypeError):
357 class Color(Enum):
358 @property
359 def red(self):
360 return 'redder'
361 red = 1
362 green = 2
363 blue = 3
364
365
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700366 def test_enum_with_value_name(self):
367 class Huh(Enum):
368 name = 1
369 value = 2
370 self.assertEqual(
371 list(Huh),
372 [Huh.name, Huh.value],
373 )
374 self.assertIs(type(Huh.name), Huh)
375 self.assertEqual(Huh.name.name, 'name')
376 self.assertEqual(Huh.name.value, 1)
Ethan Furmanec15a822013-08-31 19:17:41 -0700377
378 def test_format_enum(self):
379 Season = self.Season
380 self.assertEqual('{}'.format(Season.SPRING),
381 '{}'.format(str(Season.SPRING)))
382 self.assertEqual( '{:}'.format(Season.SPRING),
383 '{:}'.format(str(Season.SPRING)))
384 self.assertEqual('{:20}'.format(Season.SPRING),
385 '{:20}'.format(str(Season.SPRING)))
386 self.assertEqual('{:^20}'.format(Season.SPRING),
387 '{:^20}'.format(str(Season.SPRING)))
388 self.assertEqual('{:>20}'.format(Season.SPRING),
389 '{:>20}'.format(str(Season.SPRING)))
390 self.assertEqual('{:<20}'.format(Season.SPRING),
391 '{:<20}'.format(str(Season.SPRING)))
392
393 def test_format_enum_custom(self):
394 class TestFloat(float, Enum):
395 one = 1.0
396 two = 2.0
397 def __format__(self, spec):
398 return 'TestFloat success!'
399 self.assertEqual('{}'.format(TestFloat.one), 'TestFloat success!')
400
401 def assertFormatIsValue(self, spec, member):
402 self.assertEqual(spec.format(member), spec.format(member.value))
403
404 def test_format_enum_date(self):
405 Holiday = self.Holiday
406 self.assertFormatIsValue('{}', Holiday.IDES_OF_MARCH)
407 self.assertFormatIsValue('{:}', Holiday.IDES_OF_MARCH)
408 self.assertFormatIsValue('{:20}', Holiday.IDES_OF_MARCH)
409 self.assertFormatIsValue('{:^20}', Holiday.IDES_OF_MARCH)
410 self.assertFormatIsValue('{:>20}', Holiday.IDES_OF_MARCH)
411 self.assertFormatIsValue('{:<20}', Holiday.IDES_OF_MARCH)
412 self.assertFormatIsValue('{:%Y %m}', Holiday.IDES_OF_MARCH)
413 self.assertFormatIsValue('{:%Y %m %M:00}', Holiday.IDES_OF_MARCH)
414
415 def test_format_enum_float(self):
416 Konstants = self.Konstants
417 self.assertFormatIsValue('{}', Konstants.TAU)
418 self.assertFormatIsValue('{:}', Konstants.TAU)
419 self.assertFormatIsValue('{:20}', Konstants.TAU)
420 self.assertFormatIsValue('{:^20}', Konstants.TAU)
421 self.assertFormatIsValue('{:>20}', Konstants.TAU)
422 self.assertFormatIsValue('{:<20}', Konstants.TAU)
423 self.assertFormatIsValue('{:n}', Konstants.TAU)
424 self.assertFormatIsValue('{:5.2}', Konstants.TAU)
425 self.assertFormatIsValue('{:f}', Konstants.TAU)
426
427 def test_format_enum_int(self):
428 Grades = self.Grades
429 self.assertFormatIsValue('{}', Grades.C)
430 self.assertFormatIsValue('{:}', Grades.C)
431 self.assertFormatIsValue('{:20}', Grades.C)
432 self.assertFormatIsValue('{:^20}', Grades.C)
433 self.assertFormatIsValue('{:>20}', Grades.C)
434 self.assertFormatIsValue('{:<20}', Grades.C)
435 self.assertFormatIsValue('{:+}', Grades.C)
436 self.assertFormatIsValue('{:08X}', Grades.C)
437 self.assertFormatIsValue('{:b}', Grades.C)
438
439 def test_format_enum_str(self):
440 Directional = self.Directional
441 self.assertFormatIsValue('{}', Directional.WEST)
442 self.assertFormatIsValue('{:}', Directional.WEST)
443 self.assertFormatIsValue('{:20}', Directional.WEST)
444 self.assertFormatIsValue('{:^20}', Directional.WEST)
445 self.assertFormatIsValue('{:>20}', Directional.WEST)
446 self.assertFormatIsValue('{:<20}', Directional.WEST)
447
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700448 def test_hash(self):
449 Season = self.Season
450 dates = {}
451 dates[Season.WINTER] = '1225'
452 dates[Season.SPRING] = '0315'
453 dates[Season.SUMMER] = '0704'
454 dates[Season.AUTUMN] = '1031'
455 self.assertEqual(dates[Season.AUTUMN], '1031')
456
457 def test_intenum_from_scratch(self):
458 class phy(int, Enum):
459 pi = 3
460 tau = 2 * pi
461 self.assertTrue(phy.pi < phy.tau)
462
463 def test_intenum_inherited(self):
464 class IntEnum(int, Enum):
465 pass
466 class phy(IntEnum):
467 pi = 3
468 tau = 2 * pi
469 self.assertTrue(phy.pi < phy.tau)
470
471 def test_floatenum_from_scratch(self):
472 class phy(float, Enum):
Ethan Furmanec15a822013-08-31 19:17:41 -0700473 pi = 3.1415926
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700474 tau = 2 * pi
475 self.assertTrue(phy.pi < phy.tau)
476
477 def test_floatenum_inherited(self):
478 class FloatEnum(float, Enum):
479 pass
480 class phy(FloatEnum):
Ethan Furmanec15a822013-08-31 19:17:41 -0700481 pi = 3.1415926
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700482 tau = 2 * pi
483 self.assertTrue(phy.pi < phy.tau)
484
485 def test_strenum_from_scratch(self):
486 class phy(str, Enum):
487 pi = 'Pi'
488 tau = 'Tau'
489 self.assertTrue(phy.pi < phy.tau)
490
491 def test_strenum_inherited(self):
492 class StrEnum(str, Enum):
493 pass
494 class phy(StrEnum):
495 pi = 'Pi'
496 tau = 'Tau'
497 self.assertTrue(phy.pi < phy.tau)
498
499
500 def test_intenum(self):
501 class WeekDay(IntEnum):
502 SUNDAY = 1
503 MONDAY = 2
504 TUESDAY = 3
505 WEDNESDAY = 4
506 THURSDAY = 5
507 FRIDAY = 6
508 SATURDAY = 7
509
510 self.assertEqual(['a', 'b', 'c'][WeekDay.MONDAY], 'c')
511 self.assertEqual([i for i in range(WeekDay.TUESDAY)], [0, 1, 2])
512
513 lst = list(WeekDay)
514 self.assertEqual(len(lst), len(WeekDay))
515 self.assertEqual(len(WeekDay), 7)
516 target = 'SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY'
517 target = target.split()
518 for i, weekday in enumerate(target, 1):
519 e = WeekDay(i)
520 self.assertEqual(e, i)
521 self.assertEqual(int(e), i)
522 self.assertEqual(e.name, weekday)
523 self.assertIn(e, WeekDay)
524 self.assertEqual(lst.index(e)+1, i)
525 self.assertTrue(0 < e < 8)
526 self.assertIs(type(e), WeekDay)
527 self.assertIsInstance(e, int)
528 self.assertIsInstance(e, Enum)
529
530 def test_intenum_duplicates(self):
531 class WeekDay(IntEnum):
532 SUNDAY = 1
533 MONDAY = 2
534 TUESDAY = TEUSDAY = 3
535 WEDNESDAY = 4
536 THURSDAY = 5
537 FRIDAY = 6
538 SATURDAY = 7
539 self.assertIs(WeekDay.TEUSDAY, WeekDay.TUESDAY)
540 self.assertEqual(WeekDay(3).name, 'TUESDAY')
541 self.assertEqual([k for k,v in WeekDay.__members__.items()
542 if v.name != k], ['TEUSDAY', ])
543
544 def test_pickle_enum(self):
545 if isinstance(Stooges, Exception):
546 raise Stooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800547 test_pickle_dump_load(self.assertIs, Stooges.CURLY)
548 test_pickle_dump_load(self.assertIs, Stooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700549
550 def test_pickle_int(self):
551 if isinstance(IntStooges, Exception):
552 raise IntStooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800553 test_pickle_dump_load(self.assertIs, IntStooges.CURLY)
554 test_pickle_dump_load(self.assertIs, IntStooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700555
556 def test_pickle_float(self):
557 if isinstance(FloatStooges, Exception):
558 raise FloatStooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800559 test_pickle_dump_load(self.assertIs, FloatStooges.CURLY)
560 test_pickle_dump_load(self.assertIs, FloatStooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700561
562 def test_pickle_enum_function(self):
563 if isinstance(Answer, Exception):
564 raise Answer
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800565 test_pickle_dump_load(self.assertIs, Answer.him)
566 test_pickle_dump_load(self.assertIs, Answer)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700567
568 def test_pickle_enum_function_with_module(self):
569 if isinstance(Question, Exception):
570 raise Question
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800571 test_pickle_dump_load(self.assertIs, Question.who)
572 test_pickle_dump_load(self.assertIs, Question)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700573
Ethan Furmanca1b7942014-02-08 11:36:27 -0800574 def test_enum_function_with_qualname(self):
575 if isinstance(Theory, Exception):
576 raise Theory
577 self.assertEqual(Theory.__qualname__, 'spanish_inquisition')
578
579 def test_class_nested_enum_and_pickle_protocol_four(self):
580 # would normally just have this directly in the class namespace
581 class NestedEnum(Enum):
582 twigs = 'common'
583 shiny = 'rare'
584
585 self.__class__.NestedEnum = NestedEnum
586 self.NestedEnum.__qualname__ = '%s.NestedEnum' % self.__class__.__name__
Serhiy Storchakae50e7802015-03-31 16:56:49 +0300587 test_pickle_dump_load(self.assertIs, self.NestedEnum.twigs)
Ethan Furmanca1b7942014-02-08 11:36:27 -0800588
Ethan Furman24e837f2015-03-18 17:27:57 -0700589 def test_pickle_by_name(self):
590 class ReplaceGlobalInt(IntEnum):
591 ONE = 1
592 TWO = 2
593 ReplaceGlobalInt.__reduce_ex__ = enum._reduce_ex_by_name
594 for proto in range(HIGHEST_PROTOCOL):
595 self.assertEqual(ReplaceGlobalInt.TWO.__reduce_ex__(proto), 'TWO')
596
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700597 def test_exploding_pickle(self):
Ethan Furmanca1b7942014-02-08 11:36:27 -0800598 BadPickle = Enum(
599 'BadPickle', 'dill sweet bread-n-butter', module=__name__)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700600 globals()['BadPickle'] = BadPickle
Ethan Furmanca1b7942014-02-08 11:36:27 -0800601 # now break BadPickle to test exception raising
602 enum._make_class_unpicklable(BadPickle)
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800603 test_pickle_exception(self.assertRaises, TypeError, BadPickle.dill)
604 test_pickle_exception(self.assertRaises, PicklingError, BadPickle)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700605
606 def test_string_enum(self):
607 class SkillLevel(str, Enum):
608 master = 'what is the sound of one hand clapping?'
609 journeyman = 'why did the chicken cross the road?'
610 apprentice = 'knock, knock!'
611 self.assertEqual(SkillLevel.apprentice, 'knock, knock!')
612
613 def test_getattr_getitem(self):
614 class Period(Enum):
615 morning = 1
616 noon = 2
617 evening = 3
618 night = 4
619 self.assertIs(Period(2), Period.noon)
620 self.assertIs(getattr(Period, 'night'), Period.night)
621 self.assertIs(Period['morning'], Period.morning)
622
623 def test_getattr_dunder(self):
624 Season = self.Season
625 self.assertTrue(getattr(Season, '__eq__'))
626
627 def test_iteration_order(self):
628 class Season(Enum):
629 SUMMER = 2
630 WINTER = 4
631 AUTUMN = 3
632 SPRING = 1
633 self.assertEqual(
634 list(Season),
635 [Season.SUMMER, Season.WINTER, Season.AUTUMN, Season.SPRING],
636 )
637
Ethan Furman2131a4a2013-09-14 18:11:24 -0700638 def test_reversed_iteration_order(self):
639 self.assertEqual(
640 list(reversed(self.Season)),
641 [self.Season.WINTER, self.Season.AUTUMN, self.Season.SUMMER,
642 self.Season.SPRING]
643 )
644
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700645 def test_programatic_function_string(self):
646 SummerMonth = Enum('SummerMonth', 'june july august')
647 lst = list(SummerMonth)
648 self.assertEqual(len(lst), len(SummerMonth))
649 self.assertEqual(len(SummerMonth), 3, SummerMonth)
650 self.assertEqual(
651 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
652 lst,
653 )
654 for i, month in enumerate('june july august'.split(), 1):
655 e = SummerMonth(i)
656 self.assertEqual(int(e.value), i)
657 self.assertNotEqual(e, i)
658 self.assertEqual(e.name, month)
659 self.assertIn(e, SummerMonth)
660 self.assertIs(type(e), SummerMonth)
661
Ethan Furmand9925a12014-09-16 20:35:55 -0700662 def test_programatic_function_string_with_start(self):
663 SummerMonth = Enum('SummerMonth', 'june july august', start=10)
664 lst = list(SummerMonth)
665 self.assertEqual(len(lst), len(SummerMonth))
666 self.assertEqual(len(SummerMonth), 3, SummerMonth)
667 self.assertEqual(
668 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
669 lst,
670 )
671 for i, month in enumerate('june july august'.split(), 10):
672 e = SummerMonth(i)
673 self.assertEqual(int(e.value), i)
674 self.assertNotEqual(e, i)
675 self.assertEqual(e.name, month)
676 self.assertIn(e, SummerMonth)
677 self.assertIs(type(e), SummerMonth)
678
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700679 def test_programatic_function_string_list(self):
680 SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'])
681 lst = list(SummerMonth)
682 self.assertEqual(len(lst), len(SummerMonth))
683 self.assertEqual(len(SummerMonth), 3, SummerMonth)
684 self.assertEqual(
685 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
686 lst,
687 )
688 for i, month in enumerate('june july august'.split(), 1):
689 e = SummerMonth(i)
690 self.assertEqual(int(e.value), i)
691 self.assertNotEqual(e, i)
692 self.assertEqual(e.name, month)
693 self.assertIn(e, SummerMonth)
694 self.assertIs(type(e), SummerMonth)
695
Ethan Furmand9925a12014-09-16 20:35:55 -0700696 def test_programatic_function_string_list_with_start(self):
697 SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'], start=20)
698 lst = list(SummerMonth)
699 self.assertEqual(len(lst), len(SummerMonth))
700 self.assertEqual(len(SummerMonth), 3, SummerMonth)
701 self.assertEqual(
702 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
703 lst,
704 )
705 for i, month in enumerate('june july august'.split(), 20):
706 e = SummerMonth(i)
707 self.assertEqual(int(e.value), i)
708 self.assertNotEqual(e, i)
709 self.assertEqual(e.name, month)
710 self.assertIn(e, SummerMonth)
711 self.assertIs(type(e), SummerMonth)
712
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700713 def test_programatic_function_iterable(self):
714 SummerMonth = Enum(
715 'SummerMonth',
716 (('june', 1), ('july', 2), ('august', 3))
717 )
718 lst = list(SummerMonth)
719 self.assertEqual(len(lst), len(SummerMonth))
720 self.assertEqual(len(SummerMonth), 3, SummerMonth)
721 self.assertEqual(
722 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
723 lst,
724 )
725 for i, month in enumerate('june july august'.split(), 1):
726 e = SummerMonth(i)
727 self.assertEqual(int(e.value), i)
728 self.assertNotEqual(e, i)
729 self.assertEqual(e.name, month)
730 self.assertIn(e, SummerMonth)
731 self.assertIs(type(e), SummerMonth)
732
733 def test_programatic_function_from_dict(self):
734 SummerMonth = Enum(
735 'SummerMonth',
736 OrderedDict((('june', 1), ('july', 2), ('august', 3)))
737 )
738 lst = list(SummerMonth)
739 self.assertEqual(len(lst), len(SummerMonth))
740 self.assertEqual(len(SummerMonth), 3, SummerMonth)
741 self.assertEqual(
742 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
743 lst,
744 )
745 for i, month in enumerate('june july august'.split(), 1):
746 e = SummerMonth(i)
747 self.assertEqual(int(e.value), i)
748 self.assertNotEqual(e, i)
749 self.assertEqual(e.name, month)
750 self.assertIn(e, SummerMonth)
751 self.assertIs(type(e), SummerMonth)
752
753 def test_programatic_function_type(self):
754 SummerMonth = Enum('SummerMonth', 'june july august', type=int)
755 lst = list(SummerMonth)
756 self.assertEqual(len(lst), len(SummerMonth))
757 self.assertEqual(len(SummerMonth), 3, SummerMonth)
758 self.assertEqual(
759 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
760 lst,
761 )
762 for i, month in enumerate('june july august'.split(), 1):
763 e = SummerMonth(i)
764 self.assertEqual(e, i)
765 self.assertEqual(e.name, month)
766 self.assertIn(e, SummerMonth)
767 self.assertIs(type(e), SummerMonth)
768
Ethan Furmand9925a12014-09-16 20:35:55 -0700769 def test_programatic_function_type_with_start(self):
770 SummerMonth = Enum('SummerMonth', 'june july august', type=int, start=30)
771 lst = list(SummerMonth)
772 self.assertEqual(len(lst), len(SummerMonth))
773 self.assertEqual(len(SummerMonth), 3, SummerMonth)
774 self.assertEqual(
775 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
776 lst,
777 )
778 for i, month in enumerate('june july august'.split(), 30):
779 e = SummerMonth(i)
780 self.assertEqual(e, i)
781 self.assertEqual(e.name, month)
782 self.assertIn(e, SummerMonth)
783 self.assertIs(type(e), SummerMonth)
784
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700785 def test_programatic_function_type_from_subclass(self):
786 SummerMonth = IntEnum('SummerMonth', 'june july august')
787 lst = list(SummerMonth)
788 self.assertEqual(len(lst), len(SummerMonth))
789 self.assertEqual(len(SummerMonth), 3, SummerMonth)
790 self.assertEqual(
791 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
792 lst,
793 )
794 for i, month in enumerate('june july august'.split(), 1):
795 e = SummerMonth(i)
796 self.assertEqual(e, i)
797 self.assertEqual(e.name, month)
798 self.assertIn(e, SummerMonth)
799 self.assertIs(type(e), SummerMonth)
800
Ethan Furmand9925a12014-09-16 20:35:55 -0700801 def test_programatic_function_type_from_subclass_with_start(self):
802 SummerMonth = IntEnum('SummerMonth', 'june july august', start=40)
803 lst = list(SummerMonth)
804 self.assertEqual(len(lst), len(SummerMonth))
805 self.assertEqual(len(SummerMonth), 3, SummerMonth)
806 self.assertEqual(
807 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
808 lst,
809 )
810 for i, month in enumerate('june july august'.split(), 40):
811 e = SummerMonth(i)
812 self.assertEqual(e, i)
813 self.assertEqual(e.name, month)
814 self.assertIn(e, SummerMonth)
815 self.assertIs(type(e), SummerMonth)
816
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700817 def test_subclassing(self):
818 if isinstance(Name, Exception):
819 raise Name
820 self.assertEqual(Name.BDFL, 'Guido van Rossum')
821 self.assertTrue(Name.BDFL, Name('Guido van Rossum'))
822 self.assertIs(Name.BDFL, getattr(Name, 'BDFL'))
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800823 test_pickle_dump_load(self.assertIs, Name.BDFL)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700824
825 def test_extending(self):
826 class Color(Enum):
827 red = 1
828 green = 2
829 blue = 3
830 with self.assertRaises(TypeError):
831 class MoreColor(Color):
832 cyan = 4
833 magenta = 5
834 yellow = 6
835
836 def test_exclude_methods(self):
837 class whatever(Enum):
838 this = 'that'
839 these = 'those'
840 def really(self):
841 return 'no, not %s' % self.value
842 self.assertIsNot(type(whatever.really), whatever)
843 self.assertEqual(whatever.this.really(), 'no, not that')
844
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700845 def test_wrong_inheritance_order(self):
846 with self.assertRaises(TypeError):
847 class Wrong(Enum, str):
848 NotHere = 'error before this point'
849
850 def test_intenum_transitivity(self):
851 class number(IntEnum):
852 one = 1
853 two = 2
854 three = 3
855 class numero(IntEnum):
856 uno = 1
857 dos = 2
858 tres = 3
859 self.assertEqual(number.one, numero.uno)
860 self.assertEqual(number.two, numero.dos)
861 self.assertEqual(number.three, numero.tres)
862
863 def test_wrong_enum_in_call(self):
864 class Monochrome(Enum):
865 black = 0
866 white = 1
867 class Gender(Enum):
868 male = 0
869 female = 1
870 self.assertRaises(ValueError, Monochrome, Gender.male)
871
872 def test_wrong_enum_in_mixed_call(self):
873 class Monochrome(IntEnum):
874 black = 0
875 white = 1
876 class Gender(Enum):
877 male = 0
878 female = 1
879 self.assertRaises(ValueError, Monochrome, Gender.male)
880
881 def test_mixed_enum_in_call_1(self):
882 class Monochrome(IntEnum):
883 black = 0
884 white = 1
885 class Gender(IntEnum):
886 male = 0
887 female = 1
888 self.assertIs(Monochrome(Gender.female), Monochrome.white)
889
890 def test_mixed_enum_in_call_2(self):
891 class Monochrome(Enum):
892 black = 0
893 white = 1
894 class Gender(IntEnum):
895 male = 0
896 female = 1
897 self.assertIs(Monochrome(Gender.male), Monochrome.black)
898
899 def test_flufl_enum(self):
900 class Fluflnum(Enum):
901 def __int__(self):
902 return int(self.value)
903 class MailManOptions(Fluflnum):
904 option1 = 1
905 option2 = 2
906 option3 = 3
907 self.assertEqual(int(MailManOptions.option1), 1)
908
Ethan Furman5e5a8232013-08-04 08:42:23 -0700909 def test_introspection(self):
910 class Number(IntEnum):
911 one = 100
912 two = 200
913 self.assertIs(Number.one._member_type_, int)
914 self.assertIs(Number._member_type_, int)
915 class String(str, Enum):
916 yarn = 'soft'
917 rope = 'rough'
918 wire = 'hard'
919 self.assertIs(String.yarn._member_type_, str)
920 self.assertIs(String._member_type_, str)
921 class Plain(Enum):
922 vanilla = 'white'
923 one = 1
924 self.assertIs(Plain.vanilla._member_type_, object)
925 self.assertIs(Plain._member_type_, object)
926
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700927 def test_no_such_enum_member(self):
928 class Color(Enum):
929 red = 1
930 green = 2
931 blue = 3
932 with self.assertRaises(ValueError):
933 Color(4)
934 with self.assertRaises(KeyError):
935 Color['chartreuse']
936
937 def test_new_repr(self):
938 class Color(Enum):
939 red = 1
940 green = 2
941 blue = 3
942 def __repr__(self):
943 return "don't you just love shades of %s?" % self.name
944 self.assertEqual(
945 repr(Color.blue),
946 "don't you just love shades of blue?",
947 )
948
949 def test_inherited_repr(self):
950 class MyEnum(Enum):
951 def __repr__(self):
952 return "My name is %s." % self.name
953 class MyIntEnum(int, MyEnum):
954 this = 1
955 that = 2
956 theother = 3
957 self.assertEqual(repr(MyIntEnum.that), "My name is that.")
958
959 def test_multiple_mixin_mro(self):
960 class auto_enum(type(Enum)):
961 def __new__(metacls, cls, bases, classdict):
962 temp = type(classdict)()
963 names = set(classdict._member_names)
964 i = 0
965 for k in classdict._member_names:
966 v = classdict[k]
967 if v is Ellipsis:
968 v = i
969 else:
970 i = v
971 i += 1
972 temp[k] = v
973 for k, v in classdict.items():
974 if k not in names:
975 temp[k] = v
976 return super(auto_enum, metacls).__new__(
977 metacls, cls, bases, temp)
978
979 class AutoNumberedEnum(Enum, metaclass=auto_enum):
980 pass
981
982 class AutoIntEnum(IntEnum, metaclass=auto_enum):
983 pass
984
985 class TestAutoNumber(AutoNumberedEnum):
986 a = ...
987 b = 3
988 c = ...
989
990 class TestAutoInt(AutoIntEnum):
991 a = ...
992 b = 3
993 c = ...
994
995 def test_subclasses_with_getnewargs(self):
996 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800997 __qualname__ = 'NamedInt' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700998 def __new__(cls, *args):
999 _args = args
1000 name, *args = args
1001 if len(args) == 0:
1002 raise TypeError("name and value must be specified")
1003 self = int.__new__(cls, *args)
1004 self._intname = name
1005 self._args = _args
1006 return self
1007 def __getnewargs__(self):
1008 return self._args
1009 @property
1010 def __name__(self):
1011 return self._intname
1012 def __repr__(self):
1013 # repr() is updated to include the name and type info
1014 return "{}({!r}, {})".format(type(self).__name__,
1015 self.__name__,
1016 int.__repr__(self))
1017 def __str__(self):
1018 # str() is unchanged, even if it relies on the repr() fallback
1019 base = int
1020 base_str = base.__str__
1021 if base_str.__objclass__ is object:
1022 return base.__repr__(self)
1023 return base_str(self)
1024 # for simplicity, we only define one operator that
1025 # propagates expressions
1026 def __add__(self, other):
1027 temp = int(self) + int( other)
1028 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1029 return NamedInt(
1030 '({0} + {1})'.format(self.__name__, other.__name__),
1031 temp )
1032 else:
1033 return temp
1034
1035 class NEI(NamedInt, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001036 __qualname__ = 'NEI' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001037 x = ('the-x', 1)
1038 y = ('the-y', 2)
1039
Ethan Furman2aa27322013-07-19 19:35:56 -07001040
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001041 self.assertIs(NEI.__new__, Enum.__new__)
1042 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1043 globals()['NamedInt'] = NamedInt
1044 globals()['NEI'] = NEI
1045 NI5 = NamedInt('test', 5)
1046 self.assertEqual(NI5, 5)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001047 test_pickle_dump_load(self.assertEqual, NI5, 5)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001048 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001049 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001050 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001051
Ethan Furmanca1b7942014-02-08 11:36:27 -08001052 def test_subclasses_with_getnewargs_ex(self):
1053 class NamedInt(int):
1054 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1055 def __new__(cls, *args):
1056 _args = args
1057 name, *args = args
1058 if len(args) == 0:
1059 raise TypeError("name and value must be specified")
1060 self = int.__new__(cls, *args)
1061 self._intname = name
1062 self._args = _args
1063 return self
1064 def __getnewargs_ex__(self):
1065 return self._args, {}
1066 @property
1067 def __name__(self):
1068 return self._intname
1069 def __repr__(self):
1070 # repr() is updated to include the name and type info
1071 return "{}({!r}, {})".format(type(self).__name__,
1072 self.__name__,
1073 int.__repr__(self))
1074 def __str__(self):
1075 # str() is unchanged, even if it relies on the repr() fallback
1076 base = int
1077 base_str = base.__str__
1078 if base_str.__objclass__ is object:
1079 return base.__repr__(self)
1080 return base_str(self)
1081 # for simplicity, we only define one operator that
1082 # propagates expressions
1083 def __add__(self, other):
1084 temp = int(self) + int( other)
1085 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1086 return NamedInt(
1087 '({0} + {1})'.format(self.__name__, other.__name__),
1088 temp )
1089 else:
1090 return temp
1091
1092 class NEI(NamedInt, Enum):
1093 __qualname__ = 'NEI' # needed for pickle protocol 4
1094 x = ('the-x', 1)
1095 y = ('the-y', 2)
1096
1097
1098 self.assertIs(NEI.__new__, Enum.__new__)
1099 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1100 globals()['NamedInt'] = NamedInt
1101 globals()['NEI'] = NEI
1102 NI5 = NamedInt('test', 5)
1103 self.assertEqual(NI5, 5)
Serhiy Storchakae50e7802015-03-31 16:56:49 +03001104 test_pickle_dump_load(self.assertEqual, NI5, 5)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001105 self.assertEqual(NEI.y.value, 2)
Serhiy Storchakae50e7802015-03-31 16:56:49 +03001106 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001107 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001108
1109 def test_subclasses_with_reduce(self):
1110 class NamedInt(int):
1111 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1112 def __new__(cls, *args):
1113 _args = args
1114 name, *args = args
1115 if len(args) == 0:
1116 raise TypeError("name and value must be specified")
1117 self = int.__new__(cls, *args)
1118 self._intname = name
1119 self._args = _args
1120 return self
1121 def __reduce__(self):
1122 return self.__class__, self._args
1123 @property
1124 def __name__(self):
1125 return self._intname
1126 def __repr__(self):
1127 # repr() is updated to include the name and type info
1128 return "{}({!r}, {})".format(type(self).__name__,
1129 self.__name__,
1130 int.__repr__(self))
1131 def __str__(self):
1132 # str() is unchanged, even if it relies on the repr() fallback
1133 base = int
1134 base_str = base.__str__
1135 if base_str.__objclass__ is object:
1136 return base.__repr__(self)
1137 return base_str(self)
1138 # for simplicity, we only define one operator that
1139 # propagates expressions
1140 def __add__(self, other):
1141 temp = int(self) + int( other)
1142 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1143 return NamedInt(
1144 '({0} + {1})'.format(self.__name__, other.__name__),
1145 temp )
1146 else:
1147 return temp
1148
1149 class NEI(NamedInt, Enum):
1150 __qualname__ = 'NEI' # needed for pickle protocol 4
1151 x = ('the-x', 1)
1152 y = ('the-y', 2)
1153
1154
1155 self.assertIs(NEI.__new__, Enum.__new__)
1156 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1157 globals()['NamedInt'] = NamedInt
1158 globals()['NEI'] = NEI
1159 NI5 = NamedInt('test', 5)
1160 self.assertEqual(NI5, 5)
1161 test_pickle_dump_load(self.assertEqual, NI5, 5)
1162 self.assertEqual(NEI.y.value, 2)
1163 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001164 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001165
1166 def test_subclasses_with_reduce_ex(self):
1167 class NamedInt(int):
1168 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1169 def __new__(cls, *args):
1170 _args = args
1171 name, *args = args
1172 if len(args) == 0:
1173 raise TypeError("name and value must be specified")
1174 self = int.__new__(cls, *args)
1175 self._intname = name
1176 self._args = _args
1177 return self
1178 def __reduce_ex__(self, proto):
1179 return self.__class__, self._args
1180 @property
1181 def __name__(self):
1182 return self._intname
1183 def __repr__(self):
1184 # repr() is updated to include the name and type info
1185 return "{}({!r}, {})".format(type(self).__name__,
1186 self.__name__,
1187 int.__repr__(self))
1188 def __str__(self):
1189 # str() is unchanged, even if it relies on the repr() fallback
1190 base = int
1191 base_str = base.__str__
1192 if base_str.__objclass__ is object:
1193 return base.__repr__(self)
1194 return base_str(self)
1195 # for simplicity, we only define one operator that
1196 # propagates expressions
1197 def __add__(self, other):
1198 temp = int(self) + int( other)
1199 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1200 return NamedInt(
1201 '({0} + {1})'.format(self.__name__, other.__name__),
1202 temp )
1203 else:
1204 return temp
1205
1206 class NEI(NamedInt, Enum):
1207 __qualname__ = 'NEI' # needed for pickle protocol 4
1208 x = ('the-x', 1)
1209 y = ('the-y', 2)
1210
1211
1212 self.assertIs(NEI.__new__, Enum.__new__)
1213 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1214 globals()['NamedInt'] = NamedInt
1215 globals()['NEI'] = NEI
1216 NI5 = NamedInt('test', 5)
1217 self.assertEqual(NI5, 5)
1218 test_pickle_dump_load(self.assertEqual, NI5, 5)
1219 self.assertEqual(NEI.y.value, 2)
1220 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001221 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001222
Ethan Furmandc870522014-02-18 12:37:12 -08001223 def test_subclasses_without_direct_pickle_support(self):
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001224 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001225 __qualname__ = 'NamedInt'
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001226 def __new__(cls, *args):
1227 _args = args
1228 name, *args = args
1229 if len(args) == 0:
1230 raise TypeError("name and value must be specified")
1231 self = int.__new__(cls, *args)
1232 self._intname = name
1233 self._args = _args
1234 return self
1235 @property
1236 def __name__(self):
1237 return self._intname
1238 def __repr__(self):
1239 # repr() is updated to include the name and type info
1240 return "{}({!r}, {})".format(type(self).__name__,
1241 self.__name__,
1242 int.__repr__(self))
1243 def __str__(self):
1244 # str() is unchanged, even if it relies on the repr() fallback
1245 base = int
1246 base_str = base.__str__
1247 if base_str.__objclass__ is object:
1248 return base.__repr__(self)
1249 return base_str(self)
1250 # for simplicity, we only define one operator that
1251 # propagates expressions
1252 def __add__(self, other):
1253 temp = int(self) + int( other)
1254 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1255 return NamedInt(
1256 '({0} + {1})'.format(self.__name__, other.__name__),
1257 temp )
1258 else:
1259 return temp
1260
1261 class NEI(NamedInt, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001262 __qualname__ = 'NEI'
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001263 x = ('the-x', 1)
1264 y = ('the-y', 2)
1265
1266 self.assertIs(NEI.__new__, Enum.__new__)
1267 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1268 globals()['NamedInt'] = NamedInt
1269 globals()['NEI'] = NEI
1270 NI5 = NamedInt('test', 5)
1271 self.assertEqual(NI5, 5)
1272 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001273 test_pickle_exception(self.assertRaises, TypeError, NEI.x)
1274 test_pickle_exception(self.assertRaises, PicklingError, NEI)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001275
Ethan Furmandc870522014-02-18 12:37:12 -08001276 def test_subclasses_without_direct_pickle_support_using_name(self):
1277 class NamedInt(int):
1278 __qualname__ = 'NamedInt'
1279 def __new__(cls, *args):
1280 _args = args
1281 name, *args = args
1282 if len(args) == 0:
1283 raise TypeError("name and value must be specified")
1284 self = int.__new__(cls, *args)
1285 self._intname = name
1286 self._args = _args
1287 return self
1288 @property
1289 def __name__(self):
1290 return self._intname
1291 def __repr__(self):
1292 # repr() is updated to include the name and type info
1293 return "{}({!r}, {})".format(type(self).__name__,
1294 self.__name__,
1295 int.__repr__(self))
1296 def __str__(self):
1297 # str() is unchanged, even if it relies on the repr() fallback
1298 base = int
1299 base_str = base.__str__
1300 if base_str.__objclass__ is object:
1301 return base.__repr__(self)
1302 return base_str(self)
1303 # for simplicity, we only define one operator that
1304 # propagates expressions
1305 def __add__(self, other):
1306 temp = int(self) + int( other)
1307 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1308 return NamedInt(
1309 '({0} + {1})'.format(self.__name__, other.__name__),
1310 temp )
1311 else:
1312 return temp
1313
1314 class NEI(NamedInt, Enum):
1315 __qualname__ = 'NEI'
1316 x = ('the-x', 1)
1317 y = ('the-y', 2)
1318 def __reduce_ex__(self, proto):
1319 return getattr, (self.__class__, self._name_)
1320
1321 self.assertIs(NEI.__new__, Enum.__new__)
1322 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1323 globals()['NamedInt'] = NamedInt
1324 globals()['NEI'] = NEI
1325 NI5 = NamedInt('test', 5)
1326 self.assertEqual(NI5, 5)
1327 self.assertEqual(NEI.y.value, 2)
1328 test_pickle_dump_load(self.assertIs, NEI.y)
1329 test_pickle_dump_load(self.assertIs, NEI)
1330
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001331 def test_tuple_subclass(self):
1332 class SomeTuple(tuple, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001333 __qualname__ = 'SomeTuple' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001334 first = (1, 'for the money')
1335 second = (2, 'for the show')
1336 third = (3, 'for the music')
1337 self.assertIs(type(SomeTuple.first), SomeTuple)
1338 self.assertIsInstance(SomeTuple.second, tuple)
1339 self.assertEqual(SomeTuple.third, (3, 'for the music'))
1340 globals()['SomeTuple'] = SomeTuple
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001341 test_pickle_dump_load(self.assertIs, SomeTuple.first)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001342
1343 def test_duplicate_values_give_unique_enum_items(self):
1344 class AutoNumber(Enum):
1345 first = ()
1346 second = ()
1347 third = ()
1348 def __new__(cls):
1349 value = len(cls.__members__) + 1
1350 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001351 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001352 return obj
1353 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001354 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001355 self.assertEqual(
1356 list(AutoNumber),
1357 [AutoNumber.first, AutoNumber.second, AutoNumber.third],
1358 )
1359 self.assertEqual(int(AutoNumber.second), 2)
Ethan Furman2aa27322013-07-19 19:35:56 -07001360 self.assertEqual(AutoNumber.third.value, 3)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001361 self.assertIs(AutoNumber(1), AutoNumber.first)
1362
1363 def test_inherited_new_from_enhanced_enum(self):
1364 class AutoNumber(Enum):
1365 def __new__(cls):
1366 value = len(cls.__members__) + 1
1367 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001368 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001369 return obj
1370 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001371 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001372 class Color(AutoNumber):
1373 red = ()
1374 green = ()
1375 blue = ()
1376 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1377 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1378
1379 def test_inherited_new_from_mixed_enum(self):
1380 class AutoNumber(IntEnum):
1381 def __new__(cls):
1382 value = len(cls.__members__) + 1
1383 obj = int.__new__(cls, value)
Ethan Furman520ad572013-07-19 19:47:21 -07001384 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001385 return obj
1386 class Color(AutoNumber):
1387 red = ()
1388 green = ()
1389 blue = ()
1390 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1391 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1392
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001393 def test_equality(self):
1394 class AlwaysEqual:
1395 def __eq__(self, other):
1396 return True
1397 class OrdinaryEnum(Enum):
1398 a = 1
1399 self.assertEqual(AlwaysEqual(), OrdinaryEnum.a)
1400 self.assertEqual(OrdinaryEnum.a, AlwaysEqual())
1401
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001402 def test_ordered_mixin(self):
1403 class OrderedEnum(Enum):
1404 def __ge__(self, other):
1405 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001406 return self._value_ >= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001407 return NotImplemented
1408 def __gt__(self, other):
1409 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001410 return self._value_ > other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001411 return NotImplemented
1412 def __le__(self, other):
1413 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001414 return self._value_ <= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001415 return NotImplemented
1416 def __lt__(self, other):
1417 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001418 return self._value_ < other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001419 return NotImplemented
1420 class Grade(OrderedEnum):
1421 A = 5
1422 B = 4
1423 C = 3
1424 D = 2
1425 F = 1
1426 self.assertGreater(Grade.A, Grade.B)
1427 self.assertLessEqual(Grade.F, Grade.C)
1428 self.assertLess(Grade.D, Grade.A)
1429 self.assertGreaterEqual(Grade.B, Grade.B)
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001430 self.assertEqual(Grade.B, Grade.B)
1431 self.assertNotEqual(Grade.C, Grade.D)
Ethan Furman520ad572013-07-19 19:47:21 -07001432
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001433 def test_extending2(self):
1434 class Shade(Enum):
1435 def shade(self):
1436 print(self.name)
1437 class Color(Shade):
1438 red = 1
1439 green = 2
1440 blue = 3
1441 with self.assertRaises(TypeError):
1442 class MoreColor(Color):
1443 cyan = 4
1444 magenta = 5
1445 yellow = 6
1446
1447 def test_extending3(self):
1448 class Shade(Enum):
1449 def shade(self):
1450 return self.name
1451 class Color(Shade):
1452 def hex(self):
1453 return '%s hexlified!' % self.value
1454 class MoreColor(Color):
1455 cyan = 4
1456 magenta = 5
1457 yellow = 6
1458 self.assertEqual(MoreColor.magenta.hex(), '5 hexlified!')
1459
1460
1461 def test_no_duplicates(self):
1462 class UniqueEnum(Enum):
1463 def __init__(self, *args):
1464 cls = self.__class__
1465 if any(self.value == e.value for e in cls):
1466 a = self.name
1467 e = cls(self.value).name
1468 raise ValueError(
1469 "aliases not allowed in UniqueEnum: %r --> %r"
1470 % (a, e)
1471 )
1472 class Color(UniqueEnum):
1473 red = 1
1474 green = 2
1475 blue = 3
1476 with self.assertRaises(ValueError):
1477 class Color(UniqueEnum):
1478 red = 1
1479 green = 2
1480 blue = 3
1481 grene = 2
1482
1483 def test_init(self):
1484 class Planet(Enum):
1485 MERCURY = (3.303e+23, 2.4397e6)
1486 VENUS = (4.869e+24, 6.0518e6)
1487 EARTH = (5.976e+24, 6.37814e6)
1488 MARS = (6.421e+23, 3.3972e6)
1489 JUPITER = (1.9e+27, 7.1492e7)
1490 SATURN = (5.688e+26, 6.0268e7)
1491 URANUS = (8.686e+25, 2.5559e7)
1492 NEPTUNE = (1.024e+26, 2.4746e7)
1493 def __init__(self, mass, radius):
1494 self.mass = mass # in kilograms
1495 self.radius = radius # in meters
1496 @property
1497 def surface_gravity(self):
1498 # universal gravitational constant (m3 kg-1 s-2)
1499 G = 6.67300E-11
1500 return G * self.mass / (self.radius * self.radius)
1501 self.assertEqual(round(Planet.EARTH.surface_gravity, 2), 9.80)
1502 self.assertEqual(Planet.EARTH.value, (5.976e+24, 6.37814e6))
1503
Ethan Furman2aa27322013-07-19 19:35:56 -07001504 def test_nonhash_value(self):
1505 class AutoNumberInAList(Enum):
1506 def __new__(cls):
1507 value = [len(cls.__members__) + 1]
1508 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001509 obj._value_ = value
Ethan Furman2aa27322013-07-19 19:35:56 -07001510 return obj
1511 class ColorInAList(AutoNumberInAList):
1512 red = ()
1513 green = ()
1514 blue = ()
1515 self.assertEqual(list(ColorInAList), [ColorInAList.red, ColorInAList.green, ColorInAList.blue])
Ethan Furman1a162882013-10-16 19:09:31 -07001516 for enum, value in zip(ColorInAList, range(3)):
1517 value += 1
1518 self.assertEqual(enum.value, [value])
1519 self.assertIs(ColorInAList([value]), enum)
Ethan Furman2aa27322013-07-19 19:35:56 -07001520
Ethan Furmanb41803e2013-07-25 13:50:45 -07001521 def test_conflicting_types_resolved_in_new(self):
1522 class LabelledIntEnum(int, Enum):
1523 def __new__(cls, *args):
1524 value, label = args
1525 obj = int.__new__(cls, value)
1526 obj.label = label
1527 obj._value_ = value
1528 return obj
1529
1530 class LabelledList(LabelledIntEnum):
1531 unprocessed = (1, "Unprocessed")
1532 payment_complete = (2, "Payment Complete")
1533
1534 self.assertEqual(list(LabelledList), [LabelledList.unprocessed, LabelledList.payment_complete])
1535 self.assertEqual(LabelledList.unprocessed, 1)
1536 self.assertEqual(LabelledList(1), LabelledList.unprocessed)
Ethan Furman2aa27322013-07-19 19:35:56 -07001537
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001538
Ethan Furmanf24bb352013-07-18 17:05:39 -07001539class TestUnique(unittest.TestCase):
1540
1541 def test_unique_clean(self):
1542 @unique
1543 class Clean(Enum):
1544 one = 1
1545 two = 'dos'
1546 tres = 4.0
1547 @unique
1548 class Cleaner(IntEnum):
1549 single = 1
1550 double = 2
1551 triple = 3
1552
1553 def test_unique_dirty(self):
1554 with self.assertRaisesRegex(ValueError, 'tres.*one'):
1555 @unique
1556 class Dirty(Enum):
1557 one = 1
1558 two = 'dos'
1559 tres = 1
1560 with self.assertRaisesRegex(
1561 ValueError,
1562 'double.*single.*turkey.*triple',
1563 ):
1564 @unique
1565 class Dirtier(IntEnum):
1566 single = 1
1567 double = 1
1568 triple = 3
1569 turkey = 3
1570
1571
Ethan Furman3323da92015-04-11 09:39:59 -07001572expected_help_output_with_docs = """\
Ethan Furman5875d742013-10-21 20:45:55 -07001573Help on class Color in module %s:
1574
1575class Color(enum.Enum)
Ethan Furman48a724f2015-04-11 23:23:06 -07001576 | An enumeration.
Serhiy Storchakab599ca82015-04-04 12:48:04 +03001577 |\x20\x20
Ethan Furman5875d742013-10-21 20:45:55 -07001578 | Method resolution order:
1579 | Color
1580 | enum.Enum
1581 | builtins.object
1582 |\x20\x20
1583 | Data and other attributes defined here:
1584 |\x20\x20
1585 | blue = <Color.blue: 3>
1586 |\x20\x20
1587 | green = <Color.green: 2>
1588 |\x20\x20
1589 | red = <Color.red: 1>
1590 |\x20\x20
1591 | ----------------------------------------------------------------------
1592 | Data descriptors inherited from enum.Enum:
1593 |\x20\x20
1594 | name
1595 | The name of the Enum member.
1596 |\x20\x20
1597 | value
1598 | The value of the Enum member.
1599 |\x20\x20
1600 | ----------------------------------------------------------------------
1601 | Data descriptors inherited from enum.EnumMeta:
1602 |\x20\x20
1603 | __members__
1604 | Returns a mapping of member name->value.
1605 |\x20\x20\x20\x20\x20\x20
1606 | This mapping lists all enum members, including aliases. Note that this
Ethan Furman3323da92015-04-11 09:39:59 -07001607 | is a read-only view of the internal mapping."""
1608
1609expected_help_output_without_docs = """\
1610Help on class Color in module %s:
1611
1612class Color(enum.Enum)
1613 | Method resolution order:
1614 | Color
1615 | enum.Enum
1616 | builtins.object
1617 |\x20\x20
1618 | Data and other attributes defined here:
1619 |\x20\x20
1620 | blue = <Color.blue: 3>
1621 |\x20\x20
1622 | green = <Color.green: 2>
1623 |\x20\x20
1624 | red = <Color.red: 1>
1625 |\x20\x20
1626 | ----------------------------------------------------------------------
1627 | Data descriptors inherited from enum.Enum:
1628 |\x20\x20
1629 | name
1630 |\x20\x20
1631 | value
1632 |\x20\x20
1633 | ----------------------------------------------------------------------
1634 | Data descriptors inherited from enum.EnumMeta:
1635 |\x20\x20
1636 | __members__"""
Ethan Furman5875d742013-10-21 20:45:55 -07001637
1638class TestStdLib(unittest.TestCase):
1639
Ethan Furman48a724f2015-04-11 23:23:06 -07001640 maxDiff = None
1641
Ethan Furman5875d742013-10-21 20:45:55 -07001642 class Color(Enum):
1643 red = 1
1644 green = 2
1645 blue = 3
1646
1647 def test_pydoc(self):
1648 # indirectly test __objclass__
Ethan Furman3323da92015-04-11 09:39:59 -07001649 if StrEnum.__doc__ is None:
1650 expected_text = expected_help_output_without_docs % __name__
1651 else:
1652 expected_text = expected_help_output_with_docs % __name__
Ethan Furman5875d742013-10-21 20:45:55 -07001653 output = StringIO()
1654 helper = pydoc.Helper(output=output)
1655 helper(self.Color)
1656 result = output.getvalue().strip()
Victor Stinner4b0432d2014-06-16 22:48:43 +02001657 self.assertEqual(result, expected_text)
Ethan Furman5875d742013-10-21 20:45:55 -07001658
1659 def test_inspect_getmembers(self):
1660 values = dict((
1661 ('__class__', EnumMeta),
Ethan Furman48a724f2015-04-11 23:23:06 -07001662 ('__doc__', 'An enumeration.'),
Ethan Furman5875d742013-10-21 20:45:55 -07001663 ('__members__', self.Color.__members__),
1664 ('__module__', __name__),
1665 ('blue', self.Color.blue),
1666 ('green', self.Color.green),
1667 ('name', Enum.__dict__['name']),
1668 ('red', self.Color.red),
1669 ('value', Enum.__dict__['value']),
1670 ))
1671 result = dict(inspect.getmembers(self.Color))
1672 self.assertEqual(values.keys(), result.keys())
1673 failed = False
1674 for k in values.keys():
1675 if result[k] != values[k]:
1676 print()
1677 print('\n%s\n key: %s\n result: %s\nexpected: %s\n%s\n' %
1678 ('=' * 75, k, result[k], values[k], '=' * 75), sep='')
1679 failed = True
1680 if failed:
1681 self.fail("result does not equal expected, see print above")
1682
1683 def test_inspect_classify_class_attrs(self):
1684 # indirectly test __objclass__
1685 from inspect import Attribute
1686 values = [
1687 Attribute(name='__class__', kind='data',
1688 defining_class=object, object=EnumMeta),
1689 Attribute(name='__doc__', kind='data',
Ethan Furman48a724f2015-04-11 23:23:06 -07001690 defining_class=self.Color, object='An enumeration.'),
Ethan Furman5875d742013-10-21 20:45:55 -07001691 Attribute(name='__members__', kind='property',
1692 defining_class=EnumMeta, object=EnumMeta.__members__),
1693 Attribute(name='__module__', kind='data',
1694 defining_class=self.Color, object=__name__),
1695 Attribute(name='blue', kind='data',
1696 defining_class=self.Color, object=self.Color.blue),
1697 Attribute(name='green', kind='data',
1698 defining_class=self.Color, object=self.Color.green),
1699 Attribute(name='red', kind='data',
1700 defining_class=self.Color, object=self.Color.red),
1701 Attribute(name='name', kind='data',
1702 defining_class=Enum, object=Enum.__dict__['name']),
1703 Attribute(name='value', kind='data',
1704 defining_class=Enum, object=Enum.__dict__['value']),
1705 ]
1706 values.sort(key=lambda item: item.name)
1707 result = list(inspect.classify_class_attrs(self.Color))
1708 result.sort(key=lambda item: item.name)
1709 failed = False
1710 for v, r in zip(values, result):
1711 if r != v:
1712 print('\n%s\n%s\n%s\n%s\n' % ('=' * 75, r, v, '=' * 75), sep='')
1713 failed = True
1714 if failed:
1715 self.fail("result does not equal expected, see print above")
1716
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001717if __name__ == '__main__':
1718 unittest.main()