blob: 02009afbc8583ba44e6a4a66db51aab5c8ea96da [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
637 def test_programatic_function_string_list(self):
638 SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'])
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(), 1):
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
654 def test_programatic_function_iterable(self):
655 SummerMonth = Enum(
656 'SummerMonth',
657 (('june', 1), ('july', 2), ('august', 3))
658 )
659 lst = list(SummerMonth)
660 self.assertEqual(len(lst), len(SummerMonth))
661 self.assertEqual(len(SummerMonth), 3, SummerMonth)
662 self.assertEqual(
663 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
664 lst,
665 )
666 for i, month in enumerate('june july august'.split(), 1):
667 e = SummerMonth(i)
668 self.assertEqual(int(e.value), i)
669 self.assertNotEqual(e, i)
670 self.assertEqual(e.name, month)
671 self.assertIn(e, SummerMonth)
672 self.assertIs(type(e), SummerMonth)
673
674 def test_programatic_function_from_dict(self):
675 SummerMonth = Enum(
676 'SummerMonth',
677 OrderedDict((('june', 1), ('july', 2), ('august', 3)))
678 )
679 lst = list(SummerMonth)
680 self.assertEqual(len(lst), len(SummerMonth))
681 self.assertEqual(len(SummerMonth), 3, SummerMonth)
682 self.assertEqual(
683 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
684 lst,
685 )
686 for i, month in enumerate('june july august'.split(), 1):
687 e = SummerMonth(i)
688 self.assertEqual(int(e.value), i)
689 self.assertNotEqual(e, i)
690 self.assertEqual(e.name, month)
691 self.assertIn(e, SummerMonth)
692 self.assertIs(type(e), SummerMonth)
693
694 def test_programatic_function_type(self):
695 SummerMonth = Enum('SummerMonth', 'june july august', type=int)
696 lst = list(SummerMonth)
697 self.assertEqual(len(lst), len(SummerMonth))
698 self.assertEqual(len(SummerMonth), 3, SummerMonth)
699 self.assertEqual(
700 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
701 lst,
702 )
703 for i, month in enumerate('june july august'.split(), 1):
704 e = SummerMonth(i)
705 self.assertEqual(e, i)
706 self.assertEqual(e.name, month)
707 self.assertIn(e, SummerMonth)
708 self.assertIs(type(e), SummerMonth)
709
710 def test_programatic_function_type_from_subclass(self):
711 SummerMonth = IntEnum('SummerMonth', 'june july august')
712 lst = list(SummerMonth)
713 self.assertEqual(len(lst), len(SummerMonth))
714 self.assertEqual(len(SummerMonth), 3, SummerMonth)
715 self.assertEqual(
716 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
717 lst,
718 )
719 for i, month in enumerate('june july august'.split(), 1):
720 e = SummerMonth(i)
721 self.assertEqual(e, i)
722 self.assertEqual(e.name, month)
723 self.assertIn(e, SummerMonth)
724 self.assertIs(type(e), SummerMonth)
725
726 def test_subclassing(self):
727 if isinstance(Name, Exception):
728 raise Name
729 self.assertEqual(Name.BDFL, 'Guido van Rossum')
730 self.assertTrue(Name.BDFL, Name('Guido van Rossum'))
731 self.assertIs(Name.BDFL, getattr(Name, 'BDFL'))
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800732 test_pickle_dump_load(self.assertIs, Name.BDFL)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700733
734 def test_extending(self):
735 class Color(Enum):
736 red = 1
737 green = 2
738 blue = 3
739 with self.assertRaises(TypeError):
740 class MoreColor(Color):
741 cyan = 4
742 magenta = 5
743 yellow = 6
744
745 def test_exclude_methods(self):
746 class whatever(Enum):
747 this = 'that'
748 these = 'those'
749 def really(self):
750 return 'no, not %s' % self.value
751 self.assertIsNot(type(whatever.really), whatever)
752 self.assertEqual(whatever.this.really(), 'no, not that')
753
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700754 def test_wrong_inheritance_order(self):
755 with self.assertRaises(TypeError):
756 class Wrong(Enum, str):
757 NotHere = 'error before this point'
758
759 def test_intenum_transitivity(self):
760 class number(IntEnum):
761 one = 1
762 two = 2
763 three = 3
764 class numero(IntEnum):
765 uno = 1
766 dos = 2
767 tres = 3
768 self.assertEqual(number.one, numero.uno)
769 self.assertEqual(number.two, numero.dos)
770 self.assertEqual(number.three, numero.tres)
771
772 def test_wrong_enum_in_call(self):
773 class Monochrome(Enum):
774 black = 0
775 white = 1
776 class Gender(Enum):
777 male = 0
778 female = 1
779 self.assertRaises(ValueError, Monochrome, Gender.male)
780
781 def test_wrong_enum_in_mixed_call(self):
782 class Monochrome(IntEnum):
783 black = 0
784 white = 1
785 class Gender(Enum):
786 male = 0
787 female = 1
788 self.assertRaises(ValueError, Monochrome, Gender.male)
789
790 def test_mixed_enum_in_call_1(self):
791 class Monochrome(IntEnum):
792 black = 0
793 white = 1
794 class Gender(IntEnum):
795 male = 0
796 female = 1
797 self.assertIs(Monochrome(Gender.female), Monochrome.white)
798
799 def test_mixed_enum_in_call_2(self):
800 class Monochrome(Enum):
801 black = 0
802 white = 1
803 class Gender(IntEnum):
804 male = 0
805 female = 1
806 self.assertIs(Monochrome(Gender.male), Monochrome.black)
807
808 def test_flufl_enum(self):
809 class Fluflnum(Enum):
810 def __int__(self):
811 return int(self.value)
812 class MailManOptions(Fluflnum):
813 option1 = 1
814 option2 = 2
815 option3 = 3
816 self.assertEqual(int(MailManOptions.option1), 1)
817
Ethan Furman5e5a8232013-08-04 08:42:23 -0700818 def test_introspection(self):
819 class Number(IntEnum):
820 one = 100
821 two = 200
822 self.assertIs(Number.one._member_type_, int)
823 self.assertIs(Number._member_type_, int)
824 class String(str, Enum):
825 yarn = 'soft'
826 rope = 'rough'
827 wire = 'hard'
828 self.assertIs(String.yarn._member_type_, str)
829 self.assertIs(String._member_type_, str)
830 class Plain(Enum):
831 vanilla = 'white'
832 one = 1
833 self.assertIs(Plain.vanilla._member_type_, object)
834 self.assertIs(Plain._member_type_, object)
835
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700836 def test_no_such_enum_member(self):
837 class Color(Enum):
838 red = 1
839 green = 2
840 blue = 3
841 with self.assertRaises(ValueError):
842 Color(4)
843 with self.assertRaises(KeyError):
844 Color['chartreuse']
845
846 def test_new_repr(self):
847 class Color(Enum):
848 red = 1
849 green = 2
850 blue = 3
851 def __repr__(self):
852 return "don't you just love shades of %s?" % self.name
853 self.assertEqual(
854 repr(Color.blue),
855 "don't you just love shades of blue?",
856 )
857
858 def test_inherited_repr(self):
859 class MyEnum(Enum):
860 def __repr__(self):
861 return "My name is %s." % self.name
862 class MyIntEnum(int, MyEnum):
863 this = 1
864 that = 2
865 theother = 3
866 self.assertEqual(repr(MyIntEnum.that), "My name is that.")
867
868 def test_multiple_mixin_mro(self):
869 class auto_enum(type(Enum)):
870 def __new__(metacls, cls, bases, classdict):
871 temp = type(classdict)()
872 names = set(classdict._member_names)
873 i = 0
874 for k in classdict._member_names:
875 v = classdict[k]
876 if v is Ellipsis:
877 v = i
878 else:
879 i = v
880 i += 1
881 temp[k] = v
882 for k, v in classdict.items():
883 if k not in names:
884 temp[k] = v
885 return super(auto_enum, metacls).__new__(
886 metacls, cls, bases, temp)
887
888 class AutoNumberedEnum(Enum, metaclass=auto_enum):
889 pass
890
891 class AutoIntEnum(IntEnum, metaclass=auto_enum):
892 pass
893
894 class TestAutoNumber(AutoNumberedEnum):
895 a = ...
896 b = 3
897 c = ...
898
899 class TestAutoInt(AutoIntEnum):
900 a = ...
901 b = 3
902 c = ...
903
904 def test_subclasses_with_getnewargs(self):
905 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800906 __qualname__ = 'NamedInt' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700907 def __new__(cls, *args):
908 _args = args
909 name, *args = args
910 if len(args) == 0:
911 raise TypeError("name and value must be specified")
912 self = int.__new__(cls, *args)
913 self._intname = name
914 self._args = _args
915 return self
916 def __getnewargs__(self):
917 return self._args
918 @property
919 def __name__(self):
920 return self._intname
921 def __repr__(self):
922 # repr() is updated to include the name and type info
923 return "{}({!r}, {})".format(type(self).__name__,
924 self.__name__,
925 int.__repr__(self))
926 def __str__(self):
927 # str() is unchanged, even if it relies on the repr() fallback
928 base = int
929 base_str = base.__str__
930 if base_str.__objclass__ is object:
931 return base.__repr__(self)
932 return base_str(self)
933 # for simplicity, we only define one operator that
934 # propagates expressions
935 def __add__(self, other):
936 temp = int(self) + int( other)
937 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
938 return NamedInt(
939 '({0} + {1})'.format(self.__name__, other.__name__),
940 temp )
941 else:
942 return temp
943
944 class NEI(NamedInt, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800945 __qualname__ = 'NEI' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700946 x = ('the-x', 1)
947 y = ('the-y', 2)
948
Ethan Furman2aa27322013-07-19 19:35:56 -0700949
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700950 self.assertIs(NEI.__new__, Enum.__new__)
951 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
952 globals()['NamedInt'] = NamedInt
953 globals()['NEI'] = NEI
954 NI5 = NamedInt('test', 5)
955 self.assertEqual(NI5, 5)
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800956 test_pickle_dump_load(self.assertEqual, NI5, 5)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700957 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800958 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700959
Ethan Furmanca1b7942014-02-08 11:36:27 -0800960 def test_subclasses_with_getnewargs_ex(self):
961 class NamedInt(int):
962 __qualname__ = 'NamedInt' # needed for pickle protocol 4
963 def __new__(cls, *args):
964 _args = args
965 name, *args = args
966 if len(args) == 0:
967 raise TypeError("name and value must be specified")
968 self = int.__new__(cls, *args)
969 self._intname = name
970 self._args = _args
971 return self
972 def __getnewargs_ex__(self):
973 return self._args, {}
974 @property
975 def __name__(self):
976 return self._intname
977 def __repr__(self):
978 # repr() is updated to include the name and type info
979 return "{}({!r}, {})".format(type(self).__name__,
980 self.__name__,
981 int.__repr__(self))
982 def __str__(self):
983 # str() is unchanged, even if it relies on the repr() fallback
984 base = int
985 base_str = base.__str__
986 if base_str.__objclass__ is object:
987 return base.__repr__(self)
988 return base_str(self)
989 # for simplicity, we only define one operator that
990 # propagates expressions
991 def __add__(self, other):
992 temp = int(self) + int( other)
993 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
994 return NamedInt(
995 '({0} + {1})'.format(self.__name__, other.__name__),
996 temp )
997 else:
998 return temp
999
1000 class NEI(NamedInt, Enum):
1001 __qualname__ = 'NEI' # needed for pickle protocol 4
1002 x = ('the-x', 1)
1003 y = ('the-y', 2)
1004
1005
1006 self.assertIs(NEI.__new__, Enum.__new__)
1007 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1008 globals()['NamedInt'] = NamedInt
1009 globals()['NEI'] = NEI
1010 NI5 = NamedInt('test', 5)
1011 self.assertEqual(NI5, 5)
1012 test_pickle_dump_load(self.assertEqual, NI5, 5, protocol=(4, 4))
1013 self.assertEqual(NEI.y.value, 2)
1014 test_pickle_dump_load(self.assertIs, NEI.y, protocol=(4, 4))
1015
1016 def test_subclasses_with_reduce(self):
1017 class NamedInt(int):
1018 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1019 def __new__(cls, *args):
1020 _args = args
1021 name, *args = args
1022 if len(args) == 0:
1023 raise TypeError("name and value must be specified")
1024 self = int.__new__(cls, *args)
1025 self._intname = name
1026 self._args = _args
1027 return self
1028 def __reduce__(self):
1029 return self.__class__, self._args
1030 @property
1031 def __name__(self):
1032 return self._intname
1033 def __repr__(self):
1034 # repr() is updated to include the name and type info
1035 return "{}({!r}, {})".format(type(self).__name__,
1036 self.__name__,
1037 int.__repr__(self))
1038 def __str__(self):
1039 # str() is unchanged, even if it relies on the repr() fallback
1040 base = int
1041 base_str = base.__str__
1042 if base_str.__objclass__ is object:
1043 return base.__repr__(self)
1044 return base_str(self)
1045 # for simplicity, we only define one operator that
1046 # propagates expressions
1047 def __add__(self, other):
1048 temp = int(self) + int( other)
1049 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1050 return NamedInt(
1051 '({0} + {1})'.format(self.__name__, other.__name__),
1052 temp )
1053 else:
1054 return temp
1055
1056 class NEI(NamedInt, Enum):
1057 __qualname__ = 'NEI' # needed for pickle protocol 4
1058 x = ('the-x', 1)
1059 y = ('the-y', 2)
1060
1061
1062 self.assertIs(NEI.__new__, Enum.__new__)
1063 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1064 globals()['NamedInt'] = NamedInt
1065 globals()['NEI'] = NEI
1066 NI5 = NamedInt('test', 5)
1067 self.assertEqual(NI5, 5)
1068 test_pickle_dump_load(self.assertEqual, NI5, 5)
1069 self.assertEqual(NEI.y.value, 2)
1070 test_pickle_dump_load(self.assertIs, NEI.y)
1071
1072 def test_subclasses_with_reduce_ex(self):
1073 class NamedInt(int):
1074 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1075 def __new__(cls, *args):
1076 _args = args
1077 name, *args = args
1078 if len(args) == 0:
1079 raise TypeError("name and value must be specified")
1080 self = int.__new__(cls, *args)
1081 self._intname = name
1082 self._args = _args
1083 return self
1084 def __reduce_ex__(self, proto):
1085 return self.__class__, self._args
1086 @property
1087 def __name__(self):
1088 return self._intname
1089 def __repr__(self):
1090 # repr() is updated to include the name and type info
1091 return "{}({!r}, {})".format(type(self).__name__,
1092 self.__name__,
1093 int.__repr__(self))
1094 def __str__(self):
1095 # str() is unchanged, even if it relies on the repr() fallback
1096 base = int
1097 base_str = base.__str__
1098 if base_str.__objclass__ is object:
1099 return base.__repr__(self)
1100 return base_str(self)
1101 # for simplicity, we only define one operator that
1102 # propagates expressions
1103 def __add__(self, other):
1104 temp = int(self) + int( other)
1105 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1106 return NamedInt(
1107 '({0} + {1})'.format(self.__name__, other.__name__),
1108 temp )
1109 else:
1110 return temp
1111
1112 class NEI(NamedInt, Enum):
1113 __qualname__ = 'NEI' # needed for pickle protocol 4
1114 x = ('the-x', 1)
1115 y = ('the-y', 2)
1116
1117
1118 self.assertIs(NEI.__new__, Enum.__new__)
1119 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1120 globals()['NamedInt'] = NamedInt
1121 globals()['NEI'] = NEI
1122 NI5 = NamedInt('test', 5)
1123 self.assertEqual(NI5, 5)
1124 test_pickle_dump_load(self.assertEqual, NI5, 5)
1125 self.assertEqual(NEI.y.value, 2)
1126 test_pickle_dump_load(self.assertIs, NEI.y)
1127
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001128 def test_subclasses_without_getnewargs(self):
1129 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001130 __qualname__ = 'NamedInt'
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001131 def __new__(cls, *args):
1132 _args = args
1133 name, *args = args
1134 if len(args) == 0:
1135 raise TypeError("name and value must be specified")
1136 self = int.__new__(cls, *args)
1137 self._intname = name
1138 self._args = _args
1139 return self
1140 @property
1141 def __name__(self):
1142 return self._intname
1143 def __repr__(self):
1144 # repr() is updated to include the name and type info
1145 return "{}({!r}, {})".format(type(self).__name__,
1146 self.__name__,
1147 int.__repr__(self))
1148 def __str__(self):
1149 # str() is unchanged, even if it relies on the repr() fallback
1150 base = int
1151 base_str = base.__str__
1152 if base_str.__objclass__ is object:
1153 return base.__repr__(self)
1154 return base_str(self)
1155 # for simplicity, we only define one operator that
1156 # propagates expressions
1157 def __add__(self, other):
1158 temp = int(self) + int( other)
1159 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1160 return NamedInt(
1161 '({0} + {1})'.format(self.__name__, other.__name__),
1162 temp )
1163 else:
1164 return temp
1165
1166 class NEI(NamedInt, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001167 __qualname__ = 'NEI'
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001168 x = ('the-x', 1)
1169 y = ('the-y', 2)
1170
1171 self.assertIs(NEI.__new__, Enum.__new__)
1172 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1173 globals()['NamedInt'] = NamedInt
1174 globals()['NEI'] = NEI
1175 NI5 = NamedInt('test', 5)
1176 self.assertEqual(NI5, 5)
1177 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001178 test_pickle_exception(self.assertRaises, TypeError, NEI.x)
1179 test_pickle_exception(self.assertRaises, PicklingError, NEI)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001180
1181 def test_tuple_subclass(self):
1182 class SomeTuple(tuple, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001183 __qualname__ = 'SomeTuple' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001184 first = (1, 'for the money')
1185 second = (2, 'for the show')
1186 third = (3, 'for the music')
1187 self.assertIs(type(SomeTuple.first), SomeTuple)
1188 self.assertIsInstance(SomeTuple.second, tuple)
1189 self.assertEqual(SomeTuple.third, (3, 'for the music'))
1190 globals()['SomeTuple'] = SomeTuple
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001191 test_pickle_dump_load(self.assertIs, SomeTuple.first)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001192
1193 def test_duplicate_values_give_unique_enum_items(self):
1194 class AutoNumber(Enum):
1195 first = ()
1196 second = ()
1197 third = ()
1198 def __new__(cls):
1199 value = len(cls.__members__) + 1
1200 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001201 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001202 return obj
1203 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001204 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001205 self.assertEqual(
1206 list(AutoNumber),
1207 [AutoNumber.first, AutoNumber.second, AutoNumber.third],
1208 )
1209 self.assertEqual(int(AutoNumber.second), 2)
Ethan Furman2aa27322013-07-19 19:35:56 -07001210 self.assertEqual(AutoNumber.third.value, 3)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001211 self.assertIs(AutoNumber(1), AutoNumber.first)
1212
1213 def test_inherited_new_from_enhanced_enum(self):
1214 class AutoNumber(Enum):
1215 def __new__(cls):
1216 value = len(cls.__members__) + 1
1217 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001218 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001219 return obj
1220 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001221 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001222 class Color(AutoNumber):
1223 red = ()
1224 green = ()
1225 blue = ()
1226 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1227 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1228
1229 def test_inherited_new_from_mixed_enum(self):
1230 class AutoNumber(IntEnum):
1231 def __new__(cls):
1232 value = len(cls.__members__) + 1
1233 obj = int.__new__(cls, value)
Ethan Furman520ad572013-07-19 19:47:21 -07001234 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001235 return obj
1236 class Color(AutoNumber):
1237 red = ()
1238 green = ()
1239 blue = ()
1240 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1241 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1242
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001243 def test_equality(self):
1244 class AlwaysEqual:
1245 def __eq__(self, other):
1246 return True
1247 class OrdinaryEnum(Enum):
1248 a = 1
1249 self.assertEqual(AlwaysEqual(), OrdinaryEnum.a)
1250 self.assertEqual(OrdinaryEnum.a, AlwaysEqual())
1251
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001252 def test_ordered_mixin(self):
1253 class OrderedEnum(Enum):
1254 def __ge__(self, other):
1255 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001256 return self._value_ >= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001257 return NotImplemented
1258 def __gt__(self, other):
1259 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001260 return self._value_ > other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001261 return NotImplemented
1262 def __le__(self, other):
1263 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001264 return self._value_ <= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001265 return NotImplemented
1266 def __lt__(self, other):
1267 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001268 return self._value_ < other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001269 return NotImplemented
1270 class Grade(OrderedEnum):
1271 A = 5
1272 B = 4
1273 C = 3
1274 D = 2
1275 F = 1
1276 self.assertGreater(Grade.A, Grade.B)
1277 self.assertLessEqual(Grade.F, Grade.C)
1278 self.assertLess(Grade.D, Grade.A)
1279 self.assertGreaterEqual(Grade.B, Grade.B)
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001280 self.assertEqual(Grade.B, Grade.B)
1281 self.assertNotEqual(Grade.C, Grade.D)
Ethan Furman520ad572013-07-19 19:47:21 -07001282
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001283 def test_extending2(self):
1284 class Shade(Enum):
1285 def shade(self):
1286 print(self.name)
1287 class Color(Shade):
1288 red = 1
1289 green = 2
1290 blue = 3
1291 with self.assertRaises(TypeError):
1292 class MoreColor(Color):
1293 cyan = 4
1294 magenta = 5
1295 yellow = 6
1296
1297 def test_extending3(self):
1298 class Shade(Enum):
1299 def shade(self):
1300 return self.name
1301 class Color(Shade):
1302 def hex(self):
1303 return '%s hexlified!' % self.value
1304 class MoreColor(Color):
1305 cyan = 4
1306 magenta = 5
1307 yellow = 6
1308 self.assertEqual(MoreColor.magenta.hex(), '5 hexlified!')
1309
1310
1311 def test_no_duplicates(self):
1312 class UniqueEnum(Enum):
1313 def __init__(self, *args):
1314 cls = self.__class__
1315 if any(self.value == e.value for e in cls):
1316 a = self.name
1317 e = cls(self.value).name
1318 raise ValueError(
1319 "aliases not allowed in UniqueEnum: %r --> %r"
1320 % (a, e)
1321 )
1322 class Color(UniqueEnum):
1323 red = 1
1324 green = 2
1325 blue = 3
1326 with self.assertRaises(ValueError):
1327 class Color(UniqueEnum):
1328 red = 1
1329 green = 2
1330 blue = 3
1331 grene = 2
1332
1333 def test_init(self):
1334 class Planet(Enum):
1335 MERCURY = (3.303e+23, 2.4397e6)
1336 VENUS = (4.869e+24, 6.0518e6)
1337 EARTH = (5.976e+24, 6.37814e6)
1338 MARS = (6.421e+23, 3.3972e6)
1339 JUPITER = (1.9e+27, 7.1492e7)
1340 SATURN = (5.688e+26, 6.0268e7)
1341 URANUS = (8.686e+25, 2.5559e7)
1342 NEPTUNE = (1.024e+26, 2.4746e7)
1343 def __init__(self, mass, radius):
1344 self.mass = mass # in kilograms
1345 self.radius = radius # in meters
1346 @property
1347 def surface_gravity(self):
1348 # universal gravitational constant (m3 kg-1 s-2)
1349 G = 6.67300E-11
1350 return G * self.mass / (self.radius * self.radius)
1351 self.assertEqual(round(Planet.EARTH.surface_gravity, 2), 9.80)
1352 self.assertEqual(Planet.EARTH.value, (5.976e+24, 6.37814e6))
1353
Ethan Furman2aa27322013-07-19 19:35:56 -07001354 def test_nonhash_value(self):
1355 class AutoNumberInAList(Enum):
1356 def __new__(cls):
1357 value = [len(cls.__members__) + 1]
1358 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001359 obj._value_ = value
Ethan Furman2aa27322013-07-19 19:35:56 -07001360 return obj
1361 class ColorInAList(AutoNumberInAList):
1362 red = ()
1363 green = ()
1364 blue = ()
1365 self.assertEqual(list(ColorInAList), [ColorInAList.red, ColorInAList.green, ColorInAList.blue])
Ethan Furman1a162882013-10-16 19:09:31 -07001366 for enum, value in zip(ColorInAList, range(3)):
1367 value += 1
1368 self.assertEqual(enum.value, [value])
1369 self.assertIs(ColorInAList([value]), enum)
Ethan Furman2aa27322013-07-19 19:35:56 -07001370
Ethan Furmanb41803e2013-07-25 13:50:45 -07001371 def test_conflicting_types_resolved_in_new(self):
1372 class LabelledIntEnum(int, Enum):
1373 def __new__(cls, *args):
1374 value, label = args
1375 obj = int.__new__(cls, value)
1376 obj.label = label
1377 obj._value_ = value
1378 return obj
1379
1380 class LabelledList(LabelledIntEnum):
1381 unprocessed = (1, "Unprocessed")
1382 payment_complete = (2, "Payment Complete")
1383
1384 self.assertEqual(list(LabelledList), [LabelledList.unprocessed, LabelledList.payment_complete])
1385 self.assertEqual(LabelledList.unprocessed, 1)
1386 self.assertEqual(LabelledList(1), LabelledList.unprocessed)
Ethan Furman2aa27322013-07-19 19:35:56 -07001387
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001388
Ethan Furmanf24bb352013-07-18 17:05:39 -07001389class TestUnique(unittest.TestCase):
1390
1391 def test_unique_clean(self):
1392 @unique
1393 class Clean(Enum):
1394 one = 1
1395 two = 'dos'
1396 tres = 4.0
1397 @unique
1398 class Cleaner(IntEnum):
1399 single = 1
1400 double = 2
1401 triple = 3
1402
1403 def test_unique_dirty(self):
1404 with self.assertRaisesRegex(ValueError, 'tres.*one'):
1405 @unique
1406 class Dirty(Enum):
1407 one = 1
1408 two = 'dos'
1409 tres = 1
1410 with self.assertRaisesRegex(
1411 ValueError,
1412 'double.*single.*turkey.*triple',
1413 ):
1414 @unique
1415 class Dirtier(IntEnum):
1416 single = 1
1417 double = 1
1418 triple = 3
1419 turkey = 3
1420
1421
Ethan Furman5875d742013-10-21 20:45:55 -07001422expected_help_output = """
1423Help on class Color in module %s:
1424
1425class Color(enum.Enum)
1426 | Method resolution order:
1427 | Color
1428 | enum.Enum
1429 | builtins.object
1430 |\x20\x20
1431 | Data and other attributes defined here:
1432 |\x20\x20
1433 | blue = <Color.blue: 3>
1434 |\x20\x20
1435 | green = <Color.green: 2>
1436 |\x20\x20
1437 | red = <Color.red: 1>
1438 |\x20\x20
1439 | ----------------------------------------------------------------------
1440 | Data descriptors inherited from enum.Enum:
1441 |\x20\x20
1442 | name
1443 | The name of the Enum member.
1444 |\x20\x20
1445 | value
1446 | The value of the Enum member.
1447 |\x20\x20
1448 | ----------------------------------------------------------------------
1449 | Data descriptors inherited from enum.EnumMeta:
1450 |\x20\x20
1451 | __members__
1452 | Returns a mapping of member name->value.
1453 |\x20\x20\x20\x20\x20\x20
1454 | This mapping lists all enum members, including aliases. Note that this
1455 | is a read-only view of the internal mapping.
1456""".strip()
1457
1458class TestStdLib(unittest.TestCase):
1459
1460 class Color(Enum):
1461 red = 1
1462 green = 2
1463 blue = 3
1464
1465 def test_pydoc(self):
1466 # indirectly test __objclass__
1467 expected_text = expected_help_output % __name__
1468 output = StringIO()
1469 helper = pydoc.Helper(output=output)
1470 helper(self.Color)
1471 result = output.getvalue().strip()
1472 if result != expected_text:
1473 print_diffs(expected_text, result)
1474 self.fail("outputs are not equal, see diff above")
1475
1476 def test_inspect_getmembers(self):
1477 values = dict((
1478 ('__class__', EnumMeta),
1479 ('__doc__', None),
1480 ('__members__', self.Color.__members__),
1481 ('__module__', __name__),
1482 ('blue', self.Color.blue),
1483 ('green', self.Color.green),
1484 ('name', Enum.__dict__['name']),
1485 ('red', self.Color.red),
1486 ('value', Enum.__dict__['value']),
1487 ))
1488 result = dict(inspect.getmembers(self.Color))
1489 self.assertEqual(values.keys(), result.keys())
1490 failed = False
1491 for k in values.keys():
1492 if result[k] != values[k]:
1493 print()
1494 print('\n%s\n key: %s\n result: %s\nexpected: %s\n%s\n' %
1495 ('=' * 75, k, result[k], values[k], '=' * 75), sep='')
1496 failed = True
1497 if failed:
1498 self.fail("result does not equal expected, see print above")
1499
1500 def test_inspect_classify_class_attrs(self):
1501 # indirectly test __objclass__
1502 from inspect import Attribute
1503 values = [
1504 Attribute(name='__class__', kind='data',
1505 defining_class=object, object=EnumMeta),
1506 Attribute(name='__doc__', kind='data',
1507 defining_class=self.Color, object=None),
1508 Attribute(name='__members__', kind='property',
1509 defining_class=EnumMeta, object=EnumMeta.__members__),
1510 Attribute(name='__module__', kind='data',
1511 defining_class=self.Color, object=__name__),
1512 Attribute(name='blue', kind='data',
1513 defining_class=self.Color, object=self.Color.blue),
1514 Attribute(name='green', kind='data',
1515 defining_class=self.Color, object=self.Color.green),
1516 Attribute(name='red', kind='data',
1517 defining_class=self.Color, object=self.Color.red),
1518 Attribute(name='name', kind='data',
1519 defining_class=Enum, object=Enum.__dict__['name']),
1520 Attribute(name='value', kind='data',
1521 defining_class=Enum, object=Enum.__dict__['value']),
1522 ]
1523 values.sort(key=lambda item: item.name)
1524 result = list(inspect.classify_class_attrs(self.Color))
1525 result.sort(key=lambda item: item.name)
1526 failed = False
1527 for v, r in zip(values, result):
1528 if r != v:
1529 print('\n%s\n%s\n%s\n%s\n' % ('=' * 75, r, v, '=' * 75), sep='')
1530 failed = True
1531 if failed:
1532 self.fail("result does not equal expected, see print above")
1533
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001534if __name__ == '__main__':
1535 unittest.main()