blob: 51d9deb2e69473fc2250230e66b04d89d25cede8 [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 Furman24e837f2015-03-18 17:27:57 -0700584 def test_pickle_by_name(self):
585 class ReplaceGlobalInt(IntEnum):
586 ONE = 1
587 TWO = 2
588 ReplaceGlobalInt.__reduce_ex__ = enum._reduce_ex_by_name
589 for proto in range(HIGHEST_PROTOCOL):
590 self.assertEqual(ReplaceGlobalInt.TWO.__reduce_ex__(proto), 'TWO')
591
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700592 def test_exploding_pickle(self):
Ethan Furmanca1b7942014-02-08 11:36:27 -0800593 BadPickle = Enum(
594 'BadPickle', 'dill sweet bread-n-butter', module=__name__)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700595 globals()['BadPickle'] = BadPickle
Ethan Furmanca1b7942014-02-08 11:36:27 -0800596 # now break BadPickle to test exception raising
597 enum._make_class_unpicklable(BadPickle)
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800598 test_pickle_exception(self.assertRaises, TypeError, BadPickle.dill)
599 test_pickle_exception(self.assertRaises, PicklingError, BadPickle)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700600
601 def test_string_enum(self):
602 class SkillLevel(str, Enum):
603 master = 'what is the sound of one hand clapping?'
604 journeyman = 'why did the chicken cross the road?'
605 apprentice = 'knock, knock!'
606 self.assertEqual(SkillLevel.apprentice, 'knock, knock!')
607
608 def test_getattr_getitem(self):
609 class Period(Enum):
610 morning = 1
611 noon = 2
612 evening = 3
613 night = 4
614 self.assertIs(Period(2), Period.noon)
615 self.assertIs(getattr(Period, 'night'), Period.night)
616 self.assertIs(Period['morning'], Period.morning)
617
618 def test_getattr_dunder(self):
619 Season = self.Season
620 self.assertTrue(getattr(Season, '__eq__'))
621
622 def test_iteration_order(self):
623 class Season(Enum):
624 SUMMER = 2
625 WINTER = 4
626 AUTUMN = 3
627 SPRING = 1
628 self.assertEqual(
629 list(Season),
630 [Season.SUMMER, Season.WINTER, Season.AUTUMN, Season.SPRING],
631 )
632
Ethan Furman2131a4a2013-09-14 18:11:24 -0700633 def test_reversed_iteration_order(self):
634 self.assertEqual(
635 list(reversed(self.Season)),
636 [self.Season.WINTER, self.Season.AUTUMN, self.Season.SUMMER,
637 self.Season.SPRING]
638 )
639
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700640 def test_programatic_function_string(self):
641 SummerMonth = Enum('SummerMonth', 'june july august')
642 lst = list(SummerMonth)
643 self.assertEqual(len(lst), len(SummerMonth))
644 self.assertEqual(len(SummerMonth), 3, SummerMonth)
645 self.assertEqual(
646 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
647 lst,
648 )
649 for i, month in enumerate('june july august'.split(), 1):
650 e = SummerMonth(i)
651 self.assertEqual(int(e.value), i)
652 self.assertNotEqual(e, i)
653 self.assertEqual(e.name, month)
654 self.assertIn(e, SummerMonth)
655 self.assertIs(type(e), SummerMonth)
656
Ethan Furmand9925a12014-09-16 20:35:55 -0700657 def test_programatic_function_string_with_start(self):
658 SummerMonth = Enum('SummerMonth', 'june july august', start=10)
659 lst = list(SummerMonth)
660 self.assertEqual(len(lst), len(SummerMonth))
661 self.assertEqual(len(SummerMonth), 3, SummerMonth)
662 self.assertEqual(
663 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
664 lst,
665 )
666 for i, month in enumerate('june july august'.split(), 10):
667 e = SummerMonth(i)
668 self.assertEqual(int(e.value), i)
669 self.assertNotEqual(e, i)
670 self.assertEqual(e.name, month)
671 self.assertIn(e, SummerMonth)
672 self.assertIs(type(e), SummerMonth)
673
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700674 def test_programatic_function_string_list(self):
675 SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'])
676 lst = list(SummerMonth)
677 self.assertEqual(len(lst), len(SummerMonth))
678 self.assertEqual(len(SummerMonth), 3, SummerMonth)
679 self.assertEqual(
680 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
681 lst,
682 )
683 for i, month in enumerate('june july august'.split(), 1):
684 e = SummerMonth(i)
685 self.assertEqual(int(e.value), i)
686 self.assertNotEqual(e, i)
687 self.assertEqual(e.name, month)
688 self.assertIn(e, SummerMonth)
689 self.assertIs(type(e), SummerMonth)
690
Ethan Furmand9925a12014-09-16 20:35:55 -0700691 def test_programatic_function_string_list_with_start(self):
692 SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'], start=20)
693 lst = list(SummerMonth)
694 self.assertEqual(len(lst), len(SummerMonth))
695 self.assertEqual(len(SummerMonth), 3, SummerMonth)
696 self.assertEqual(
697 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
698 lst,
699 )
700 for i, month in enumerate('june july august'.split(), 20):
701 e = SummerMonth(i)
702 self.assertEqual(int(e.value), i)
703 self.assertNotEqual(e, i)
704 self.assertEqual(e.name, month)
705 self.assertIn(e, SummerMonth)
706 self.assertIs(type(e), SummerMonth)
707
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700708 def test_programatic_function_iterable(self):
709 SummerMonth = Enum(
710 'SummerMonth',
711 (('june', 1), ('july', 2), ('august', 3))
712 )
713 lst = list(SummerMonth)
714 self.assertEqual(len(lst), len(SummerMonth))
715 self.assertEqual(len(SummerMonth), 3, SummerMonth)
716 self.assertEqual(
717 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
718 lst,
719 )
720 for i, month in enumerate('june july august'.split(), 1):
721 e = SummerMonth(i)
722 self.assertEqual(int(e.value), i)
723 self.assertNotEqual(e, i)
724 self.assertEqual(e.name, month)
725 self.assertIn(e, SummerMonth)
726 self.assertIs(type(e), SummerMonth)
727
728 def test_programatic_function_from_dict(self):
729 SummerMonth = Enum(
730 'SummerMonth',
731 OrderedDict((('june', 1), ('july', 2), ('august', 3)))
732 )
733 lst = list(SummerMonth)
734 self.assertEqual(len(lst), len(SummerMonth))
735 self.assertEqual(len(SummerMonth), 3, SummerMonth)
736 self.assertEqual(
737 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
738 lst,
739 )
740 for i, month in enumerate('june july august'.split(), 1):
741 e = SummerMonth(i)
742 self.assertEqual(int(e.value), i)
743 self.assertNotEqual(e, i)
744 self.assertEqual(e.name, month)
745 self.assertIn(e, SummerMonth)
746 self.assertIs(type(e), SummerMonth)
747
748 def test_programatic_function_type(self):
749 SummerMonth = Enum('SummerMonth', 'june july august', type=int)
750 lst = list(SummerMonth)
751 self.assertEqual(len(lst), len(SummerMonth))
752 self.assertEqual(len(SummerMonth), 3, SummerMonth)
753 self.assertEqual(
754 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
755 lst,
756 )
757 for i, month in enumerate('june july august'.split(), 1):
758 e = SummerMonth(i)
759 self.assertEqual(e, i)
760 self.assertEqual(e.name, month)
761 self.assertIn(e, SummerMonth)
762 self.assertIs(type(e), SummerMonth)
763
Ethan Furmand9925a12014-09-16 20:35:55 -0700764 def test_programatic_function_type_with_start(self):
765 SummerMonth = Enum('SummerMonth', 'june july august', type=int, start=30)
766 lst = list(SummerMonth)
767 self.assertEqual(len(lst), len(SummerMonth))
768 self.assertEqual(len(SummerMonth), 3, SummerMonth)
769 self.assertEqual(
770 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
771 lst,
772 )
773 for i, month in enumerate('june july august'.split(), 30):
774 e = SummerMonth(i)
775 self.assertEqual(e, i)
776 self.assertEqual(e.name, month)
777 self.assertIn(e, SummerMonth)
778 self.assertIs(type(e), SummerMonth)
779
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700780 def test_programatic_function_type_from_subclass(self):
781 SummerMonth = IntEnum('SummerMonth', 'june july august')
782 lst = list(SummerMonth)
783 self.assertEqual(len(lst), len(SummerMonth))
784 self.assertEqual(len(SummerMonth), 3, SummerMonth)
785 self.assertEqual(
786 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
787 lst,
788 )
789 for i, month in enumerate('june july august'.split(), 1):
790 e = SummerMonth(i)
791 self.assertEqual(e, i)
792 self.assertEqual(e.name, month)
793 self.assertIn(e, SummerMonth)
794 self.assertIs(type(e), SummerMonth)
795
Ethan Furmand9925a12014-09-16 20:35:55 -0700796 def test_programatic_function_type_from_subclass_with_start(self):
797 SummerMonth = IntEnum('SummerMonth', 'june july august', start=40)
798 lst = list(SummerMonth)
799 self.assertEqual(len(lst), len(SummerMonth))
800 self.assertEqual(len(SummerMonth), 3, SummerMonth)
801 self.assertEqual(
802 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
803 lst,
804 )
805 for i, month in enumerate('june july august'.split(), 40):
806 e = SummerMonth(i)
807 self.assertEqual(e, i)
808 self.assertEqual(e.name, month)
809 self.assertIn(e, SummerMonth)
810 self.assertIs(type(e), SummerMonth)
811
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700812 def test_subclassing(self):
813 if isinstance(Name, Exception):
814 raise Name
815 self.assertEqual(Name.BDFL, 'Guido van Rossum')
816 self.assertTrue(Name.BDFL, Name('Guido van Rossum'))
817 self.assertIs(Name.BDFL, getattr(Name, 'BDFL'))
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800818 test_pickle_dump_load(self.assertIs, Name.BDFL)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700819
820 def test_extending(self):
821 class Color(Enum):
822 red = 1
823 green = 2
824 blue = 3
825 with self.assertRaises(TypeError):
826 class MoreColor(Color):
827 cyan = 4
828 magenta = 5
829 yellow = 6
830
831 def test_exclude_methods(self):
832 class whatever(Enum):
833 this = 'that'
834 these = 'those'
835 def really(self):
836 return 'no, not %s' % self.value
837 self.assertIsNot(type(whatever.really), whatever)
838 self.assertEqual(whatever.this.really(), 'no, not that')
839
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700840 def test_wrong_inheritance_order(self):
841 with self.assertRaises(TypeError):
842 class Wrong(Enum, str):
843 NotHere = 'error before this point'
844
845 def test_intenum_transitivity(self):
846 class number(IntEnum):
847 one = 1
848 two = 2
849 three = 3
850 class numero(IntEnum):
851 uno = 1
852 dos = 2
853 tres = 3
854 self.assertEqual(number.one, numero.uno)
855 self.assertEqual(number.two, numero.dos)
856 self.assertEqual(number.three, numero.tres)
857
858 def test_wrong_enum_in_call(self):
859 class Monochrome(Enum):
860 black = 0
861 white = 1
862 class Gender(Enum):
863 male = 0
864 female = 1
865 self.assertRaises(ValueError, Monochrome, Gender.male)
866
867 def test_wrong_enum_in_mixed_call(self):
868 class Monochrome(IntEnum):
869 black = 0
870 white = 1
871 class Gender(Enum):
872 male = 0
873 female = 1
874 self.assertRaises(ValueError, Monochrome, Gender.male)
875
876 def test_mixed_enum_in_call_1(self):
877 class Monochrome(IntEnum):
878 black = 0
879 white = 1
880 class Gender(IntEnum):
881 male = 0
882 female = 1
883 self.assertIs(Monochrome(Gender.female), Monochrome.white)
884
885 def test_mixed_enum_in_call_2(self):
886 class Monochrome(Enum):
887 black = 0
888 white = 1
889 class Gender(IntEnum):
890 male = 0
891 female = 1
892 self.assertIs(Monochrome(Gender.male), Monochrome.black)
893
894 def test_flufl_enum(self):
895 class Fluflnum(Enum):
896 def __int__(self):
897 return int(self.value)
898 class MailManOptions(Fluflnum):
899 option1 = 1
900 option2 = 2
901 option3 = 3
902 self.assertEqual(int(MailManOptions.option1), 1)
903
Ethan Furman5e5a8232013-08-04 08:42:23 -0700904 def test_introspection(self):
905 class Number(IntEnum):
906 one = 100
907 two = 200
908 self.assertIs(Number.one._member_type_, int)
909 self.assertIs(Number._member_type_, int)
910 class String(str, Enum):
911 yarn = 'soft'
912 rope = 'rough'
913 wire = 'hard'
914 self.assertIs(String.yarn._member_type_, str)
915 self.assertIs(String._member_type_, str)
916 class Plain(Enum):
917 vanilla = 'white'
918 one = 1
919 self.assertIs(Plain.vanilla._member_type_, object)
920 self.assertIs(Plain._member_type_, object)
921
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700922 def test_no_such_enum_member(self):
923 class Color(Enum):
924 red = 1
925 green = 2
926 blue = 3
927 with self.assertRaises(ValueError):
928 Color(4)
929 with self.assertRaises(KeyError):
930 Color['chartreuse']
931
932 def test_new_repr(self):
933 class Color(Enum):
934 red = 1
935 green = 2
936 blue = 3
937 def __repr__(self):
938 return "don't you just love shades of %s?" % self.name
939 self.assertEqual(
940 repr(Color.blue),
941 "don't you just love shades of blue?",
942 )
943
944 def test_inherited_repr(self):
945 class MyEnum(Enum):
946 def __repr__(self):
947 return "My name is %s." % self.name
948 class MyIntEnum(int, MyEnum):
949 this = 1
950 that = 2
951 theother = 3
952 self.assertEqual(repr(MyIntEnum.that), "My name is that.")
953
954 def test_multiple_mixin_mro(self):
955 class auto_enum(type(Enum)):
956 def __new__(metacls, cls, bases, classdict):
957 temp = type(classdict)()
958 names = set(classdict._member_names)
959 i = 0
960 for k in classdict._member_names:
961 v = classdict[k]
962 if v is Ellipsis:
963 v = i
964 else:
965 i = v
966 i += 1
967 temp[k] = v
968 for k, v in classdict.items():
969 if k not in names:
970 temp[k] = v
971 return super(auto_enum, metacls).__new__(
972 metacls, cls, bases, temp)
973
974 class AutoNumberedEnum(Enum, metaclass=auto_enum):
975 pass
976
977 class AutoIntEnum(IntEnum, metaclass=auto_enum):
978 pass
979
980 class TestAutoNumber(AutoNumberedEnum):
981 a = ...
982 b = 3
983 c = ...
984
985 class TestAutoInt(AutoIntEnum):
986 a = ...
987 b = 3
988 c = ...
989
990 def test_subclasses_with_getnewargs(self):
991 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800992 __qualname__ = 'NamedInt' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700993 def __new__(cls, *args):
994 _args = args
995 name, *args = args
996 if len(args) == 0:
997 raise TypeError("name and value must be specified")
998 self = int.__new__(cls, *args)
999 self._intname = name
1000 self._args = _args
1001 return self
1002 def __getnewargs__(self):
1003 return self._args
1004 @property
1005 def __name__(self):
1006 return self._intname
1007 def __repr__(self):
1008 # repr() is updated to include the name and type info
1009 return "{}({!r}, {})".format(type(self).__name__,
1010 self.__name__,
1011 int.__repr__(self))
1012 def __str__(self):
1013 # str() is unchanged, even if it relies on the repr() fallback
1014 base = int
1015 base_str = base.__str__
1016 if base_str.__objclass__ is object:
1017 return base.__repr__(self)
1018 return base_str(self)
1019 # for simplicity, we only define one operator that
1020 # propagates expressions
1021 def __add__(self, other):
1022 temp = int(self) + int( other)
1023 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1024 return NamedInt(
1025 '({0} + {1})'.format(self.__name__, other.__name__),
1026 temp )
1027 else:
1028 return temp
1029
1030 class NEI(NamedInt, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001031 __qualname__ = 'NEI' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001032 x = ('the-x', 1)
1033 y = ('the-y', 2)
1034
Ethan Furman2aa27322013-07-19 19:35:56 -07001035
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001036 self.assertIs(NEI.__new__, Enum.__new__)
1037 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1038 globals()['NamedInt'] = NamedInt
1039 globals()['NEI'] = NEI
1040 NI5 = NamedInt('test', 5)
1041 self.assertEqual(NI5, 5)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001042 test_pickle_dump_load(self.assertEqual, NI5, 5)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001043 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001044 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001045 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001046
Ethan Furmanca1b7942014-02-08 11:36:27 -08001047 def test_subclasses_with_getnewargs_ex(self):
1048 class NamedInt(int):
1049 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1050 def __new__(cls, *args):
1051 _args = args
1052 name, *args = args
1053 if len(args) == 0:
1054 raise TypeError("name and value must be specified")
1055 self = int.__new__(cls, *args)
1056 self._intname = name
1057 self._args = _args
1058 return self
1059 def __getnewargs_ex__(self):
1060 return self._args, {}
1061 @property
1062 def __name__(self):
1063 return self._intname
1064 def __repr__(self):
1065 # repr() is updated to include the name and type info
1066 return "{}({!r}, {})".format(type(self).__name__,
1067 self.__name__,
1068 int.__repr__(self))
1069 def __str__(self):
1070 # str() is unchanged, even if it relies on the repr() fallback
1071 base = int
1072 base_str = base.__str__
1073 if base_str.__objclass__ is object:
1074 return base.__repr__(self)
1075 return base_str(self)
1076 # for simplicity, we only define one operator that
1077 # propagates expressions
1078 def __add__(self, other):
1079 temp = int(self) + int( other)
1080 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1081 return NamedInt(
1082 '({0} + {1})'.format(self.__name__, other.__name__),
1083 temp )
1084 else:
1085 return temp
1086
1087 class NEI(NamedInt, Enum):
1088 __qualname__ = 'NEI' # needed for pickle protocol 4
1089 x = ('the-x', 1)
1090 y = ('the-y', 2)
1091
1092
1093 self.assertIs(NEI.__new__, Enum.__new__)
1094 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1095 globals()['NamedInt'] = NamedInt
1096 globals()['NEI'] = NEI
1097 NI5 = NamedInt('test', 5)
1098 self.assertEqual(NI5, 5)
1099 test_pickle_dump_load(self.assertEqual, NI5, 5, protocol=(4, 4))
1100 self.assertEqual(NEI.y.value, 2)
1101 test_pickle_dump_load(self.assertIs, NEI.y, protocol=(4, 4))
Ethan Furmandc870522014-02-18 12:37:12 -08001102 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001103
1104 def test_subclasses_with_reduce(self):
1105 class NamedInt(int):
1106 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1107 def __new__(cls, *args):
1108 _args = args
1109 name, *args = args
1110 if len(args) == 0:
1111 raise TypeError("name and value must be specified")
1112 self = int.__new__(cls, *args)
1113 self._intname = name
1114 self._args = _args
1115 return self
1116 def __reduce__(self):
1117 return self.__class__, self._args
1118 @property
1119 def __name__(self):
1120 return self._intname
1121 def __repr__(self):
1122 # repr() is updated to include the name and type info
1123 return "{}({!r}, {})".format(type(self).__name__,
1124 self.__name__,
1125 int.__repr__(self))
1126 def __str__(self):
1127 # str() is unchanged, even if it relies on the repr() fallback
1128 base = int
1129 base_str = base.__str__
1130 if base_str.__objclass__ is object:
1131 return base.__repr__(self)
1132 return base_str(self)
1133 # for simplicity, we only define one operator that
1134 # propagates expressions
1135 def __add__(self, other):
1136 temp = int(self) + int( other)
1137 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1138 return NamedInt(
1139 '({0} + {1})'.format(self.__name__, other.__name__),
1140 temp )
1141 else:
1142 return temp
1143
1144 class NEI(NamedInt, Enum):
1145 __qualname__ = 'NEI' # needed for pickle protocol 4
1146 x = ('the-x', 1)
1147 y = ('the-y', 2)
1148
1149
1150 self.assertIs(NEI.__new__, Enum.__new__)
1151 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1152 globals()['NamedInt'] = NamedInt
1153 globals()['NEI'] = NEI
1154 NI5 = NamedInt('test', 5)
1155 self.assertEqual(NI5, 5)
1156 test_pickle_dump_load(self.assertEqual, NI5, 5)
1157 self.assertEqual(NEI.y.value, 2)
1158 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001159 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001160
1161 def test_subclasses_with_reduce_ex(self):
1162 class NamedInt(int):
1163 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1164 def __new__(cls, *args):
1165 _args = args
1166 name, *args = args
1167 if len(args) == 0:
1168 raise TypeError("name and value must be specified")
1169 self = int.__new__(cls, *args)
1170 self._intname = name
1171 self._args = _args
1172 return self
1173 def __reduce_ex__(self, proto):
1174 return self.__class__, self._args
1175 @property
1176 def __name__(self):
1177 return self._intname
1178 def __repr__(self):
1179 # repr() is updated to include the name and type info
1180 return "{}({!r}, {})".format(type(self).__name__,
1181 self.__name__,
1182 int.__repr__(self))
1183 def __str__(self):
1184 # str() is unchanged, even if it relies on the repr() fallback
1185 base = int
1186 base_str = base.__str__
1187 if base_str.__objclass__ is object:
1188 return base.__repr__(self)
1189 return base_str(self)
1190 # for simplicity, we only define one operator that
1191 # propagates expressions
1192 def __add__(self, other):
1193 temp = int(self) + int( other)
1194 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1195 return NamedInt(
1196 '({0} + {1})'.format(self.__name__, other.__name__),
1197 temp )
1198 else:
1199 return temp
1200
1201 class NEI(NamedInt, Enum):
1202 __qualname__ = 'NEI' # needed for pickle protocol 4
1203 x = ('the-x', 1)
1204 y = ('the-y', 2)
1205
1206
1207 self.assertIs(NEI.__new__, Enum.__new__)
1208 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1209 globals()['NamedInt'] = NamedInt
1210 globals()['NEI'] = NEI
1211 NI5 = NamedInt('test', 5)
1212 self.assertEqual(NI5, 5)
1213 test_pickle_dump_load(self.assertEqual, NI5, 5)
1214 self.assertEqual(NEI.y.value, 2)
1215 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001216 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001217
Ethan Furmandc870522014-02-18 12:37:12 -08001218 def test_subclasses_without_direct_pickle_support(self):
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001219 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001220 __qualname__ = 'NamedInt'
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001221 def __new__(cls, *args):
1222 _args = args
1223 name, *args = args
1224 if len(args) == 0:
1225 raise TypeError("name and value must be specified")
1226 self = int.__new__(cls, *args)
1227 self._intname = name
1228 self._args = _args
1229 return self
1230 @property
1231 def __name__(self):
1232 return self._intname
1233 def __repr__(self):
1234 # repr() is updated to include the name and type info
1235 return "{}({!r}, {})".format(type(self).__name__,
1236 self.__name__,
1237 int.__repr__(self))
1238 def __str__(self):
1239 # str() is unchanged, even if it relies on the repr() fallback
1240 base = int
1241 base_str = base.__str__
1242 if base_str.__objclass__ is object:
1243 return base.__repr__(self)
1244 return base_str(self)
1245 # for simplicity, we only define one operator that
1246 # propagates expressions
1247 def __add__(self, other):
1248 temp = int(self) + int( other)
1249 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1250 return NamedInt(
1251 '({0} + {1})'.format(self.__name__, other.__name__),
1252 temp )
1253 else:
1254 return temp
1255
1256 class NEI(NamedInt, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001257 __qualname__ = 'NEI'
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001258 x = ('the-x', 1)
1259 y = ('the-y', 2)
1260
1261 self.assertIs(NEI.__new__, Enum.__new__)
1262 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1263 globals()['NamedInt'] = NamedInt
1264 globals()['NEI'] = NEI
1265 NI5 = NamedInt('test', 5)
1266 self.assertEqual(NI5, 5)
1267 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001268 test_pickle_exception(self.assertRaises, TypeError, NEI.x)
1269 test_pickle_exception(self.assertRaises, PicklingError, NEI)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001270
Ethan Furmandc870522014-02-18 12:37:12 -08001271 def test_subclasses_without_direct_pickle_support_using_name(self):
1272 class NamedInt(int):
1273 __qualname__ = 'NamedInt'
1274 def __new__(cls, *args):
1275 _args = args
1276 name, *args = args
1277 if len(args) == 0:
1278 raise TypeError("name and value must be specified")
1279 self = int.__new__(cls, *args)
1280 self._intname = name
1281 self._args = _args
1282 return self
1283 @property
1284 def __name__(self):
1285 return self._intname
1286 def __repr__(self):
1287 # repr() is updated to include the name and type info
1288 return "{}({!r}, {})".format(type(self).__name__,
1289 self.__name__,
1290 int.__repr__(self))
1291 def __str__(self):
1292 # str() is unchanged, even if it relies on the repr() fallback
1293 base = int
1294 base_str = base.__str__
1295 if base_str.__objclass__ is object:
1296 return base.__repr__(self)
1297 return base_str(self)
1298 # for simplicity, we only define one operator that
1299 # propagates expressions
1300 def __add__(self, other):
1301 temp = int(self) + int( other)
1302 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1303 return NamedInt(
1304 '({0} + {1})'.format(self.__name__, other.__name__),
1305 temp )
1306 else:
1307 return temp
1308
1309 class NEI(NamedInt, Enum):
1310 __qualname__ = 'NEI'
1311 x = ('the-x', 1)
1312 y = ('the-y', 2)
1313 def __reduce_ex__(self, proto):
1314 return getattr, (self.__class__, self._name_)
1315
1316 self.assertIs(NEI.__new__, Enum.__new__)
1317 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1318 globals()['NamedInt'] = NamedInt
1319 globals()['NEI'] = NEI
1320 NI5 = NamedInt('test', 5)
1321 self.assertEqual(NI5, 5)
1322 self.assertEqual(NEI.y.value, 2)
1323 test_pickle_dump_load(self.assertIs, NEI.y)
1324 test_pickle_dump_load(self.assertIs, NEI)
1325
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001326 def test_tuple_subclass(self):
1327 class SomeTuple(tuple, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001328 __qualname__ = 'SomeTuple' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001329 first = (1, 'for the money')
1330 second = (2, 'for the show')
1331 third = (3, 'for the music')
1332 self.assertIs(type(SomeTuple.first), SomeTuple)
1333 self.assertIsInstance(SomeTuple.second, tuple)
1334 self.assertEqual(SomeTuple.third, (3, 'for the music'))
1335 globals()['SomeTuple'] = SomeTuple
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001336 test_pickle_dump_load(self.assertIs, SomeTuple.first)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001337
1338 def test_duplicate_values_give_unique_enum_items(self):
1339 class AutoNumber(Enum):
1340 first = ()
1341 second = ()
1342 third = ()
1343 def __new__(cls):
1344 value = len(cls.__members__) + 1
1345 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001346 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001347 return obj
1348 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001349 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001350 self.assertEqual(
1351 list(AutoNumber),
1352 [AutoNumber.first, AutoNumber.second, AutoNumber.third],
1353 )
1354 self.assertEqual(int(AutoNumber.second), 2)
Ethan Furman2aa27322013-07-19 19:35:56 -07001355 self.assertEqual(AutoNumber.third.value, 3)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001356 self.assertIs(AutoNumber(1), AutoNumber.first)
1357
1358 def test_inherited_new_from_enhanced_enum(self):
1359 class AutoNumber(Enum):
1360 def __new__(cls):
1361 value = len(cls.__members__) + 1
1362 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001363 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001364 return obj
1365 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001366 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001367 class Color(AutoNumber):
1368 red = ()
1369 green = ()
1370 blue = ()
1371 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1372 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1373
1374 def test_inherited_new_from_mixed_enum(self):
1375 class AutoNumber(IntEnum):
1376 def __new__(cls):
1377 value = len(cls.__members__) + 1
1378 obj = int.__new__(cls, value)
Ethan Furman520ad572013-07-19 19:47:21 -07001379 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001380 return obj
1381 class Color(AutoNumber):
1382 red = ()
1383 green = ()
1384 blue = ()
1385 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1386 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1387
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001388 def test_equality(self):
1389 class AlwaysEqual:
1390 def __eq__(self, other):
1391 return True
1392 class OrdinaryEnum(Enum):
1393 a = 1
1394 self.assertEqual(AlwaysEqual(), OrdinaryEnum.a)
1395 self.assertEqual(OrdinaryEnum.a, AlwaysEqual())
1396
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001397 def test_ordered_mixin(self):
1398 class OrderedEnum(Enum):
1399 def __ge__(self, other):
1400 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001401 return self._value_ >= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001402 return NotImplemented
1403 def __gt__(self, other):
1404 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001405 return self._value_ > other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001406 return NotImplemented
1407 def __le__(self, other):
1408 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001409 return self._value_ <= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001410 return NotImplemented
1411 def __lt__(self, other):
1412 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001413 return self._value_ < other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001414 return NotImplemented
1415 class Grade(OrderedEnum):
1416 A = 5
1417 B = 4
1418 C = 3
1419 D = 2
1420 F = 1
1421 self.assertGreater(Grade.A, Grade.B)
1422 self.assertLessEqual(Grade.F, Grade.C)
1423 self.assertLess(Grade.D, Grade.A)
1424 self.assertGreaterEqual(Grade.B, Grade.B)
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001425 self.assertEqual(Grade.B, Grade.B)
1426 self.assertNotEqual(Grade.C, Grade.D)
Ethan Furman520ad572013-07-19 19:47:21 -07001427
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001428 def test_extending2(self):
1429 class Shade(Enum):
1430 def shade(self):
1431 print(self.name)
1432 class Color(Shade):
1433 red = 1
1434 green = 2
1435 blue = 3
1436 with self.assertRaises(TypeError):
1437 class MoreColor(Color):
1438 cyan = 4
1439 magenta = 5
1440 yellow = 6
1441
1442 def test_extending3(self):
1443 class Shade(Enum):
1444 def shade(self):
1445 return self.name
1446 class Color(Shade):
1447 def hex(self):
1448 return '%s hexlified!' % self.value
1449 class MoreColor(Color):
1450 cyan = 4
1451 magenta = 5
1452 yellow = 6
1453 self.assertEqual(MoreColor.magenta.hex(), '5 hexlified!')
1454
1455
1456 def test_no_duplicates(self):
1457 class UniqueEnum(Enum):
1458 def __init__(self, *args):
1459 cls = self.__class__
1460 if any(self.value == e.value for e in cls):
1461 a = self.name
1462 e = cls(self.value).name
1463 raise ValueError(
1464 "aliases not allowed in UniqueEnum: %r --> %r"
1465 % (a, e)
1466 )
1467 class Color(UniqueEnum):
1468 red = 1
1469 green = 2
1470 blue = 3
1471 with self.assertRaises(ValueError):
1472 class Color(UniqueEnum):
1473 red = 1
1474 green = 2
1475 blue = 3
1476 grene = 2
1477
1478 def test_init(self):
1479 class Planet(Enum):
1480 MERCURY = (3.303e+23, 2.4397e6)
1481 VENUS = (4.869e+24, 6.0518e6)
1482 EARTH = (5.976e+24, 6.37814e6)
1483 MARS = (6.421e+23, 3.3972e6)
1484 JUPITER = (1.9e+27, 7.1492e7)
1485 SATURN = (5.688e+26, 6.0268e7)
1486 URANUS = (8.686e+25, 2.5559e7)
1487 NEPTUNE = (1.024e+26, 2.4746e7)
1488 def __init__(self, mass, radius):
1489 self.mass = mass # in kilograms
1490 self.radius = radius # in meters
1491 @property
1492 def surface_gravity(self):
1493 # universal gravitational constant (m3 kg-1 s-2)
1494 G = 6.67300E-11
1495 return G * self.mass / (self.radius * self.radius)
1496 self.assertEqual(round(Planet.EARTH.surface_gravity, 2), 9.80)
1497 self.assertEqual(Planet.EARTH.value, (5.976e+24, 6.37814e6))
1498
Ethan Furman2aa27322013-07-19 19:35:56 -07001499 def test_nonhash_value(self):
1500 class AutoNumberInAList(Enum):
1501 def __new__(cls):
1502 value = [len(cls.__members__) + 1]
1503 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001504 obj._value_ = value
Ethan Furman2aa27322013-07-19 19:35:56 -07001505 return obj
1506 class ColorInAList(AutoNumberInAList):
1507 red = ()
1508 green = ()
1509 blue = ()
1510 self.assertEqual(list(ColorInAList), [ColorInAList.red, ColorInAList.green, ColorInAList.blue])
Ethan Furman1a162882013-10-16 19:09:31 -07001511 for enum, value in zip(ColorInAList, range(3)):
1512 value += 1
1513 self.assertEqual(enum.value, [value])
1514 self.assertIs(ColorInAList([value]), enum)
Ethan Furman2aa27322013-07-19 19:35:56 -07001515
Ethan Furmanb41803e2013-07-25 13:50:45 -07001516 def test_conflicting_types_resolved_in_new(self):
1517 class LabelledIntEnum(int, Enum):
1518 def __new__(cls, *args):
1519 value, label = args
1520 obj = int.__new__(cls, value)
1521 obj.label = label
1522 obj._value_ = value
1523 return obj
1524
1525 class LabelledList(LabelledIntEnum):
1526 unprocessed = (1, "Unprocessed")
1527 payment_complete = (2, "Payment Complete")
1528
1529 self.assertEqual(list(LabelledList), [LabelledList.unprocessed, LabelledList.payment_complete])
1530 self.assertEqual(LabelledList.unprocessed, 1)
1531 self.assertEqual(LabelledList(1), LabelledList.unprocessed)
Ethan Furman2aa27322013-07-19 19:35:56 -07001532
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001533
Ethan Furmanf24bb352013-07-18 17:05:39 -07001534class TestUnique(unittest.TestCase):
1535
1536 def test_unique_clean(self):
1537 @unique
1538 class Clean(Enum):
1539 one = 1
1540 two = 'dos'
1541 tres = 4.0
1542 @unique
1543 class Cleaner(IntEnum):
1544 single = 1
1545 double = 2
1546 triple = 3
1547
1548 def test_unique_dirty(self):
1549 with self.assertRaisesRegex(ValueError, 'tres.*one'):
1550 @unique
1551 class Dirty(Enum):
1552 one = 1
1553 two = 'dos'
1554 tres = 1
1555 with self.assertRaisesRegex(
1556 ValueError,
1557 'double.*single.*turkey.*triple',
1558 ):
1559 @unique
1560 class Dirtier(IntEnum):
1561 single = 1
1562 double = 1
1563 triple = 3
1564 turkey = 3
1565
1566
Ethan Furman5875d742013-10-21 20:45:55 -07001567expected_help_output = """
1568Help on class Color in module %s:
1569
1570class Color(enum.Enum)
1571 | Method resolution order:
1572 | Color
1573 | enum.Enum
1574 | builtins.object
1575 |\x20\x20
1576 | Data and other attributes defined here:
1577 |\x20\x20
1578 | blue = <Color.blue: 3>
1579 |\x20\x20
1580 | green = <Color.green: 2>
1581 |\x20\x20
1582 | red = <Color.red: 1>
1583 |\x20\x20
1584 | ----------------------------------------------------------------------
1585 | Data descriptors inherited from enum.Enum:
1586 |\x20\x20
1587 | name
1588 | The name of the Enum member.
1589 |\x20\x20
1590 | value
1591 | The value of the Enum member.
1592 |\x20\x20
1593 | ----------------------------------------------------------------------
1594 | Data descriptors inherited from enum.EnumMeta:
1595 |\x20\x20
1596 | __members__
1597 | Returns a mapping of member name->value.
1598 |\x20\x20\x20\x20\x20\x20
1599 | This mapping lists all enum members, including aliases. Note that this
1600 | is a read-only view of the internal mapping.
1601""".strip()
1602
1603class TestStdLib(unittest.TestCase):
1604
1605 class Color(Enum):
1606 red = 1
1607 green = 2
1608 blue = 3
1609
1610 def test_pydoc(self):
1611 # indirectly test __objclass__
1612 expected_text = expected_help_output % __name__
1613 output = StringIO()
1614 helper = pydoc.Helper(output=output)
1615 helper(self.Color)
1616 result = output.getvalue().strip()
Victor Stinner4b0432d2014-06-16 22:48:43 +02001617 self.assertEqual(result, expected_text)
Ethan Furman5875d742013-10-21 20:45:55 -07001618
1619 def test_inspect_getmembers(self):
1620 values = dict((
1621 ('__class__', EnumMeta),
1622 ('__doc__', None),
1623 ('__members__', self.Color.__members__),
1624 ('__module__', __name__),
1625 ('blue', self.Color.blue),
1626 ('green', self.Color.green),
1627 ('name', Enum.__dict__['name']),
1628 ('red', self.Color.red),
1629 ('value', Enum.__dict__['value']),
1630 ))
1631 result = dict(inspect.getmembers(self.Color))
1632 self.assertEqual(values.keys(), result.keys())
1633 failed = False
1634 for k in values.keys():
1635 if result[k] != values[k]:
1636 print()
1637 print('\n%s\n key: %s\n result: %s\nexpected: %s\n%s\n' %
1638 ('=' * 75, k, result[k], values[k], '=' * 75), sep='')
1639 failed = True
1640 if failed:
1641 self.fail("result does not equal expected, see print above")
1642
1643 def test_inspect_classify_class_attrs(self):
1644 # indirectly test __objclass__
1645 from inspect import Attribute
1646 values = [
1647 Attribute(name='__class__', kind='data',
1648 defining_class=object, object=EnumMeta),
1649 Attribute(name='__doc__', kind='data',
1650 defining_class=self.Color, object=None),
1651 Attribute(name='__members__', kind='property',
1652 defining_class=EnumMeta, object=EnumMeta.__members__),
1653 Attribute(name='__module__', kind='data',
1654 defining_class=self.Color, object=__name__),
1655 Attribute(name='blue', kind='data',
1656 defining_class=self.Color, object=self.Color.blue),
1657 Attribute(name='green', kind='data',
1658 defining_class=self.Color, object=self.Color.green),
1659 Attribute(name='red', kind='data',
1660 defining_class=self.Color, object=self.Color.red),
1661 Attribute(name='name', kind='data',
1662 defining_class=Enum, object=Enum.__dict__['name']),
1663 Attribute(name='value', kind='data',
1664 defining_class=Enum, object=Enum.__dict__['value']),
1665 ]
1666 values.sort(key=lambda item: item.name)
1667 result = list(inspect.classify_class_attrs(self.Color))
1668 result.sort(key=lambda item: item.name)
1669 failed = False
1670 for v, r in zip(values, result):
1671 if r != v:
1672 print('\n%s\n%s\n%s\n%s\n' % ('=' * 75, r, v, '=' * 75), sep='')
1673 failed = True
1674 if failed:
1675 self.fail("result does not equal expected, see print above")
1676
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001677if __name__ == '__main__':
1678 unittest.main()