blob: bf9d6338f1ef4b70d0777181d3ef22ca16d35f49 [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 Furman6b3d64a2013-06-14 16:55:46 -0700179 def test_enum_in_enum_out(self):
180 Season = self.Season
181 self.assertIs(Season(Season.WINTER), Season.WINTER)
182
183 def test_enum_value(self):
184 Season = self.Season
185 self.assertEqual(Season.SPRING.value, 1)
186
187 def test_intenum_value(self):
188 self.assertEqual(IntStooges.CURLY.value, 2)
189
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700190 def test_enum(self):
191 Season = self.Season
192 lst = list(Season)
193 self.assertEqual(len(lst), len(Season))
194 self.assertEqual(len(Season), 4, Season)
195 self.assertEqual(
196 [Season.SPRING, Season.SUMMER, Season.AUTUMN, Season.WINTER], lst)
197
198 for i, season in enumerate('SPRING SUMMER AUTUMN WINTER'.split(), 1):
199 e = Season(i)
200 self.assertEqual(e, getattr(Season, season))
201 self.assertEqual(e.value, i)
202 self.assertNotEqual(e, i)
203 self.assertEqual(e.name, season)
204 self.assertIn(e, Season)
205 self.assertIs(type(e), Season)
206 self.assertIsInstance(e, Season)
207 self.assertEqual(str(e), 'Season.' + season)
208 self.assertEqual(
209 repr(e),
210 '<Season.{0}: {1}>'.format(season, i),
211 )
212
213 def test_value_name(self):
214 Season = self.Season
215 self.assertEqual(Season.SPRING.name, 'SPRING')
216 self.assertEqual(Season.SPRING.value, 1)
217 with self.assertRaises(AttributeError):
218 Season.SPRING.name = 'invierno'
219 with self.assertRaises(AttributeError):
220 Season.SPRING.value = 2
221
Ethan Furmanf203f2d2013-09-06 07:16:48 -0700222 def test_changing_member(self):
223 Season = self.Season
224 with self.assertRaises(AttributeError):
225 Season.WINTER = 'really cold'
226
Ethan Furman64a99722013-09-22 16:18:19 -0700227 def test_attribute_deletion(self):
228 class Season(Enum):
229 SPRING = 1
230 SUMMER = 2
231 AUTUMN = 3
232 WINTER = 4
233
234 def spam(cls):
235 pass
236
237 self.assertTrue(hasattr(Season, 'spam'))
238 del Season.spam
239 self.assertFalse(hasattr(Season, 'spam'))
240
241 with self.assertRaises(AttributeError):
242 del Season.SPRING
243 with self.assertRaises(AttributeError):
244 del Season.DRY
245 with self.assertRaises(AttributeError):
246 del Season.SPRING.name
247
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700248 def test_invalid_names(self):
249 with self.assertRaises(ValueError):
250 class Wrong(Enum):
251 mro = 9
252 with self.assertRaises(ValueError):
253 class Wrong(Enum):
254 _create_= 11
255 with self.assertRaises(ValueError):
256 class Wrong(Enum):
257 _get_mixins_ = 9
258 with self.assertRaises(ValueError):
259 class Wrong(Enum):
260 _find_new_ = 1
261 with self.assertRaises(ValueError):
262 class Wrong(Enum):
263 _any_name_ = 9
264
265 def test_contains(self):
266 Season = self.Season
267 self.assertIn(Season.AUTUMN, Season)
268 self.assertNotIn(3, Season)
269
270 val = Season(3)
271 self.assertIn(val, Season)
272
273 class OtherEnum(Enum):
274 one = 1; two = 2
275 self.assertNotIn(OtherEnum.two, Season)
276
277 def test_comparisons(self):
278 Season = self.Season
279 with self.assertRaises(TypeError):
280 Season.SPRING < Season.WINTER
281 with self.assertRaises(TypeError):
282 Season.SPRING > 4
283
284 self.assertNotEqual(Season.SPRING, 1)
285
286 class Part(Enum):
287 SPRING = 1
288 CLIP = 2
289 BARREL = 3
290
291 self.assertNotEqual(Season.SPRING, Part.SPRING)
292 with self.assertRaises(TypeError):
293 Season.SPRING < Part.CLIP
294
295 def test_enum_duplicates(self):
296 class Season(Enum):
297 SPRING = 1
298 SUMMER = 2
299 AUTUMN = FALL = 3
300 WINTER = 4
301 ANOTHER_SPRING = 1
302 lst = list(Season)
303 self.assertEqual(
304 lst,
305 [Season.SPRING, Season.SUMMER,
306 Season.AUTUMN, Season.WINTER,
307 ])
308 self.assertIs(Season.FALL, Season.AUTUMN)
309 self.assertEqual(Season.FALL.value, 3)
310 self.assertEqual(Season.AUTUMN.value, 3)
311 self.assertIs(Season(3), Season.AUTUMN)
312 self.assertIs(Season(1), Season.SPRING)
313 self.assertEqual(Season.FALL.name, 'AUTUMN')
314 self.assertEqual(
315 [k for k,v in Season.__members__.items() if v.name != k],
316 ['FALL', 'ANOTHER_SPRING'],
317 )
318
Ethan Furman101e0742013-09-15 12:34:36 -0700319 def test_duplicate_name(self):
320 with self.assertRaises(TypeError):
321 class Color(Enum):
322 red = 1
323 green = 2
324 blue = 3
325 red = 4
326
327 with self.assertRaises(TypeError):
328 class Color(Enum):
329 red = 1
330 green = 2
331 blue = 3
332 def red(self):
333 return 'red'
334
335 with self.assertRaises(TypeError):
336 class Color(Enum):
337 @property
338 def red(self):
339 return 'redder'
340 red = 1
341 green = 2
342 blue = 3
343
344
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700345 def test_enum_with_value_name(self):
346 class Huh(Enum):
347 name = 1
348 value = 2
349 self.assertEqual(
350 list(Huh),
351 [Huh.name, Huh.value],
352 )
353 self.assertIs(type(Huh.name), Huh)
354 self.assertEqual(Huh.name.name, 'name')
355 self.assertEqual(Huh.name.value, 1)
Ethan Furmanec15a822013-08-31 19:17:41 -0700356
357 def test_format_enum(self):
358 Season = self.Season
359 self.assertEqual('{}'.format(Season.SPRING),
360 '{}'.format(str(Season.SPRING)))
361 self.assertEqual( '{:}'.format(Season.SPRING),
362 '{:}'.format(str(Season.SPRING)))
363 self.assertEqual('{:20}'.format(Season.SPRING),
364 '{:20}'.format(str(Season.SPRING)))
365 self.assertEqual('{:^20}'.format(Season.SPRING),
366 '{:^20}'.format(str(Season.SPRING)))
367 self.assertEqual('{:>20}'.format(Season.SPRING),
368 '{:>20}'.format(str(Season.SPRING)))
369 self.assertEqual('{:<20}'.format(Season.SPRING),
370 '{:<20}'.format(str(Season.SPRING)))
371
372 def test_format_enum_custom(self):
373 class TestFloat(float, Enum):
374 one = 1.0
375 two = 2.0
376 def __format__(self, spec):
377 return 'TestFloat success!'
378 self.assertEqual('{}'.format(TestFloat.one), 'TestFloat success!')
379
380 def assertFormatIsValue(self, spec, member):
381 self.assertEqual(spec.format(member), spec.format(member.value))
382
383 def test_format_enum_date(self):
384 Holiday = self.Holiday
385 self.assertFormatIsValue('{}', Holiday.IDES_OF_MARCH)
386 self.assertFormatIsValue('{:}', Holiday.IDES_OF_MARCH)
387 self.assertFormatIsValue('{:20}', Holiday.IDES_OF_MARCH)
388 self.assertFormatIsValue('{:^20}', Holiday.IDES_OF_MARCH)
389 self.assertFormatIsValue('{:>20}', Holiday.IDES_OF_MARCH)
390 self.assertFormatIsValue('{:<20}', Holiday.IDES_OF_MARCH)
391 self.assertFormatIsValue('{:%Y %m}', Holiday.IDES_OF_MARCH)
392 self.assertFormatIsValue('{:%Y %m %M:00}', Holiday.IDES_OF_MARCH)
393
394 def test_format_enum_float(self):
395 Konstants = self.Konstants
396 self.assertFormatIsValue('{}', Konstants.TAU)
397 self.assertFormatIsValue('{:}', Konstants.TAU)
398 self.assertFormatIsValue('{:20}', Konstants.TAU)
399 self.assertFormatIsValue('{:^20}', Konstants.TAU)
400 self.assertFormatIsValue('{:>20}', Konstants.TAU)
401 self.assertFormatIsValue('{:<20}', Konstants.TAU)
402 self.assertFormatIsValue('{:n}', Konstants.TAU)
403 self.assertFormatIsValue('{:5.2}', Konstants.TAU)
404 self.assertFormatIsValue('{:f}', Konstants.TAU)
405
406 def test_format_enum_int(self):
407 Grades = self.Grades
408 self.assertFormatIsValue('{}', Grades.C)
409 self.assertFormatIsValue('{:}', Grades.C)
410 self.assertFormatIsValue('{:20}', Grades.C)
411 self.assertFormatIsValue('{:^20}', Grades.C)
412 self.assertFormatIsValue('{:>20}', Grades.C)
413 self.assertFormatIsValue('{:<20}', Grades.C)
414 self.assertFormatIsValue('{:+}', Grades.C)
415 self.assertFormatIsValue('{:08X}', Grades.C)
416 self.assertFormatIsValue('{:b}', Grades.C)
417
418 def test_format_enum_str(self):
419 Directional = self.Directional
420 self.assertFormatIsValue('{}', Directional.WEST)
421 self.assertFormatIsValue('{:}', Directional.WEST)
422 self.assertFormatIsValue('{:20}', Directional.WEST)
423 self.assertFormatIsValue('{:^20}', Directional.WEST)
424 self.assertFormatIsValue('{:>20}', Directional.WEST)
425 self.assertFormatIsValue('{:<20}', Directional.WEST)
426
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700427 def test_hash(self):
428 Season = self.Season
429 dates = {}
430 dates[Season.WINTER] = '1225'
431 dates[Season.SPRING] = '0315'
432 dates[Season.SUMMER] = '0704'
433 dates[Season.AUTUMN] = '1031'
434 self.assertEqual(dates[Season.AUTUMN], '1031')
435
436 def test_intenum_from_scratch(self):
437 class phy(int, Enum):
438 pi = 3
439 tau = 2 * pi
440 self.assertTrue(phy.pi < phy.tau)
441
442 def test_intenum_inherited(self):
443 class IntEnum(int, Enum):
444 pass
445 class phy(IntEnum):
446 pi = 3
447 tau = 2 * pi
448 self.assertTrue(phy.pi < phy.tau)
449
450 def test_floatenum_from_scratch(self):
451 class phy(float, Enum):
Ethan Furmanec15a822013-08-31 19:17:41 -0700452 pi = 3.1415926
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700453 tau = 2 * pi
454 self.assertTrue(phy.pi < phy.tau)
455
456 def test_floatenum_inherited(self):
457 class FloatEnum(float, Enum):
458 pass
459 class phy(FloatEnum):
Ethan Furmanec15a822013-08-31 19:17:41 -0700460 pi = 3.1415926
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700461 tau = 2 * pi
462 self.assertTrue(phy.pi < phy.tau)
463
464 def test_strenum_from_scratch(self):
465 class phy(str, Enum):
466 pi = 'Pi'
467 tau = 'Tau'
468 self.assertTrue(phy.pi < phy.tau)
469
470 def test_strenum_inherited(self):
471 class StrEnum(str, Enum):
472 pass
473 class phy(StrEnum):
474 pi = 'Pi'
475 tau = 'Tau'
476 self.assertTrue(phy.pi < phy.tau)
477
478
479 def test_intenum(self):
480 class WeekDay(IntEnum):
481 SUNDAY = 1
482 MONDAY = 2
483 TUESDAY = 3
484 WEDNESDAY = 4
485 THURSDAY = 5
486 FRIDAY = 6
487 SATURDAY = 7
488
489 self.assertEqual(['a', 'b', 'c'][WeekDay.MONDAY], 'c')
490 self.assertEqual([i for i in range(WeekDay.TUESDAY)], [0, 1, 2])
491
492 lst = list(WeekDay)
493 self.assertEqual(len(lst), len(WeekDay))
494 self.assertEqual(len(WeekDay), 7)
495 target = 'SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY'
496 target = target.split()
497 for i, weekday in enumerate(target, 1):
498 e = WeekDay(i)
499 self.assertEqual(e, i)
500 self.assertEqual(int(e), i)
501 self.assertEqual(e.name, weekday)
502 self.assertIn(e, WeekDay)
503 self.assertEqual(lst.index(e)+1, i)
504 self.assertTrue(0 < e < 8)
505 self.assertIs(type(e), WeekDay)
506 self.assertIsInstance(e, int)
507 self.assertIsInstance(e, Enum)
508
509 def test_intenum_duplicates(self):
510 class WeekDay(IntEnum):
511 SUNDAY = 1
512 MONDAY = 2
513 TUESDAY = TEUSDAY = 3
514 WEDNESDAY = 4
515 THURSDAY = 5
516 FRIDAY = 6
517 SATURDAY = 7
518 self.assertIs(WeekDay.TEUSDAY, WeekDay.TUESDAY)
519 self.assertEqual(WeekDay(3).name, 'TUESDAY')
520 self.assertEqual([k for k,v in WeekDay.__members__.items()
521 if v.name != k], ['TEUSDAY', ])
522
523 def test_pickle_enum(self):
524 if isinstance(Stooges, Exception):
525 raise Stooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800526 test_pickle_dump_load(self.assertIs, Stooges.CURLY)
527 test_pickle_dump_load(self.assertIs, Stooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700528
529 def test_pickle_int(self):
530 if isinstance(IntStooges, Exception):
531 raise IntStooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800532 test_pickle_dump_load(self.assertIs, IntStooges.CURLY)
533 test_pickle_dump_load(self.assertIs, IntStooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700534
535 def test_pickle_float(self):
536 if isinstance(FloatStooges, Exception):
537 raise FloatStooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800538 test_pickle_dump_load(self.assertIs, FloatStooges.CURLY)
539 test_pickle_dump_load(self.assertIs, FloatStooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700540
541 def test_pickle_enum_function(self):
542 if isinstance(Answer, Exception):
543 raise Answer
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800544 test_pickle_dump_load(self.assertIs, Answer.him)
545 test_pickle_dump_load(self.assertIs, Answer)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700546
547 def test_pickle_enum_function_with_module(self):
548 if isinstance(Question, Exception):
549 raise Question
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800550 test_pickle_dump_load(self.assertIs, Question.who)
551 test_pickle_dump_load(self.assertIs, Question)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700552
Ethan Furmanca1b7942014-02-08 11:36:27 -0800553 def test_enum_function_with_qualname(self):
554 if isinstance(Theory, Exception):
555 raise Theory
556 self.assertEqual(Theory.__qualname__, 'spanish_inquisition')
557
558 def test_class_nested_enum_and_pickle_protocol_four(self):
559 # would normally just have this directly in the class namespace
560 class NestedEnum(Enum):
561 twigs = 'common'
562 shiny = 'rare'
563
564 self.__class__.NestedEnum = NestedEnum
565 self.NestedEnum.__qualname__ = '%s.NestedEnum' % self.__class__.__name__
566 test_pickle_exception(
567 self.assertRaises, PicklingError, self.NestedEnum.twigs,
568 protocol=(0, 3))
569 test_pickle_dump_load(self.assertIs, self.NestedEnum.twigs,
570 protocol=(4, HIGHEST_PROTOCOL))
571
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700572 def test_exploding_pickle(self):
Ethan Furmanca1b7942014-02-08 11:36:27 -0800573 BadPickle = Enum(
574 'BadPickle', 'dill sweet bread-n-butter', module=__name__)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700575 globals()['BadPickle'] = BadPickle
Ethan Furmanca1b7942014-02-08 11:36:27 -0800576 # now break BadPickle to test exception raising
577 enum._make_class_unpicklable(BadPickle)
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800578 test_pickle_exception(self.assertRaises, TypeError, BadPickle.dill)
579 test_pickle_exception(self.assertRaises, PicklingError, BadPickle)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700580
581 def test_string_enum(self):
582 class SkillLevel(str, Enum):
583 master = 'what is the sound of one hand clapping?'
584 journeyman = 'why did the chicken cross the road?'
585 apprentice = 'knock, knock!'
586 self.assertEqual(SkillLevel.apprentice, 'knock, knock!')
587
588 def test_getattr_getitem(self):
589 class Period(Enum):
590 morning = 1
591 noon = 2
592 evening = 3
593 night = 4
594 self.assertIs(Period(2), Period.noon)
595 self.assertIs(getattr(Period, 'night'), Period.night)
596 self.assertIs(Period['morning'], Period.morning)
597
598 def test_getattr_dunder(self):
599 Season = self.Season
600 self.assertTrue(getattr(Season, '__eq__'))
601
602 def test_iteration_order(self):
603 class Season(Enum):
604 SUMMER = 2
605 WINTER = 4
606 AUTUMN = 3
607 SPRING = 1
608 self.assertEqual(
609 list(Season),
610 [Season.SUMMER, Season.WINTER, Season.AUTUMN, Season.SPRING],
611 )
612
Ethan Furman2131a4a2013-09-14 18:11:24 -0700613 def test_reversed_iteration_order(self):
614 self.assertEqual(
615 list(reversed(self.Season)),
616 [self.Season.WINTER, self.Season.AUTUMN, self.Season.SUMMER,
617 self.Season.SPRING]
618 )
619
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700620 def test_programatic_function_string(self):
621 SummerMonth = Enum('SummerMonth', 'june july august')
622 lst = list(SummerMonth)
623 self.assertEqual(len(lst), len(SummerMonth))
624 self.assertEqual(len(SummerMonth), 3, SummerMonth)
625 self.assertEqual(
626 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
627 lst,
628 )
629 for i, month in enumerate('june july august'.split(), 1):
630 e = SummerMonth(i)
631 self.assertEqual(int(e.value), i)
632 self.assertNotEqual(e, i)
633 self.assertEqual(e.name, month)
634 self.assertIn(e, SummerMonth)
635 self.assertIs(type(e), SummerMonth)
636
Ethan Furmand9925a12014-09-16 20:35:55 -0700637 def test_programatic_function_string_with_start(self):
638 SummerMonth = Enum('SummerMonth', 'june july august', start=10)
639 lst = list(SummerMonth)
640 self.assertEqual(len(lst), len(SummerMonth))
641 self.assertEqual(len(SummerMonth), 3, SummerMonth)
642 self.assertEqual(
643 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
644 lst,
645 )
646 for i, month in enumerate('june july august'.split(), 10):
647 e = SummerMonth(i)
648 self.assertEqual(int(e.value), i)
649 self.assertNotEqual(e, i)
650 self.assertEqual(e.name, month)
651 self.assertIn(e, SummerMonth)
652 self.assertIs(type(e), SummerMonth)
653
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700654 def test_programatic_function_string_list(self):
655 SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'])
656 lst = list(SummerMonth)
657 self.assertEqual(len(lst), len(SummerMonth))
658 self.assertEqual(len(SummerMonth), 3, SummerMonth)
659 self.assertEqual(
660 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
661 lst,
662 )
663 for i, month in enumerate('june july august'.split(), 1):
664 e = SummerMonth(i)
665 self.assertEqual(int(e.value), i)
666 self.assertNotEqual(e, i)
667 self.assertEqual(e.name, month)
668 self.assertIn(e, SummerMonth)
669 self.assertIs(type(e), SummerMonth)
670
Ethan Furmand9925a12014-09-16 20:35:55 -0700671 def test_programatic_function_string_list_with_start(self):
672 SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'], start=20)
673 lst = list(SummerMonth)
674 self.assertEqual(len(lst), len(SummerMonth))
675 self.assertEqual(len(SummerMonth), 3, SummerMonth)
676 self.assertEqual(
677 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
678 lst,
679 )
680 for i, month in enumerate('june july august'.split(), 20):
681 e = SummerMonth(i)
682 self.assertEqual(int(e.value), i)
683 self.assertNotEqual(e, i)
684 self.assertEqual(e.name, month)
685 self.assertIn(e, SummerMonth)
686 self.assertIs(type(e), SummerMonth)
687
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700688 def test_programatic_function_iterable(self):
689 SummerMonth = Enum(
690 'SummerMonth',
691 (('june', 1), ('july', 2), ('august', 3))
692 )
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(), 1):
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
708 def test_programatic_function_from_dict(self):
709 SummerMonth = Enum(
710 'SummerMonth',
711 OrderedDict((('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_type(self):
729 SummerMonth = Enum('SummerMonth', 'june july august', type=int)
730 lst = list(SummerMonth)
731 self.assertEqual(len(lst), len(SummerMonth))
732 self.assertEqual(len(SummerMonth), 3, SummerMonth)
733 self.assertEqual(
734 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
735 lst,
736 )
737 for i, month in enumerate('june july august'.split(), 1):
738 e = SummerMonth(i)
739 self.assertEqual(e, i)
740 self.assertEqual(e.name, month)
741 self.assertIn(e, SummerMonth)
742 self.assertIs(type(e), SummerMonth)
743
Ethan Furmand9925a12014-09-16 20:35:55 -0700744 def test_programatic_function_type_with_start(self):
745 SummerMonth = Enum('SummerMonth', 'june july august', type=int, start=30)
746 lst = list(SummerMonth)
747 self.assertEqual(len(lst), len(SummerMonth))
748 self.assertEqual(len(SummerMonth), 3, SummerMonth)
749 self.assertEqual(
750 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
751 lst,
752 )
753 for i, month in enumerate('june july august'.split(), 30):
754 e = SummerMonth(i)
755 self.assertEqual(e, i)
756 self.assertEqual(e.name, month)
757 self.assertIn(e, SummerMonth)
758 self.assertIs(type(e), SummerMonth)
759
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700760 def test_programatic_function_type_from_subclass(self):
761 SummerMonth = IntEnum('SummerMonth', 'june july august')
762 lst = list(SummerMonth)
763 self.assertEqual(len(lst), len(SummerMonth))
764 self.assertEqual(len(SummerMonth), 3, SummerMonth)
765 self.assertEqual(
766 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
767 lst,
768 )
769 for i, month in enumerate('june july august'.split(), 1):
770 e = SummerMonth(i)
771 self.assertEqual(e, i)
772 self.assertEqual(e.name, month)
773 self.assertIn(e, SummerMonth)
774 self.assertIs(type(e), SummerMonth)
775
Ethan Furmand9925a12014-09-16 20:35:55 -0700776 def test_programatic_function_type_from_subclass_with_start(self):
777 SummerMonth = IntEnum('SummerMonth', 'june july august', start=40)
778 lst = list(SummerMonth)
779 self.assertEqual(len(lst), len(SummerMonth))
780 self.assertEqual(len(SummerMonth), 3, SummerMonth)
781 self.assertEqual(
782 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
783 lst,
784 )
785 for i, month in enumerate('june july august'.split(), 40):
786 e = SummerMonth(i)
787 self.assertEqual(e, i)
788 self.assertEqual(e.name, month)
789 self.assertIn(e, SummerMonth)
790 self.assertIs(type(e), SummerMonth)
791
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700792 def test_subclassing(self):
793 if isinstance(Name, Exception):
794 raise Name
795 self.assertEqual(Name.BDFL, 'Guido van Rossum')
796 self.assertTrue(Name.BDFL, Name('Guido van Rossum'))
797 self.assertIs(Name.BDFL, getattr(Name, 'BDFL'))
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800798 test_pickle_dump_load(self.assertIs, Name.BDFL)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700799
800 def test_extending(self):
801 class Color(Enum):
802 red = 1
803 green = 2
804 blue = 3
805 with self.assertRaises(TypeError):
806 class MoreColor(Color):
807 cyan = 4
808 magenta = 5
809 yellow = 6
810
811 def test_exclude_methods(self):
812 class whatever(Enum):
813 this = 'that'
814 these = 'those'
815 def really(self):
816 return 'no, not %s' % self.value
817 self.assertIsNot(type(whatever.really), whatever)
818 self.assertEqual(whatever.this.really(), 'no, not that')
819
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700820 def test_wrong_inheritance_order(self):
821 with self.assertRaises(TypeError):
822 class Wrong(Enum, str):
823 NotHere = 'error before this point'
824
825 def test_intenum_transitivity(self):
826 class number(IntEnum):
827 one = 1
828 two = 2
829 three = 3
830 class numero(IntEnum):
831 uno = 1
832 dos = 2
833 tres = 3
834 self.assertEqual(number.one, numero.uno)
835 self.assertEqual(number.two, numero.dos)
836 self.assertEqual(number.three, numero.tres)
837
838 def test_wrong_enum_in_call(self):
839 class Monochrome(Enum):
840 black = 0
841 white = 1
842 class Gender(Enum):
843 male = 0
844 female = 1
845 self.assertRaises(ValueError, Monochrome, Gender.male)
846
847 def test_wrong_enum_in_mixed_call(self):
848 class Monochrome(IntEnum):
849 black = 0
850 white = 1
851 class Gender(Enum):
852 male = 0
853 female = 1
854 self.assertRaises(ValueError, Monochrome, Gender.male)
855
856 def test_mixed_enum_in_call_1(self):
857 class Monochrome(IntEnum):
858 black = 0
859 white = 1
860 class Gender(IntEnum):
861 male = 0
862 female = 1
863 self.assertIs(Monochrome(Gender.female), Monochrome.white)
864
865 def test_mixed_enum_in_call_2(self):
866 class Monochrome(Enum):
867 black = 0
868 white = 1
869 class Gender(IntEnum):
870 male = 0
871 female = 1
872 self.assertIs(Monochrome(Gender.male), Monochrome.black)
873
874 def test_flufl_enum(self):
875 class Fluflnum(Enum):
876 def __int__(self):
877 return int(self.value)
878 class MailManOptions(Fluflnum):
879 option1 = 1
880 option2 = 2
881 option3 = 3
882 self.assertEqual(int(MailManOptions.option1), 1)
883
Ethan Furman5e5a8232013-08-04 08:42:23 -0700884 def test_introspection(self):
885 class Number(IntEnum):
886 one = 100
887 two = 200
888 self.assertIs(Number.one._member_type_, int)
889 self.assertIs(Number._member_type_, int)
890 class String(str, Enum):
891 yarn = 'soft'
892 rope = 'rough'
893 wire = 'hard'
894 self.assertIs(String.yarn._member_type_, str)
895 self.assertIs(String._member_type_, str)
896 class Plain(Enum):
897 vanilla = 'white'
898 one = 1
899 self.assertIs(Plain.vanilla._member_type_, object)
900 self.assertIs(Plain._member_type_, object)
901
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700902 def test_no_such_enum_member(self):
903 class Color(Enum):
904 red = 1
905 green = 2
906 blue = 3
907 with self.assertRaises(ValueError):
908 Color(4)
909 with self.assertRaises(KeyError):
910 Color['chartreuse']
911
912 def test_new_repr(self):
913 class Color(Enum):
914 red = 1
915 green = 2
916 blue = 3
917 def __repr__(self):
918 return "don't you just love shades of %s?" % self.name
919 self.assertEqual(
920 repr(Color.blue),
921 "don't you just love shades of blue?",
922 )
923
924 def test_inherited_repr(self):
925 class MyEnum(Enum):
926 def __repr__(self):
927 return "My name is %s." % self.name
928 class MyIntEnum(int, MyEnum):
929 this = 1
930 that = 2
931 theother = 3
932 self.assertEqual(repr(MyIntEnum.that), "My name is that.")
933
934 def test_multiple_mixin_mro(self):
935 class auto_enum(type(Enum)):
936 def __new__(metacls, cls, bases, classdict):
937 temp = type(classdict)()
938 names = set(classdict._member_names)
939 i = 0
940 for k in classdict._member_names:
941 v = classdict[k]
942 if v is Ellipsis:
943 v = i
944 else:
945 i = v
946 i += 1
947 temp[k] = v
948 for k, v in classdict.items():
949 if k not in names:
950 temp[k] = v
951 return super(auto_enum, metacls).__new__(
952 metacls, cls, bases, temp)
953
954 class AutoNumberedEnum(Enum, metaclass=auto_enum):
955 pass
956
957 class AutoIntEnum(IntEnum, metaclass=auto_enum):
958 pass
959
960 class TestAutoNumber(AutoNumberedEnum):
961 a = ...
962 b = 3
963 c = ...
964
965 class TestAutoInt(AutoIntEnum):
966 a = ...
967 b = 3
968 c = ...
969
970 def test_subclasses_with_getnewargs(self):
971 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800972 __qualname__ = 'NamedInt' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700973 def __new__(cls, *args):
974 _args = args
975 name, *args = args
976 if len(args) == 0:
977 raise TypeError("name and value must be specified")
978 self = int.__new__(cls, *args)
979 self._intname = name
980 self._args = _args
981 return self
982 def __getnewargs__(self):
983 return self._args
984 @property
985 def __name__(self):
986 return self._intname
987 def __repr__(self):
988 # repr() is updated to include the name and type info
989 return "{}({!r}, {})".format(type(self).__name__,
990 self.__name__,
991 int.__repr__(self))
992 def __str__(self):
993 # str() is unchanged, even if it relies on the repr() fallback
994 base = int
995 base_str = base.__str__
996 if base_str.__objclass__ is object:
997 return base.__repr__(self)
998 return base_str(self)
999 # for simplicity, we only define one operator that
1000 # propagates expressions
1001 def __add__(self, other):
1002 temp = int(self) + int( other)
1003 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1004 return NamedInt(
1005 '({0} + {1})'.format(self.__name__, other.__name__),
1006 temp )
1007 else:
1008 return temp
1009
1010 class NEI(NamedInt, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001011 __qualname__ = 'NEI' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001012 x = ('the-x', 1)
1013 y = ('the-y', 2)
1014
Ethan Furman2aa27322013-07-19 19:35:56 -07001015
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001016 self.assertIs(NEI.__new__, Enum.__new__)
1017 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1018 globals()['NamedInt'] = NamedInt
1019 globals()['NEI'] = NEI
1020 NI5 = NamedInt('test', 5)
1021 self.assertEqual(NI5, 5)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001022 test_pickle_dump_load(self.assertEqual, NI5, 5)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001023 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001024 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001025 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001026
Ethan Furmanca1b7942014-02-08 11:36:27 -08001027 def test_subclasses_with_getnewargs_ex(self):
1028 class NamedInt(int):
1029 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1030 def __new__(cls, *args):
1031 _args = args
1032 name, *args = args
1033 if len(args) == 0:
1034 raise TypeError("name and value must be specified")
1035 self = int.__new__(cls, *args)
1036 self._intname = name
1037 self._args = _args
1038 return self
1039 def __getnewargs_ex__(self):
1040 return self._args, {}
1041 @property
1042 def __name__(self):
1043 return self._intname
1044 def __repr__(self):
1045 # repr() is updated to include the name and type info
1046 return "{}({!r}, {})".format(type(self).__name__,
1047 self.__name__,
1048 int.__repr__(self))
1049 def __str__(self):
1050 # str() is unchanged, even if it relies on the repr() fallback
1051 base = int
1052 base_str = base.__str__
1053 if base_str.__objclass__ is object:
1054 return base.__repr__(self)
1055 return base_str(self)
1056 # for simplicity, we only define one operator that
1057 # propagates expressions
1058 def __add__(self, other):
1059 temp = int(self) + int( other)
1060 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1061 return NamedInt(
1062 '({0} + {1})'.format(self.__name__, other.__name__),
1063 temp )
1064 else:
1065 return temp
1066
1067 class NEI(NamedInt, Enum):
1068 __qualname__ = 'NEI' # needed for pickle protocol 4
1069 x = ('the-x', 1)
1070 y = ('the-y', 2)
1071
1072
1073 self.assertIs(NEI.__new__, Enum.__new__)
1074 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1075 globals()['NamedInt'] = NamedInt
1076 globals()['NEI'] = NEI
1077 NI5 = NamedInt('test', 5)
1078 self.assertEqual(NI5, 5)
1079 test_pickle_dump_load(self.assertEqual, NI5, 5, protocol=(4, 4))
1080 self.assertEqual(NEI.y.value, 2)
1081 test_pickle_dump_load(self.assertIs, NEI.y, protocol=(4, 4))
Ethan Furmandc870522014-02-18 12:37:12 -08001082 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001083
1084 def test_subclasses_with_reduce(self):
1085 class NamedInt(int):
1086 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1087 def __new__(cls, *args):
1088 _args = args
1089 name, *args = args
1090 if len(args) == 0:
1091 raise TypeError("name and value must be specified")
1092 self = int.__new__(cls, *args)
1093 self._intname = name
1094 self._args = _args
1095 return self
1096 def __reduce__(self):
1097 return self.__class__, self._args
1098 @property
1099 def __name__(self):
1100 return self._intname
1101 def __repr__(self):
1102 # repr() is updated to include the name and type info
1103 return "{}({!r}, {})".format(type(self).__name__,
1104 self.__name__,
1105 int.__repr__(self))
1106 def __str__(self):
1107 # str() is unchanged, even if it relies on the repr() fallback
1108 base = int
1109 base_str = base.__str__
1110 if base_str.__objclass__ is object:
1111 return base.__repr__(self)
1112 return base_str(self)
1113 # for simplicity, we only define one operator that
1114 # propagates expressions
1115 def __add__(self, other):
1116 temp = int(self) + int( other)
1117 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1118 return NamedInt(
1119 '({0} + {1})'.format(self.__name__, other.__name__),
1120 temp )
1121 else:
1122 return temp
1123
1124 class NEI(NamedInt, Enum):
1125 __qualname__ = 'NEI' # needed for pickle protocol 4
1126 x = ('the-x', 1)
1127 y = ('the-y', 2)
1128
1129
1130 self.assertIs(NEI.__new__, Enum.__new__)
1131 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1132 globals()['NamedInt'] = NamedInt
1133 globals()['NEI'] = NEI
1134 NI5 = NamedInt('test', 5)
1135 self.assertEqual(NI5, 5)
1136 test_pickle_dump_load(self.assertEqual, NI5, 5)
1137 self.assertEqual(NEI.y.value, 2)
1138 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001139 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001140
1141 def test_subclasses_with_reduce_ex(self):
1142 class NamedInt(int):
1143 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1144 def __new__(cls, *args):
1145 _args = args
1146 name, *args = args
1147 if len(args) == 0:
1148 raise TypeError("name and value must be specified")
1149 self = int.__new__(cls, *args)
1150 self._intname = name
1151 self._args = _args
1152 return self
1153 def __reduce_ex__(self, proto):
1154 return self.__class__, self._args
1155 @property
1156 def __name__(self):
1157 return self._intname
1158 def __repr__(self):
1159 # repr() is updated to include the name and type info
1160 return "{}({!r}, {})".format(type(self).__name__,
1161 self.__name__,
1162 int.__repr__(self))
1163 def __str__(self):
1164 # str() is unchanged, even if it relies on the repr() fallback
1165 base = int
1166 base_str = base.__str__
1167 if base_str.__objclass__ is object:
1168 return base.__repr__(self)
1169 return base_str(self)
1170 # for simplicity, we only define one operator that
1171 # propagates expressions
1172 def __add__(self, other):
1173 temp = int(self) + int( other)
1174 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1175 return NamedInt(
1176 '({0} + {1})'.format(self.__name__, other.__name__),
1177 temp )
1178 else:
1179 return temp
1180
1181 class NEI(NamedInt, Enum):
1182 __qualname__ = 'NEI' # needed for pickle protocol 4
1183 x = ('the-x', 1)
1184 y = ('the-y', 2)
1185
1186
1187 self.assertIs(NEI.__new__, Enum.__new__)
1188 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1189 globals()['NamedInt'] = NamedInt
1190 globals()['NEI'] = NEI
1191 NI5 = NamedInt('test', 5)
1192 self.assertEqual(NI5, 5)
1193 test_pickle_dump_load(self.assertEqual, NI5, 5)
1194 self.assertEqual(NEI.y.value, 2)
1195 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001196 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001197
Ethan Furmandc870522014-02-18 12:37:12 -08001198 def test_subclasses_without_direct_pickle_support(self):
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001199 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001200 __qualname__ = 'NamedInt'
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001201 def __new__(cls, *args):
1202 _args = args
1203 name, *args = args
1204 if len(args) == 0:
1205 raise TypeError("name and value must be specified")
1206 self = int.__new__(cls, *args)
1207 self._intname = name
1208 self._args = _args
1209 return self
1210 @property
1211 def __name__(self):
1212 return self._intname
1213 def __repr__(self):
1214 # repr() is updated to include the name and type info
1215 return "{}({!r}, {})".format(type(self).__name__,
1216 self.__name__,
1217 int.__repr__(self))
1218 def __str__(self):
1219 # str() is unchanged, even if it relies on the repr() fallback
1220 base = int
1221 base_str = base.__str__
1222 if base_str.__objclass__ is object:
1223 return base.__repr__(self)
1224 return base_str(self)
1225 # for simplicity, we only define one operator that
1226 # propagates expressions
1227 def __add__(self, other):
1228 temp = int(self) + int( other)
1229 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1230 return NamedInt(
1231 '({0} + {1})'.format(self.__name__, other.__name__),
1232 temp )
1233 else:
1234 return temp
1235
1236 class NEI(NamedInt, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001237 __qualname__ = 'NEI'
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001238 x = ('the-x', 1)
1239 y = ('the-y', 2)
1240
1241 self.assertIs(NEI.__new__, Enum.__new__)
1242 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1243 globals()['NamedInt'] = NamedInt
1244 globals()['NEI'] = NEI
1245 NI5 = NamedInt('test', 5)
1246 self.assertEqual(NI5, 5)
1247 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001248 test_pickle_exception(self.assertRaises, TypeError, NEI.x)
1249 test_pickle_exception(self.assertRaises, PicklingError, NEI)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001250
Ethan Furmandc870522014-02-18 12:37:12 -08001251 def test_subclasses_without_direct_pickle_support_using_name(self):
1252 class NamedInt(int):
1253 __qualname__ = 'NamedInt'
1254 def __new__(cls, *args):
1255 _args = args
1256 name, *args = args
1257 if len(args) == 0:
1258 raise TypeError("name and value must be specified")
1259 self = int.__new__(cls, *args)
1260 self._intname = name
1261 self._args = _args
1262 return self
1263 @property
1264 def __name__(self):
1265 return self._intname
1266 def __repr__(self):
1267 # repr() is updated to include the name and type info
1268 return "{}({!r}, {})".format(type(self).__name__,
1269 self.__name__,
1270 int.__repr__(self))
1271 def __str__(self):
1272 # str() is unchanged, even if it relies on the repr() fallback
1273 base = int
1274 base_str = base.__str__
1275 if base_str.__objclass__ is object:
1276 return base.__repr__(self)
1277 return base_str(self)
1278 # for simplicity, we only define one operator that
1279 # propagates expressions
1280 def __add__(self, other):
1281 temp = int(self) + int( other)
1282 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1283 return NamedInt(
1284 '({0} + {1})'.format(self.__name__, other.__name__),
1285 temp )
1286 else:
1287 return temp
1288
1289 class NEI(NamedInt, Enum):
1290 __qualname__ = 'NEI'
1291 x = ('the-x', 1)
1292 y = ('the-y', 2)
1293 def __reduce_ex__(self, proto):
1294 return getattr, (self.__class__, self._name_)
1295
1296 self.assertIs(NEI.__new__, Enum.__new__)
1297 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1298 globals()['NamedInt'] = NamedInt
1299 globals()['NEI'] = NEI
1300 NI5 = NamedInt('test', 5)
1301 self.assertEqual(NI5, 5)
1302 self.assertEqual(NEI.y.value, 2)
1303 test_pickle_dump_load(self.assertIs, NEI.y)
1304 test_pickle_dump_load(self.assertIs, NEI)
1305
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001306 def test_tuple_subclass(self):
1307 class SomeTuple(tuple, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001308 __qualname__ = 'SomeTuple' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001309 first = (1, 'for the money')
1310 second = (2, 'for the show')
1311 third = (3, 'for the music')
1312 self.assertIs(type(SomeTuple.first), SomeTuple)
1313 self.assertIsInstance(SomeTuple.second, tuple)
1314 self.assertEqual(SomeTuple.third, (3, 'for the music'))
1315 globals()['SomeTuple'] = SomeTuple
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001316 test_pickle_dump_load(self.assertIs, SomeTuple.first)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001317
1318 def test_duplicate_values_give_unique_enum_items(self):
1319 class AutoNumber(Enum):
1320 first = ()
1321 second = ()
1322 third = ()
1323 def __new__(cls):
1324 value = len(cls.__members__) + 1
1325 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001326 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001327 return obj
1328 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001329 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001330 self.assertEqual(
1331 list(AutoNumber),
1332 [AutoNumber.first, AutoNumber.second, AutoNumber.third],
1333 )
1334 self.assertEqual(int(AutoNumber.second), 2)
Ethan Furman2aa27322013-07-19 19:35:56 -07001335 self.assertEqual(AutoNumber.third.value, 3)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001336 self.assertIs(AutoNumber(1), AutoNumber.first)
1337
1338 def test_inherited_new_from_enhanced_enum(self):
1339 class AutoNumber(Enum):
1340 def __new__(cls):
1341 value = len(cls.__members__) + 1
1342 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001343 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001344 return obj
1345 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001346 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001347 class Color(AutoNumber):
1348 red = ()
1349 green = ()
1350 blue = ()
1351 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1352 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1353
1354 def test_inherited_new_from_mixed_enum(self):
1355 class AutoNumber(IntEnum):
1356 def __new__(cls):
1357 value = len(cls.__members__) + 1
1358 obj = int.__new__(cls, value)
Ethan Furman520ad572013-07-19 19:47:21 -07001359 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001360 return obj
1361 class Color(AutoNumber):
1362 red = ()
1363 green = ()
1364 blue = ()
1365 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1366 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1367
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001368 def test_equality(self):
1369 class AlwaysEqual:
1370 def __eq__(self, other):
1371 return True
1372 class OrdinaryEnum(Enum):
1373 a = 1
1374 self.assertEqual(AlwaysEqual(), OrdinaryEnum.a)
1375 self.assertEqual(OrdinaryEnum.a, AlwaysEqual())
1376
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001377 def test_ordered_mixin(self):
1378 class OrderedEnum(Enum):
1379 def __ge__(self, other):
1380 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001381 return self._value_ >= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001382 return NotImplemented
1383 def __gt__(self, other):
1384 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001385 return self._value_ > other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001386 return NotImplemented
1387 def __le__(self, other):
1388 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001389 return self._value_ <= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001390 return NotImplemented
1391 def __lt__(self, other):
1392 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001393 return self._value_ < other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001394 return NotImplemented
1395 class Grade(OrderedEnum):
1396 A = 5
1397 B = 4
1398 C = 3
1399 D = 2
1400 F = 1
1401 self.assertGreater(Grade.A, Grade.B)
1402 self.assertLessEqual(Grade.F, Grade.C)
1403 self.assertLess(Grade.D, Grade.A)
1404 self.assertGreaterEqual(Grade.B, Grade.B)
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001405 self.assertEqual(Grade.B, Grade.B)
1406 self.assertNotEqual(Grade.C, Grade.D)
Ethan Furman520ad572013-07-19 19:47:21 -07001407
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001408 def test_extending2(self):
1409 class Shade(Enum):
1410 def shade(self):
1411 print(self.name)
1412 class Color(Shade):
1413 red = 1
1414 green = 2
1415 blue = 3
1416 with self.assertRaises(TypeError):
1417 class MoreColor(Color):
1418 cyan = 4
1419 magenta = 5
1420 yellow = 6
1421
1422 def test_extending3(self):
1423 class Shade(Enum):
1424 def shade(self):
1425 return self.name
1426 class Color(Shade):
1427 def hex(self):
1428 return '%s hexlified!' % self.value
1429 class MoreColor(Color):
1430 cyan = 4
1431 magenta = 5
1432 yellow = 6
1433 self.assertEqual(MoreColor.magenta.hex(), '5 hexlified!')
1434
1435
1436 def test_no_duplicates(self):
1437 class UniqueEnum(Enum):
1438 def __init__(self, *args):
1439 cls = self.__class__
1440 if any(self.value == e.value for e in cls):
1441 a = self.name
1442 e = cls(self.value).name
1443 raise ValueError(
1444 "aliases not allowed in UniqueEnum: %r --> %r"
1445 % (a, e)
1446 )
1447 class Color(UniqueEnum):
1448 red = 1
1449 green = 2
1450 blue = 3
1451 with self.assertRaises(ValueError):
1452 class Color(UniqueEnum):
1453 red = 1
1454 green = 2
1455 blue = 3
1456 grene = 2
1457
1458 def test_init(self):
1459 class Planet(Enum):
1460 MERCURY = (3.303e+23, 2.4397e6)
1461 VENUS = (4.869e+24, 6.0518e6)
1462 EARTH = (5.976e+24, 6.37814e6)
1463 MARS = (6.421e+23, 3.3972e6)
1464 JUPITER = (1.9e+27, 7.1492e7)
1465 SATURN = (5.688e+26, 6.0268e7)
1466 URANUS = (8.686e+25, 2.5559e7)
1467 NEPTUNE = (1.024e+26, 2.4746e7)
1468 def __init__(self, mass, radius):
1469 self.mass = mass # in kilograms
1470 self.radius = radius # in meters
1471 @property
1472 def surface_gravity(self):
1473 # universal gravitational constant (m3 kg-1 s-2)
1474 G = 6.67300E-11
1475 return G * self.mass / (self.radius * self.radius)
1476 self.assertEqual(round(Planet.EARTH.surface_gravity, 2), 9.80)
1477 self.assertEqual(Planet.EARTH.value, (5.976e+24, 6.37814e6))
1478
Ethan Furman2aa27322013-07-19 19:35:56 -07001479 def test_nonhash_value(self):
1480 class AutoNumberInAList(Enum):
1481 def __new__(cls):
1482 value = [len(cls.__members__) + 1]
1483 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001484 obj._value_ = value
Ethan Furman2aa27322013-07-19 19:35:56 -07001485 return obj
1486 class ColorInAList(AutoNumberInAList):
1487 red = ()
1488 green = ()
1489 blue = ()
1490 self.assertEqual(list(ColorInAList), [ColorInAList.red, ColorInAList.green, ColorInAList.blue])
Ethan Furman1a162882013-10-16 19:09:31 -07001491 for enum, value in zip(ColorInAList, range(3)):
1492 value += 1
1493 self.assertEqual(enum.value, [value])
1494 self.assertIs(ColorInAList([value]), enum)
Ethan Furman2aa27322013-07-19 19:35:56 -07001495
Ethan Furmanb41803e2013-07-25 13:50:45 -07001496 def test_conflicting_types_resolved_in_new(self):
1497 class LabelledIntEnum(int, Enum):
1498 def __new__(cls, *args):
1499 value, label = args
1500 obj = int.__new__(cls, value)
1501 obj.label = label
1502 obj._value_ = value
1503 return obj
1504
1505 class LabelledList(LabelledIntEnum):
1506 unprocessed = (1, "Unprocessed")
1507 payment_complete = (2, "Payment Complete")
1508
1509 self.assertEqual(list(LabelledList), [LabelledList.unprocessed, LabelledList.payment_complete])
1510 self.assertEqual(LabelledList.unprocessed, 1)
1511 self.assertEqual(LabelledList(1), LabelledList.unprocessed)
Ethan Furman2aa27322013-07-19 19:35:56 -07001512
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001513
Ethan Furmanf24bb352013-07-18 17:05:39 -07001514class TestUnique(unittest.TestCase):
1515
1516 def test_unique_clean(self):
1517 @unique
1518 class Clean(Enum):
1519 one = 1
1520 two = 'dos'
1521 tres = 4.0
1522 @unique
1523 class Cleaner(IntEnum):
1524 single = 1
1525 double = 2
1526 triple = 3
1527
1528 def test_unique_dirty(self):
1529 with self.assertRaisesRegex(ValueError, 'tres.*one'):
1530 @unique
1531 class Dirty(Enum):
1532 one = 1
1533 two = 'dos'
1534 tres = 1
1535 with self.assertRaisesRegex(
1536 ValueError,
1537 'double.*single.*turkey.*triple',
1538 ):
1539 @unique
1540 class Dirtier(IntEnum):
1541 single = 1
1542 double = 1
1543 triple = 3
1544 turkey = 3
1545
1546
Ethan Furman5875d742013-10-21 20:45:55 -07001547expected_help_output = """
1548Help on class Color in module %s:
1549
1550class Color(enum.Enum)
1551 | Method resolution order:
1552 | Color
1553 | enum.Enum
1554 | builtins.object
1555 |\x20\x20
1556 | Data and other attributes defined here:
1557 |\x20\x20
1558 | blue = <Color.blue: 3>
1559 |\x20\x20
1560 | green = <Color.green: 2>
1561 |\x20\x20
1562 | red = <Color.red: 1>
1563 |\x20\x20
1564 | ----------------------------------------------------------------------
1565 | Data descriptors inherited from enum.Enum:
1566 |\x20\x20
1567 | name
1568 | The name of the Enum member.
1569 |\x20\x20
1570 | value
1571 | The value of the Enum member.
1572 |\x20\x20
1573 | ----------------------------------------------------------------------
1574 | Data descriptors inherited from enum.EnumMeta:
1575 |\x20\x20
1576 | __members__
1577 | Returns a mapping of member name->value.
1578 |\x20\x20\x20\x20\x20\x20
1579 | This mapping lists all enum members, including aliases. Note that this
1580 | is a read-only view of the internal mapping.
1581""".strip()
1582
1583class TestStdLib(unittest.TestCase):
1584
1585 class Color(Enum):
1586 red = 1
1587 green = 2
1588 blue = 3
1589
1590 def test_pydoc(self):
1591 # indirectly test __objclass__
1592 expected_text = expected_help_output % __name__
1593 output = StringIO()
1594 helper = pydoc.Helper(output=output)
1595 helper(self.Color)
1596 result = output.getvalue().strip()
Victor Stinner4b0432d2014-06-16 22:48:43 +02001597 self.assertEqual(result, expected_text)
Ethan Furman5875d742013-10-21 20:45:55 -07001598
1599 def test_inspect_getmembers(self):
1600 values = dict((
1601 ('__class__', EnumMeta),
1602 ('__doc__', None),
1603 ('__members__', self.Color.__members__),
1604 ('__module__', __name__),
1605 ('blue', self.Color.blue),
1606 ('green', self.Color.green),
1607 ('name', Enum.__dict__['name']),
1608 ('red', self.Color.red),
1609 ('value', Enum.__dict__['value']),
1610 ))
1611 result = dict(inspect.getmembers(self.Color))
1612 self.assertEqual(values.keys(), result.keys())
1613 failed = False
1614 for k in values.keys():
1615 if result[k] != values[k]:
1616 print()
1617 print('\n%s\n key: %s\n result: %s\nexpected: %s\n%s\n' %
1618 ('=' * 75, k, result[k], values[k], '=' * 75), sep='')
1619 failed = True
1620 if failed:
1621 self.fail("result does not equal expected, see print above")
1622
1623 def test_inspect_classify_class_attrs(self):
1624 # indirectly test __objclass__
1625 from inspect import Attribute
1626 values = [
1627 Attribute(name='__class__', kind='data',
1628 defining_class=object, object=EnumMeta),
1629 Attribute(name='__doc__', kind='data',
1630 defining_class=self.Color, object=None),
1631 Attribute(name='__members__', kind='property',
1632 defining_class=EnumMeta, object=EnumMeta.__members__),
1633 Attribute(name='__module__', kind='data',
1634 defining_class=self.Color, object=__name__),
1635 Attribute(name='blue', kind='data',
1636 defining_class=self.Color, object=self.Color.blue),
1637 Attribute(name='green', kind='data',
1638 defining_class=self.Color, object=self.Color.green),
1639 Attribute(name='red', kind='data',
1640 defining_class=self.Color, object=self.Color.red),
1641 Attribute(name='name', kind='data',
1642 defining_class=Enum, object=Enum.__dict__['name']),
1643 Attribute(name='value', kind='data',
1644 defining_class=Enum, object=Enum.__dict__['value']),
1645 ]
1646 values.sort(key=lambda item: item.name)
1647 result = list(inspect.classify_class_attrs(self.Color))
1648 result.sort(key=lambda item: item.name)
1649 failed = False
1650 for v, r in zip(values, result):
1651 if r != v:
1652 print('\n%s\n%s\n%s\n%s\n' % ('=' * 75, r, v, '=' * 75), sep='')
1653 failed = True
1654 if failed:
1655 self.fail("result does not equal expected, see print above")
1656
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001657if __name__ == '__main__':
1658 unittest.main()