blob: dfade17873387cfc4fe5ee13e687edffaec8f2fe [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
55# for doctests
56try:
57 class Fruit(Enum):
58 tomato = 1
59 banana = 2
60 cherry = 3
61except Exception:
62 pass
63
Ethan Furman2ddb39a2014-02-06 17:28:50 -080064def test_pickle_dump_load(assertion, source, target=None):
65 if target is None:
66 target = source
67 for protocol in range(2, HIGHEST_PROTOCOL+1):
68 assertion(loads(dumps(source, protocol=protocol)), target)
69
70def test_pickle_exception(assertion, exception, obj):
71 for protocol in range(2, HIGHEST_PROTOCOL+1):
72 with assertion(exception):
73 dumps(obj, protocol=protocol)
Ethan Furman648f8602013-10-06 17:19:54 -070074
75class TestHelpers(unittest.TestCase):
76 # _is_descriptor, _is_sunder, _is_dunder
77
78 def test_is_descriptor(self):
79 class foo:
80 pass
81 for attr in ('__get__','__set__','__delete__'):
82 obj = foo()
83 self.assertFalse(enum._is_descriptor(obj))
84 setattr(obj, attr, 1)
85 self.assertTrue(enum._is_descriptor(obj))
86
87 def test_is_sunder(self):
88 for s in ('_a_', '_aa_'):
89 self.assertTrue(enum._is_sunder(s))
90
91 for s in ('a', 'a_', '_a', '__a', 'a__', '__a__', '_a__', '__a_', '_',
92 '__', '___', '____', '_____',):
93 self.assertFalse(enum._is_sunder(s))
94
95 def test_is_dunder(self):
96 for s in ('__a__', '__aa__'):
97 self.assertTrue(enum._is_dunder(s))
98 for s in ('a', 'a_', '_a', '__a', 'a__', '_a_', '_a__', '__a_', '_',
99 '__', '___', '____', '_____',):
100 self.assertFalse(enum._is_dunder(s))
101
102
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700103class TestEnum(unittest.TestCase):
104 def setUp(self):
105 class Season(Enum):
106 SPRING = 1
107 SUMMER = 2
108 AUTUMN = 3
109 WINTER = 4
110 self.Season = Season
111
Ethan Furmanec15a822013-08-31 19:17:41 -0700112 class Konstants(float, Enum):
113 E = 2.7182818
114 PI = 3.1415926
115 TAU = 2 * PI
116 self.Konstants = Konstants
117
118 class Grades(IntEnum):
119 A = 5
120 B = 4
121 C = 3
122 D = 2
123 F = 0
124 self.Grades = Grades
125
126 class Directional(str, Enum):
127 EAST = 'east'
128 WEST = 'west'
129 NORTH = 'north'
130 SOUTH = 'south'
131 self.Directional = Directional
132
133 from datetime import date
134 class Holiday(date, Enum):
135 NEW_YEAR = 2013, 1, 1
136 IDES_OF_MARCH = 2013, 3, 15
137 self.Holiday = Holiday
138
Ethan Furman388a3922013-08-12 06:51:41 -0700139 def test_dir_on_class(self):
140 Season = self.Season
141 self.assertEqual(
142 set(dir(Season)),
Ethan Furmanc850f342013-09-15 16:59:35 -0700143 set(['__class__', '__doc__', '__members__', '__module__',
Ethan Furman388a3922013-08-12 06:51:41 -0700144 'SPRING', 'SUMMER', 'AUTUMN', 'WINTER']),
145 )
146
147 def test_dir_on_item(self):
148 Season = self.Season
149 self.assertEqual(
150 set(dir(Season.WINTER)),
Ethan Furmanc850f342013-09-15 16:59:35 -0700151 set(['__class__', '__doc__', '__module__', 'name', 'value']),
Ethan Furman388a3922013-08-12 06:51:41 -0700152 )
153
Ethan Furmanc850f342013-09-15 16:59:35 -0700154 def test_dir_with_added_behavior(self):
155 class Test(Enum):
156 this = 'that'
157 these = 'those'
158 def wowser(self):
159 return ("Wowser! I'm %s!" % self.name)
160 self.assertEqual(
161 set(dir(Test)),
162 set(['__class__', '__doc__', '__members__', '__module__', 'this', 'these']),
163 )
164 self.assertEqual(
165 set(dir(Test.this)),
166 set(['__class__', '__doc__', '__module__', 'name', 'value', 'wowser']),
167 )
168
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700169 def test_enum_in_enum_out(self):
170 Season = self.Season
171 self.assertIs(Season(Season.WINTER), Season.WINTER)
172
173 def test_enum_value(self):
174 Season = self.Season
175 self.assertEqual(Season.SPRING.value, 1)
176
177 def test_intenum_value(self):
178 self.assertEqual(IntStooges.CURLY.value, 2)
179
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700180 def test_enum(self):
181 Season = self.Season
182 lst = list(Season)
183 self.assertEqual(len(lst), len(Season))
184 self.assertEqual(len(Season), 4, Season)
185 self.assertEqual(
186 [Season.SPRING, Season.SUMMER, Season.AUTUMN, Season.WINTER], lst)
187
188 for i, season in enumerate('SPRING SUMMER AUTUMN WINTER'.split(), 1):
189 e = Season(i)
190 self.assertEqual(e, getattr(Season, season))
191 self.assertEqual(e.value, i)
192 self.assertNotEqual(e, i)
193 self.assertEqual(e.name, season)
194 self.assertIn(e, Season)
195 self.assertIs(type(e), Season)
196 self.assertIsInstance(e, Season)
197 self.assertEqual(str(e), 'Season.' + season)
198 self.assertEqual(
199 repr(e),
200 '<Season.{0}: {1}>'.format(season, i),
201 )
202
203 def test_value_name(self):
204 Season = self.Season
205 self.assertEqual(Season.SPRING.name, 'SPRING')
206 self.assertEqual(Season.SPRING.value, 1)
207 with self.assertRaises(AttributeError):
208 Season.SPRING.name = 'invierno'
209 with self.assertRaises(AttributeError):
210 Season.SPRING.value = 2
211
Ethan Furmanf203f2d2013-09-06 07:16:48 -0700212 def test_changing_member(self):
213 Season = self.Season
214 with self.assertRaises(AttributeError):
215 Season.WINTER = 'really cold'
216
Ethan Furman64a99722013-09-22 16:18:19 -0700217 def test_attribute_deletion(self):
218 class Season(Enum):
219 SPRING = 1
220 SUMMER = 2
221 AUTUMN = 3
222 WINTER = 4
223
224 def spam(cls):
225 pass
226
227 self.assertTrue(hasattr(Season, 'spam'))
228 del Season.spam
229 self.assertFalse(hasattr(Season, 'spam'))
230
231 with self.assertRaises(AttributeError):
232 del Season.SPRING
233 with self.assertRaises(AttributeError):
234 del Season.DRY
235 with self.assertRaises(AttributeError):
236 del Season.SPRING.name
237
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700238 def test_invalid_names(self):
239 with self.assertRaises(ValueError):
240 class Wrong(Enum):
241 mro = 9
242 with self.assertRaises(ValueError):
243 class Wrong(Enum):
244 _create_= 11
245 with self.assertRaises(ValueError):
246 class Wrong(Enum):
247 _get_mixins_ = 9
248 with self.assertRaises(ValueError):
249 class Wrong(Enum):
250 _find_new_ = 1
251 with self.assertRaises(ValueError):
252 class Wrong(Enum):
253 _any_name_ = 9
254
255 def test_contains(self):
256 Season = self.Season
257 self.assertIn(Season.AUTUMN, Season)
258 self.assertNotIn(3, Season)
259
260 val = Season(3)
261 self.assertIn(val, Season)
262
263 class OtherEnum(Enum):
264 one = 1; two = 2
265 self.assertNotIn(OtherEnum.two, Season)
266
267 def test_comparisons(self):
268 Season = self.Season
269 with self.assertRaises(TypeError):
270 Season.SPRING < Season.WINTER
271 with self.assertRaises(TypeError):
272 Season.SPRING > 4
273
274 self.assertNotEqual(Season.SPRING, 1)
275
276 class Part(Enum):
277 SPRING = 1
278 CLIP = 2
279 BARREL = 3
280
281 self.assertNotEqual(Season.SPRING, Part.SPRING)
282 with self.assertRaises(TypeError):
283 Season.SPRING < Part.CLIP
284
285 def test_enum_duplicates(self):
286 class Season(Enum):
287 SPRING = 1
288 SUMMER = 2
289 AUTUMN = FALL = 3
290 WINTER = 4
291 ANOTHER_SPRING = 1
292 lst = list(Season)
293 self.assertEqual(
294 lst,
295 [Season.SPRING, Season.SUMMER,
296 Season.AUTUMN, Season.WINTER,
297 ])
298 self.assertIs(Season.FALL, Season.AUTUMN)
299 self.assertEqual(Season.FALL.value, 3)
300 self.assertEqual(Season.AUTUMN.value, 3)
301 self.assertIs(Season(3), Season.AUTUMN)
302 self.assertIs(Season(1), Season.SPRING)
303 self.assertEqual(Season.FALL.name, 'AUTUMN')
304 self.assertEqual(
305 [k for k,v in Season.__members__.items() if v.name != k],
306 ['FALL', 'ANOTHER_SPRING'],
307 )
308
Ethan Furman101e0742013-09-15 12:34:36 -0700309 def test_duplicate_name(self):
310 with self.assertRaises(TypeError):
311 class Color(Enum):
312 red = 1
313 green = 2
314 blue = 3
315 red = 4
316
317 with self.assertRaises(TypeError):
318 class Color(Enum):
319 red = 1
320 green = 2
321 blue = 3
322 def red(self):
323 return 'red'
324
325 with self.assertRaises(TypeError):
326 class Color(Enum):
327 @property
328 def red(self):
329 return 'redder'
330 red = 1
331 green = 2
332 blue = 3
333
334
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700335 def test_enum_with_value_name(self):
336 class Huh(Enum):
337 name = 1
338 value = 2
339 self.assertEqual(
340 list(Huh),
341 [Huh.name, Huh.value],
342 )
343 self.assertIs(type(Huh.name), Huh)
344 self.assertEqual(Huh.name.name, 'name')
345 self.assertEqual(Huh.name.value, 1)
Ethan Furmanec15a822013-08-31 19:17:41 -0700346
347 def test_format_enum(self):
348 Season = self.Season
349 self.assertEqual('{}'.format(Season.SPRING),
350 '{}'.format(str(Season.SPRING)))
351 self.assertEqual( '{:}'.format(Season.SPRING),
352 '{:}'.format(str(Season.SPRING)))
353 self.assertEqual('{:20}'.format(Season.SPRING),
354 '{:20}'.format(str(Season.SPRING)))
355 self.assertEqual('{:^20}'.format(Season.SPRING),
356 '{:^20}'.format(str(Season.SPRING)))
357 self.assertEqual('{:>20}'.format(Season.SPRING),
358 '{:>20}'.format(str(Season.SPRING)))
359 self.assertEqual('{:<20}'.format(Season.SPRING),
360 '{:<20}'.format(str(Season.SPRING)))
361
362 def test_format_enum_custom(self):
363 class TestFloat(float, Enum):
364 one = 1.0
365 two = 2.0
366 def __format__(self, spec):
367 return 'TestFloat success!'
368 self.assertEqual('{}'.format(TestFloat.one), 'TestFloat success!')
369
370 def assertFormatIsValue(self, spec, member):
371 self.assertEqual(spec.format(member), spec.format(member.value))
372
373 def test_format_enum_date(self):
374 Holiday = self.Holiday
375 self.assertFormatIsValue('{}', Holiday.IDES_OF_MARCH)
376 self.assertFormatIsValue('{:}', Holiday.IDES_OF_MARCH)
377 self.assertFormatIsValue('{:20}', Holiday.IDES_OF_MARCH)
378 self.assertFormatIsValue('{:^20}', Holiday.IDES_OF_MARCH)
379 self.assertFormatIsValue('{:>20}', Holiday.IDES_OF_MARCH)
380 self.assertFormatIsValue('{:<20}', Holiday.IDES_OF_MARCH)
381 self.assertFormatIsValue('{:%Y %m}', Holiday.IDES_OF_MARCH)
382 self.assertFormatIsValue('{:%Y %m %M:00}', Holiday.IDES_OF_MARCH)
383
384 def test_format_enum_float(self):
385 Konstants = self.Konstants
386 self.assertFormatIsValue('{}', Konstants.TAU)
387 self.assertFormatIsValue('{:}', Konstants.TAU)
388 self.assertFormatIsValue('{:20}', Konstants.TAU)
389 self.assertFormatIsValue('{:^20}', Konstants.TAU)
390 self.assertFormatIsValue('{:>20}', Konstants.TAU)
391 self.assertFormatIsValue('{:<20}', Konstants.TAU)
392 self.assertFormatIsValue('{:n}', Konstants.TAU)
393 self.assertFormatIsValue('{:5.2}', Konstants.TAU)
394 self.assertFormatIsValue('{:f}', Konstants.TAU)
395
396 def test_format_enum_int(self):
397 Grades = self.Grades
398 self.assertFormatIsValue('{}', Grades.C)
399 self.assertFormatIsValue('{:}', Grades.C)
400 self.assertFormatIsValue('{:20}', Grades.C)
401 self.assertFormatIsValue('{:^20}', Grades.C)
402 self.assertFormatIsValue('{:>20}', Grades.C)
403 self.assertFormatIsValue('{:<20}', Grades.C)
404 self.assertFormatIsValue('{:+}', Grades.C)
405 self.assertFormatIsValue('{:08X}', Grades.C)
406 self.assertFormatIsValue('{:b}', Grades.C)
407
408 def test_format_enum_str(self):
409 Directional = self.Directional
410 self.assertFormatIsValue('{}', Directional.WEST)
411 self.assertFormatIsValue('{:}', Directional.WEST)
412 self.assertFormatIsValue('{:20}', Directional.WEST)
413 self.assertFormatIsValue('{:^20}', Directional.WEST)
414 self.assertFormatIsValue('{:>20}', Directional.WEST)
415 self.assertFormatIsValue('{:<20}', Directional.WEST)
416
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700417 def test_hash(self):
418 Season = self.Season
419 dates = {}
420 dates[Season.WINTER] = '1225'
421 dates[Season.SPRING] = '0315'
422 dates[Season.SUMMER] = '0704'
423 dates[Season.AUTUMN] = '1031'
424 self.assertEqual(dates[Season.AUTUMN], '1031')
425
426 def test_intenum_from_scratch(self):
427 class phy(int, Enum):
428 pi = 3
429 tau = 2 * pi
430 self.assertTrue(phy.pi < phy.tau)
431
432 def test_intenum_inherited(self):
433 class IntEnum(int, Enum):
434 pass
435 class phy(IntEnum):
436 pi = 3
437 tau = 2 * pi
438 self.assertTrue(phy.pi < phy.tau)
439
440 def test_floatenum_from_scratch(self):
441 class phy(float, Enum):
Ethan Furmanec15a822013-08-31 19:17:41 -0700442 pi = 3.1415926
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700443 tau = 2 * pi
444 self.assertTrue(phy.pi < phy.tau)
445
446 def test_floatenum_inherited(self):
447 class FloatEnum(float, Enum):
448 pass
449 class phy(FloatEnum):
Ethan Furmanec15a822013-08-31 19:17:41 -0700450 pi = 3.1415926
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700451 tau = 2 * pi
452 self.assertTrue(phy.pi < phy.tau)
453
454 def test_strenum_from_scratch(self):
455 class phy(str, Enum):
456 pi = 'Pi'
457 tau = 'Tau'
458 self.assertTrue(phy.pi < phy.tau)
459
460 def test_strenum_inherited(self):
461 class StrEnum(str, Enum):
462 pass
463 class phy(StrEnum):
464 pi = 'Pi'
465 tau = 'Tau'
466 self.assertTrue(phy.pi < phy.tau)
467
468
469 def test_intenum(self):
470 class WeekDay(IntEnum):
471 SUNDAY = 1
472 MONDAY = 2
473 TUESDAY = 3
474 WEDNESDAY = 4
475 THURSDAY = 5
476 FRIDAY = 6
477 SATURDAY = 7
478
479 self.assertEqual(['a', 'b', 'c'][WeekDay.MONDAY], 'c')
480 self.assertEqual([i for i in range(WeekDay.TUESDAY)], [0, 1, 2])
481
482 lst = list(WeekDay)
483 self.assertEqual(len(lst), len(WeekDay))
484 self.assertEqual(len(WeekDay), 7)
485 target = 'SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY'
486 target = target.split()
487 for i, weekday in enumerate(target, 1):
488 e = WeekDay(i)
489 self.assertEqual(e, i)
490 self.assertEqual(int(e), i)
491 self.assertEqual(e.name, weekday)
492 self.assertIn(e, WeekDay)
493 self.assertEqual(lst.index(e)+1, i)
494 self.assertTrue(0 < e < 8)
495 self.assertIs(type(e), WeekDay)
496 self.assertIsInstance(e, int)
497 self.assertIsInstance(e, Enum)
498
499 def test_intenum_duplicates(self):
500 class WeekDay(IntEnum):
501 SUNDAY = 1
502 MONDAY = 2
503 TUESDAY = TEUSDAY = 3
504 WEDNESDAY = 4
505 THURSDAY = 5
506 FRIDAY = 6
507 SATURDAY = 7
508 self.assertIs(WeekDay.TEUSDAY, WeekDay.TUESDAY)
509 self.assertEqual(WeekDay(3).name, 'TUESDAY')
510 self.assertEqual([k for k,v in WeekDay.__members__.items()
511 if v.name != k], ['TEUSDAY', ])
512
513 def test_pickle_enum(self):
514 if isinstance(Stooges, Exception):
515 raise Stooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800516 test_pickle_dump_load(self.assertIs, Stooges.CURLY)
517 test_pickle_dump_load(self.assertIs, Stooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700518
519 def test_pickle_int(self):
520 if isinstance(IntStooges, Exception):
521 raise IntStooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800522 test_pickle_dump_load(self.assertIs, IntStooges.CURLY)
523 test_pickle_dump_load(self.assertIs, IntStooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700524
525 def test_pickle_float(self):
526 if isinstance(FloatStooges, Exception):
527 raise FloatStooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800528 test_pickle_dump_load(self.assertIs, FloatStooges.CURLY)
529 test_pickle_dump_load(self.assertIs, FloatStooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700530
531 def test_pickle_enum_function(self):
532 if isinstance(Answer, Exception):
533 raise Answer
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800534 test_pickle_dump_load(self.assertIs, Answer.him)
535 test_pickle_dump_load(self.assertIs, Answer)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700536
537 def test_pickle_enum_function_with_module(self):
538 if isinstance(Question, Exception):
539 raise Question
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800540 test_pickle_dump_load(self.assertIs, Question.who)
541 test_pickle_dump_load(self.assertIs, Question)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700542
543 def test_exploding_pickle(self):
544 BadPickle = Enum('BadPickle', 'dill sweet bread-n-butter')
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800545 BadPickle.__qualname__ = 'BadPickle' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700546 globals()['BadPickle'] = BadPickle
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800547 enum._make_class_unpicklable(BadPickle) # will overwrite __qualname__
548 test_pickle_exception(self.assertRaises, TypeError, BadPickle.dill)
549 test_pickle_exception(self.assertRaises, PicklingError, BadPickle)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700550
551 def test_string_enum(self):
552 class SkillLevel(str, Enum):
553 master = 'what is the sound of one hand clapping?'
554 journeyman = 'why did the chicken cross the road?'
555 apprentice = 'knock, knock!'
556 self.assertEqual(SkillLevel.apprentice, 'knock, knock!')
557
558 def test_getattr_getitem(self):
559 class Period(Enum):
560 morning = 1
561 noon = 2
562 evening = 3
563 night = 4
564 self.assertIs(Period(2), Period.noon)
565 self.assertIs(getattr(Period, 'night'), Period.night)
566 self.assertIs(Period['morning'], Period.morning)
567
568 def test_getattr_dunder(self):
569 Season = self.Season
570 self.assertTrue(getattr(Season, '__eq__'))
571
572 def test_iteration_order(self):
573 class Season(Enum):
574 SUMMER = 2
575 WINTER = 4
576 AUTUMN = 3
577 SPRING = 1
578 self.assertEqual(
579 list(Season),
580 [Season.SUMMER, Season.WINTER, Season.AUTUMN, Season.SPRING],
581 )
582
Ethan Furman2131a4a2013-09-14 18:11:24 -0700583 def test_reversed_iteration_order(self):
584 self.assertEqual(
585 list(reversed(self.Season)),
586 [self.Season.WINTER, self.Season.AUTUMN, self.Season.SUMMER,
587 self.Season.SPRING]
588 )
589
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700590 def test_programatic_function_string(self):
591 SummerMonth = Enum('SummerMonth', 'june july august')
592 lst = list(SummerMonth)
593 self.assertEqual(len(lst), len(SummerMonth))
594 self.assertEqual(len(SummerMonth), 3, SummerMonth)
595 self.assertEqual(
596 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
597 lst,
598 )
599 for i, month in enumerate('june july august'.split(), 1):
600 e = SummerMonth(i)
601 self.assertEqual(int(e.value), i)
602 self.assertNotEqual(e, i)
603 self.assertEqual(e.name, month)
604 self.assertIn(e, SummerMonth)
605 self.assertIs(type(e), SummerMonth)
606
607 def test_programatic_function_string_list(self):
608 SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'])
609 lst = list(SummerMonth)
610 self.assertEqual(len(lst), len(SummerMonth))
611 self.assertEqual(len(SummerMonth), 3, SummerMonth)
612 self.assertEqual(
613 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
614 lst,
615 )
616 for i, month in enumerate('june july august'.split(), 1):
617 e = SummerMonth(i)
618 self.assertEqual(int(e.value), i)
619 self.assertNotEqual(e, i)
620 self.assertEqual(e.name, month)
621 self.assertIn(e, SummerMonth)
622 self.assertIs(type(e), SummerMonth)
623
624 def test_programatic_function_iterable(self):
625 SummerMonth = Enum(
626 'SummerMonth',
627 (('june', 1), ('july', 2), ('august', 3))
628 )
629 lst = list(SummerMonth)
630 self.assertEqual(len(lst), len(SummerMonth))
631 self.assertEqual(len(SummerMonth), 3, SummerMonth)
632 self.assertEqual(
633 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
634 lst,
635 )
636 for i, month in enumerate('june july august'.split(), 1):
637 e = SummerMonth(i)
638 self.assertEqual(int(e.value), i)
639 self.assertNotEqual(e, i)
640 self.assertEqual(e.name, month)
641 self.assertIn(e, SummerMonth)
642 self.assertIs(type(e), SummerMonth)
643
644 def test_programatic_function_from_dict(self):
645 SummerMonth = Enum(
646 'SummerMonth',
647 OrderedDict((('june', 1), ('july', 2), ('august', 3)))
648 )
649 lst = list(SummerMonth)
650 self.assertEqual(len(lst), len(SummerMonth))
651 self.assertEqual(len(SummerMonth), 3, SummerMonth)
652 self.assertEqual(
653 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
654 lst,
655 )
656 for i, month in enumerate('june july august'.split(), 1):
657 e = SummerMonth(i)
658 self.assertEqual(int(e.value), i)
659 self.assertNotEqual(e, i)
660 self.assertEqual(e.name, month)
661 self.assertIn(e, SummerMonth)
662 self.assertIs(type(e), SummerMonth)
663
664 def test_programatic_function_type(self):
665 SummerMonth = Enum('SummerMonth', 'june july august', type=int)
666 lst = list(SummerMonth)
667 self.assertEqual(len(lst), len(SummerMonth))
668 self.assertEqual(len(SummerMonth), 3, SummerMonth)
669 self.assertEqual(
670 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
671 lst,
672 )
673 for i, month in enumerate('june july august'.split(), 1):
674 e = SummerMonth(i)
675 self.assertEqual(e, i)
676 self.assertEqual(e.name, month)
677 self.assertIn(e, SummerMonth)
678 self.assertIs(type(e), SummerMonth)
679
680 def test_programatic_function_type_from_subclass(self):
681 SummerMonth = IntEnum('SummerMonth', 'june july august')
682 lst = list(SummerMonth)
683 self.assertEqual(len(lst), len(SummerMonth))
684 self.assertEqual(len(SummerMonth), 3, SummerMonth)
685 self.assertEqual(
686 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
687 lst,
688 )
689 for i, month in enumerate('june july august'.split(), 1):
690 e = SummerMonth(i)
691 self.assertEqual(e, i)
692 self.assertEqual(e.name, month)
693 self.assertIn(e, SummerMonth)
694 self.assertIs(type(e), SummerMonth)
695
696 def test_subclassing(self):
697 if isinstance(Name, Exception):
698 raise Name
699 self.assertEqual(Name.BDFL, 'Guido van Rossum')
700 self.assertTrue(Name.BDFL, Name('Guido van Rossum'))
701 self.assertIs(Name.BDFL, getattr(Name, 'BDFL'))
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800702 test_pickle_dump_load(self.assertIs, Name.BDFL)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700703
704 def test_extending(self):
705 class Color(Enum):
706 red = 1
707 green = 2
708 blue = 3
709 with self.assertRaises(TypeError):
710 class MoreColor(Color):
711 cyan = 4
712 magenta = 5
713 yellow = 6
714
715 def test_exclude_methods(self):
716 class whatever(Enum):
717 this = 'that'
718 these = 'those'
719 def really(self):
720 return 'no, not %s' % self.value
721 self.assertIsNot(type(whatever.really), whatever)
722 self.assertEqual(whatever.this.really(), 'no, not that')
723
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700724 def test_wrong_inheritance_order(self):
725 with self.assertRaises(TypeError):
726 class Wrong(Enum, str):
727 NotHere = 'error before this point'
728
729 def test_intenum_transitivity(self):
730 class number(IntEnum):
731 one = 1
732 two = 2
733 three = 3
734 class numero(IntEnum):
735 uno = 1
736 dos = 2
737 tres = 3
738 self.assertEqual(number.one, numero.uno)
739 self.assertEqual(number.two, numero.dos)
740 self.assertEqual(number.three, numero.tres)
741
742 def test_wrong_enum_in_call(self):
743 class Monochrome(Enum):
744 black = 0
745 white = 1
746 class Gender(Enum):
747 male = 0
748 female = 1
749 self.assertRaises(ValueError, Monochrome, Gender.male)
750
751 def test_wrong_enum_in_mixed_call(self):
752 class Monochrome(IntEnum):
753 black = 0
754 white = 1
755 class Gender(Enum):
756 male = 0
757 female = 1
758 self.assertRaises(ValueError, Monochrome, Gender.male)
759
760 def test_mixed_enum_in_call_1(self):
761 class Monochrome(IntEnum):
762 black = 0
763 white = 1
764 class Gender(IntEnum):
765 male = 0
766 female = 1
767 self.assertIs(Monochrome(Gender.female), Monochrome.white)
768
769 def test_mixed_enum_in_call_2(self):
770 class Monochrome(Enum):
771 black = 0
772 white = 1
773 class Gender(IntEnum):
774 male = 0
775 female = 1
776 self.assertIs(Monochrome(Gender.male), Monochrome.black)
777
778 def test_flufl_enum(self):
779 class Fluflnum(Enum):
780 def __int__(self):
781 return int(self.value)
782 class MailManOptions(Fluflnum):
783 option1 = 1
784 option2 = 2
785 option3 = 3
786 self.assertEqual(int(MailManOptions.option1), 1)
787
Ethan Furman5e5a8232013-08-04 08:42:23 -0700788 def test_introspection(self):
789 class Number(IntEnum):
790 one = 100
791 two = 200
792 self.assertIs(Number.one._member_type_, int)
793 self.assertIs(Number._member_type_, int)
794 class String(str, Enum):
795 yarn = 'soft'
796 rope = 'rough'
797 wire = 'hard'
798 self.assertIs(String.yarn._member_type_, str)
799 self.assertIs(String._member_type_, str)
800 class Plain(Enum):
801 vanilla = 'white'
802 one = 1
803 self.assertIs(Plain.vanilla._member_type_, object)
804 self.assertIs(Plain._member_type_, object)
805
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700806 def test_no_such_enum_member(self):
807 class Color(Enum):
808 red = 1
809 green = 2
810 blue = 3
811 with self.assertRaises(ValueError):
812 Color(4)
813 with self.assertRaises(KeyError):
814 Color['chartreuse']
815
816 def test_new_repr(self):
817 class Color(Enum):
818 red = 1
819 green = 2
820 blue = 3
821 def __repr__(self):
822 return "don't you just love shades of %s?" % self.name
823 self.assertEqual(
824 repr(Color.blue),
825 "don't you just love shades of blue?",
826 )
827
828 def test_inherited_repr(self):
829 class MyEnum(Enum):
830 def __repr__(self):
831 return "My name is %s." % self.name
832 class MyIntEnum(int, MyEnum):
833 this = 1
834 that = 2
835 theother = 3
836 self.assertEqual(repr(MyIntEnum.that), "My name is that.")
837
838 def test_multiple_mixin_mro(self):
839 class auto_enum(type(Enum)):
840 def __new__(metacls, cls, bases, classdict):
841 temp = type(classdict)()
842 names = set(classdict._member_names)
843 i = 0
844 for k in classdict._member_names:
845 v = classdict[k]
846 if v is Ellipsis:
847 v = i
848 else:
849 i = v
850 i += 1
851 temp[k] = v
852 for k, v in classdict.items():
853 if k not in names:
854 temp[k] = v
855 return super(auto_enum, metacls).__new__(
856 metacls, cls, bases, temp)
857
858 class AutoNumberedEnum(Enum, metaclass=auto_enum):
859 pass
860
861 class AutoIntEnum(IntEnum, metaclass=auto_enum):
862 pass
863
864 class TestAutoNumber(AutoNumberedEnum):
865 a = ...
866 b = 3
867 c = ...
868
869 class TestAutoInt(AutoIntEnum):
870 a = ...
871 b = 3
872 c = ...
873
874 def test_subclasses_with_getnewargs(self):
875 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800876 __qualname__ = 'NamedInt' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700877 def __new__(cls, *args):
878 _args = args
879 name, *args = args
880 if len(args) == 0:
881 raise TypeError("name and value must be specified")
882 self = int.__new__(cls, *args)
883 self._intname = name
884 self._args = _args
885 return self
886 def __getnewargs__(self):
887 return self._args
888 @property
889 def __name__(self):
890 return self._intname
891 def __repr__(self):
892 # repr() is updated to include the name and type info
893 return "{}({!r}, {})".format(type(self).__name__,
894 self.__name__,
895 int.__repr__(self))
896 def __str__(self):
897 # str() is unchanged, even if it relies on the repr() fallback
898 base = int
899 base_str = base.__str__
900 if base_str.__objclass__ is object:
901 return base.__repr__(self)
902 return base_str(self)
903 # for simplicity, we only define one operator that
904 # propagates expressions
905 def __add__(self, other):
906 temp = int(self) + int( other)
907 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
908 return NamedInt(
909 '({0} + {1})'.format(self.__name__, other.__name__),
910 temp )
911 else:
912 return temp
913
914 class NEI(NamedInt, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800915 __qualname__ = 'NEI' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700916 x = ('the-x', 1)
917 y = ('the-y', 2)
918
Ethan Furman2aa27322013-07-19 19:35:56 -0700919
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700920 self.assertIs(NEI.__new__, Enum.__new__)
921 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
922 globals()['NamedInt'] = NamedInt
923 globals()['NEI'] = NEI
924 NI5 = NamedInt('test', 5)
925 self.assertEqual(NI5, 5)
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800926 test_pickle_dump_load(self.assertEqual, NI5, 5)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700927 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800928 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700929
930 def test_subclasses_without_getnewargs(self):
931 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800932 __qualname__ = 'NamedInt'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700933 def __new__(cls, *args):
934 _args = args
935 name, *args = args
936 if len(args) == 0:
937 raise TypeError("name and value must be specified")
938 self = int.__new__(cls, *args)
939 self._intname = name
940 self._args = _args
941 return self
942 @property
943 def __name__(self):
944 return self._intname
945 def __repr__(self):
946 # repr() is updated to include the name and type info
947 return "{}({!r}, {})".format(type(self).__name__,
948 self.__name__,
949 int.__repr__(self))
950 def __str__(self):
951 # str() is unchanged, even if it relies on the repr() fallback
952 base = int
953 base_str = base.__str__
954 if base_str.__objclass__ is object:
955 return base.__repr__(self)
956 return base_str(self)
957 # for simplicity, we only define one operator that
958 # propagates expressions
959 def __add__(self, other):
960 temp = int(self) + int( other)
961 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
962 return NamedInt(
963 '({0} + {1})'.format(self.__name__, other.__name__),
964 temp )
965 else:
966 return temp
967
968 class NEI(NamedInt, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800969 __qualname__ = 'NEI'
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700970 x = ('the-x', 1)
971 y = ('the-y', 2)
972
973 self.assertIs(NEI.__new__, Enum.__new__)
974 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
975 globals()['NamedInt'] = NamedInt
976 globals()['NEI'] = NEI
977 NI5 = NamedInt('test', 5)
978 self.assertEqual(NI5, 5)
979 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800980 test_pickle_exception(self.assertRaises, TypeError, NEI.x)
981 test_pickle_exception(self.assertRaises, PicklingError, NEI)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700982
983 def test_tuple_subclass(self):
984 class SomeTuple(tuple, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800985 __qualname__ = 'SomeTuple' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700986 first = (1, 'for the money')
987 second = (2, 'for the show')
988 third = (3, 'for the music')
989 self.assertIs(type(SomeTuple.first), SomeTuple)
990 self.assertIsInstance(SomeTuple.second, tuple)
991 self.assertEqual(SomeTuple.third, (3, 'for the music'))
992 globals()['SomeTuple'] = SomeTuple
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800993 test_pickle_dump_load(self.assertIs, SomeTuple.first)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700994
995 def test_duplicate_values_give_unique_enum_items(self):
996 class AutoNumber(Enum):
997 first = ()
998 second = ()
999 third = ()
1000 def __new__(cls):
1001 value = len(cls.__members__) + 1
1002 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001003 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001004 return obj
1005 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001006 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001007 self.assertEqual(
1008 list(AutoNumber),
1009 [AutoNumber.first, AutoNumber.second, AutoNumber.third],
1010 )
1011 self.assertEqual(int(AutoNumber.second), 2)
Ethan Furman2aa27322013-07-19 19:35:56 -07001012 self.assertEqual(AutoNumber.third.value, 3)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001013 self.assertIs(AutoNumber(1), AutoNumber.first)
1014
1015 def test_inherited_new_from_enhanced_enum(self):
1016 class AutoNumber(Enum):
1017 def __new__(cls):
1018 value = len(cls.__members__) + 1
1019 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001020 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001021 return obj
1022 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001023 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001024 class Color(AutoNumber):
1025 red = ()
1026 green = ()
1027 blue = ()
1028 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1029 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1030
1031 def test_inherited_new_from_mixed_enum(self):
1032 class AutoNumber(IntEnum):
1033 def __new__(cls):
1034 value = len(cls.__members__) + 1
1035 obj = int.__new__(cls, value)
Ethan Furman520ad572013-07-19 19:47:21 -07001036 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001037 return obj
1038 class Color(AutoNumber):
1039 red = ()
1040 green = ()
1041 blue = ()
1042 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1043 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1044
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001045 def test_equality(self):
1046 class AlwaysEqual:
1047 def __eq__(self, other):
1048 return True
1049 class OrdinaryEnum(Enum):
1050 a = 1
1051 self.assertEqual(AlwaysEqual(), OrdinaryEnum.a)
1052 self.assertEqual(OrdinaryEnum.a, AlwaysEqual())
1053
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001054 def test_ordered_mixin(self):
1055 class OrderedEnum(Enum):
1056 def __ge__(self, other):
1057 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001058 return self._value_ >= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001059 return NotImplemented
1060 def __gt__(self, other):
1061 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001062 return self._value_ > other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001063 return NotImplemented
1064 def __le__(self, other):
1065 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001066 return self._value_ <= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001067 return NotImplemented
1068 def __lt__(self, other):
1069 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001070 return self._value_ < other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001071 return NotImplemented
1072 class Grade(OrderedEnum):
1073 A = 5
1074 B = 4
1075 C = 3
1076 D = 2
1077 F = 1
1078 self.assertGreater(Grade.A, Grade.B)
1079 self.assertLessEqual(Grade.F, Grade.C)
1080 self.assertLess(Grade.D, Grade.A)
1081 self.assertGreaterEqual(Grade.B, Grade.B)
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001082 self.assertEqual(Grade.B, Grade.B)
1083 self.assertNotEqual(Grade.C, Grade.D)
Ethan Furman520ad572013-07-19 19:47:21 -07001084
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001085 def test_extending2(self):
1086 class Shade(Enum):
1087 def shade(self):
1088 print(self.name)
1089 class Color(Shade):
1090 red = 1
1091 green = 2
1092 blue = 3
1093 with self.assertRaises(TypeError):
1094 class MoreColor(Color):
1095 cyan = 4
1096 magenta = 5
1097 yellow = 6
1098
1099 def test_extending3(self):
1100 class Shade(Enum):
1101 def shade(self):
1102 return self.name
1103 class Color(Shade):
1104 def hex(self):
1105 return '%s hexlified!' % self.value
1106 class MoreColor(Color):
1107 cyan = 4
1108 magenta = 5
1109 yellow = 6
1110 self.assertEqual(MoreColor.magenta.hex(), '5 hexlified!')
1111
1112
1113 def test_no_duplicates(self):
1114 class UniqueEnum(Enum):
1115 def __init__(self, *args):
1116 cls = self.__class__
1117 if any(self.value == e.value for e in cls):
1118 a = self.name
1119 e = cls(self.value).name
1120 raise ValueError(
1121 "aliases not allowed in UniqueEnum: %r --> %r"
1122 % (a, e)
1123 )
1124 class Color(UniqueEnum):
1125 red = 1
1126 green = 2
1127 blue = 3
1128 with self.assertRaises(ValueError):
1129 class Color(UniqueEnum):
1130 red = 1
1131 green = 2
1132 blue = 3
1133 grene = 2
1134
1135 def test_init(self):
1136 class Planet(Enum):
1137 MERCURY = (3.303e+23, 2.4397e6)
1138 VENUS = (4.869e+24, 6.0518e6)
1139 EARTH = (5.976e+24, 6.37814e6)
1140 MARS = (6.421e+23, 3.3972e6)
1141 JUPITER = (1.9e+27, 7.1492e7)
1142 SATURN = (5.688e+26, 6.0268e7)
1143 URANUS = (8.686e+25, 2.5559e7)
1144 NEPTUNE = (1.024e+26, 2.4746e7)
1145 def __init__(self, mass, radius):
1146 self.mass = mass # in kilograms
1147 self.radius = radius # in meters
1148 @property
1149 def surface_gravity(self):
1150 # universal gravitational constant (m3 kg-1 s-2)
1151 G = 6.67300E-11
1152 return G * self.mass / (self.radius * self.radius)
1153 self.assertEqual(round(Planet.EARTH.surface_gravity, 2), 9.80)
1154 self.assertEqual(Planet.EARTH.value, (5.976e+24, 6.37814e6))
1155
Ethan Furman2aa27322013-07-19 19:35:56 -07001156 def test_nonhash_value(self):
1157 class AutoNumberInAList(Enum):
1158 def __new__(cls):
1159 value = [len(cls.__members__) + 1]
1160 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001161 obj._value_ = value
Ethan Furman2aa27322013-07-19 19:35:56 -07001162 return obj
1163 class ColorInAList(AutoNumberInAList):
1164 red = ()
1165 green = ()
1166 blue = ()
1167 self.assertEqual(list(ColorInAList), [ColorInAList.red, ColorInAList.green, ColorInAList.blue])
Ethan Furman1a162882013-10-16 19:09:31 -07001168 for enum, value in zip(ColorInAList, range(3)):
1169 value += 1
1170 self.assertEqual(enum.value, [value])
1171 self.assertIs(ColorInAList([value]), enum)
Ethan Furman2aa27322013-07-19 19:35:56 -07001172
Ethan Furmanb41803e2013-07-25 13:50:45 -07001173 def test_conflicting_types_resolved_in_new(self):
1174 class LabelledIntEnum(int, Enum):
1175 def __new__(cls, *args):
1176 value, label = args
1177 obj = int.__new__(cls, value)
1178 obj.label = label
1179 obj._value_ = value
1180 return obj
1181
1182 class LabelledList(LabelledIntEnum):
1183 unprocessed = (1, "Unprocessed")
1184 payment_complete = (2, "Payment Complete")
1185
1186 self.assertEqual(list(LabelledList), [LabelledList.unprocessed, LabelledList.payment_complete])
1187 self.assertEqual(LabelledList.unprocessed, 1)
1188 self.assertEqual(LabelledList(1), LabelledList.unprocessed)
Ethan Furman2aa27322013-07-19 19:35:56 -07001189
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001190
Ethan Furmanf24bb352013-07-18 17:05:39 -07001191class TestUnique(unittest.TestCase):
1192
1193 def test_unique_clean(self):
1194 @unique
1195 class Clean(Enum):
1196 one = 1
1197 two = 'dos'
1198 tres = 4.0
1199 @unique
1200 class Cleaner(IntEnum):
1201 single = 1
1202 double = 2
1203 triple = 3
1204
1205 def test_unique_dirty(self):
1206 with self.assertRaisesRegex(ValueError, 'tres.*one'):
1207 @unique
1208 class Dirty(Enum):
1209 one = 1
1210 two = 'dos'
1211 tres = 1
1212 with self.assertRaisesRegex(
1213 ValueError,
1214 'double.*single.*turkey.*triple',
1215 ):
1216 @unique
1217 class Dirtier(IntEnum):
1218 single = 1
1219 double = 1
1220 triple = 3
1221 turkey = 3
1222
1223
Ethan Furman5875d742013-10-21 20:45:55 -07001224expected_help_output = """
1225Help on class Color in module %s:
1226
1227class Color(enum.Enum)
1228 | Method resolution order:
1229 | Color
1230 | enum.Enum
1231 | builtins.object
1232 |\x20\x20
1233 | Data and other attributes defined here:
1234 |\x20\x20
1235 | blue = <Color.blue: 3>
1236 |\x20\x20
1237 | green = <Color.green: 2>
1238 |\x20\x20
1239 | red = <Color.red: 1>
1240 |\x20\x20
1241 | ----------------------------------------------------------------------
1242 | Data descriptors inherited from enum.Enum:
1243 |\x20\x20
1244 | name
1245 | The name of the Enum member.
1246 |\x20\x20
1247 | value
1248 | The value of the Enum member.
1249 |\x20\x20
1250 | ----------------------------------------------------------------------
1251 | Data descriptors inherited from enum.EnumMeta:
1252 |\x20\x20
1253 | __members__
1254 | Returns a mapping of member name->value.
1255 |\x20\x20\x20\x20\x20\x20
1256 | This mapping lists all enum members, including aliases. Note that this
1257 | is a read-only view of the internal mapping.
1258""".strip()
1259
1260class TestStdLib(unittest.TestCase):
1261
1262 class Color(Enum):
1263 red = 1
1264 green = 2
1265 blue = 3
1266
1267 def test_pydoc(self):
1268 # indirectly test __objclass__
1269 expected_text = expected_help_output % __name__
1270 output = StringIO()
1271 helper = pydoc.Helper(output=output)
1272 helper(self.Color)
1273 result = output.getvalue().strip()
1274 if result != expected_text:
1275 print_diffs(expected_text, result)
1276 self.fail("outputs are not equal, see diff above")
1277
1278 def test_inspect_getmembers(self):
1279 values = dict((
1280 ('__class__', EnumMeta),
1281 ('__doc__', None),
1282 ('__members__', self.Color.__members__),
1283 ('__module__', __name__),
1284 ('blue', self.Color.blue),
1285 ('green', self.Color.green),
1286 ('name', Enum.__dict__['name']),
1287 ('red', self.Color.red),
1288 ('value', Enum.__dict__['value']),
1289 ))
1290 result = dict(inspect.getmembers(self.Color))
1291 self.assertEqual(values.keys(), result.keys())
1292 failed = False
1293 for k in values.keys():
1294 if result[k] != values[k]:
1295 print()
1296 print('\n%s\n key: %s\n result: %s\nexpected: %s\n%s\n' %
1297 ('=' * 75, k, result[k], values[k], '=' * 75), sep='')
1298 failed = True
1299 if failed:
1300 self.fail("result does not equal expected, see print above")
1301
1302 def test_inspect_classify_class_attrs(self):
1303 # indirectly test __objclass__
1304 from inspect import Attribute
1305 values = [
1306 Attribute(name='__class__', kind='data',
1307 defining_class=object, object=EnumMeta),
1308 Attribute(name='__doc__', kind='data',
1309 defining_class=self.Color, object=None),
1310 Attribute(name='__members__', kind='property',
1311 defining_class=EnumMeta, object=EnumMeta.__members__),
1312 Attribute(name='__module__', kind='data',
1313 defining_class=self.Color, object=__name__),
1314 Attribute(name='blue', kind='data',
1315 defining_class=self.Color, object=self.Color.blue),
1316 Attribute(name='green', kind='data',
1317 defining_class=self.Color, object=self.Color.green),
1318 Attribute(name='red', kind='data',
1319 defining_class=self.Color, object=self.Color.red),
1320 Attribute(name='name', kind='data',
1321 defining_class=Enum, object=Enum.__dict__['name']),
1322 Attribute(name='value', kind='data',
1323 defining_class=Enum, object=Enum.__dict__['value']),
1324 ]
1325 values.sort(key=lambda item: item.name)
1326 result = list(inspect.classify_class_attrs(self.Color))
1327 result.sort(key=lambda item: item.name)
1328 failed = False
1329 for v, r in zip(values, result):
1330 if r != v:
1331 print('\n%s\n%s\n%s\n%s\n' % ('=' * 75, r, v, '=' * 75), sep='')
1332 failed = True
1333 if failed:
1334 self.fail("result does not equal expected, see print above")
1335
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001336if __name__ == '__main__':
1337 unittest.main()