blob: dccaa4ffaaf2f16060b7cb4b1e7077fbf7763dc9 [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
Ethan Furmanca1b7942014-02-08 11:36:27 -080069def test_pickle_dump_load(assertion, source, target=None,
70 *, protocol=(0, HIGHEST_PROTOCOL)):
71 start, stop = protocol
Ethan Furman2ddb39a2014-02-06 17:28:50 -080072 if target is None:
73 target = source
Ethan Furmanca1b7942014-02-08 11:36:27 -080074 for protocol in range(start, stop+1):
Ethan Furman2ddb39a2014-02-06 17:28:50 -080075 assertion(loads(dumps(source, protocol=protocol)), target)
76
Ethan Furmanca1b7942014-02-08 11:36:27 -080077def test_pickle_exception(assertion, exception, obj,
78 *, protocol=(0, HIGHEST_PROTOCOL)):
79 start, stop = protocol
80 for protocol in range(start, stop+1):
Ethan Furman2ddb39a2014-02-06 17:28:50 -080081 with assertion(exception):
82 dumps(obj, protocol=protocol)
Ethan Furman648f8602013-10-06 17:19:54 -070083
84class TestHelpers(unittest.TestCase):
85 # _is_descriptor, _is_sunder, _is_dunder
86
87 def test_is_descriptor(self):
88 class foo:
89 pass
90 for attr in ('__get__','__set__','__delete__'):
91 obj = foo()
92 self.assertFalse(enum._is_descriptor(obj))
93 setattr(obj, attr, 1)
94 self.assertTrue(enum._is_descriptor(obj))
95
96 def test_is_sunder(self):
97 for s in ('_a_', '_aa_'):
98 self.assertTrue(enum._is_sunder(s))
99
100 for s in ('a', 'a_', '_a', '__a', 'a__', '__a__', '_a__', '__a_', '_',
101 '__', '___', '____', '_____',):
102 self.assertFalse(enum._is_sunder(s))
103
104 def test_is_dunder(self):
105 for s in ('__a__', '__aa__'):
106 self.assertTrue(enum._is_dunder(s))
107 for s in ('a', 'a_', '_a', '__a', 'a__', '_a_', '_a__', '__a_', '_',
108 '__', '___', '____', '_____',):
109 self.assertFalse(enum._is_dunder(s))
110
111
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700112class TestEnum(unittest.TestCase):
Ethan Furmanca1b7942014-02-08 11:36:27 -0800113
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700114 def setUp(self):
115 class Season(Enum):
116 SPRING = 1
117 SUMMER = 2
118 AUTUMN = 3
119 WINTER = 4
120 self.Season = Season
121
Ethan Furmanec15a822013-08-31 19:17:41 -0700122 class Konstants(float, Enum):
123 E = 2.7182818
124 PI = 3.1415926
125 TAU = 2 * PI
126 self.Konstants = Konstants
127
128 class Grades(IntEnum):
129 A = 5
130 B = 4
131 C = 3
132 D = 2
133 F = 0
134 self.Grades = Grades
135
136 class Directional(str, Enum):
137 EAST = 'east'
138 WEST = 'west'
139 NORTH = 'north'
140 SOUTH = 'south'
141 self.Directional = Directional
142
143 from datetime import date
144 class Holiday(date, Enum):
145 NEW_YEAR = 2013, 1, 1
146 IDES_OF_MARCH = 2013, 3, 15
147 self.Holiday = Holiday
148
Ethan Furman388a3922013-08-12 06:51:41 -0700149 def test_dir_on_class(self):
150 Season = self.Season
151 self.assertEqual(
152 set(dir(Season)),
Ethan Furmanc850f342013-09-15 16:59:35 -0700153 set(['__class__', '__doc__', '__members__', '__module__',
Ethan Furman388a3922013-08-12 06:51:41 -0700154 'SPRING', 'SUMMER', 'AUTUMN', 'WINTER']),
155 )
156
157 def test_dir_on_item(self):
158 Season = self.Season
159 self.assertEqual(
160 set(dir(Season.WINTER)),
Ethan Furmanc850f342013-09-15 16:59:35 -0700161 set(['__class__', '__doc__', '__module__', 'name', 'value']),
Ethan Furman388a3922013-08-12 06:51:41 -0700162 )
163
Ethan Furmanc850f342013-09-15 16:59:35 -0700164 def test_dir_with_added_behavior(self):
165 class Test(Enum):
166 this = 'that'
167 these = 'those'
168 def wowser(self):
169 return ("Wowser! I'm %s!" % self.name)
170 self.assertEqual(
171 set(dir(Test)),
172 set(['__class__', '__doc__', '__members__', '__module__', 'this', 'these']),
173 )
174 self.assertEqual(
175 set(dir(Test.this)),
176 set(['__class__', '__doc__', '__module__', 'name', 'value', 'wowser']),
177 )
178
Ethan Furman0ae550b2014-10-14 08:58:32 -0700179 def test_dir_on_sub_with_behavior_on_super(self):
180 # see issue22506
181 class SuperEnum(Enum):
182 def invisible(self):
183 return "did you see me?"
184 class SubEnum(SuperEnum):
185 sample = 5
186 self.assertEqual(
187 set(dir(SubEnum.sample)),
188 set(['__class__', '__doc__', '__module__', 'name', 'value', 'invisible']),
189 )
190
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700191 def test_enum_in_enum_out(self):
192 Season = self.Season
193 self.assertIs(Season(Season.WINTER), Season.WINTER)
194
195 def test_enum_value(self):
196 Season = self.Season
197 self.assertEqual(Season.SPRING.value, 1)
198
199 def test_intenum_value(self):
200 self.assertEqual(IntStooges.CURLY.value, 2)
201
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700202 def test_enum(self):
203 Season = self.Season
204 lst = list(Season)
205 self.assertEqual(len(lst), len(Season))
206 self.assertEqual(len(Season), 4, Season)
207 self.assertEqual(
208 [Season.SPRING, Season.SUMMER, Season.AUTUMN, Season.WINTER], lst)
209
210 for i, season in enumerate('SPRING SUMMER AUTUMN WINTER'.split(), 1):
211 e = Season(i)
212 self.assertEqual(e, getattr(Season, season))
213 self.assertEqual(e.value, i)
214 self.assertNotEqual(e, i)
215 self.assertEqual(e.name, season)
216 self.assertIn(e, Season)
217 self.assertIs(type(e), Season)
218 self.assertIsInstance(e, Season)
219 self.assertEqual(str(e), 'Season.' + season)
220 self.assertEqual(
221 repr(e),
222 '<Season.{0}: {1}>'.format(season, i),
223 )
224
225 def test_value_name(self):
226 Season = self.Season
227 self.assertEqual(Season.SPRING.name, 'SPRING')
228 self.assertEqual(Season.SPRING.value, 1)
229 with self.assertRaises(AttributeError):
230 Season.SPRING.name = 'invierno'
231 with self.assertRaises(AttributeError):
232 Season.SPRING.value = 2
233
Ethan Furmanf203f2d2013-09-06 07:16:48 -0700234 def test_changing_member(self):
235 Season = self.Season
236 with self.assertRaises(AttributeError):
237 Season.WINTER = 'really cold'
238
Ethan Furman64a99722013-09-22 16:18:19 -0700239 def test_attribute_deletion(self):
240 class Season(Enum):
241 SPRING = 1
242 SUMMER = 2
243 AUTUMN = 3
244 WINTER = 4
245
246 def spam(cls):
247 pass
248
249 self.assertTrue(hasattr(Season, 'spam'))
250 del Season.spam
251 self.assertFalse(hasattr(Season, 'spam'))
252
253 with self.assertRaises(AttributeError):
254 del Season.SPRING
255 with self.assertRaises(AttributeError):
256 del Season.DRY
257 with self.assertRaises(AttributeError):
258 del Season.SPRING.name
259
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700260 def test_invalid_names(self):
261 with self.assertRaises(ValueError):
262 class Wrong(Enum):
263 mro = 9
264 with self.assertRaises(ValueError):
265 class Wrong(Enum):
266 _create_= 11
267 with self.assertRaises(ValueError):
268 class Wrong(Enum):
269 _get_mixins_ = 9
270 with self.assertRaises(ValueError):
271 class Wrong(Enum):
272 _find_new_ = 1
273 with self.assertRaises(ValueError):
274 class Wrong(Enum):
275 _any_name_ = 9
276
277 def test_contains(self):
278 Season = self.Season
279 self.assertIn(Season.AUTUMN, Season)
280 self.assertNotIn(3, Season)
281
282 val = Season(3)
283 self.assertIn(val, Season)
284
285 class OtherEnum(Enum):
286 one = 1; two = 2
287 self.assertNotIn(OtherEnum.two, Season)
288
289 def test_comparisons(self):
290 Season = self.Season
291 with self.assertRaises(TypeError):
292 Season.SPRING < Season.WINTER
293 with self.assertRaises(TypeError):
294 Season.SPRING > 4
295
296 self.assertNotEqual(Season.SPRING, 1)
297
298 class Part(Enum):
299 SPRING = 1
300 CLIP = 2
301 BARREL = 3
302
303 self.assertNotEqual(Season.SPRING, Part.SPRING)
304 with self.assertRaises(TypeError):
305 Season.SPRING < Part.CLIP
306
307 def test_enum_duplicates(self):
308 class Season(Enum):
309 SPRING = 1
310 SUMMER = 2
311 AUTUMN = FALL = 3
312 WINTER = 4
313 ANOTHER_SPRING = 1
314 lst = list(Season)
315 self.assertEqual(
316 lst,
317 [Season.SPRING, Season.SUMMER,
318 Season.AUTUMN, Season.WINTER,
319 ])
320 self.assertIs(Season.FALL, Season.AUTUMN)
321 self.assertEqual(Season.FALL.value, 3)
322 self.assertEqual(Season.AUTUMN.value, 3)
323 self.assertIs(Season(3), Season.AUTUMN)
324 self.assertIs(Season(1), Season.SPRING)
325 self.assertEqual(Season.FALL.name, 'AUTUMN')
326 self.assertEqual(
327 [k for k,v in Season.__members__.items() if v.name != k],
328 ['FALL', 'ANOTHER_SPRING'],
329 )
330
Ethan Furman101e0742013-09-15 12:34:36 -0700331 def test_duplicate_name(self):
332 with self.assertRaises(TypeError):
333 class Color(Enum):
334 red = 1
335 green = 2
336 blue = 3
337 red = 4
338
339 with self.assertRaises(TypeError):
340 class Color(Enum):
341 red = 1
342 green = 2
343 blue = 3
344 def red(self):
345 return 'red'
346
347 with self.assertRaises(TypeError):
348 class Color(Enum):
349 @property
350 def red(self):
351 return 'redder'
352 red = 1
353 green = 2
354 blue = 3
355
356
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700357 def test_enum_with_value_name(self):
358 class Huh(Enum):
359 name = 1
360 value = 2
361 self.assertEqual(
362 list(Huh),
363 [Huh.name, Huh.value],
364 )
365 self.assertIs(type(Huh.name), Huh)
366 self.assertEqual(Huh.name.name, 'name')
367 self.assertEqual(Huh.name.value, 1)
Ethan Furmanec15a822013-08-31 19:17:41 -0700368
369 def test_format_enum(self):
370 Season = self.Season
371 self.assertEqual('{}'.format(Season.SPRING),
372 '{}'.format(str(Season.SPRING)))
373 self.assertEqual( '{:}'.format(Season.SPRING),
374 '{:}'.format(str(Season.SPRING)))
375 self.assertEqual('{:20}'.format(Season.SPRING),
376 '{:20}'.format(str(Season.SPRING)))
377 self.assertEqual('{:^20}'.format(Season.SPRING),
378 '{:^20}'.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
384 def test_format_enum_custom(self):
385 class TestFloat(float, Enum):
386 one = 1.0
387 two = 2.0
388 def __format__(self, spec):
389 return 'TestFloat success!'
390 self.assertEqual('{}'.format(TestFloat.one), 'TestFloat success!')
391
392 def assertFormatIsValue(self, spec, member):
393 self.assertEqual(spec.format(member), spec.format(member.value))
394
395 def test_format_enum_date(self):
396 Holiday = self.Holiday
397 self.assertFormatIsValue('{}', Holiday.IDES_OF_MARCH)
398 self.assertFormatIsValue('{:}', Holiday.IDES_OF_MARCH)
399 self.assertFormatIsValue('{:20}', Holiday.IDES_OF_MARCH)
400 self.assertFormatIsValue('{:^20}', Holiday.IDES_OF_MARCH)
401 self.assertFormatIsValue('{:>20}', Holiday.IDES_OF_MARCH)
402 self.assertFormatIsValue('{:<20}', Holiday.IDES_OF_MARCH)
403 self.assertFormatIsValue('{:%Y %m}', Holiday.IDES_OF_MARCH)
404 self.assertFormatIsValue('{:%Y %m %M:00}', Holiday.IDES_OF_MARCH)
405
406 def test_format_enum_float(self):
407 Konstants = self.Konstants
408 self.assertFormatIsValue('{}', Konstants.TAU)
409 self.assertFormatIsValue('{:}', Konstants.TAU)
410 self.assertFormatIsValue('{:20}', Konstants.TAU)
411 self.assertFormatIsValue('{:^20}', Konstants.TAU)
412 self.assertFormatIsValue('{:>20}', Konstants.TAU)
413 self.assertFormatIsValue('{:<20}', Konstants.TAU)
414 self.assertFormatIsValue('{:n}', Konstants.TAU)
415 self.assertFormatIsValue('{:5.2}', Konstants.TAU)
416 self.assertFormatIsValue('{:f}', Konstants.TAU)
417
418 def test_format_enum_int(self):
419 Grades = self.Grades
420 self.assertFormatIsValue('{}', Grades.C)
421 self.assertFormatIsValue('{:}', Grades.C)
422 self.assertFormatIsValue('{:20}', Grades.C)
423 self.assertFormatIsValue('{:^20}', Grades.C)
424 self.assertFormatIsValue('{:>20}', Grades.C)
425 self.assertFormatIsValue('{:<20}', Grades.C)
426 self.assertFormatIsValue('{:+}', Grades.C)
427 self.assertFormatIsValue('{:08X}', Grades.C)
428 self.assertFormatIsValue('{:b}', Grades.C)
429
430 def test_format_enum_str(self):
431 Directional = self.Directional
432 self.assertFormatIsValue('{}', Directional.WEST)
433 self.assertFormatIsValue('{:}', Directional.WEST)
434 self.assertFormatIsValue('{:20}', Directional.WEST)
435 self.assertFormatIsValue('{:^20}', Directional.WEST)
436 self.assertFormatIsValue('{:>20}', Directional.WEST)
437 self.assertFormatIsValue('{:<20}', Directional.WEST)
438
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700439 def test_hash(self):
440 Season = self.Season
441 dates = {}
442 dates[Season.WINTER] = '1225'
443 dates[Season.SPRING] = '0315'
444 dates[Season.SUMMER] = '0704'
445 dates[Season.AUTUMN] = '1031'
446 self.assertEqual(dates[Season.AUTUMN], '1031')
447
448 def test_intenum_from_scratch(self):
449 class phy(int, Enum):
450 pi = 3
451 tau = 2 * pi
452 self.assertTrue(phy.pi < phy.tau)
453
454 def test_intenum_inherited(self):
455 class IntEnum(int, Enum):
456 pass
457 class phy(IntEnum):
458 pi = 3
459 tau = 2 * pi
460 self.assertTrue(phy.pi < phy.tau)
461
462 def test_floatenum_from_scratch(self):
463 class phy(float, Enum):
Ethan Furmanec15a822013-08-31 19:17:41 -0700464 pi = 3.1415926
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700465 tau = 2 * pi
466 self.assertTrue(phy.pi < phy.tau)
467
468 def test_floatenum_inherited(self):
469 class FloatEnum(float, Enum):
470 pass
471 class phy(FloatEnum):
Ethan Furmanec15a822013-08-31 19:17:41 -0700472 pi = 3.1415926
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700473 tau = 2 * pi
474 self.assertTrue(phy.pi < phy.tau)
475
476 def test_strenum_from_scratch(self):
477 class phy(str, Enum):
478 pi = 'Pi'
479 tau = 'Tau'
480 self.assertTrue(phy.pi < phy.tau)
481
482 def test_strenum_inherited(self):
483 class StrEnum(str, Enum):
484 pass
485 class phy(StrEnum):
486 pi = 'Pi'
487 tau = 'Tau'
488 self.assertTrue(phy.pi < phy.tau)
489
490
491 def test_intenum(self):
492 class WeekDay(IntEnum):
493 SUNDAY = 1
494 MONDAY = 2
495 TUESDAY = 3
496 WEDNESDAY = 4
497 THURSDAY = 5
498 FRIDAY = 6
499 SATURDAY = 7
500
501 self.assertEqual(['a', 'b', 'c'][WeekDay.MONDAY], 'c')
502 self.assertEqual([i for i in range(WeekDay.TUESDAY)], [0, 1, 2])
503
504 lst = list(WeekDay)
505 self.assertEqual(len(lst), len(WeekDay))
506 self.assertEqual(len(WeekDay), 7)
507 target = 'SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY'
508 target = target.split()
509 for i, weekday in enumerate(target, 1):
510 e = WeekDay(i)
511 self.assertEqual(e, i)
512 self.assertEqual(int(e), i)
513 self.assertEqual(e.name, weekday)
514 self.assertIn(e, WeekDay)
515 self.assertEqual(lst.index(e)+1, i)
516 self.assertTrue(0 < e < 8)
517 self.assertIs(type(e), WeekDay)
518 self.assertIsInstance(e, int)
519 self.assertIsInstance(e, Enum)
520
521 def test_intenum_duplicates(self):
522 class WeekDay(IntEnum):
523 SUNDAY = 1
524 MONDAY = 2
525 TUESDAY = TEUSDAY = 3
526 WEDNESDAY = 4
527 THURSDAY = 5
528 FRIDAY = 6
529 SATURDAY = 7
530 self.assertIs(WeekDay.TEUSDAY, WeekDay.TUESDAY)
531 self.assertEqual(WeekDay(3).name, 'TUESDAY')
532 self.assertEqual([k for k,v in WeekDay.__members__.items()
533 if v.name != k], ['TEUSDAY', ])
534
535 def test_pickle_enum(self):
536 if isinstance(Stooges, Exception):
537 raise Stooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800538 test_pickle_dump_load(self.assertIs, Stooges.CURLY)
539 test_pickle_dump_load(self.assertIs, Stooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700540
541 def test_pickle_int(self):
542 if isinstance(IntStooges, Exception):
543 raise IntStooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800544 test_pickle_dump_load(self.assertIs, IntStooges.CURLY)
545 test_pickle_dump_load(self.assertIs, IntStooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700546
547 def test_pickle_float(self):
548 if isinstance(FloatStooges, Exception):
549 raise FloatStooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800550 test_pickle_dump_load(self.assertIs, FloatStooges.CURLY)
551 test_pickle_dump_load(self.assertIs, FloatStooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700552
553 def test_pickle_enum_function(self):
554 if isinstance(Answer, Exception):
555 raise Answer
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800556 test_pickle_dump_load(self.assertIs, Answer.him)
557 test_pickle_dump_load(self.assertIs, Answer)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700558
559 def test_pickle_enum_function_with_module(self):
560 if isinstance(Question, Exception):
561 raise Question
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800562 test_pickle_dump_load(self.assertIs, Question.who)
563 test_pickle_dump_load(self.assertIs, Question)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700564
Ethan Furmanca1b7942014-02-08 11:36:27 -0800565 def test_enum_function_with_qualname(self):
566 if isinstance(Theory, Exception):
567 raise Theory
568 self.assertEqual(Theory.__qualname__, 'spanish_inquisition')
569
570 def test_class_nested_enum_and_pickle_protocol_four(self):
571 # would normally just have this directly in the class namespace
572 class NestedEnum(Enum):
573 twigs = 'common'
574 shiny = 'rare'
575
576 self.__class__.NestedEnum = NestedEnum
577 self.NestedEnum.__qualname__ = '%s.NestedEnum' % self.__class__.__name__
578 test_pickle_exception(
579 self.assertRaises, PicklingError, self.NestedEnum.twigs,
580 protocol=(0, 3))
581 test_pickle_dump_load(self.assertIs, self.NestedEnum.twigs,
582 protocol=(4, HIGHEST_PROTOCOL))
583
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700584 def test_exploding_pickle(self):
Ethan Furmanca1b7942014-02-08 11:36:27 -0800585 BadPickle = Enum(
586 'BadPickle', 'dill sweet bread-n-butter', module=__name__)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700587 globals()['BadPickle'] = BadPickle
Ethan Furmanca1b7942014-02-08 11:36:27 -0800588 # now break BadPickle to test exception raising
589 enum._make_class_unpicklable(BadPickle)
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800590 test_pickle_exception(self.assertRaises, TypeError, BadPickle.dill)
591 test_pickle_exception(self.assertRaises, PicklingError, BadPickle)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700592
593 def test_string_enum(self):
594 class SkillLevel(str, Enum):
595 master = 'what is the sound of one hand clapping?'
596 journeyman = 'why did the chicken cross the road?'
597 apprentice = 'knock, knock!'
598 self.assertEqual(SkillLevel.apprentice, 'knock, knock!')
599
600 def test_getattr_getitem(self):
601 class Period(Enum):
602 morning = 1
603 noon = 2
604 evening = 3
605 night = 4
606 self.assertIs(Period(2), Period.noon)
607 self.assertIs(getattr(Period, 'night'), Period.night)
608 self.assertIs(Period['morning'], Period.morning)
609
610 def test_getattr_dunder(self):
611 Season = self.Season
612 self.assertTrue(getattr(Season, '__eq__'))
613
614 def test_iteration_order(self):
615 class Season(Enum):
616 SUMMER = 2
617 WINTER = 4
618 AUTUMN = 3
619 SPRING = 1
620 self.assertEqual(
621 list(Season),
622 [Season.SUMMER, Season.WINTER, Season.AUTUMN, Season.SPRING],
623 )
624
Ethan Furman2131a4a2013-09-14 18:11:24 -0700625 def test_reversed_iteration_order(self):
626 self.assertEqual(
627 list(reversed(self.Season)),
628 [self.Season.WINTER, self.Season.AUTUMN, self.Season.SUMMER,
629 self.Season.SPRING]
630 )
631
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700632 def test_programatic_function_string(self):
633 SummerMonth = Enum('SummerMonth', 'june july august')
634 lst = list(SummerMonth)
635 self.assertEqual(len(lst), len(SummerMonth))
636 self.assertEqual(len(SummerMonth), 3, SummerMonth)
637 self.assertEqual(
638 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
639 lst,
640 )
641 for i, month in enumerate('june july august'.split(), 1):
642 e = SummerMonth(i)
643 self.assertEqual(int(e.value), i)
644 self.assertNotEqual(e, i)
645 self.assertEqual(e.name, month)
646 self.assertIn(e, SummerMonth)
647 self.assertIs(type(e), SummerMonth)
648
649 def test_programatic_function_string_list(self):
650 SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'])
651 lst = list(SummerMonth)
652 self.assertEqual(len(lst), len(SummerMonth))
653 self.assertEqual(len(SummerMonth), 3, SummerMonth)
654 self.assertEqual(
655 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
656 lst,
657 )
658 for i, month in enumerate('june july august'.split(), 1):
659 e = SummerMonth(i)
660 self.assertEqual(int(e.value), i)
661 self.assertNotEqual(e, i)
662 self.assertEqual(e.name, month)
663 self.assertIn(e, SummerMonth)
664 self.assertIs(type(e), SummerMonth)
665
666 def test_programatic_function_iterable(self):
667 SummerMonth = Enum(
668 'SummerMonth',
669 (('june', 1), ('july', 2), ('august', 3))
670 )
671 lst = list(SummerMonth)
672 self.assertEqual(len(lst), len(SummerMonth))
673 self.assertEqual(len(SummerMonth), 3, SummerMonth)
674 self.assertEqual(
675 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
676 lst,
677 )
678 for i, month in enumerate('june july august'.split(), 1):
679 e = SummerMonth(i)
680 self.assertEqual(int(e.value), i)
681 self.assertNotEqual(e, i)
682 self.assertEqual(e.name, month)
683 self.assertIn(e, SummerMonth)
684 self.assertIs(type(e), SummerMonth)
685
686 def test_programatic_function_from_dict(self):
687 SummerMonth = Enum(
688 'SummerMonth',
689 OrderedDict((('june', 1), ('july', 2), ('august', 3)))
690 )
691 lst = list(SummerMonth)
692 self.assertEqual(len(lst), len(SummerMonth))
693 self.assertEqual(len(SummerMonth), 3, SummerMonth)
694 self.assertEqual(
695 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
696 lst,
697 )
698 for i, month in enumerate('june july august'.split(), 1):
699 e = SummerMonth(i)
700 self.assertEqual(int(e.value), i)
701 self.assertNotEqual(e, i)
702 self.assertEqual(e.name, month)
703 self.assertIn(e, SummerMonth)
704 self.assertIs(type(e), SummerMonth)
705
706 def test_programatic_function_type(self):
707 SummerMonth = Enum('SummerMonth', 'june july august', type=int)
708 lst = list(SummerMonth)
709 self.assertEqual(len(lst), len(SummerMonth))
710 self.assertEqual(len(SummerMonth), 3, SummerMonth)
711 self.assertEqual(
712 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
713 lst,
714 )
715 for i, month in enumerate('june july august'.split(), 1):
716 e = SummerMonth(i)
717 self.assertEqual(e, i)
718 self.assertEqual(e.name, month)
719 self.assertIn(e, SummerMonth)
720 self.assertIs(type(e), SummerMonth)
721
722 def test_programatic_function_type_from_subclass(self):
723 SummerMonth = IntEnum('SummerMonth', 'june july august')
724 lst = list(SummerMonth)
725 self.assertEqual(len(lst), len(SummerMonth))
726 self.assertEqual(len(SummerMonth), 3, SummerMonth)
727 self.assertEqual(
728 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
729 lst,
730 )
731 for i, month in enumerate('june july august'.split(), 1):
732 e = SummerMonth(i)
733 self.assertEqual(e, i)
734 self.assertEqual(e.name, month)
735 self.assertIn(e, SummerMonth)
736 self.assertIs(type(e), SummerMonth)
737
738 def test_subclassing(self):
739 if isinstance(Name, Exception):
740 raise Name
741 self.assertEqual(Name.BDFL, 'Guido van Rossum')
742 self.assertTrue(Name.BDFL, Name('Guido van Rossum'))
743 self.assertIs(Name.BDFL, getattr(Name, 'BDFL'))
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800744 test_pickle_dump_load(self.assertIs, Name.BDFL)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700745
746 def test_extending(self):
747 class Color(Enum):
748 red = 1
749 green = 2
750 blue = 3
751 with self.assertRaises(TypeError):
752 class MoreColor(Color):
753 cyan = 4
754 magenta = 5
755 yellow = 6
756
757 def test_exclude_methods(self):
758 class whatever(Enum):
759 this = 'that'
760 these = 'those'
761 def really(self):
762 return 'no, not %s' % self.value
763 self.assertIsNot(type(whatever.really), whatever)
764 self.assertEqual(whatever.this.really(), 'no, not that')
765
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700766 def test_wrong_inheritance_order(self):
767 with self.assertRaises(TypeError):
768 class Wrong(Enum, str):
769 NotHere = 'error before this point'
770
771 def test_intenum_transitivity(self):
772 class number(IntEnum):
773 one = 1
774 two = 2
775 three = 3
776 class numero(IntEnum):
777 uno = 1
778 dos = 2
779 tres = 3
780 self.assertEqual(number.one, numero.uno)
781 self.assertEqual(number.two, numero.dos)
782 self.assertEqual(number.three, numero.tres)
783
784 def test_wrong_enum_in_call(self):
785 class Monochrome(Enum):
786 black = 0
787 white = 1
788 class Gender(Enum):
789 male = 0
790 female = 1
791 self.assertRaises(ValueError, Monochrome, Gender.male)
792
793 def test_wrong_enum_in_mixed_call(self):
794 class Monochrome(IntEnum):
795 black = 0
796 white = 1
797 class Gender(Enum):
798 male = 0
799 female = 1
800 self.assertRaises(ValueError, Monochrome, Gender.male)
801
802 def test_mixed_enum_in_call_1(self):
803 class Monochrome(IntEnum):
804 black = 0
805 white = 1
806 class Gender(IntEnum):
807 male = 0
808 female = 1
809 self.assertIs(Monochrome(Gender.female), Monochrome.white)
810
811 def test_mixed_enum_in_call_2(self):
812 class Monochrome(Enum):
813 black = 0
814 white = 1
815 class Gender(IntEnum):
816 male = 0
817 female = 1
818 self.assertIs(Monochrome(Gender.male), Monochrome.black)
819
820 def test_flufl_enum(self):
821 class Fluflnum(Enum):
822 def __int__(self):
823 return int(self.value)
824 class MailManOptions(Fluflnum):
825 option1 = 1
826 option2 = 2
827 option3 = 3
828 self.assertEqual(int(MailManOptions.option1), 1)
829
Ethan Furman5e5a8232013-08-04 08:42:23 -0700830 def test_introspection(self):
831 class Number(IntEnum):
832 one = 100
833 two = 200
834 self.assertIs(Number.one._member_type_, int)
835 self.assertIs(Number._member_type_, int)
836 class String(str, Enum):
837 yarn = 'soft'
838 rope = 'rough'
839 wire = 'hard'
840 self.assertIs(String.yarn._member_type_, str)
841 self.assertIs(String._member_type_, str)
842 class Plain(Enum):
843 vanilla = 'white'
844 one = 1
845 self.assertIs(Plain.vanilla._member_type_, object)
846 self.assertIs(Plain._member_type_, object)
847
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700848 def test_no_such_enum_member(self):
849 class Color(Enum):
850 red = 1
851 green = 2
852 blue = 3
853 with self.assertRaises(ValueError):
854 Color(4)
855 with self.assertRaises(KeyError):
856 Color['chartreuse']
857
858 def test_new_repr(self):
859 class Color(Enum):
860 red = 1
861 green = 2
862 blue = 3
863 def __repr__(self):
864 return "don't you just love shades of %s?" % self.name
865 self.assertEqual(
866 repr(Color.blue),
867 "don't you just love shades of blue?",
868 )
869
870 def test_inherited_repr(self):
871 class MyEnum(Enum):
872 def __repr__(self):
873 return "My name is %s." % self.name
874 class MyIntEnum(int, MyEnum):
875 this = 1
876 that = 2
877 theother = 3
878 self.assertEqual(repr(MyIntEnum.that), "My name is that.")
879
880 def test_multiple_mixin_mro(self):
881 class auto_enum(type(Enum)):
882 def __new__(metacls, cls, bases, classdict):
883 temp = type(classdict)()
884 names = set(classdict._member_names)
885 i = 0
886 for k in classdict._member_names:
887 v = classdict[k]
888 if v is Ellipsis:
889 v = i
890 else:
891 i = v
892 i += 1
893 temp[k] = v
894 for k, v in classdict.items():
895 if k not in names:
896 temp[k] = v
897 return super(auto_enum, metacls).__new__(
898 metacls, cls, bases, temp)
899
900 class AutoNumberedEnum(Enum, metaclass=auto_enum):
901 pass
902
903 class AutoIntEnum(IntEnum, metaclass=auto_enum):
904 pass
905
906 class TestAutoNumber(AutoNumberedEnum):
907 a = ...
908 b = 3
909 c = ...
910
911 class TestAutoInt(AutoIntEnum):
912 a = ...
913 b = 3
914 c = ...
915
916 def test_subclasses_with_getnewargs(self):
917 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800918 __qualname__ = 'NamedInt' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700919 def __new__(cls, *args):
920 _args = args
921 name, *args = args
922 if len(args) == 0:
923 raise TypeError("name and value must be specified")
924 self = int.__new__(cls, *args)
925 self._intname = name
926 self._args = _args
927 return self
928 def __getnewargs__(self):
929 return self._args
930 @property
931 def __name__(self):
932 return self._intname
933 def __repr__(self):
934 # repr() is updated to include the name and type info
935 return "{}({!r}, {})".format(type(self).__name__,
936 self.__name__,
937 int.__repr__(self))
938 def __str__(self):
939 # str() is unchanged, even if it relies on the repr() fallback
940 base = int
941 base_str = base.__str__
942 if base_str.__objclass__ is object:
943 return base.__repr__(self)
944 return base_str(self)
945 # for simplicity, we only define one operator that
946 # propagates expressions
947 def __add__(self, other):
948 temp = int(self) + int( other)
949 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
950 return NamedInt(
951 '({0} + {1})'.format(self.__name__, other.__name__),
952 temp )
953 else:
954 return temp
955
956 class NEI(NamedInt, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800957 __qualname__ = 'NEI' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700958 x = ('the-x', 1)
959 y = ('the-y', 2)
960
Ethan Furman2aa27322013-07-19 19:35:56 -0700961
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700962 self.assertIs(NEI.__new__, Enum.__new__)
963 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
964 globals()['NamedInt'] = NamedInt
965 globals()['NEI'] = NEI
966 NI5 = NamedInt('test', 5)
967 self.assertEqual(NI5, 5)
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800968 test_pickle_dump_load(self.assertEqual, NI5, 5)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700969 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800970 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -0800971 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700972
Ethan Furmanca1b7942014-02-08 11:36:27 -0800973 def test_subclasses_with_getnewargs_ex(self):
974 class NamedInt(int):
975 __qualname__ = 'NamedInt' # needed for pickle protocol 4
976 def __new__(cls, *args):
977 _args = args
978 name, *args = args
979 if len(args) == 0:
980 raise TypeError("name and value must be specified")
981 self = int.__new__(cls, *args)
982 self._intname = name
983 self._args = _args
984 return self
985 def __getnewargs_ex__(self):
986 return self._args, {}
987 @property
988 def __name__(self):
989 return self._intname
990 def __repr__(self):
991 # repr() is updated to include the name and type info
992 return "{}({!r}, {})".format(type(self).__name__,
993 self.__name__,
994 int.__repr__(self))
995 def __str__(self):
996 # str() is unchanged, even if it relies on the repr() fallback
997 base = int
998 base_str = base.__str__
999 if base_str.__objclass__ is object:
1000 return base.__repr__(self)
1001 return base_str(self)
1002 # for simplicity, we only define one operator that
1003 # propagates expressions
1004 def __add__(self, other):
1005 temp = int(self) + int( other)
1006 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1007 return NamedInt(
1008 '({0} + {1})'.format(self.__name__, other.__name__),
1009 temp )
1010 else:
1011 return temp
1012
1013 class NEI(NamedInt, Enum):
1014 __qualname__ = 'NEI' # needed for pickle protocol 4
1015 x = ('the-x', 1)
1016 y = ('the-y', 2)
1017
1018
1019 self.assertIs(NEI.__new__, Enum.__new__)
1020 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1021 globals()['NamedInt'] = NamedInt
1022 globals()['NEI'] = NEI
1023 NI5 = NamedInt('test', 5)
1024 self.assertEqual(NI5, 5)
1025 test_pickle_dump_load(self.assertEqual, NI5, 5, protocol=(4, 4))
1026 self.assertEqual(NEI.y.value, 2)
1027 test_pickle_dump_load(self.assertIs, NEI.y, protocol=(4, 4))
Ethan Furmandc870522014-02-18 12:37:12 -08001028 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001029
1030 def test_subclasses_with_reduce(self):
1031 class NamedInt(int):
1032 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1033 def __new__(cls, *args):
1034 _args = args
1035 name, *args = args
1036 if len(args) == 0:
1037 raise TypeError("name and value must be specified")
1038 self = int.__new__(cls, *args)
1039 self._intname = name
1040 self._args = _args
1041 return self
1042 def __reduce__(self):
1043 return self.__class__, self._args
1044 @property
1045 def __name__(self):
1046 return self._intname
1047 def __repr__(self):
1048 # repr() is updated to include the name and type info
1049 return "{}({!r}, {})".format(type(self).__name__,
1050 self.__name__,
1051 int.__repr__(self))
1052 def __str__(self):
1053 # str() is unchanged, even if it relies on the repr() fallback
1054 base = int
1055 base_str = base.__str__
1056 if base_str.__objclass__ is object:
1057 return base.__repr__(self)
1058 return base_str(self)
1059 # for simplicity, we only define one operator that
1060 # propagates expressions
1061 def __add__(self, other):
1062 temp = int(self) + int( other)
1063 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1064 return NamedInt(
1065 '({0} + {1})'.format(self.__name__, other.__name__),
1066 temp )
1067 else:
1068 return temp
1069
1070 class NEI(NamedInt, Enum):
1071 __qualname__ = 'NEI' # needed for pickle protocol 4
1072 x = ('the-x', 1)
1073 y = ('the-y', 2)
1074
1075
1076 self.assertIs(NEI.__new__, Enum.__new__)
1077 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1078 globals()['NamedInt'] = NamedInt
1079 globals()['NEI'] = NEI
1080 NI5 = NamedInt('test', 5)
1081 self.assertEqual(NI5, 5)
1082 test_pickle_dump_load(self.assertEqual, NI5, 5)
1083 self.assertEqual(NEI.y.value, 2)
1084 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001085 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001086
1087 def test_subclasses_with_reduce_ex(self):
1088 class NamedInt(int):
1089 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1090 def __new__(cls, *args):
1091 _args = args
1092 name, *args = args
1093 if len(args) == 0:
1094 raise TypeError("name and value must be specified")
1095 self = int.__new__(cls, *args)
1096 self._intname = name
1097 self._args = _args
1098 return self
1099 def __reduce_ex__(self, proto):
1100 return self.__class__, self._args
1101 @property
1102 def __name__(self):
1103 return self._intname
1104 def __repr__(self):
1105 # repr() is updated to include the name and type info
1106 return "{}({!r}, {})".format(type(self).__name__,
1107 self.__name__,
1108 int.__repr__(self))
1109 def __str__(self):
1110 # str() is unchanged, even if it relies on the repr() fallback
1111 base = int
1112 base_str = base.__str__
1113 if base_str.__objclass__ is object:
1114 return base.__repr__(self)
1115 return base_str(self)
1116 # for simplicity, we only define one operator that
1117 # propagates expressions
1118 def __add__(self, other):
1119 temp = int(self) + int( other)
1120 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1121 return NamedInt(
1122 '({0} + {1})'.format(self.__name__, other.__name__),
1123 temp )
1124 else:
1125 return temp
1126
1127 class NEI(NamedInt, Enum):
1128 __qualname__ = 'NEI' # needed for pickle protocol 4
1129 x = ('the-x', 1)
1130 y = ('the-y', 2)
1131
1132
1133 self.assertIs(NEI.__new__, Enum.__new__)
1134 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1135 globals()['NamedInt'] = NamedInt
1136 globals()['NEI'] = NEI
1137 NI5 = NamedInt('test', 5)
1138 self.assertEqual(NI5, 5)
1139 test_pickle_dump_load(self.assertEqual, NI5, 5)
1140 self.assertEqual(NEI.y.value, 2)
1141 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001142 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001143
Ethan Furmandc870522014-02-18 12:37:12 -08001144 def test_subclasses_without_direct_pickle_support(self):
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001145 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001146 __qualname__ = 'NamedInt'
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001147 def __new__(cls, *args):
1148 _args = args
1149 name, *args = args
1150 if len(args) == 0:
1151 raise TypeError("name and value must be specified")
1152 self = int.__new__(cls, *args)
1153 self._intname = name
1154 self._args = _args
1155 return self
1156 @property
1157 def __name__(self):
1158 return self._intname
1159 def __repr__(self):
1160 # repr() is updated to include the name and type info
1161 return "{}({!r}, {})".format(type(self).__name__,
1162 self.__name__,
1163 int.__repr__(self))
1164 def __str__(self):
1165 # str() is unchanged, even if it relies on the repr() fallback
1166 base = int
1167 base_str = base.__str__
1168 if base_str.__objclass__ is object:
1169 return base.__repr__(self)
1170 return base_str(self)
1171 # for simplicity, we only define one operator that
1172 # propagates expressions
1173 def __add__(self, other):
1174 temp = int(self) + int( other)
1175 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1176 return NamedInt(
1177 '({0} + {1})'.format(self.__name__, other.__name__),
1178 temp )
1179 else:
1180 return temp
1181
1182 class NEI(NamedInt, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001183 __qualname__ = 'NEI'
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001184 x = ('the-x', 1)
1185 y = ('the-y', 2)
1186
1187 self.assertIs(NEI.__new__, Enum.__new__)
1188 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1189 globals()['NamedInt'] = NamedInt
1190 globals()['NEI'] = NEI
1191 NI5 = NamedInt('test', 5)
1192 self.assertEqual(NI5, 5)
1193 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001194 test_pickle_exception(self.assertRaises, TypeError, NEI.x)
1195 test_pickle_exception(self.assertRaises, PicklingError, NEI)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001196
Ethan Furmandc870522014-02-18 12:37:12 -08001197 def test_subclasses_without_direct_pickle_support_using_name(self):
1198 class NamedInt(int):
1199 __qualname__ = 'NamedInt'
1200 def __new__(cls, *args):
1201 _args = args
1202 name, *args = args
1203 if len(args) == 0:
1204 raise TypeError("name and value must be specified")
1205 self = int.__new__(cls, *args)
1206 self._intname = name
1207 self._args = _args
1208 return self
1209 @property
1210 def __name__(self):
1211 return self._intname
1212 def __repr__(self):
1213 # repr() is updated to include the name and type info
1214 return "{}({!r}, {})".format(type(self).__name__,
1215 self.__name__,
1216 int.__repr__(self))
1217 def __str__(self):
1218 # str() is unchanged, even if it relies on the repr() fallback
1219 base = int
1220 base_str = base.__str__
1221 if base_str.__objclass__ is object:
1222 return base.__repr__(self)
1223 return base_str(self)
1224 # for simplicity, we only define one operator that
1225 # propagates expressions
1226 def __add__(self, other):
1227 temp = int(self) + int( other)
1228 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1229 return NamedInt(
1230 '({0} + {1})'.format(self.__name__, other.__name__),
1231 temp )
1232 else:
1233 return temp
1234
1235 class NEI(NamedInt, Enum):
1236 __qualname__ = 'NEI'
1237 x = ('the-x', 1)
1238 y = ('the-y', 2)
1239 def __reduce_ex__(self, proto):
1240 return getattr, (self.__class__, self._name_)
1241
1242 self.assertIs(NEI.__new__, Enum.__new__)
1243 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1244 globals()['NamedInt'] = NamedInt
1245 globals()['NEI'] = NEI
1246 NI5 = NamedInt('test', 5)
1247 self.assertEqual(NI5, 5)
1248 self.assertEqual(NEI.y.value, 2)
1249 test_pickle_dump_load(self.assertIs, NEI.y)
1250 test_pickle_dump_load(self.assertIs, NEI)
1251
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001252 def test_tuple_subclass(self):
1253 class SomeTuple(tuple, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001254 __qualname__ = 'SomeTuple' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001255 first = (1, 'for the money')
1256 second = (2, 'for the show')
1257 third = (3, 'for the music')
1258 self.assertIs(type(SomeTuple.first), SomeTuple)
1259 self.assertIsInstance(SomeTuple.second, tuple)
1260 self.assertEqual(SomeTuple.third, (3, 'for the music'))
1261 globals()['SomeTuple'] = SomeTuple
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001262 test_pickle_dump_load(self.assertIs, SomeTuple.first)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001263
1264 def test_duplicate_values_give_unique_enum_items(self):
1265 class AutoNumber(Enum):
1266 first = ()
1267 second = ()
1268 third = ()
1269 def __new__(cls):
1270 value = len(cls.__members__) + 1
1271 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001272 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001273 return obj
1274 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001275 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001276 self.assertEqual(
1277 list(AutoNumber),
1278 [AutoNumber.first, AutoNumber.second, AutoNumber.third],
1279 )
1280 self.assertEqual(int(AutoNumber.second), 2)
Ethan Furman2aa27322013-07-19 19:35:56 -07001281 self.assertEqual(AutoNumber.third.value, 3)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001282 self.assertIs(AutoNumber(1), AutoNumber.first)
1283
1284 def test_inherited_new_from_enhanced_enum(self):
1285 class AutoNumber(Enum):
1286 def __new__(cls):
1287 value = len(cls.__members__) + 1
1288 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001289 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001290 return obj
1291 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001292 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001293 class Color(AutoNumber):
1294 red = ()
1295 green = ()
1296 blue = ()
1297 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1298 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1299
1300 def test_inherited_new_from_mixed_enum(self):
1301 class AutoNumber(IntEnum):
1302 def __new__(cls):
1303 value = len(cls.__members__) + 1
1304 obj = int.__new__(cls, value)
Ethan Furman520ad572013-07-19 19:47:21 -07001305 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001306 return obj
1307 class Color(AutoNumber):
1308 red = ()
1309 green = ()
1310 blue = ()
1311 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1312 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1313
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001314 def test_equality(self):
1315 class AlwaysEqual:
1316 def __eq__(self, other):
1317 return True
1318 class OrdinaryEnum(Enum):
1319 a = 1
1320 self.assertEqual(AlwaysEqual(), OrdinaryEnum.a)
1321 self.assertEqual(OrdinaryEnum.a, AlwaysEqual())
1322
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001323 def test_ordered_mixin(self):
1324 class OrderedEnum(Enum):
1325 def __ge__(self, other):
1326 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001327 return self._value_ >= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001328 return NotImplemented
1329 def __gt__(self, other):
1330 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001331 return self._value_ > other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001332 return NotImplemented
1333 def __le__(self, other):
1334 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001335 return self._value_ <= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001336 return NotImplemented
1337 def __lt__(self, other):
1338 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001339 return self._value_ < other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001340 return NotImplemented
1341 class Grade(OrderedEnum):
1342 A = 5
1343 B = 4
1344 C = 3
1345 D = 2
1346 F = 1
1347 self.assertGreater(Grade.A, Grade.B)
1348 self.assertLessEqual(Grade.F, Grade.C)
1349 self.assertLess(Grade.D, Grade.A)
1350 self.assertGreaterEqual(Grade.B, Grade.B)
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001351 self.assertEqual(Grade.B, Grade.B)
1352 self.assertNotEqual(Grade.C, Grade.D)
Ethan Furman520ad572013-07-19 19:47:21 -07001353
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001354 def test_extending2(self):
1355 class Shade(Enum):
1356 def shade(self):
1357 print(self.name)
1358 class Color(Shade):
1359 red = 1
1360 green = 2
1361 blue = 3
1362 with self.assertRaises(TypeError):
1363 class MoreColor(Color):
1364 cyan = 4
1365 magenta = 5
1366 yellow = 6
1367
1368 def test_extending3(self):
1369 class Shade(Enum):
1370 def shade(self):
1371 return self.name
1372 class Color(Shade):
1373 def hex(self):
1374 return '%s hexlified!' % self.value
1375 class MoreColor(Color):
1376 cyan = 4
1377 magenta = 5
1378 yellow = 6
1379 self.assertEqual(MoreColor.magenta.hex(), '5 hexlified!')
1380
1381
1382 def test_no_duplicates(self):
1383 class UniqueEnum(Enum):
1384 def __init__(self, *args):
1385 cls = self.__class__
1386 if any(self.value == e.value for e in cls):
1387 a = self.name
1388 e = cls(self.value).name
1389 raise ValueError(
1390 "aliases not allowed in UniqueEnum: %r --> %r"
1391 % (a, e)
1392 )
1393 class Color(UniqueEnum):
1394 red = 1
1395 green = 2
1396 blue = 3
1397 with self.assertRaises(ValueError):
1398 class Color(UniqueEnum):
1399 red = 1
1400 green = 2
1401 blue = 3
1402 grene = 2
1403
1404 def test_init(self):
1405 class Planet(Enum):
1406 MERCURY = (3.303e+23, 2.4397e6)
1407 VENUS = (4.869e+24, 6.0518e6)
1408 EARTH = (5.976e+24, 6.37814e6)
1409 MARS = (6.421e+23, 3.3972e6)
1410 JUPITER = (1.9e+27, 7.1492e7)
1411 SATURN = (5.688e+26, 6.0268e7)
1412 URANUS = (8.686e+25, 2.5559e7)
1413 NEPTUNE = (1.024e+26, 2.4746e7)
1414 def __init__(self, mass, radius):
1415 self.mass = mass # in kilograms
1416 self.radius = radius # in meters
1417 @property
1418 def surface_gravity(self):
1419 # universal gravitational constant (m3 kg-1 s-2)
1420 G = 6.67300E-11
1421 return G * self.mass / (self.radius * self.radius)
1422 self.assertEqual(round(Planet.EARTH.surface_gravity, 2), 9.80)
1423 self.assertEqual(Planet.EARTH.value, (5.976e+24, 6.37814e6))
1424
Ethan Furman2aa27322013-07-19 19:35:56 -07001425 def test_nonhash_value(self):
1426 class AutoNumberInAList(Enum):
1427 def __new__(cls):
1428 value = [len(cls.__members__) + 1]
1429 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001430 obj._value_ = value
Ethan Furman2aa27322013-07-19 19:35:56 -07001431 return obj
1432 class ColorInAList(AutoNumberInAList):
1433 red = ()
1434 green = ()
1435 blue = ()
1436 self.assertEqual(list(ColorInAList), [ColorInAList.red, ColorInAList.green, ColorInAList.blue])
Ethan Furman1a162882013-10-16 19:09:31 -07001437 for enum, value in zip(ColorInAList, range(3)):
1438 value += 1
1439 self.assertEqual(enum.value, [value])
1440 self.assertIs(ColorInAList([value]), enum)
Ethan Furman2aa27322013-07-19 19:35:56 -07001441
Ethan Furmanb41803e2013-07-25 13:50:45 -07001442 def test_conflicting_types_resolved_in_new(self):
1443 class LabelledIntEnum(int, Enum):
1444 def __new__(cls, *args):
1445 value, label = args
1446 obj = int.__new__(cls, value)
1447 obj.label = label
1448 obj._value_ = value
1449 return obj
1450
1451 class LabelledList(LabelledIntEnum):
1452 unprocessed = (1, "Unprocessed")
1453 payment_complete = (2, "Payment Complete")
1454
1455 self.assertEqual(list(LabelledList), [LabelledList.unprocessed, LabelledList.payment_complete])
1456 self.assertEqual(LabelledList.unprocessed, 1)
1457 self.assertEqual(LabelledList(1), LabelledList.unprocessed)
Ethan Furman2aa27322013-07-19 19:35:56 -07001458
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001459
Ethan Furmanf24bb352013-07-18 17:05:39 -07001460class TestUnique(unittest.TestCase):
1461
1462 def test_unique_clean(self):
1463 @unique
1464 class Clean(Enum):
1465 one = 1
1466 two = 'dos'
1467 tres = 4.0
1468 @unique
1469 class Cleaner(IntEnum):
1470 single = 1
1471 double = 2
1472 triple = 3
1473
1474 def test_unique_dirty(self):
1475 with self.assertRaisesRegex(ValueError, 'tres.*one'):
1476 @unique
1477 class Dirty(Enum):
1478 one = 1
1479 two = 'dos'
1480 tres = 1
1481 with self.assertRaisesRegex(
1482 ValueError,
1483 'double.*single.*turkey.*triple',
1484 ):
1485 @unique
1486 class Dirtier(IntEnum):
1487 single = 1
1488 double = 1
1489 triple = 3
1490 turkey = 3
1491
1492
Ethan Furman5875d742013-10-21 20:45:55 -07001493expected_help_output = """
1494Help on class Color in module %s:
1495
1496class Color(enum.Enum)
1497 | Method resolution order:
1498 | Color
1499 | enum.Enum
1500 | builtins.object
1501 |\x20\x20
1502 | Data and other attributes defined here:
1503 |\x20\x20
1504 | blue = <Color.blue: 3>
1505 |\x20\x20
1506 | green = <Color.green: 2>
1507 |\x20\x20
1508 | red = <Color.red: 1>
1509 |\x20\x20
1510 | ----------------------------------------------------------------------
1511 | Data descriptors inherited from enum.Enum:
1512 |\x20\x20
1513 | name
1514 | The name of the Enum member.
1515 |\x20\x20
1516 | value
1517 | The value of the Enum member.
1518 |\x20\x20
1519 | ----------------------------------------------------------------------
1520 | Data descriptors inherited from enum.EnumMeta:
1521 |\x20\x20
1522 | __members__
1523 | Returns a mapping of member name->value.
1524 |\x20\x20\x20\x20\x20\x20
1525 | This mapping lists all enum members, including aliases. Note that this
1526 | is a read-only view of the internal mapping.
1527""".strip()
1528
1529class TestStdLib(unittest.TestCase):
1530
1531 class Color(Enum):
1532 red = 1
1533 green = 2
1534 blue = 3
1535
1536 def test_pydoc(self):
1537 # indirectly test __objclass__
1538 expected_text = expected_help_output % __name__
1539 output = StringIO()
1540 helper = pydoc.Helper(output=output)
1541 helper(self.Color)
1542 result = output.getvalue().strip()
Victor Stinner4b0432d2014-06-16 22:48:43 +02001543 self.assertEqual(result, expected_text)
Ethan Furman5875d742013-10-21 20:45:55 -07001544
1545 def test_inspect_getmembers(self):
1546 values = dict((
1547 ('__class__', EnumMeta),
1548 ('__doc__', None),
1549 ('__members__', self.Color.__members__),
1550 ('__module__', __name__),
1551 ('blue', self.Color.blue),
1552 ('green', self.Color.green),
1553 ('name', Enum.__dict__['name']),
1554 ('red', self.Color.red),
1555 ('value', Enum.__dict__['value']),
1556 ))
1557 result = dict(inspect.getmembers(self.Color))
1558 self.assertEqual(values.keys(), result.keys())
1559 failed = False
1560 for k in values.keys():
1561 if result[k] != values[k]:
1562 print()
1563 print('\n%s\n key: %s\n result: %s\nexpected: %s\n%s\n' %
1564 ('=' * 75, k, result[k], values[k], '=' * 75), sep='')
1565 failed = True
1566 if failed:
1567 self.fail("result does not equal expected, see print above")
1568
1569 def test_inspect_classify_class_attrs(self):
1570 # indirectly test __objclass__
1571 from inspect import Attribute
1572 values = [
1573 Attribute(name='__class__', kind='data',
1574 defining_class=object, object=EnumMeta),
1575 Attribute(name='__doc__', kind='data',
1576 defining_class=self.Color, object=None),
1577 Attribute(name='__members__', kind='property',
1578 defining_class=EnumMeta, object=EnumMeta.__members__),
1579 Attribute(name='__module__', kind='data',
1580 defining_class=self.Color, object=__name__),
1581 Attribute(name='blue', kind='data',
1582 defining_class=self.Color, object=self.Color.blue),
1583 Attribute(name='green', kind='data',
1584 defining_class=self.Color, object=self.Color.green),
1585 Attribute(name='red', kind='data',
1586 defining_class=self.Color, object=self.Color.red),
1587 Attribute(name='name', kind='data',
1588 defining_class=Enum, object=Enum.__dict__['name']),
1589 Attribute(name='value', kind='data',
1590 defining_class=Enum, object=Enum.__dict__['value']),
1591 ]
1592 values.sort(key=lambda item: item.name)
1593 result = list(inspect.classify_class_attrs(self.Color))
1594 result.sort(key=lambda item: item.name)
1595 failed = False
1596 for v, r in zip(values, result):
1597 if r != v:
1598 print('\n%s\n%s\n%s\n%s\n' % ('=' * 75, r, v, '=' * 75), sep='')
1599 failed = True
1600 if failed:
1601 self.fail("result does not equal expected, see print above")
1602
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001603if __name__ == '__main__':
1604 unittest.main()