blob: b1a58557906cf8a534291be66158a1dadd415750 [file] [log] [blame]
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001import enum
Ethan Furman5875d742013-10-21 20:45:55 -07002import inspect
3import pydoc
Ethan Furman6b3d64a2013-06-14 16:55:46 -07004import unittest
5from collections import OrderedDict
Ethan Furman5875d742013-10-21 20:45:55 -07006from enum import Enum, IntEnum, EnumMeta, unique
7from io import StringIO
Ethan Furman2ddb39a2014-02-06 17:28:50 -08008from pickle import dumps, loads, PicklingError, HIGHEST_PROTOCOL
Martin Panter19e69c52015-11-14 12:46:42 +00009from test import support
Ethan Furman6b3d64a2013-06-14 16:55:46 -070010
11# for pickle tests
12try:
13 class Stooges(Enum):
14 LARRY = 1
15 CURLY = 2
16 MOE = 3
17except Exception as exc:
18 Stooges = exc
19
20try:
21 class IntStooges(int, Enum):
22 LARRY = 1
23 CURLY = 2
24 MOE = 3
25except Exception as exc:
26 IntStooges = exc
27
28try:
29 class FloatStooges(float, Enum):
30 LARRY = 1.39
31 CURLY = 2.72
32 MOE = 3.142596
33except Exception as exc:
34 FloatStooges = exc
35
36# for pickle test and subclass tests
37try:
38 class StrEnum(str, Enum):
39 'accepts only string values'
40 class Name(StrEnum):
41 BDFL = 'Guido van Rossum'
42 FLUFL = 'Barry Warsaw'
43except Exception as exc:
44 Name = exc
45
46try:
47 Question = Enum('Question', 'who what when where why', module=__name__)
48except Exception as exc:
49 Question = exc
50
51try:
52 Answer = Enum('Answer', 'him this then there because')
53except Exception as exc:
54 Answer = exc
55
Ethan Furmanca1b7942014-02-08 11:36:27 -080056try:
57 Theory = Enum('Theory', 'rule law supposition', qualname='spanish_inquisition')
58except Exception as exc:
59 Theory = exc
60
Ethan Furman6b3d64a2013-06-14 16:55:46 -070061# for doctests
62try:
63 class Fruit(Enum):
64 tomato = 1
65 banana = 2
66 cherry = 3
67except Exception:
68 pass
69
Serhiy Storchakae50e7802015-03-31 16:56:49 +030070def test_pickle_dump_load(assertion, source, target=None):
Ethan Furman2ddb39a2014-02-06 17:28:50 -080071 if target is None:
72 target = source
Serhiy Storchakae50e7802015-03-31 16:56:49 +030073 for protocol in range(HIGHEST_PROTOCOL + 1):
Ethan Furman2ddb39a2014-02-06 17:28:50 -080074 assertion(loads(dumps(source, protocol=protocol)), target)
75
Serhiy Storchakae50e7802015-03-31 16:56:49 +030076def test_pickle_exception(assertion, exception, obj):
77 for protocol in range(HIGHEST_PROTOCOL + 1):
Ethan Furman2ddb39a2014-02-06 17:28:50 -080078 with assertion(exception):
79 dumps(obj, protocol=protocol)
Ethan Furman648f8602013-10-06 17:19:54 -070080
81class TestHelpers(unittest.TestCase):
82 # _is_descriptor, _is_sunder, _is_dunder
83
84 def test_is_descriptor(self):
85 class foo:
86 pass
87 for attr in ('__get__','__set__','__delete__'):
88 obj = foo()
89 self.assertFalse(enum._is_descriptor(obj))
90 setattr(obj, attr, 1)
91 self.assertTrue(enum._is_descriptor(obj))
92
93 def test_is_sunder(self):
94 for s in ('_a_', '_aa_'):
95 self.assertTrue(enum._is_sunder(s))
96
97 for s in ('a', 'a_', '_a', '__a', 'a__', '__a__', '_a__', '__a_', '_',
98 '__', '___', '____', '_____',):
99 self.assertFalse(enum._is_sunder(s))
100
101 def test_is_dunder(self):
102 for s in ('__a__', '__aa__'):
103 self.assertTrue(enum._is_dunder(s))
104 for s in ('a', 'a_', '_a', '__a', 'a__', '_a_', '_a__', '__a_', '_',
105 '__', '___', '____', '_____',):
106 self.assertFalse(enum._is_dunder(s))
107
108
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700109class TestEnum(unittest.TestCase):
Ethan Furmanca1b7942014-02-08 11:36:27 -0800110
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700111 def setUp(self):
112 class Season(Enum):
113 SPRING = 1
114 SUMMER = 2
115 AUTUMN = 3
116 WINTER = 4
117 self.Season = Season
118
Ethan Furmanec15a822013-08-31 19:17:41 -0700119 class Konstants(float, Enum):
120 E = 2.7182818
121 PI = 3.1415926
122 TAU = 2 * PI
123 self.Konstants = Konstants
124
125 class Grades(IntEnum):
126 A = 5
127 B = 4
128 C = 3
129 D = 2
130 F = 0
131 self.Grades = Grades
132
133 class Directional(str, Enum):
134 EAST = 'east'
135 WEST = 'west'
136 NORTH = 'north'
137 SOUTH = 'south'
138 self.Directional = Directional
139
140 from datetime import date
141 class Holiday(date, Enum):
142 NEW_YEAR = 2013, 1, 1
143 IDES_OF_MARCH = 2013, 3, 15
144 self.Holiday = Holiday
145
Ethan Furman388a3922013-08-12 06:51:41 -0700146 def test_dir_on_class(self):
147 Season = self.Season
148 self.assertEqual(
149 set(dir(Season)),
Ethan Furmanc850f342013-09-15 16:59:35 -0700150 set(['__class__', '__doc__', '__members__', '__module__',
Ethan Furman388a3922013-08-12 06:51:41 -0700151 'SPRING', 'SUMMER', 'AUTUMN', 'WINTER']),
152 )
153
154 def test_dir_on_item(self):
155 Season = self.Season
156 self.assertEqual(
157 set(dir(Season.WINTER)),
Ethan Furmanc850f342013-09-15 16:59:35 -0700158 set(['__class__', '__doc__', '__module__', 'name', 'value']),
Ethan Furman388a3922013-08-12 06:51:41 -0700159 )
160
Ethan Furmanc850f342013-09-15 16:59:35 -0700161 def test_dir_with_added_behavior(self):
162 class Test(Enum):
163 this = 'that'
164 these = 'those'
165 def wowser(self):
166 return ("Wowser! I'm %s!" % self.name)
167 self.assertEqual(
168 set(dir(Test)),
169 set(['__class__', '__doc__', '__members__', '__module__', 'this', 'these']),
170 )
171 self.assertEqual(
172 set(dir(Test.this)),
173 set(['__class__', '__doc__', '__module__', 'name', 'value', 'wowser']),
174 )
175
Ethan Furman0ae550b2014-10-14 08:58:32 -0700176 def test_dir_on_sub_with_behavior_on_super(self):
177 # see issue22506
178 class SuperEnum(Enum):
179 def invisible(self):
180 return "did you see me?"
181 class SubEnum(SuperEnum):
182 sample = 5
183 self.assertEqual(
184 set(dir(SubEnum.sample)),
185 set(['__class__', '__doc__', '__module__', 'name', 'value', 'invisible']),
186 )
187
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700188 def test_enum_in_enum_out(self):
189 Season = self.Season
190 self.assertIs(Season(Season.WINTER), Season.WINTER)
191
192 def test_enum_value(self):
193 Season = self.Season
194 self.assertEqual(Season.SPRING.value, 1)
195
196 def test_intenum_value(self):
197 self.assertEqual(IntStooges.CURLY.value, 2)
198
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700199 def test_enum(self):
200 Season = self.Season
201 lst = list(Season)
202 self.assertEqual(len(lst), len(Season))
203 self.assertEqual(len(Season), 4, Season)
204 self.assertEqual(
205 [Season.SPRING, Season.SUMMER, Season.AUTUMN, Season.WINTER], lst)
206
207 for i, season in enumerate('SPRING SUMMER AUTUMN WINTER'.split(), 1):
208 e = Season(i)
209 self.assertEqual(e, getattr(Season, season))
210 self.assertEqual(e.value, i)
211 self.assertNotEqual(e, i)
212 self.assertEqual(e.name, season)
213 self.assertIn(e, Season)
214 self.assertIs(type(e), Season)
215 self.assertIsInstance(e, Season)
216 self.assertEqual(str(e), 'Season.' + season)
217 self.assertEqual(
218 repr(e),
219 '<Season.{0}: {1}>'.format(season, i),
220 )
221
222 def test_value_name(self):
223 Season = self.Season
224 self.assertEqual(Season.SPRING.name, 'SPRING')
225 self.assertEqual(Season.SPRING.value, 1)
226 with self.assertRaises(AttributeError):
227 Season.SPRING.name = 'invierno'
228 with self.assertRaises(AttributeError):
229 Season.SPRING.value = 2
230
Ethan Furmanf203f2d2013-09-06 07:16:48 -0700231 def test_changing_member(self):
232 Season = self.Season
233 with self.assertRaises(AttributeError):
234 Season.WINTER = 'really cold'
235
Ethan Furman64a99722013-09-22 16:18:19 -0700236 def test_attribute_deletion(self):
237 class Season(Enum):
238 SPRING = 1
239 SUMMER = 2
240 AUTUMN = 3
241 WINTER = 4
242
243 def spam(cls):
244 pass
245
246 self.assertTrue(hasattr(Season, 'spam'))
247 del Season.spam
248 self.assertFalse(hasattr(Season, 'spam'))
249
250 with self.assertRaises(AttributeError):
251 del Season.SPRING
252 with self.assertRaises(AttributeError):
253 del Season.DRY
254 with self.assertRaises(AttributeError):
255 del Season.SPRING.name
256
Ethan Furman5de67b12016-04-13 23:52:09 -0700257 def test_bool_of_class(self):
258 class Empty(Enum):
259 pass
260 self.assertTrue(bool(Empty))
261
262 def test_bool_of_member(self):
263 class Count(Enum):
264 zero = 0
265 one = 1
266 two = 2
267 for member in Count:
268 self.assertTrue(bool(member))
269
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700270 def test_invalid_names(self):
271 with self.assertRaises(ValueError):
272 class Wrong(Enum):
273 mro = 9
274 with self.assertRaises(ValueError):
275 class Wrong(Enum):
276 _create_= 11
277 with self.assertRaises(ValueError):
278 class Wrong(Enum):
279 _get_mixins_ = 9
280 with self.assertRaises(ValueError):
281 class Wrong(Enum):
282 _find_new_ = 1
283 with self.assertRaises(ValueError):
284 class Wrong(Enum):
285 _any_name_ = 9
286
Ethan Furman6db1fd52015-09-17 21:49:12 -0700287 def test_bool(self):
Ethan Furman60255b62016-01-15 15:01:33 -0800288 # plain Enum members are always True
Ethan Furman6db1fd52015-09-17 21:49:12 -0700289 class Logic(Enum):
290 true = True
291 false = False
292 self.assertTrue(Logic.true)
Ethan Furman60255b62016-01-15 15:01:33 -0800293 self.assertTrue(Logic.false)
294 # unless overridden
295 class RealLogic(Enum):
296 true = True
297 false = False
298 def __bool__(self):
299 return bool(self._value_)
300 self.assertTrue(RealLogic.true)
301 self.assertFalse(RealLogic.false)
302 # mixed Enums depend on mixed-in type
303 class IntLogic(int, Enum):
304 true = 1
305 false = 0
306 self.assertTrue(IntLogic.true)
307 self.assertFalse(IntLogic.false)
Ethan Furman6db1fd52015-09-17 21:49:12 -0700308
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700309 def test_contains(self):
310 Season = self.Season
311 self.assertIn(Season.AUTUMN, Season)
312 self.assertNotIn(3, Season)
313
314 val = Season(3)
315 self.assertIn(val, Season)
316
317 class OtherEnum(Enum):
318 one = 1; two = 2
319 self.assertNotIn(OtherEnum.two, Season)
320
321 def test_comparisons(self):
322 Season = self.Season
323 with self.assertRaises(TypeError):
324 Season.SPRING < Season.WINTER
325 with self.assertRaises(TypeError):
326 Season.SPRING > 4
327
328 self.assertNotEqual(Season.SPRING, 1)
329
330 class Part(Enum):
331 SPRING = 1
332 CLIP = 2
333 BARREL = 3
334
335 self.assertNotEqual(Season.SPRING, Part.SPRING)
336 with self.assertRaises(TypeError):
337 Season.SPRING < Part.CLIP
338
339 def test_enum_duplicates(self):
340 class Season(Enum):
341 SPRING = 1
342 SUMMER = 2
343 AUTUMN = FALL = 3
344 WINTER = 4
345 ANOTHER_SPRING = 1
346 lst = list(Season)
347 self.assertEqual(
348 lst,
349 [Season.SPRING, Season.SUMMER,
350 Season.AUTUMN, Season.WINTER,
351 ])
352 self.assertIs(Season.FALL, Season.AUTUMN)
353 self.assertEqual(Season.FALL.value, 3)
354 self.assertEqual(Season.AUTUMN.value, 3)
355 self.assertIs(Season(3), Season.AUTUMN)
356 self.assertIs(Season(1), Season.SPRING)
357 self.assertEqual(Season.FALL.name, 'AUTUMN')
358 self.assertEqual(
359 [k for k,v in Season.__members__.items() if v.name != k],
360 ['FALL', 'ANOTHER_SPRING'],
361 )
362
Ethan Furman101e0742013-09-15 12:34:36 -0700363 def test_duplicate_name(self):
364 with self.assertRaises(TypeError):
365 class Color(Enum):
366 red = 1
367 green = 2
368 blue = 3
369 red = 4
370
371 with self.assertRaises(TypeError):
372 class Color(Enum):
373 red = 1
374 green = 2
375 blue = 3
376 def red(self):
377 return 'red'
378
379 with self.assertRaises(TypeError):
380 class Color(Enum):
381 @property
382 def red(self):
383 return 'redder'
384 red = 1
385 green = 2
386 blue = 3
387
388
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700389 def test_enum_with_value_name(self):
390 class Huh(Enum):
391 name = 1
392 value = 2
393 self.assertEqual(
394 list(Huh),
395 [Huh.name, Huh.value],
396 )
397 self.assertIs(type(Huh.name), Huh)
398 self.assertEqual(Huh.name.name, 'name')
399 self.assertEqual(Huh.name.value, 1)
Ethan Furmanec15a822013-08-31 19:17:41 -0700400
401 def test_format_enum(self):
402 Season = self.Season
403 self.assertEqual('{}'.format(Season.SPRING),
404 '{}'.format(str(Season.SPRING)))
405 self.assertEqual( '{:}'.format(Season.SPRING),
406 '{:}'.format(str(Season.SPRING)))
407 self.assertEqual('{:20}'.format(Season.SPRING),
408 '{:20}'.format(str(Season.SPRING)))
409 self.assertEqual('{:^20}'.format(Season.SPRING),
410 '{:^20}'.format(str(Season.SPRING)))
411 self.assertEqual('{:>20}'.format(Season.SPRING),
412 '{:>20}'.format(str(Season.SPRING)))
413 self.assertEqual('{:<20}'.format(Season.SPRING),
414 '{:<20}'.format(str(Season.SPRING)))
415
416 def test_format_enum_custom(self):
417 class TestFloat(float, Enum):
418 one = 1.0
419 two = 2.0
420 def __format__(self, spec):
421 return 'TestFloat success!'
422 self.assertEqual('{}'.format(TestFloat.one), 'TestFloat success!')
423
424 def assertFormatIsValue(self, spec, member):
425 self.assertEqual(spec.format(member), spec.format(member.value))
426
427 def test_format_enum_date(self):
428 Holiday = self.Holiday
429 self.assertFormatIsValue('{}', Holiday.IDES_OF_MARCH)
430 self.assertFormatIsValue('{:}', Holiday.IDES_OF_MARCH)
431 self.assertFormatIsValue('{:20}', Holiday.IDES_OF_MARCH)
432 self.assertFormatIsValue('{:^20}', Holiday.IDES_OF_MARCH)
433 self.assertFormatIsValue('{:>20}', Holiday.IDES_OF_MARCH)
434 self.assertFormatIsValue('{:<20}', Holiday.IDES_OF_MARCH)
435 self.assertFormatIsValue('{:%Y %m}', Holiday.IDES_OF_MARCH)
436 self.assertFormatIsValue('{:%Y %m %M:00}', Holiday.IDES_OF_MARCH)
437
438 def test_format_enum_float(self):
439 Konstants = self.Konstants
440 self.assertFormatIsValue('{}', Konstants.TAU)
441 self.assertFormatIsValue('{:}', Konstants.TAU)
442 self.assertFormatIsValue('{:20}', Konstants.TAU)
443 self.assertFormatIsValue('{:^20}', Konstants.TAU)
444 self.assertFormatIsValue('{:>20}', Konstants.TAU)
445 self.assertFormatIsValue('{:<20}', Konstants.TAU)
446 self.assertFormatIsValue('{:n}', Konstants.TAU)
447 self.assertFormatIsValue('{:5.2}', Konstants.TAU)
448 self.assertFormatIsValue('{:f}', Konstants.TAU)
449
450 def test_format_enum_int(self):
451 Grades = self.Grades
452 self.assertFormatIsValue('{}', Grades.C)
453 self.assertFormatIsValue('{:}', Grades.C)
454 self.assertFormatIsValue('{:20}', Grades.C)
455 self.assertFormatIsValue('{:^20}', Grades.C)
456 self.assertFormatIsValue('{:>20}', Grades.C)
457 self.assertFormatIsValue('{:<20}', Grades.C)
458 self.assertFormatIsValue('{:+}', Grades.C)
459 self.assertFormatIsValue('{:08X}', Grades.C)
460 self.assertFormatIsValue('{:b}', Grades.C)
461
462 def test_format_enum_str(self):
463 Directional = self.Directional
464 self.assertFormatIsValue('{}', Directional.WEST)
465 self.assertFormatIsValue('{:}', Directional.WEST)
466 self.assertFormatIsValue('{:20}', Directional.WEST)
467 self.assertFormatIsValue('{:^20}', Directional.WEST)
468 self.assertFormatIsValue('{:>20}', Directional.WEST)
469 self.assertFormatIsValue('{:<20}', Directional.WEST)
470
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700471 def test_hash(self):
472 Season = self.Season
473 dates = {}
474 dates[Season.WINTER] = '1225'
475 dates[Season.SPRING] = '0315'
476 dates[Season.SUMMER] = '0704'
477 dates[Season.AUTUMN] = '1031'
478 self.assertEqual(dates[Season.AUTUMN], '1031')
479
480 def test_intenum_from_scratch(self):
481 class phy(int, Enum):
482 pi = 3
483 tau = 2 * pi
484 self.assertTrue(phy.pi < phy.tau)
485
486 def test_intenum_inherited(self):
487 class IntEnum(int, Enum):
488 pass
489 class phy(IntEnum):
490 pi = 3
491 tau = 2 * pi
492 self.assertTrue(phy.pi < phy.tau)
493
494 def test_floatenum_from_scratch(self):
495 class phy(float, Enum):
Ethan Furmanec15a822013-08-31 19:17:41 -0700496 pi = 3.1415926
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700497 tau = 2 * pi
498 self.assertTrue(phy.pi < phy.tau)
499
500 def test_floatenum_inherited(self):
501 class FloatEnum(float, Enum):
502 pass
503 class phy(FloatEnum):
Ethan Furmanec15a822013-08-31 19:17:41 -0700504 pi = 3.1415926
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700505 tau = 2 * pi
506 self.assertTrue(phy.pi < phy.tau)
507
508 def test_strenum_from_scratch(self):
509 class phy(str, Enum):
510 pi = 'Pi'
511 tau = 'Tau'
512 self.assertTrue(phy.pi < phy.tau)
513
514 def test_strenum_inherited(self):
515 class StrEnum(str, Enum):
516 pass
517 class phy(StrEnum):
518 pi = 'Pi'
519 tau = 'Tau'
520 self.assertTrue(phy.pi < phy.tau)
521
522
523 def test_intenum(self):
524 class WeekDay(IntEnum):
525 SUNDAY = 1
526 MONDAY = 2
527 TUESDAY = 3
528 WEDNESDAY = 4
529 THURSDAY = 5
530 FRIDAY = 6
531 SATURDAY = 7
532
533 self.assertEqual(['a', 'b', 'c'][WeekDay.MONDAY], 'c')
534 self.assertEqual([i for i in range(WeekDay.TUESDAY)], [0, 1, 2])
535
536 lst = list(WeekDay)
537 self.assertEqual(len(lst), len(WeekDay))
538 self.assertEqual(len(WeekDay), 7)
539 target = 'SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY'
540 target = target.split()
541 for i, weekday in enumerate(target, 1):
542 e = WeekDay(i)
543 self.assertEqual(e, i)
544 self.assertEqual(int(e), i)
545 self.assertEqual(e.name, weekday)
546 self.assertIn(e, WeekDay)
547 self.assertEqual(lst.index(e)+1, i)
548 self.assertTrue(0 < e < 8)
549 self.assertIs(type(e), WeekDay)
550 self.assertIsInstance(e, int)
551 self.assertIsInstance(e, Enum)
552
553 def test_intenum_duplicates(self):
554 class WeekDay(IntEnum):
555 SUNDAY = 1
556 MONDAY = 2
557 TUESDAY = TEUSDAY = 3
558 WEDNESDAY = 4
559 THURSDAY = 5
560 FRIDAY = 6
561 SATURDAY = 7
562 self.assertIs(WeekDay.TEUSDAY, WeekDay.TUESDAY)
563 self.assertEqual(WeekDay(3).name, 'TUESDAY')
564 self.assertEqual([k for k,v in WeekDay.__members__.items()
565 if v.name != k], ['TEUSDAY', ])
566
Serhiy Storchakaea36c942016-05-12 10:37:58 +0300567 def test_intenum_from_bytes(self):
568 self.assertIs(IntStooges.from_bytes(b'\x00\x03', 'big'), IntStooges.MOE)
569 with self.assertRaises(ValueError):
570 IntStooges.from_bytes(b'\x00\x05', 'big')
571
572 def test_floatenum_fromhex(self):
573 h = float.hex(FloatStooges.MOE.value)
574 self.assertIs(FloatStooges.fromhex(h), FloatStooges.MOE)
575 h = float.hex(FloatStooges.MOE.value + 0.01)
576 with self.assertRaises(ValueError):
577 FloatStooges.fromhex(h)
578
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700579 def test_pickle_enum(self):
580 if isinstance(Stooges, Exception):
581 raise Stooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800582 test_pickle_dump_load(self.assertIs, Stooges.CURLY)
583 test_pickle_dump_load(self.assertIs, Stooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700584
585 def test_pickle_int(self):
586 if isinstance(IntStooges, Exception):
587 raise IntStooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800588 test_pickle_dump_load(self.assertIs, IntStooges.CURLY)
589 test_pickle_dump_load(self.assertIs, IntStooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700590
591 def test_pickle_float(self):
592 if isinstance(FloatStooges, Exception):
593 raise FloatStooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800594 test_pickle_dump_load(self.assertIs, FloatStooges.CURLY)
595 test_pickle_dump_load(self.assertIs, FloatStooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700596
597 def test_pickle_enum_function(self):
598 if isinstance(Answer, Exception):
599 raise Answer
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800600 test_pickle_dump_load(self.assertIs, Answer.him)
601 test_pickle_dump_load(self.assertIs, Answer)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700602
603 def test_pickle_enum_function_with_module(self):
604 if isinstance(Question, Exception):
605 raise Question
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800606 test_pickle_dump_load(self.assertIs, Question.who)
607 test_pickle_dump_load(self.assertIs, Question)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700608
Ethan Furmanca1b7942014-02-08 11:36:27 -0800609 def test_enum_function_with_qualname(self):
610 if isinstance(Theory, Exception):
611 raise Theory
612 self.assertEqual(Theory.__qualname__, 'spanish_inquisition')
613
614 def test_class_nested_enum_and_pickle_protocol_four(self):
615 # would normally just have this directly in the class namespace
616 class NestedEnum(Enum):
617 twigs = 'common'
618 shiny = 'rare'
619
620 self.__class__.NestedEnum = NestedEnum
621 self.NestedEnum.__qualname__ = '%s.NestedEnum' % self.__class__.__name__
Serhiy Storchakae50e7802015-03-31 16:56:49 +0300622 test_pickle_dump_load(self.assertIs, self.NestedEnum.twigs)
Ethan Furmanca1b7942014-02-08 11:36:27 -0800623
Ethan Furman24e837f2015-03-18 17:27:57 -0700624 def test_pickle_by_name(self):
625 class ReplaceGlobalInt(IntEnum):
626 ONE = 1
627 TWO = 2
628 ReplaceGlobalInt.__reduce_ex__ = enum._reduce_ex_by_name
629 for proto in range(HIGHEST_PROTOCOL):
630 self.assertEqual(ReplaceGlobalInt.TWO.__reduce_ex__(proto), 'TWO')
631
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700632 def test_exploding_pickle(self):
Ethan Furmanca1b7942014-02-08 11:36:27 -0800633 BadPickle = Enum(
634 'BadPickle', 'dill sweet bread-n-butter', module=__name__)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700635 globals()['BadPickle'] = BadPickle
Ethan Furmanca1b7942014-02-08 11:36:27 -0800636 # now break BadPickle to test exception raising
637 enum._make_class_unpicklable(BadPickle)
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800638 test_pickle_exception(self.assertRaises, TypeError, BadPickle.dill)
639 test_pickle_exception(self.assertRaises, PicklingError, BadPickle)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700640
641 def test_string_enum(self):
642 class SkillLevel(str, Enum):
643 master = 'what is the sound of one hand clapping?'
644 journeyman = 'why did the chicken cross the road?'
645 apprentice = 'knock, knock!'
646 self.assertEqual(SkillLevel.apprentice, 'knock, knock!')
647
648 def test_getattr_getitem(self):
649 class Period(Enum):
650 morning = 1
651 noon = 2
652 evening = 3
653 night = 4
654 self.assertIs(Period(2), Period.noon)
655 self.assertIs(getattr(Period, 'night'), Period.night)
656 self.assertIs(Period['morning'], Period.morning)
657
658 def test_getattr_dunder(self):
659 Season = self.Season
660 self.assertTrue(getattr(Season, '__eq__'))
661
662 def test_iteration_order(self):
663 class Season(Enum):
664 SUMMER = 2
665 WINTER = 4
666 AUTUMN = 3
667 SPRING = 1
668 self.assertEqual(
669 list(Season),
670 [Season.SUMMER, Season.WINTER, Season.AUTUMN, Season.SPRING],
671 )
672
Ethan Furman2131a4a2013-09-14 18:11:24 -0700673 def test_reversed_iteration_order(self):
674 self.assertEqual(
675 list(reversed(self.Season)),
676 [self.Season.WINTER, self.Season.AUTUMN, self.Season.SUMMER,
677 self.Season.SPRING]
678 )
679
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700680 def test_programatic_function_string(self):
681 SummerMonth = Enum('SummerMonth', 'june july august')
682 lst = list(SummerMonth)
683 self.assertEqual(len(lst), len(SummerMonth))
684 self.assertEqual(len(SummerMonth), 3, SummerMonth)
685 self.assertEqual(
686 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
687 lst,
688 )
689 for i, month in enumerate('june july august'.split(), 1):
690 e = SummerMonth(i)
691 self.assertEqual(int(e.value), i)
692 self.assertNotEqual(e, i)
693 self.assertEqual(e.name, month)
694 self.assertIn(e, SummerMonth)
695 self.assertIs(type(e), SummerMonth)
696
Ethan Furmand9925a12014-09-16 20:35:55 -0700697 def test_programatic_function_string_with_start(self):
698 SummerMonth = Enum('SummerMonth', 'june july august', start=10)
699 lst = list(SummerMonth)
700 self.assertEqual(len(lst), len(SummerMonth))
701 self.assertEqual(len(SummerMonth), 3, SummerMonth)
702 self.assertEqual(
703 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
704 lst,
705 )
706 for i, month in enumerate('june july august'.split(), 10):
707 e = SummerMonth(i)
708 self.assertEqual(int(e.value), i)
709 self.assertNotEqual(e, i)
710 self.assertEqual(e.name, month)
711 self.assertIn(e, SummerMonth)
712 self.assertIs(type(e), SummerMonth)
713
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700714 def test_programatic_function_string_list(self):
715 SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'])
716 lst = list(SummerMonth)
717 self.assertEqual(len(lst), len(SummerMonth))
718 self.assertEqual(len(SummerMonth), 3, SummerMonth)
719 self.assertEqual(
720 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
721 lst,
722 )
723 for i, month in enumerate('june july august'.split(), 1):
724 e = SummerMonth(i)
725 self.assertEqual(int(e.value), i)
726 self.assertNotEqual(e, i)
727 self.assertEqual(e.name, month)
728 self.assertIn(e, SummerMonth)
729 self.assertIs(type(e), SummerMonth)
730
Ethan Furmand9925a12014-09-16 20:35:55 -0700731 def test_programatic_function_string_list_with_start(self):
732 SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'], start=20)
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(), 20):
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
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700748 def test_programatic_function_iterable(self):
749 SummerMonth = Enum(
750 'SummerMonth',
751 (('june', 1), ('july', 2), ('august', 3))
752 )
753 lst = list(SummerMonth)
754 self.assertEqual(len(lst), len(SummerMonth))
755 self.assertEqual(len(SummerMonth), 3, SummerMonth)
756 self.assertEqual(
757 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
758 lst,
759 )
760 for i, month in enumerate('june july august'.split(), 1):
761 e = SummerMonth(i)
762 self.assertEqual(int(e.value), i)
763 self.assertNotEqual(e, i)
764 self.assertEqual(e.name, month)
765 self.assertIn(e, SummerMonth)
766 self.assertIs(type(e), SummerMonth)
767
768 def test_programatic_function_from_dict(self):
769 SummerMonth = Enum(
770 'SummerMonth',
771 OrderedDict((('june', 1), ('july', 2), ('august', 3)))
772 )
773 lst = list(SummerMonth)
774 self.assertEqual(len(lst), len(SummerMonth))
775 self.assertEqual(len(SummerMonth), 3, SummerMonth)
776 self.assertEqual(
777 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
778 lst,
779 )
780 for i, month in enumerate('june july august'.split(), 1):
781 e = SummerMonth(i)
782 self.assertEqual(int(e.value), i)
783 self.assertNotEqual(e, i)
784 self.assertEqual(e.name, month)
785 self.assertIn(e, SummerMonth)
786 self.assertIs(type(e), SummerMonth)
787
788 def test_programatic_function_type(self):
789 SummerMonth = Enum('SummerMonth', 'june july august', type=int)
790 lst = list(SummerMonth)
791 self.assertEqual(len(lst), len(SummerMonth))
792 self.assertEqual(len(SummerMonth), 3, SummerMonth)
793 self.assertEqual(
794 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
795 lst,
796 )
797 for i, month in enumerate('june july august'.split(), 1):
798 e = SummerMonth(i)
799 self.assertEqual(e, i)
800 self.assertEqual(e.name, month)
801 self.assertIn(e, SummerMonth)
802 self.assertIs(type(e), SummerMonth)
803
Ethan Furmand9925a12014-09-16 20:35:55 -0700804 def test_programatic_function_type_with_start(self):
805 SummerMonth = Enum('SummerMonth', 'june july august', type=int, start=30)
806 lst = list(SummerMonth)
807 self.assertEqual(len(lst), len(SummerMonth))
808 self.assertEqual(len(SummerMonth), 3, SummerMonth)
809 self.assertEqual(
810 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
811 lst,
812 )
813 for i, month in enumerate('june july august'.split(), 30):
814 e = SummerMonth(i)
815 self.assertEqual(e, i)
816 self.assertEqual(e.name, month)
817 self.assertIn(e, SummerMonth)
818 self.assertIs(type(e), SummerMonth)
819
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700820 def test_programatic_function_type_from_subclass(self):
821 SummerMonth = IntEnum('SummerMonth', 'june july august')
822 lst = list(SummerMonth)
823 self.assertEqual(len(lst), len(SummerMonth))
824 self.assertEqual(len(SummerMonth), 3, SummerMonth)
825 self.assertEqual(
826 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
827 lst,
828 )
829 for i, month in enumerate('june july august'.split(), 1):
830 e = SummerMonth(i)
831 self.assertEqual(e, i)
832 self.assertEqual(e.name, month)
833 self.assertIn(e, SummerMonth)
834 self.assertIs(type(e), SummerMonth)
835
Ethan Furmand9925a12014-09-16 20:35:55 -0700836 def test_programatic_function_type_from_subclass_with_start(self):
837 SummerMonth = IntEnum('SummerMonth', 'june july august', start=40)
838 lst = list(SummerMonth)
839 self.assertEqual(len(lst), len(SummerMonth))
840 self.assertEqual(len(SummerMonth), 3, SummerMonth)
841 self.assertEqual(
842 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
843 lst,
844 )
845 for i, month in enumerate('june july august'.split(), 40):
846 e = SummerMonth(i)
847 self.assertEqual(e, i)
848 self.assertEqual(e.name, month)
849 self.assertIn(e, SummerMonth)
850 self.assertIs(type(e), SummerMonth)
851
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700852 def test_subclassing(self):
853 if isinstance(Name, Exception):
854 raise Name
855 self.assertEqual(Name.BDFL, 'Guido van Rossum')
856 self.assertTrue(Name.BDFL, Name('Guido van Rossum'))
857 self.assertIs(Name.BDFL, getattr(Name, 'BDFL'))
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800858 test_pickle_dump_load(self.assertIs, Name.BDFL)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700859
860 def test_extending(self):
861 class Color(Enum):
862 red = 1
863 green = 2
864 blue = 3
865 with self.assertRaises(TypeError):
866 class MoreColor(Color):
867 cyan = 4
868 magenta = 5
869 yellow = 6
870
871 def test_exclude_methods(self):
872 class whatever(Enum):
873 this = 'that'
874 these = 'those'
875 def really(self):
876 return 'no, not %s' % self.value
877 self.assertIsNot(type(whatever.really), whatever)
878 self.assertEqual(whatever.this.really(), 'no, not that')
879
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700880 def test_wrong_inheritance_order(self):
881 with self.assertRaises(TypeError):
882 class Wrong(Enum, str):
883 NotHere = 'error before this point'
884
885 def test_intenum_transitivity(self):
886 class number(IntEnum):
887 one = 1
888 two = 2
889 three = 3
890 class numero(IntEnum):
891 uno = 1
892 dos = 2
893 tres = 3
894 self.assertEqual(number.one, numero.uno)
895 self.assertEqual(number.two, numero.dos)
896 self.assertEqual(number.three, numero.tres)
897
898 def test_wrong_enum_in_call(self):
899 class Monochrome(Enum):
900 black = 0
901 white = 1
902 class Gender(Enum):
903 male = 0
904 female = 1
905 self.assertRaises(ValueError, Monochrome, Gender.male)
906
907 def test_wrong_enum_in_mixed_call(self):
908 class Monochrome(IntEnum):
909 black = 0
910 white = 1
911 class Gender(Enum):
912 male = 0
913 female = 1
914 self.assertRaises(ValueError, Monochrome, Gender.male)
915
916 def test_mixed_enum_in_call_1(self):
917 class Monochrome(IntEnum):
918 black = 0
919 white = 1
920 class Gender(IntEnum):
921 male = 0
922 female = 1
923 self.assertIs(Monochrome(Gender.female), Monochrome.white)
924
925 def test_mixed_enum_in_call_2(self):
926 class Monochrome(Enum):
927 black = 0
928 white = 1
929 class Gender(IntEnum):
930 male = 0
931 female = 1
932 self.assertIs(Monochrome(Gender.male), Monochrome.black)
933
934 def test_flufl_enum(self):
935 class Fluflnum(Enum):
936 def __int__(self):
937 return int(self.value)
938 class MailManOptions(Fluflnum):
939 option1 = 1
940 option2 = 2
941 option3 = 3
942 self.assertEqual(int(MailManOptions.option1), 1)
943
Ethan Furman5e5a8232013-08-04 08:42:23 -0700944 def test_introspection(self):
945 class Number(IntEnum):
946 one = 100
947 two = 200
948 self.assertIs(Number.one._member_type_, int)
949 self.assertIs(Number._member_type_, int)
950 class String(str, Enum):
951 yarn = 'soft'
952 rope = 'rough'
953 wire = 'hard'
954 self.assertIs(String.yarn._member_type_, str)
955 self.assertIs(String._member_type_, str)
956 class Plain(Enum):
957 vanilla = 'white'
958 one = 1
959 self.assertIs(Plain.vanilla._member_type_, object)
960 self.assertIs(Plain._member_type_, object)
961
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700962 def test_no_such_enum_member(self):
963 class Color(Enum):
964 red = 1
965 green = 2
966 blue = 3
967 with self.assertRaises(ValueError):
968 Color(4)
969 with self.assertRaises(KeyError):
970 Color['chartreuse']
971
972 def test_new_repr(self):
973 class Color(Enum):
974 red = 1
975 green = 2
976 blue = 3
977 def __repr__(self):
978 return "don't you just love shades of %s?" % self.name
979 self.assertEqual(
980 repr(Color.blue),
981 "don't you just love shades of blue?",
982 )
983
984 def test_inherited_repr(self):
985 class MyEnum(Enum):
986 def __repr__(self):
987 return "My name is %s." % self.name
988 class MyIntEnum(int, MyEnum):
989 this = 1
990 that = 2
991 theother = 3
992 self.assertEqual(repr(MyIntEnum.that), "My name is that.")
993
994 def test_multiple_mixin_mro(self):
995 class auto_enum(type(Enum)):
996 def __new__(metacls, cls, bases, classdict):
997 temp = type(classdict)()
998 names = set(classdict._member_names)
999 i = 0
1000 for k in classdict._member_names:
1001 v = classdict[k]
1002 if v is Ellipsis:
1003 v = i
1004 else:
1005 i = v
1006 i += 1
1007 temp[k] = v
1008 for k, v in classdict.items():
1009 if k not in names:
1010 temp[k] = v
1011 return super(auto_enum, metacls).__new__(
1012 metacls, cls, bases, temp)
1013
1014 class AutoNumberedEnum(Enum, metaclass=auto_enum):
1015 pass
1016
1017 class AutoIntEnum(IntEnum, metaclass=auto_enum):
1018 pass
1019
1020 class TestAutoNumber(AutoNumberedEnum):
1021 a = ...
1022 b = 3
1023 c = ...
1024
1025 class TestAutoInt(AutoIntEnum):
1026 a = ...
1027 b = 3
1028 c = ...
1029
1030 def test_subclasses_with_getnewargs(self):
1031 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001032 __qualname__ = 'NamedInt' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001033 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 __getnewargs__(self):
1043 return 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):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001071 __qualname__ = 'NEI' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001072 x = ('the-x', 1)
1073 y = ('the-y', 2)
1074
Ethan Furman2aa27322013-07-19 19:35:56 -07001075
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001076 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)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001082 test_pickle_dump_load(self.assertEqual, NI5, 5)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001083 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001084 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001085 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001086
Ethan Furmanca1b7942014-02-08 11:36:27 -08001087 def test_subclasses_with_getnewargs_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 __getnewargs_ex__(self):
1100 return 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)
Serhiy Storchakae50e7802015-03-31 16:56:49 +03001139 test_pickle_dump_load(self.assertEqual, NI5, 5)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001140 self.assertEqual(NEI.y.value, 2)
Serhiy Storchakae50e7802015-03-31 16:56:49 +03001141 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
1144 def test_subclasses_with_reduce(self):
1145 class NamedInt(int):
1146 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1147 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 def __reduce__(self):
1157 return self.__class__, self._args
1158 @property
1159 def __name__(self):
1160 return self._intname
1161 def __repr__(self):
1162 # repr() is updated to include the name and type info
1163 return "{}({!r}, {})".format(type(self).__name__,
1164 self.__name__,
1165 int.__repr__(self))
1166 def __str__(self):
1167 # str() is unchanged, even if it relies on the repr() fallback
1168 base = int
1169 base_str = base.__str__
1170 if base_str.__objclass__ is object:
1171 return base.__repr__(self)
1172 return base_str(self)
1173 # for simplicity, we only define one operator that
1174 # propagates expressions
1175 def __add__(self, other):
1176 temp = int(self) + int( other)
1177 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1178 return NamedInt(
1179 '({0} + {1})'.format(self.__name__, other.__name__),
1180 temp )
1181 else:
1182 return temp
1183
1184 class NEI(NamedInt, Enum):
1185 __qualname__ = 'NEI' # needed for pickle protocol 4
1186 x = ('the-x', 1)
1187 y = ('the-y', 2)
1188
1189
1190 self.assertIs(NEI.__new__, Enum.__new__)
1191 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1192 globals()['NamedInt'] = NamedInt
1193 globals()['NEI'] = NEI
1194 NI5 = NamedInt('test', 5)
1195 self.assertEqual(NI5, 5)
1196 test_pickle_dump_load(self.assertEqual, NI5, 5)
1197 self.assertEqual(NEI.y.value, 2)
1198 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001199 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001200
1201 def test_subclasses_with_reduce_ex(self):
1202 class NamedInt(int):
1203 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1204 def __new__(cls, *args):
1205 _args = args
1206 name, *args = args
1207 if len(args) == 0:
1208 raise TypeError("name and value must be specified")
1209 self = int.__new__(cls, *args)
1210 self._intname = name
1211 self._args = _args
1212 return self
1213 def __reduce_ex__(self, proto):
1214 return self.__class__, self._args
1215 @property
1216 def __name__(self):
1217 return self._intname
1218 def __repr__(self):
1219 # repr() is updated to include the name and type info
1220 return "{}({!r}, {})".format(type(self).__name__,
1221 self.__name__,
1222 int.__repr__(self))
1223 def __str__(self):
1224 # str() is unchanged, even if it relies on the repr() fallback
1225 base = int
1226 base_str = base.__str__
1227 if base_str.__objclass__ is object:
1228 return base.__repr__(self)
1229 return base_str(self)
1230 # for simplicity, we only define one operator that
1231 # propagates expressions
1232 def __add__(self, other):
1233 temp = int(self) + int( other)
1234 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1235 return NamedInt(
1236 '({0} + {1})'.format(self.__name__, other.__name__),
1237 temp )
1238 else:
1239 return temp
1240
1241 class NEI(NamedInt, Enum):
1242 __qualname__ = 'NEI' # needed for pickle protocol 4
1243 x = ('the-x', 1)
1244 y = ('the-y', 2)
1245
1246
1247 self.assertIs(NEI.__new__, Enum.__new__)
1248 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1249 globals()['NamedInt'] = NamedInt
1250 globals()['NEI'] = NEI
1251 NI5 = NamedInt('test', 5)
1252 self.assertEqual(NI5, 5)
1253 test_pickle_dump_load(self.assertEqual, NI5, 5)
1254 self.assertEqual(NEI.y.value, 2)
1255 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001256 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001257
Ethan Furmandc870522014-02-18 12:37:12 -08001258 def test_subclasses_without_direct_pickle_support(self):
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001259 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001260 __qualname__ = 'NamedInt'
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001261 def __new__(cls, *args):
1262 _args = args
1263 name, *args = args
1264 if len(args) == 0:
1265 raise TypeError("name and value must be specified")
1266 self = int.__new__(cls, *args)
1267 self._intname = name
1268 self._args = _args
1269 return self
1270 @property
1271 def __name__(self):
1272 return self._intname
1273 def __repr__(self):
1274 # repr() is updated to include the name and type info
1275 return "{}({!r}, {})".format(type(self).__name__,
1276 self.__name__,
1277 int.__repr__(self))
1278 def __str__(self):
1279 # str() is unchanged, even if it relies on the repr() fallback
1280 base = int
1281 base_str = base.__str__
1282 if base_str.__objclass__ is object:
1283 return base.__repr__(self)
1284 return base_str(self)
1285 # for simplicity, we only define one operator that
1286 # propagates expressions
1287 def __add__(self, other):
1288 temp = int(self) + int( other)
1289 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1290 return NamedInt(
1291 '({0} + {1})'.format(self.__name__, other.__name__),
1292 temp )
1293 else:
1294 return temp
1295
1296 class NEI(NamedInt, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001297 __qualname__ = 'NEI'
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001298 x = ('the-x', 1)
1299 y = ('the-y', 2)
1300
1301 self.assertIs(NEI.__new__, Enum.__new__)
1302 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1303 globals()['NamedInt'] = NamedInt
1304 globals()['NEI'] = NEI
1305 NI5 = NamedInt('test', 5)
1306 self.assertEqual(NI5, 5)
1307 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001308 test_pickle_exception(self.assertRaises, TypeError, NEI.x)
1309 test_pickle_exception(self.assertRaises, PicklingError, NEI)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001310
Ethan Furmandc870522014-02-18 12:37:12 -08001311 def test_subclasses_without_direct_pickle_support_using_name(self):
1312 class NamedInt(int):
1313 __qualname__ = 'NamedInt'
1314 def __new__(cls, *args):
1315 _args = args
1316 name, *args = args
1317 if len(args) == 0:
1318 raise TypeError("name and value must be specified")
1319 self = int.__new__(cls, *args)
1320 self._intname = name
1321 self._args = _args
1322 return self
1323 @property
1324 def __name__(self):
1325 return self._intname
1326 def __repr__(self):
1327 # repr() is updated to include the name and type info
1328 return "{}({!r}, {})".format(type(self).__name__,
1329 self.__name__,
1330 int.__repr__(self))
1331 def __str__(self):
1332 # str() is unchanged, even if it relies on the repr() fallback
1333 base = int
1334 base_str = base.__str__
1335 if base_str.__objclass__ is object:
1336 return base.__repr__(self)
1337 return base_str(self)
1338 # for simplicity, we only define one operator that
1339 # propagates expressions
1340 def __add__(self, other):
1341 temp = int(self) + int( other)
1342 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1343 return NamedInt(
1344 '({0} + {1})'.format(self.__name__, other.__name__),
1345 temp )
1346 else:
1347 return temp
1348
1349 class NEI(NamedInt, Enum):
1350 __qualname__ = 'NEI'
1351 x = ('the-x', 1)
1352 y = ('the-y', 2)
1353 def __reduce_ex__(self, proto):
1354 return getattr, (self.__class__, self._name_)
1355
1356 self.assertIs(NEI.__new__, Enum.__new__)
1357 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1358 globals()['NamedInt'] = NamedInt
1359 globals()['NEI'] = NEI
1360 NI5 = NamedInt('test', 5)
1361 self.assertEqual(NI5, 5)
1362 self.assertEqual(NEI.y.value, 2)
1363 test_pickle_dump_load(self.assertIs, NEI.y)
1364 test_pickle_dump_load(self.assertIs, NEI)
1365
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001366 def test_tuple_subclass(self):
1367 class SomeTuple(tuple, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001368 __qualname__ = 'SomeTuple' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001369 first = (1, 'for the money')
1370 second = (2, 'for the show')
1371 third = (3, 'for the music')
1372 self.assertIs(type(SomeTuple.first), SomeTuple)
1373 self.assertIsInstance(SomeTuple.second, tuple)
1374 self.assertEqual(SomeTuple.third, (3, 'for the music'))
1375 globals()['SomeTuple'] = SomeTuple
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001376 test_pickle_dump_load(self.assertIs, SomeTuple.first)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001377
1378 def test_duplicate_values_give_unique_enum_items(self):
1379 class AutoNumber(Enum):
1380 first = ()
1381 second = ()
1382 third = ()
1383 def __new__(cls):
1384 value = len(cls.__members__) + 1
1385 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001386 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001387 return obj
1388 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001389 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001390 self.assertEqual(
1391 list(AutoNumber),
1392 [AutoNumber.first, AutoNumber.second, AutoNumber.third],
1393 )
1394 self.assertEqual(int(AutoNumber.second), 2)
Ethan Furman2aa27322013-07-19 19:35:56 -07001395 self.assertEqual(AutoNumber.third.value, 3)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001396 self.assertIs(AutoNumber(1), AutoNumber.first)
1397
1398 def test_inherited_new_from_enhanced_enum(self):
1399 class AutoNumber(Enum):
1400 def __new__(cls):
1401 value = len(cls.__members__) + 1
1402 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001403 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001404 return obj
1405 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001406 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001407 class Color(AutoNumber):
1408 red = ()
1409 green = ()
1410 blue = ()
1411 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1412 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1413
1414 def test_inherited_new_from_mixed_enum(self):
1415 class AutoNumber(IntEnum):
1416 def __new__(cls):
1417 value = len(cls.__members__) + 1
1418 obj = int.__new__(cls, value)
Ethan Furman520ad572013-07-19 19:47:21 -07001419 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001420 return obj
1421 class Color(AutoNumber):
1422 red = ()
1423 green = ()
1424 blue = ()
1425 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1426 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1427
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001428 def test_equality(self):
1429 class AlwaysEqual:
1430 def __eq__(self, other):
1431 return True
1432 class OrdinaryEnum(Enum):
1433 a = 1
1434 self.assertEqual(AlwaysEqual(), OrdinaryEnum.a)
1435 self.assertEqual(OrdinaryEnum.a, AlwaysEqual())
1436
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001437 def test_ordered_mixin(self):
1438 class OrderedEnum(Enum):
1439 def __ge__(self, other):
1440 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001441 return self._value_ >= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001442 return NotImplemented
1443 def __gt__(self, other):
1444 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001445 return self._value_ > other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001446 return NotImplemented
1447 def __le__(self, other):
1448 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001449 return self._value_ <= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001450 return NotImplemented
1451 def __lt__(self, other):
1452 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001453 return self._value_ < other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001454 return NotImplemented
1455 class Grade(OrderedEnum):
1456 A = 5
1457 B = 4
1458 C = 3
1459 D = 2
1460 F = 1
1461 self.assertGreater(Grade.A, Grade.B)
1462 self.assertLessEqual(Grade.F, Grade.C)
1463 self.assertLess(Grade.D, Grade.A)
1464 self.assertGreaterEqual(Grade.B, Grade.B)
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001465 self.assertEqual(Grade.B, Grade.B)
1466 self.assertNotEqual(Grade.C, Grade.D)
Ethan Furman520ad572013-07-19 19:47:21 -07001467
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001468 def test_extending2(self):
1469 class Shade(Enum):
1470 def shade(self):
1471 print(self.name)
1472 class Color(Shade):
1473 red = 1
1474 green = 2
1475 blue = 3
1476 with self.assertRaises(TypeError):
1477 class MoreColor(Color):
1478 cyan = 4
1479 magenta = 5
1480 yellow = 6
1481
1482 def test_extending3(self):
1483 class Shade(Enum):
1484 def shade(self):
1485 return self.name
1486 class Color(Shade):
1487 def hex(self):
1488 return '%s hexlified!' % self.value
1489 class MoreColor(Color):
1490 cyan = 4
1491 magenta = 5
1492 yellow = 6
1493 self.assertEqual(MoreColor.magenta.hex(), '5 hexlified!')
1494
1495
1496 def test_no_duplicates(self):
1497 class UniqueEnum(Enum):
1498 def __init__(self, *args):
1499 cls = self.__class__
1500 if any(self.value == e.value for e in cls):
1501 a = self.name
1502 e = cls(self.value).name
1503 raise ValueError(
1504 "aliases not allowed in UniqueEnum: %r --> %r"
1505 % (a, e)
1506 )
1507 class Color(UniqueEnum):
1508 red = 1
1509 green = 2
1510 blue = 3
1511 with self.assertRaises(ValueError):
1512 class Color(UniqueEnum):
1513 red = 1
1514 green = 2
1515 blue = 3
1516 grene = 2
1517
1518 def test_init(self):
1519 class Planet(Enum):
1520 MERCURY = (3.303e+23, 2.4397e6)
1521 VENUS = (4.869e+24, 6.0518e6)
1522 EARTH = (5.976e+24, 6.37814e6)
1523 MARS = (6.421e+23, 3.3972e6)
1524 JUPITER = (1.9e+27, 7.1492e7)
1525 SATURN = (5.688e+26, 6.0268e7)
1526 URANUS = (8.686e+25, 2.5559e7)
1527 NEPTUNE = (1.024e+26, 2.4746e7)
1528 def __init__(self, mass, radius):
1529 self.mass = mass # in kilograms
1530 self.radius = radius # in meters
1531 @property
1532 def surface_gravity(self):
1533 # universal gravitational constant (m3 kg-1 s-2)
1534 G = 6.67300E-11
1535 return G * self.mass / (self.radius * self.radius)
1536 self.assertEqual(round(Planet.EARTH.surface_gravity, 2), 9.80)
1537 self.assertEqual(Planet.EARTH.value, (5.976e+24, 6.37814e6))
1538
Ethan Furman2aa27322013-07-19 19:35:56 -07001539 def test_nonhash_value(self):
1540 class AutoNumberInAList(Enum):
1541 def __new__(cls):
1542 value = [len(cls.__members__) + 1]
1543 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001544 obj._value_ = value
Ethan Furman2aa27322013-07-19 19:35:56 -07001545 return obj
1546 class ColorInAList(AutoNumberInAList):
1547 red = ()
1548 green = ()
1549 blue = ()
1550 self.assertEqual(list(ColorInAList), [ColorInAList.red, ColorInAList.green, ColorInAList.blue])
Ethan Furman1a162882013-10-16 19:09:31 -07001551 for enum, value in zip(ColorInAList, range(3)):
1552 value += 1
1553 self.assertEqual(enum.value, [value])
1554 self.assertIs(ColorInAList([value]), enum)
Ethan Furman2aa27322013-07-19 19:35:56 -07001555
Ethan Furmanb41803e2013-07-25 13:50:45 -07001556 def test_conflicting_types_resolved_in_new(self):
1557 class LabelledIntEnum(int, Enum):
1558 def __new__(cls, *args):
1559 value, label = args
1560 obj = int.__new__(cls, value)
1561 obj.label = label
1562 obj._value_ = value
1563 return obj
1564
1565 class LabelledList(LabelledIntEnum):
1566 unprocessed = (1, "Unprocessed")
1567 payment_complete = (2, "Payment Complete")
1568
1569 self.assertEqual(list(LabelledList), [LabelledList.unprocessed, LabelledList.payment_complete])
1570 self.assertEqual(LabelledList.unprocessed, 1)
1571 self.assertEqual(LabelledList(1), LabelledList.unprocessed)
Ethan Furman2aa27322013-07-19 19:35:56 -07001572
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001573
Ethan Furmanf24bb352013-07-18 17:05:39 -07001574class TestUnique(unittest.TestCase):
1575
1576 def test_unique_clean(self):
1577 @unique
1578 class Clean(Enum):
1579 one = 1
1580 two = 'dos'
1581 tres = 4.0
1582 @unique
1583 class Cleaner(IntEnum):
1584 single = 1
1585 double = 2
1586 triple = 3
1587
1588 def test_unique_dirty(self):
1589 with self.assertRaisesRegex(ValueError, 'tres.*one'):
1590 @unique
1591 class Dirty(Enum):
1592 one = 1
1593 two = 'dos'
1594 tres = 1
1595 with self.assertRaisesRegex(
1596 ValueError,
1597 'double.*single.*turkey.*triple',
1598 ):
1599 @unique
1600 class Dirtier(IntEnum):
1601 single = 1
1602 double = 1
1603 triple = 3
1604 turkey = 3
1605
Ethan Furman3803ad42016-05-01 10:03:53 -07001606 def test_unique_with_name(self):
1607 @unique
1608 class Silly(Enum):
1609 one = 1
1610 two = 'dos'
1611 name = 3
1612 @unique
1613 class Sillier(IntEnum):
1614 single = 1
1615 name = 2
1616 triple = 3
1617 value = 4
1618
Ethan Furmanf24bb352013-07-18 17:05:39 -07001619
Ethan Furman3323da92015-04-11 09:39:59 -07001620expected_help_output_with_docs = """\
Ethan Furman5875d742013-10-21 20:45:55 -07001621Help on class Color in module %s:
1622
1623class Color(enum.Enum)
Ethan Furman48a724f2015-04-11 23:23:06 -07001624 | An enumeration.
Serhiy Storchakab599ca82015-04-04 12:48:04 +03001625 |\x20\x20
Ethan Furman5875d742013-10-21 20:45:55 -07001626 | Method resolution order:
1627 | Color
1628 | enum.Enum
1629 | builtins.object
1630 |\x20\x20
1631 | Data and other attributes defined here:
1632 |\x20\x20
1633 | blue = <Color.blue: 3>
1634 |\x20\x20
1635 | green = <Color.green: 2>
1636 |\x20\x20
1637 | red = <Color.red: 1>
1638 |\x20\x20
1639 | ----------------------------------------------------------------------
1640 | Data descriptors inherited from enum.Enum:
1641 |\x20\x20
1642 | name
1643 | The name of the Enum member.
1644 |\x20\x20
1645 | value
1646 | The value of the Enum member.
1647 |\x20\x20
1648 | ----------------------------------------------------------------------
1649 | Data descriptors inherited from enum.EnumMeta:
1650 |\x20\x20
1651 | __members__
1652 | Returns a mapping of member name->value.
1653 |\x20\x20\x20\x20\x20\x20
1654 | This mapping lists all enum members, including aliases. Note that this
Ethan Furman3323da92015-04-11 09:39:59 -07001655 | is a read-only view of the internal mapping."""
1656
1657expected_help_output_without_docs = """\
1658Help on class Color in module %s:
1659
1660class Color(enum.Enum)
1661 | Method resolution order:
1662 | Color
1663 | enum.Enum
1664 | builtins.object
1665 |\x20\x20
1666 | Data and other attributes defined here:
1667 |\x20\x20
1668 | blue = <Color.blue: 3>
1669 |\x20\x20
1670 | green = <Color.green: 2>
1671 |\x20\x20
1672 | red = <Color.red: 1>
1673 |\x20\x20
1674 | ----------------------------------------------------------------------
1675 | Data descriptors inherited from enum.Enum:
1676 |\x20\x20
1677 | name
1678 |\x20\x20
1679 | value
1680 |\x20\x20
1681 | ----------------------------------------------------------------------
1682 | Data descriptors inherited from enum.EnumMeta:
1683 |\x20\x20
1684 | __members__"""
Ethan Furman5875d742013-10-21 20:45:55 -07001685
1686class TestStdLib(unittest.TestCase):
1687
Ethan Furman48a724f2015-04-11 23:23:06 -07001688 maxDiff = None
1689
Ethan Furman5875d742013-10-21 20:45:55 -07001690 class Color(Enum):
1691 red = 1
1692 green = 2
1693 blue = 3
1694
1695 def test_pydoc(self):
1696 # indirectly test __objclass__
Ethan Furman3323da92015-04-11 09:39:59 -07001697 if StrEnum.__doc__ is None:
1698 expected_text = expected_help_output_without_docs % __name__
1699 else:
1700 expected_text = expected_help_output_with_docs % __name__
Ethan Furman5875d742013-10-21 20:45:55 -07001701 output = StringIO()
1702 helper = pydoc.Helper(output=output)
1703 helper(self.Color)
1704 result = output.getvalue().strip()
Victor Stinner4b0432d2014-06-16 22:48:43 +02001705 self.assertEqual(result, expected_text)
Ethan Furman5875d742013-10-21 20:45:55 -07001706
1707 def test_inspect_getmembers(self):
1708 values = dict((
1709 ('__class__', EnumMeta),
Ethan Furman48a724f2015-04-11 23:23:06 -07001710 ('__doc__', 'An enumeration.'),
Ethan Furman5875d742013-10-21 20:45:55 -07001711 ('__members__', self.Color.__members__),
1712 ('__module__', __name__),
1713 ('blue', self.Color.blue),
1714 ('green', self.Color.green),
1715 ('name', Enum.__dict__['name']),
1716 ('red', self.Color.red),
1717 ('value', Enum.__dict__['value']),
1718 ))
1719 result = dict(inspect.getmembers(self.Color))
1720 self.assertEqual(values.keys(), result.keys())
1721 failed = False
1722 for k in values.keys():
1723 if result[k] != values[k]:
1724 print()
1725 print('\n%s\n key: %s\n result: %s\nexpected: %s\n%s\n' %
1726 ('=' * 75, k, result[k], values[k], '=' * 75), sep='')
1727 failed = True
1728 if failed:
1729 self.fail("result does not equal expected, see print above")
1730
1731 def test_inspect_classify_class_attrs(self):
1732 # indirectly test __objclass__
1733 from inspect import Attribute
1734 values = [
1735 Attribute(name='__class__', kind='data',
1736 defining_class=object, object=EnumMeta),
1737 Attribute(name='__doc__', kind='data',
Ethan Furman48a724f2015-04-11 23:23:06 -07001738 defining_class=self.Color, object='An enumeration.'),
Ethan Furman5875d742013-10-21 20:45:55 -07001739 Attribute(name='__members__', kind='property',
1740 defining_class=EnumMeta, object=EnumMeta.__members__),
1741 Attribute(name='__module__', kind='data',
1742 defining_class=self.Color, object=__name__),
1743 Attribute(name='blue', kind='data',
1744 defining_class=self.Color, object=self.Color.blue),
1745 Attribute(name='green', kind='data',
1746 defining_class=self.Color, object=self.Color.green),
1747 Attribute(name='red', kind='data',
1748 defining_class=self.Color, object=self.Color.red),
1749 Attribute(name='name', kind='data',
1750 defining_class=Enum, object=Enum.__dict__['name']),
1751 Attribute(name='value', kind='data',
1752 defining_class=Enum, object=Enum.__dict__['value']),
1753 ]
1754 values.sort(key=lambda item: item.name)
1755 result = list(inspect.classify_class_attrs(self.Color))
1756 result.sort(key=lambda item: item.name)
1757 failed = False
1758 for v, r in zip(values, result):
1759 if r != v:
1760 print('\n%s\n%s\n%s\n%s\n' % ('=' * 75, r, v, '=' * 75), sep='')
1761 failed = True
1762 if failed:
1763 self.fail("result does not equal expected, see print above")
1764
Martin Panter19e69c52015-11-14 12:46:42 +00001765
1766class MiscTestCase(unittest.TestCase):
1767 def test__all__(self):
1768 support.check__all__(self, enum)
1769
1770
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)6f20bd62016-06-03 19:14:52 +00001771# These are unordered here on purpose to ensure that declaration order
1772# makes no difference.
1773CONVERT_TEST_NAME_D = 5
1774CONVERT_TEST_NAME_C = 5
1775CONVERT_TEST_NAME_B = 5
1776CONVERT_TEST_NAME_A = 5 # This one should sort first.
1777CONVERT_TEST_NAME_E = 5
1778CONVERT_TEST_NAME_F = 5
1779
1780class TestIntEnumConvert(unittest.TestCase):
1781 def test_convert_value_lookup_priority(self):
1782 test_type = enum.IntEnum._convert(
1783 'UnittestConvert', 'test.test_enum',
1784 filter=lambda x: x.startswith('CONVERT_TEST_'))
1785 # We don't want the reverse lookup value to vary when there are
1786 # multiple possible names for a given value. It should always
1787 # report the first lexigraphical name in that case.
1788 self.assertEqual(test_type(5).name, 'CONVERT_TEST_NAME_A')
1789
1790 def test_convert(self):
1791 test_type = enum.IntEnum._convert(
1792 'UnittestConvert', 'test.test_enum',
1793 filter=lambda x: x.startswith('CONVERT_TEST_'))
1794 # Ensure that test_type has all of the desired names and values.
1795 self.assertEqual(test_type.CONVERT_TEST_NAME_F,
1796 test_type.CONVERT_TEST_NAME_A)
1797 self.assertEqual(test_type.CONVERT_TEST_NAME_B, 5)
1798 self.assertEqual(test_type.CONVERT_TEST_NAME_C, 5)
1799 self.assertEqual(test_type.CONVERT_TEST_NAME_D, 5)
1800 self.assertEqual(test_type.CONVERT_TEST_NAME_E, 5)
1801 # Ensure that test_type only picked up names matching the filter.
1802 self.assertEqual([name for name in dir(test_type)
1803 if name[0:2] not in ('CO', '__')],
1804 [], msg='Names other than CONVERT_TEST_* found.')
1805
1806
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001807if __name__ == '__main__':
1808 unittest.main()