blob: e5e0ec02d0f77c550fd4c9e5ce23fcb15e662bd2 [file] [log] [blame]
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001import enum
Ethan Furman5875d742013-10-21 20:45:55 -07002import inspect
3import pydoc
Ethan Furman6b3d64a2013-06-14 16:55:46 -07004import unittest
5from collections import OrderedDict
Ethan Furman5875d742013-10-21 20:45:55 -07006from enum import Enum, IntEnum, EnumMeta, unique
7from io import StringIO
Ethan Furman2ddb39a2014-02-06 17:28:50 -08008from pickle import dumps, loads, PicklingError, HIGHEST_PROTOCOL
Martin Panter19e69c52015-11-14 12:46:42 +00009from test import support
Ethan Furman6b3d64a2013-06-14 16:55:46 -070010
11# for pickle tests
12try:
13 class Stooges(Enum):
14 LARRY = 1
15 CURLY = 2
16 MOE = 3
17except Exception as exc:
18 Stooges = exc
19
20try:
21 class IntStooges(int, Enum):
22 LARRY = 1
23 CURLY = 2
24 MOE = 3
25except Exception as exc:
26 IntStooges = exc
27
28try:
29 class FloatStooges(float, Enum):
30 LARRY = 1.39
31 CURLY = 2.72
32 MOE = 3.142596
33except Exception as exc:
34 FloatStooges = exc
35
36# for pickle test and subclass tests
37try:
38 class StrEnum(str, Enum):
39 'accepts only string values'
40 class Name(StrEnum):
41 BDFL = 'Guido van Rossum'
42 FLUFL = 'Barry Warsaw'
43except Exception as exc:
44 Name = exc
45
46try:
47 Question = Enum('Question', 'who what when where why', module=__name__)
48except Exception as exc:
49 Question = exc
50
51try:
52 Answer = Enum('Answer', 'him this then there because')
53except Exception as exc:
54 Answer = exc
55
Ethan Furmanca1b7942014-02-08 11:36:27 -080056try:
57 Theory = Enum('Theory', 'rule law supposition', qualname='spanish_inquisition')
58except Exception as exc:
59 Theory = exc
60
Ethan Furman6b3d64a2013-06-14 16:55:46 -070061# for doctests
62try:
63 class Fruit(Enum):
64 tomato = 1
65 banana = 2
66 cherry = 3
67except Exception:
68 pass
69
Serhiy Storchakae50e7802015-03-31 16:56:49 +030070def test_pickle_dump_load(assertion, source, target=None):
Ethan Furman2ddb39a2014-02-06 17:28:50 -080071 if target is None:
72 target = source
Serhiy Storchakae50e7802015-03-31 16:56:49 +030073 for protocol in range(HIGHEST_PROTOCOL + 1):
Ethan Furman2ddb39a2014-02-06 17:28:50 -080074 assertion(loads(dumps(source, protocol=protocol)), target)
75
Serhiy Storchakae50e7802015-03-31 16:56:49 +030076def test_pickle_exception(assertion, exception, obj):
77 for protocol in range(HIGHEST_PROTOCOL + 1):
Ethan Furman2ddb39a2014-02-06 17:28:50 -080078 with assertion(exception):
79 dumps(obj, protocol=protocol)
Ethan Furman648f8602013-10-06 17:19:54 -070080
81class TestHelpers(unittest.TestCase):
82 # _is_descriptor, _is_sunder, _is_dunder
83
84 def test_is_descriptor(self):
85 class foo:
86 pass
87 for attr in ('__get__','__set__','__delete__'):
88 obj = foo()
89 self.assertFalse(enum._is_descriptor(obj))
90 setattr(obj, attr, 1)
91 self.assertTrue(enum._is_descriptor(obj))
92
93 def test_is_sunder(self):
94 for s in ('_a_', '_aa_'):
95 self.assertTrue(enum._is_sunder(s))
96
97 for s in ('a', 'a_', '_a', '__a', 'a__', '__a__', '_a__', '__a_', '_',
98 '__', '___', '____', '_____',):
99 self.assertFalse(enum._is_sunder(s))
100
101 def test_is_dunder(self):
102 for s in ('__a__', '__aa__'):
103 self.assertTrue(enum._is_dunder(s))
104 for s in ('a', 'a_', '_a', '__a', 'a__', '_a_', '_a__', '__a_', '_',
105 '__', '___', '____', '_____',):
106 self.assertFalse(enum._is_dunder(s))
107
108
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700109class TestEnum(unittest.TestCase):
Ethan Furmanca1b7942014-02-08 11:36:27 -0800110
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700111 def setUp(self):
112 class Season(Enum):
113 SPRING = 1
114 SUMMER = 2
115 AUTUMN = 3
116 WINTER = 4
117 self.Season = Season
118
Ethan Furmanec15a822013-08-31 19:17:41 -0700119 class Konstants(float, Enum):
120 E = 2.7182818
121 PI = 3.1415926
122 TAU = 2 * PI
123 self.Konstants = Konstants
124
125 class Grades(IntEnum):
126 A = 5
127 B = 4
128 C = 3
129 D = 2
130 F = 0
131 self.Grades = Grades
132
133 class Directional(str, Enum):
134 EAST = 'east'
135 WEST = 'west'
136 NORTH = 'north'
137 SOUTH = 'south'
138 self.Directional = Directional
139
140 from datetime import date
141 class Holiday(date, Enum):
142 NEW_YEAR = 2013, 1, 1
143 IDES_OF_MARCH = 2013, 3, 15
144 self.Holiday = Holiday
145
Ethan Furman388a3922013-08-12 06:51:41 -0700146 def test_dir_on_class(self):
147 Season = self.Season
148 self.assertEqual(
149 set(dir(Season)),
Ethan Furmanc850f342013-09-15 16:59:35 -0700150 set(['__class__', '__doc__', '__members__', '__module__',
Ethan Furman388a3922013-08-12 06:51:41 -0700151 'SPRING', 'SUMMER', 'AUTUMN', 'WINTER']),
152 )
153
154 def test_dir_on_item(self):
155 Season = self.Season
156 self.assertEqual(
157 set(dir(Season.WINTER)),
Ethan Furmanc850f342013-09-15 16:59:35 -0700158 set(['__class__', '__doc__', '__module__', 'name', 'value']),
Ethan Furman388a3922013-08-12 06:51:41 -0700159 )
160
Ethan Furmanc850f342013-09-15 16:59:35 -0700161 def test_dir_with_added_behavior(self):
162 class Test(Enum):
163 this = 'that'
164 these = 'those'
165 def wowser(self):
166 return ("Wowser! I'm %s!" % self.name)
167 self.assertEqual(
168 set(dir(Test)),
169 set(['__class__', '__doc__', '__members__', '__module__', 'this', 'these']),
170 )
171 self.assertEqual(
172 set(dir(Test.this)),
173 set(['__class__', '__doc__', '__module__', 'name', 'value', 'wowser']),
174 )
175
Ethan Furman0ae550b2014-10-14 08:58:32 -0700176 def test_dir_on_sub_with_behavior_on_super(self):
177 # see issue22506
178 class SuperEnum(Enum):
179 def invisible(self):
180 return "did you see me?"
181 class SubEnum(SuperEnum):
182 sample = 5
183 self.assertEqual(
184 set(dir(SubEnum.sample)),
185 set(['__class__', '__doc__', '__module__', 'name', 'value', 'invisible']),
186 )
187
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700188 def test_enum_in_enum_out(self):
189 Season = self.Season
190 self.assertIs(Season(Season.WINTER), Season.WINTER)
191
192 def test_enum_value(self):
193 Season = self.Season
194 self.assertEqual(Season.SPRING.value, 1)
195
196 def test_intenum_value(self):
197 self.assertEqual(IntStooges.CURLY.value, 2)
198
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700199 def test_enum(self):
200 Season = self.Season
201 lst = list(Season)
202 self.assertEqual(len(lst), len(Season))
203 self.assertEqual(len(Season), 4, Season)
204 self.assertEqual(
205 [Season.SPRING, Season.SUMMER, Season.AUTUMN, Season.WINTER], lst)
206
207 for i, season in enumerate('SPRING SUMMER AUTUMN WINTER'.split(), 1):
208 e = Season(i)
209 self.assertEqual(e, getattr(Season, season))
210 self.assertEqual(e.value, i)
211 self.assertNotEqual(e, i)
212 self.assertEqual(e.name, season)
213 self.assertIn(e, Season)
214 self.assertIs(type(e), Season)
215 self.assertIsInstance(e, Season)
216 self.assertEqual(str(e), 'Season.' + season)
217 self.assertEqual(
218 repr(e),
219 '<Season.{0}: {1}>'.format(season, i),
220 )
221
222 def test_value_name(self):
223 Season = self.Season
224 self.assertEqual(Season.SPRING.name, 'SPRING')
225 self.assertEqual(Season.SPRING.value, 1)
226 with self.assertRaises(AttributeError):
227 Season.SPRING.name = 'invierno'
228 with self.assertRaises(AttributeError):
229 Season.SPRING.value = 2
230
Ethan Furmanf203f2d2013-09-06 07:16:48 -0700231 def test_changing_member(self):
232 Season = self.Season
233 with self.assertRaises(AttributeError):
234 Season.WINTER = 'really cold'
235
Ethan Furman64a99722013-09-22 16:18:19 -0700236 def test_attribute_deletion(self):
237 class Season(Enum):
238 SPRING = 1
239 SUMMER = 2
240 AUTUMN = 3
241 WINTER = 4
242
243 def spam(cls):
244 pass
245
246 self.assertTrue(hasattr(Season, 'spam'))
247 del Season.spam
248 self.assertFalse(hasattr(Season, 'spam'))
249
250 with self.assertRaises(AttributeError):
251 del Season.SPRING
252 with self.assertRaises(AttributeError):
253 del Season.DRY
254 with self.assertRaises(AttributeError):
255 del Season.SPRING.name
256
Ethan Furman5de67b12016-04-13 23:52:09 -0700257 def test_bool_of_class(self):
258 class Empty(Enum):
259 pass
260 self.assertTrue(bool(Empty))
261
262 def test_bool_of_member(self):
263 class Count(Enum):
264 zero = 0
265 one = 1
266 two = 2
267 for member in Count:
268 self.assertTrue(bool(member))
269
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700270 def test_invalid_names(self):
271 with self.assertRaises(ValueError):
272 class Wrong(Enum):
273 mro = 9
274 with self.assertRaises(ValueError):
275 class Wrong(Enum):
276 _create_= 11
277 with self.assertRaises(ValueError):
278 class Wrong(Enum):
279 _get_mixins_ = 9
280 with self.assertRaises(ValueError):
281 class Wrong(Enum):
282 _find_new_ = 1
283 with self.assertRaises(ValueError):
284 class Wrong(Enum):
285 _any_name_ = 9
286
Ethan Furman6db1fd52015-09-17 21:49:12 -0700287 def test_bool(self):
Ethan Furman60255b62016-01-15 15:01:33 -0800288 # plain Enum members are always True
Ethan Furman6db1fd52015-09-17 21:49:12 -0700289 class Logic(Enum):
290 true = True
291 false = False
292 self.assertTrue(Logic.true)
Ethan Furman60255b62016-01-15 15:01:33 -0800293 self.assertTrue(Logic.false)
294 # unless overridden
295 class RealLogic(Enum):
296 true = True
297 false = False
298 def __bool__(self):
299 return bool(self._value_)
300 self.assertTrue(RealLogic.true)
301 self.assertFalse(RealLogic.false)
302 # mixed Enums depend on mixed-in type
303 class IntLogic(int, Enum):
304 true = 1
305 false = 0
306 self.assertTrue(IntLogic.true)
307 self.assertFalse(IntLogic.false)
Ethan Furman6db1fd52015-09-17 21:49:12 -0700308
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700309 def test_contains(self):
310 Season = self.Season
311 self.assertIn(Season.AUTUMN, Season)
312 self.assertNotIn(3, Season)
313
314 val = Season(3)
315 self.assertIn(val, Season)
316
317 class OtherEnum(Enum):
318 one = 1; two = 2
319 self.assertNotIn(OtherEnum.two, Season)
320
321 def test_comparisons(self):
322 Season = self.Season
323 with self.assertRaises(TypeError):
324 Season.SPRING < Season.WINTER
325 with self.assertRaises(TypeError):
326 Season.SPRING > 4
327
328 self.assertNotEqual(Season.SPRING, 1)
329
330 class Part(Enum):
331 SPRING = 1
332 CLIP = 2
333 BARREL = 3
334
335 self.assertNotEqual(Season.SPRING, Part.SPRING)
336 with self.assertRaises(TypeError):
337 Season.SPRING < Part.CLIP
338
339 def test_enum_duplicates(self):
340 class Season(Enum):
341 SPRING = 1
342 SUMMER = 2
343 AUTUMN = FALL = 3
344 WINTER = 4
345 ANOTHER_SPRING = 1
346 lst = list(Season)
347 self.assertEqual(
348 lst,
349 [Season.SPRING, Season.SUMMER,
350 Season.AUTUMN, Season.WINTER,
351 ])
352 self.assertIs(Season.FALL, Season.AUTUMN)
353 self.assertEqual(Season.FALL.value, 3)
354 self.assertEqual(Season.AUTUMN.value, 3)
355 self.assertIs(Season(3), Season.AUTUMN)
356 self.assertIs(Season(1), Season.SPRING)
357 self.assertEqual(Season.FALL.name, 'AUTUMN')
358 self.assertEqual(
359 [k for k,v in Season.__members__.items() if v.name != k],
360 ['FALL', 'ANOTHER_SPRING'],
361 )
362
Ethan Furman101e0742013-09-15 12:34:36 -0700363 def test_duplicate_name(self):
364 with self.assertRaises(TypeError):
365 class Color(Enum):
366 red = 1
367 green = 2
368 blue = 3
369 red = 4
370
371 with self.assertRaises(TypeError):
372 class Color(Enum):
373 red = 1
374 green = 2
375 blue = 3
376 def red(self):
377 return 'red'
378
379 with self.assertRaises(TypeError):
380 class Color(Enum):
381 @property
382 def red(self):
383 return 'redder'
384 red = 1
385 green = 2
386 blue = 3
387
388
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700389 def test_enum_with_value_name(self):
390 class Huh(Enum):
391 name = 1
392 value = 2
393 self.assertEqual(
394 list(Huh),
395 [Huh.name, Huh.value],
396 )
397 self.assertIs(type(Huh.name), Huh)
398 self.assertEqual(Huh.name.name, 'name')
399 self.assertEqual(Huh.name.value, 1)
Ethan Furmanec15a822013-08-31 19:17:41 -0700400
401 def test_format_enum(self):
402 Season = self.Season
403 self.assertEqual('{}'.format(Season.SPRING),
404 '{}'.format(str(Season.SPRING)))
405 self.assertEqual( '{:}'.format(Season.SPRING),
406 '{:}'.format(str(Season.SPRING)))
407 self.assertEqual('{:20}'.format(Season.SPRING),
408 '{:20}'.format(str(Season.SPRING)))
409 self.assertEqual('{:^20}'.format(Season.SPRING),
410 '{:^20}'.format(str(Season.SPRING)))
411 self.assertEqual('{:>20}'.format(Season.SPRING),
412 '{:>20}'.format(str(Season.SPRING)))
413 self.assertEqual('{:<20}'.format(Season.SPRING),
414 '{:<20}'.format(str(Season.SPRING)))
415
416 def test_format_enum_custom(self):
417 class TestFloat(float, Enum):
418 one = 1.0
419 two = 2.0
420 def __format__(self, spec):
421 return 'TestFloat success!'
422 self.assertEqual('{}'.format(TestFloat.one), 'TestFloat success!')
423
424 def assertFormatIsValue(self, spec, member):
425 self.assertEqual(spec.format(member), spec.format(member.value))
426
427 def test_format_enum_date(self):
428 Holiday = self.Holiday
429 self.assertFormatIsValue('{}', Holiday.IDES_OF_MARCH)
430 self.assertFormatIsValue('{:}', Holiday.IDES_OF_MARCH)
431 self.assertFormatIsValue('{:20}', Holiday.IDES_OF_MARCH)
432 self.assertFormatIsValue('{:^20}', Holiday.IDES_OF_MARCH)
433 self.assertFormatIsValue('{:>20}', Holiday.IDES_OF_MARCH)
434 self.assertFormatIsValue('{:<20}', Holiday.IDES_OF_MARCH)
435 self.assertFormatIsValue('{:%Y %m}', Holiday.IDES_OF_MARCH)
436 self.assertFormatIsValue('{:%Y %m %M:00}', Holiday.IDES_OF_MARCH)
437
438 def test_format_enum_float(self):
439 Konstants = self.Konstants
440 self.assertFormatIsValue('{}', Konstants.TAU)
441 self.assertFormatIsValue('{:}', Konstants.TAU)
442 self.assertFormatIsValue('{:20}', Konstants.TAU)
443 self.assertFormatIsValue('{:^20}', Konstants.TAU)
444 self.assertFormatIsValue('{:>20}', Konstants.TAU)
445 self.assertFormatIsValue('{:<20}', Konstants.TAU)
446 self.assertFormatIsValue('{:n}', Konstants.TAU)
447 self.assertFormatIsValue('{:5.2}', Konstants.TAU)
448 self.assertFormatIsValue('{:f}', Konstants.TAU)
449
450 def test_format_enum_int(self):
451 Grades = self.Grades
452 self.assertFormatIsValue('{}', Grades.C)
453 self.assertFormatIsValue('{:}', Grades.C)
454 self.assertFormatIsValue('{:20}', Grades.C)
455 self.assertFormatIsValue('{:^20}', Grades.C)
456 self.assertFormatIsValue('{:>20}', Grades.C)
457 self.assertFormatIsValue('{:<20}', Grades.C)
458 self.assertFormatIsValue('{:+}', Grades.C)
459 self.assertFormatIsValue('{:08X}', Grades.C)
460 self.assertFormatIsValue('{:b}', Grades.C)
461
462 def test_format_enum_str(self):
463 Directional = self.Directional
464 self.assertFormatIsValue('{}', Directional.WEST)
465 self.assertFormatIsValue('{:}', Directional.WEST)
466 self.assertFormatIsValue('{:20}', Directional.WEST)
467 self.assertFormatIsValue('{:^20}', Directional.WEST)
468 self.assertFormatIsValue('{:>20}', Directional.WEST)
469 self.assertFormatIsValue('{:<20}', Directional.WEST)
470
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700471 def test_hash(self):
472 Season = self.Season
473 dates = {}
474 dates[Season.WINTER] = '1225'
475 dates[Season.SPRING] = '0315'
476 dates[Season.SUMMER] = '0704'
477 dates[Season.AUTUMN] = '1031'
478 self.assertEqual(dates[Season.AUTUMN], '1031')
479
480 def test_intenum_from_scratch(self):
481 class phy(int, Enum):
482 pi = 3
483 tau = 2 * pi
484 self.assertTrue(phy.pi < phy.tau)
485
486 def test_intenum_inherited(self):
487 class IntEnum(int, Enum):
488 pass
489 class phy(IntEnum):
490 pi = 3
491 tau = 2 * pi
492 self.assertTrue(phy.pi < phy.tau)
493
494 def test_floatenum_from_scratch(self):
495 class phy(float, Enum):
Ethan Furmanec15a822013-08-31 19:17:41 -0700496 pi = 3.1415926
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700497 tau = 2 * pi
498 self.assertTrue(phy.pi < phy.tau)
499
500 def test_floatenum_inherited(self):
501 class FloatEnum(float, Enum):
502 pass
503 class phy(FloatEnum):
Ethan Furmanec15a822013-08-31 19:17:41 -0700504 pi = 3.1415926
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700505 tau = 2 * pi
506 self.assertTrue(phy.pi < phy.tau)
507
508 def test_strenum_from_scratch(self):
509 class phy(str, Enum):
510 pi = 'Pi'
511 tau = 'Tau'
512 self.assertTrue(phy.pi < phy.tau)
513
514 def test_strenum_inherited(self):
515 class StrEnum(str, Enum):
516 pass
517 class phy(StrEnum):
518 pi = 'Pi'
519 tau = 'Tau'
520 self.assertTrue(phy.pi < phy.tau)
521
522
523 def test_intenum(self):
524 class WeekDay(IntEnum):
525 SUNDAY = 1
526 MONDAY = 2
527 TUESDAY = 3
528 WEDNESDAY = 4
529 THURSDAY = 5
530 FRIDAY = 6
531 SATURDAY = 7
532
533 self.assertEqual(['a', 'b', 'c'][WeekDay.MONDAY], 'c')
534 self.assertEqual([i for i in range(WeekDay.TUESDAY)], [0, 1, 2])
535
536 lst = list(WeekDay)
537 self.assertEqual(len(lst), len(WeekDay))
538 self.assertEqual(len(WeekDay), 7)
539 target = 'SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY'
540 target = target.split()
541 for i, weekday in enumerate(target, 1):
542 e = WeekDay(i)
543 self.assertEqual(e, i)
544 self.assertEqual(int(e), i)
545 self.assertEqual(e.name, weekday)
546 self.assertIn(e, WeekDay)
547 self.assertEqual(lst.index(e)+1, i)
548 self.assertTrue(0 < e < 8)
549 self.assertIs(type(e), WeekDay)
550 self.assertIsInstance(e, int)
551 self.assertIsInstance(e, Enum)
552
553 def test_intenum_duplicates(self):
554 class WeekDay(IntEnum):
555 SUNDAY = 1
556 MONDAY = 2
557 TUESDAY = TEUSDAY = 3
558 WEDNESDAY = 4
559 THURSDAY = 5
560 FRIDAY = 6
561 SATURDAY = 7
562 self.assertIs(WeekDay.TEUSDAY, WeekDay.TUESDAY)
563 self.assertEqual(WeekDay(3).name, 'TUESDAY')
564 self.assertEqual([k for k,v in WeekDay.__members__.items()
565 if v.name != k], ['TEUSDAY', ])
566
567 def test_pickle_enum(self):
568 if isinstance(Stooges, Exception):
569 raise Stooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800570 test_pickle_dump_load(self.assertIs, Stooges.CURLY)
571 test_pickle_dump_load(self.assertIs, Stooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700572
573 def test_pickle_int(self):
574 if isinstance(IntStooges, Exception):
575 raise IntStooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800576 test_pickle_dump_load(self.assertIs, IntStooges.CURLY)
577 test_pickle_dump_load(self.assertIs, IntStooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700578
579 def test_pickle_float(self):
580 if isinstance(FloatStooges, Exception):
581 raise FloatStooges
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800582 test_pickle_dump_load(self.assertIs, FloatStooges.CURLY)
583 test_pickle_dump_load(self.assertIs, FloatStooges)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700584
585 def test_pickle_enum_function(self):
586 if isinstance(Answer, Exception):
587 raise Answer
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800588 test_pickle_dump_load(self.assertIs, Answer.him)
589 test_pickle_dump_load(self.assertIs, Answer)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700590
591 def test_pickle_enum_function_with_module(self):
592 if isinstance(Question, Exception):
593 raise Question
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800594 test_pickle_dump_load(self.assertIs, Question.who)
595 test_pickle_dump_load(self.assertIs, Question)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700596
Ethan Furmanca1b7942014-02-08 11:36:27 -0800597 def test_enum_function_with_qualname(self):
598 if isinstance(Theory, Exception):
599 raise Theory
600 self.assertEqual(Theory.__qualname__, 'spanish_inquisition')
601
602 def test_class_nested_enum_and_pickle_protocol_four(self):
603 # would normally just have this directly in the class namespace
604 class NestedEnum(Enum):
605 twigs = 'common'
606 shiny = 'rare'
607
608 self.__class__.NestedEnum = NestedEnum
609 self.NestedEnum.__qualname__ = '%s.NestedEnum' % self.__class__.__name__
Serhiy Storchakae50e7802015-03-31 16:56:49 +0300610 test_pickle_dump_load(self.assertIs, self.NestedEnum.twigs)
Ethan Furmanca1b7942014-02-08 11:36:27 -0800611
Ethan Furman24e837f2015-03-18 17:27:57 -0700612 def test_pickle_by_name(self):
613 class ReplaceGlobalInt(IntEnum):
614 ONE = 1
615 TWO = 2
616 ReplaceGlobalInt.__reduce_ex__ = enum._reduce_ex_by_name
617 for proto in range(HIGHEST_PROTOCOL):
618 self.assertEqual(ReplaceGlobalInt.TWO.__reduce_ex__(proto), 'TWO')
619
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700620 def test_exploding_pickle(self):
Ethan Furmanca1b7942014-02-08 11:36:27 -0800621 BadPickle = Enum(
622 'BadPickle', 'dill sweet bread-n-butter', module=__name__)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700623 globals()['BadPickle'] = BadPickle
Ethan Furmanca1b7942014-02-08 11:36:27 -0800624 # now break BadPickle to test exception raising
625 enum._make_class_unpicklable(BadPickle)
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800626 test_pickle_exception(self.assertRaises, TypeError, BadPickle.dill)
627 test_pickle_exception(self.assertRaises, PicklingError, BadPickle)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700628
629 def test_string_enum(self):
630 class SkillLevel(str, Enum):
631 master = 'what is the sound of one hand clapping?'
632 journeyman = 'why did the chicken cross the road?'
633 apprentice = 'knock, knock!'
634 self.assertEqual(SkillLevel.apprentice, 'knock, knock!')
635
636 def test_getattr_getitem(self):
637 class Period(Enum):
638 morning = 1
639 noon = 2
640 evening = 3
641 night = 4
642 self.assertIs(Period(2), Period.noon)
643 self.assertIs(getattr(Period, 'night'), Period.night)
644 self.assertIs(Period['morning'], Period.morning)
645
646 def test_getattr_dunder(self):
647 Season = self.Season
648 self.assertTrue(getattr(Season, '__eq__'))
649
650 def test_iteration_order(self):
651 class Season(Enum):
652 SUMMER = 2
653 WINTER = 4
654 AUTUMN = 3
655 SPRING = 1
656 self.assertEqual(
657 list(Season),
658 [Season.SUMMER, Season.WINTER, Season.AUTUMN, Season.SPRING],
659 )
660
Ethan Furman2131a4a2013-09-14 18:11:24 -0700661 def test_reversed_iteration_order(self):
662 self.assertEqual(
663 list(reversed(self.Season)),
664 [self.Season.WINTER, self.Season.AUTUMN, self.Season.SUMMER,
665 self.Season.SPRING]
666 )
667
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700668 def test_programatic_function_string(self):
669 SummerMonth = Enum('SummerMonth', 'june july august')
670 lst = list(SummerMonth)
671 self.assertEqual(len(lst), len(SummerMonth))
672 self.assertEqual(len(SummerMonth), 3, SummerMonth)
673 self.assertEqual(
674 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
675 lst,
676 )
677 for i, month in enumerate('june july august'.split(), 1):
678 e = SummerMonth(i)
679 self.assertEqual(int(e.value), i)
680 self.assertNotEqual(e, i)
681 self.assertEqual(e.name, month)
682 self.assertIn(e, SummerMonth)
683 self.assertIs(type(e), SummerMonth)
684
Ethan Furmand9925a12014-09-16 20:35:55 -0700685 def test_programatic_function_string_with_start(self):
686 SummerMonth = Enum('SummerMonth', 'june july august', start=10)
687 lst = list(SummerMonth)
688 self.assertEqual(len(lst), len(SummerMonth))
689 self.assertEqual(len(SummerMonth), 3, SummerMonth)
690 self.assertEqual(
691 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
692 lst,
693 )
694 for i, month in enumerate('june july august'.split(), 10):
695 e = SummerMonth(i)
696 self.assertEqual(int(e.value), i)
697 self.assertNotEqual(e, i)
698 self.assertEqual(e.name, month)
699 self.assertIn(e, SummerMonth)
700 self.assertIs(type(e), SummerMonth)
701
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700702 def test_programatic_function_string_list(self):
703 SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'])
704 lst = list(SummerMonth)
705 self.assertEqual(len(lst), len(SummerMonth))
706 self.assertEqual(len(SummerMonth), 3, SummerMonth)
707 self.assertEqual(
708 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
709 lst,
710 )
711 for i, month in enumerate('june july august'.split(), 1):
712 e = SummerMonth(i)
713 self.assertEqual(int(e.value), i)
714 self.assertNotEqual(e, i)
715 self.assertEqual(e.name, month)
716 self.assertIn(e, SummerMonth)
717 self.assertIs(type(e), SummerMonth)
718
Ethan Furmand9925a12014-09-16 20:35:55 -0700719 def test_programatic_function_string_list_with_start(self):
720 SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'], start=20)
721 lst = list(SummerMonth)
722 self.assertEqual(len(lst), len(SummerMonth))
723 self.assertEqual(len(SummerMonth), 3, SummerMonth)
724 self.assertEqual(
725 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
726 lst,
727 )
728 for i, month in enumerate('june july august'.split(), 20):
729 e = SummerMonth(i)
730 self.assertEqual(int(e.value), i)
731 self.assertNotEqual(e, i)
732 self.assertEqual(e.name, month)
733 self.assertIn(e, SummerMonth)
734 self.assertIs(type(e), SummerMonth)
735
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700736 def test_programatic_function_iterable(self):
737 SummerMonth = Enum(
738 'SummerMonth',
739 (('june', 1), ('july', 2), ('august', 3))
740 )
741 lst = list(SummerMonth)
742 self.assertEqual(len(lst), len(SummerMonth))
743 self.assertEqual(len(SummerMonth), 3, SummerMonth)
744 self.assertEqual(
745 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
746 lst,
747 )
748 for i, month in enumerate('june july august'.split(), 1):
749 e = SummerMonth(i)
750 self.assertEqual(int(e.value), i)
751 self.assertNotEqual(e, i)
752 self.assertEqual(e.name, month)
753 self.assertIn(e, SummerMonth)
754 self.assertIs(type(e), SummerMonth)
755
756 def test_programatic_function_from_dict(self):
757 SummerMonth = Enum(
758 'SummerMonth',
759 OrderedDict((('june', 1), ('july', 2), ('august', 3)))
760 )
761 lst = list(SummerMonth)
762 self.assertEqual(len(lst), len(SummerMonth))
763 self.assertEqual(len(SummerMonth), 3, SummerMonth)
764 self.assertEqual(
765 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
766 lst,
767 )
768 for i, month in enumerate('june july august'.split(), 1):
769 e = SummerMonth(i)
770 self.assertEqual(int(e.value), i)
771 self.assertNotEqual(e, i)
772 self.assertEqual(e.name, month)
773 self.assertIn(e, SummerMonth)
774 self.assertIs(type(e), SummerMonth)
775
776 def test_programatic_function_type(self):
777 SummerMonth = Enum('SummerMonth', 'june july august', type=int)
778 lst = list(SummerMonth)
779 self.assertEqual(len(lst), len(SummerMonth))
780 self.assertEqual(len(SummerMonth), 3, SummerMonth)
781 self.assertEqual(
782 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
783 lst,
784 )
785 for i, month in enumerate('june july august'.split(), 1):
786 e = SummerMonth(i)
787 self.assertEqual(e, i)
788 self.assertEqual(e.name, month)
789 self.assertIn(e, SummerMonth)
790 self.assertIs(type(e), SummerMonth)
791
Ethan Furmand9925a12014-09-16 20:35:55 -0700792 def test_programatic_function_type_with_start(self):
793 SummerMonth = Enum('SummerMonth', 'june july august', type=int, start=30)
794 lst = list(SummerMonth)
795 self.assertEqual(len(lst), len(SummerMonth))
796 self.assertEqual(len(SummerMonth), 3, SummerMonth)
797 self.assertEqual(
798 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
799 lst,
800 )
801 for i, month in enumerate('june july august'.split(), 30):
802 e = SummerMonth(i)
803 self.assertEqual(e, i)
804 self.assertEqual(e.name, month)
805 self.assertIn(e, SummerMonth)
806 self.assertIs(type(e), SummerMonth)
807
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700808 def test_programatic_function_type_from_subclass(self):
809 SummerMonth = IntEnum('SummerMonth', 'june july august')
810 lst = list(SummerMonth)
811 self.assertEqual(len(lst), len(SummerMonth))
812 self.assertEqual(len(SummerMonth), 3, SummerMonth)
813 self.assertEqual(
814 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
815 lst,
816 )
817 for i, month in enumerate('june july august'.split(), 1):
818 e = SummerMonth(i)
819 self.assertEqual(e, i)
820 self.assertEqual(e.name, month)
821 self.assertIn(e, SummerMonth)
822 self.assertIs(type(e), SummerMonth)
823
Ethan Furmand9925a12014-09-16 20:35:55 -0700824 def test_programatic_function_type_from_subclass_with_start(self):
825 SummerMonth = IntEnum('SummerMonth', 'june july august', start=40)
826 lst = list(SummerMonth)
827 self.assertEqual(len(lst), len(SummerMonth))
828 self.assertEqual(len(SummerMonth), 3, SummerMonth)
829 self.assertEqual(
830 [SummerMonth.june, SummerMonth.july, SummerMonth.august],
831 lst,
832 )
833 for i, month in enumerate('june july august'.split(), 40):
834 e = SummerMonth(i)
835 self.assertEqual(e, i)
836 self.assertEqual(e.name, month)
837 self.assertIn(e, SummerMonth)
838 self.assertIs(type(e), SummerMonth)
839
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700840 def test_subclassing(self):
841 if isinstance(Name, Exception):
842 raise Name
843 self.assertEqual(Name.BDFL, 'Guido van Rossum')
844 self.assertTrue(Name.BDFL, Name('Guido van Rossum'))
845 self.assertIs(Name.BDFL, getattr(Name, 'BDFL'))
Ethan Furman2ddb39a2014-02-06 17:28:50 -0800846 test_pickle_dump_load(self.assertIs, Name.BDFL)
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700847
848 def test_extending(self):
849 class Color(Enum):
850 red = 1
851 green = 2
852 blue = 3
853 with self.assertRaises(TypeError):
854 class MoreColor(Color):
855 cyan = 4
856 magenta = 5
857 yellow = 6
858
859 def test_exclude_methods(self):
860 class whatever(Enum):
861 this = 'that'
862 these = 'those'
863 def really(self):
864 return 'no, not %s' % self.value
865 self.assertIsNot(type(whatever.really), whatever)
866 self.assertEqual(whatever.this.really(), 'no, not that')
867
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700868 def test_wrong_inheritance_order(self):
869 with self.assertRaises(TypeError):
870 class Wrong(Enum, str):
871 NotHere = 'error before this point'
872
873 def test_intenum_transitivity(self):
874 class number(IntEnum):
875 one = 1
876 two = 2
877 three = 3
878 class numero(IntEnum):
879 uno = 1
880 dos = 2
881 tres = 3
882 self.assertEqual(number.one, numero.uno)
883 self.assertEqual(number.two, numero.dos)
884 self.assertEqual(number.three, numero.tres)
885
886 def test_wrong_enum_in_call(self):
887 class Monochrome(Enum):
888 black = 0
889 white = 1
890 class Gender(Enum):
891 male = 0
892 female = 1
893 self.assertRaises(ValueError, Monochrome, Gender.male)
894
895 def test_wrong_enum_in_mixed_call(self):
896 class Monochrome(IntEnum):
897 black = 0
898 white = 1
899 class Gender(Enum):
900 male = 0
901 female = 1
902 self.assertRaises(ValueError, Monochrome, Gender.male)
903
904 def test_mixed_enum_in_call_1(self):
905 class Monochrome(IntEnum):
906 black = 0
907 white = 1
908 class Gender(IntEnum):
909 male = 0
910 female = 1
911 self.assertIs(Monochrome(Gender.female), Monochrome.white)
912
913 def test_mixed_enum_in_call_2(self):
914 class Monochrome(Enum):
915 black = 0
916 white = 1
917 class Gender(IntEnum):
918 male = 0
919 female = 1
920 self.assertIs(Monochrome(Gender.male), Monochrome.black)
921
922 def test_flufl_enum(self):
923 class Fluflnum(Enum):
924 def __int__(self):
925 return int(self.value)
926 class MailManOptions(Fluflnum):
927 option1 = 1
928 option2 = 2
929 option3 = 3
930 self.assertEqual(int(MailManOptions.option1), 1)
931
Ethan Furman5e5a8232013-08-04 08:42:23 -0700932 def test_introspection(self):
933 class Number(IntEnum):
934 one = 100
935 two = 200
936 self.assertIs(Number.one._member_type_, int)
937 self.assertIs(Number._member_type_, int)
938 class String(str, Enum):
939 yarn = 'soft'
940 rope = 'rough'
941 wire = 'hard'
942 self.assertIs(String.yarn._member_type_, str)
943 self.assertIs(String._member_type_, str)
944 class Plain(Enum):
945 vanilla = 'white'
946 one = 1
947 self.assertIs(Plain.vanilla._member_type_, object)
948 self.assertIs(Plain._member_type_, object)
949
Ethan Furman6b3d64a2013-06-14 16:55:46 -0700950 def test_no_such_enum_member(self):
951 class Color(Enum):
952 red = 1
953 green = 2
954 blue = 3
955 with self.assertRaises(ValueError):
956 Color(4)
957 with self.assertRaises(KeyError):
958 Color['chartreuse']
959
960 def test_new_repr(self):
961 class Color(Enum):
962 red = 1
963 green = 2
964 blue = 3
965 def __repr__(self):
966 return "don't you just love shades of %s?" % self.name
967 self.assertEqual(
968 repr(Color.blue),
969 "don't you just love shades of blue?",
970 )
971
972 def test_inherited_repr(self):
973 class MyEnum(Enum):
974 def __repr__(self):
975 return "My name is %s." % self.name
976 class MyIntEnum(int, MyEnum):
977 this = 1
978 that = 2
979 theother = 3
980 self.assertEqual(repr(MyIntEnum.that), "My name is that.")
981
982 def test_multiple_mixin_mro(self):
983 class auto_enum(type(Enum)):
984 def __new__(metacls, cls, bases, classdict):
985 temp = type(classdict)()
986 names = set(classdict._member_names)
987 i = 0
988 for k in classdict._member_names:
989 v = classdict[k]
990 if v is Ellipsis:
991 v = i
992 else:
993 i = v
994 i += 1
995 temp[k] = v
996 for k, v in classdict.items():
997 if k not in names:
998 temp[k] = v
999 return super(auto_enum, metacls).__new__(
1000 metacls, cls, bases, temp)
1001
1002 class AutoNumberedEnum(Enum, metaclass=auto_enum):
1003 pass
1004
1005 class AutoIntEnum(IntEnum, metaclass=auto_enum):
1006 pass
1007
1008 class TestAutoNumber(AutoNumberedEnum):
1009 a = ...
1010 b = 3
1011 c = ...
1012
1013 class TestAutoInt(AutoIntEnum):
1014 a = ...
1015 b = 3
1016 c = ...
1017
1018 def test_subclasses_with_getnewargs(self):
1019 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001020 __qualname__ = 'NamedInt' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001021 def __new__(cls, *args):
1022 _args = args
1023 name, *args = args
1024 if len(args) == 0:
1025 raise TypeError("name and value must be specified")
1026 self = int.__new__(cls, *args)
1027 self._intname = name
1028 self._args = _args
1029 return self
1030 def __getnewargs__(self):
1031 return self._args
1032 @property
1033 def __name__(self):
1034 return self._intname
1035 def __repr__(self):
1036 # repr() is updated to include the name and type info
1037 return "{}({!r}, {})".format(type(self).__name__,
1038 self.__name__,
1039 int.__repr__(self))
1040 def __str__(self):
1041 # str() is unchanged, even if it relies on the repr() fallback
1042 base = int
1043 base_str = base.__str__
1044 if base_str.__objclass__ is object:
1045 return base.__repr__(self)
1046 return base_str(self)
1047 # for simplicity, we only define one operator that
1048 # propagates expressions
1049 def __add__(self, other):
1050 temp = int(self) + int( other)
1051 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1052 return NamedInt(
1053 '({0} + {1})'.format(self.__name__, other.__name__),
1054 temp )
1055 else:
1056 return temp
1057
1058 class NEI(NamedInt, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001059 __qualname__ = 'NEI' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001060 x = ('the-x', 1)
1061 y = ('the-y', 2)
1062
Ethan Furman2aa27322013-07-19 19:35:56 -07001063
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001064 self.assertIs(NEI.__new__, Enum.__new__)
1065 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1066 globals()['NamedInt'] = NamedInt
1067 globals()['NEI'] = NEI
1068 NI5 = NamedInt('test', 5)
1069 self.assertEqual(NI5, 5)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001070 test_pickle_dump_load(self.assertEqual, NI5, 5)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001071 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001072 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001073 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001074
Ethan Furmanca1b7942014-02-08 11:36:27 -08001075 def test_subclasses_with_getnewargs_ex(self):
1076 class NamedInt(int):
1077 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1078 def __new__(cls, *args):
1079 _args = args
1080 name, *args = args
1081 if len(args) == 0:
1082 raise TypeError("name and value must be specified")
1083 self = int.__new__(cls, *args)
1084 self._intname = name
1085 self._args = _args
1086 return self
1087 def __getnewargs_ex__(self):
1088 return self._args, {}
1089 @property
1090 def __name__(self):
1091 return self._intname
1092 def __repr__(self):
1093 # repr() is updated to include the name and type info
1094 return "{}({!r}, {})".format(type(self).__name__,
1095 self.__name__,
1096 int.__repr__(self))
1097 def __str__(self):
1098 # str() is unchanged, even if it relies on the repr() fallback
1099 base = int
1100 base_str = base.__str__
1101 if base_str.__objclass__ is object:
1102 return base.__repr__(self)
1103 return base_str(self)
1104 # for simplicity, we only define one operator that
1105 # propagates expressions
1106 def __add__(self, other):
1107 temp = int(self) + int( other)
1108 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1109 return NamedInt(
1110 '({0} + {1})'.format(self.__name__, other.__name__),
1111 temp )
1112 else:
1113 return temp
1114
1115 class NEI(NamedInt, Enum):
1116 __qualname__ = 'NEI' # needed for pickle protocol 4
1117 x = ('the-x', 1)
1118 y = ('the-y', 2)
1119
1120
1121 self.assertIs(NEI.__new__, Enum.__new__)
1122 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1123 globals()['NamedInt'] = NamedInt
1124 globals()['NEI'] = NEI
1125 NI5 = NamedInt('test', 5)
1126 self.assertEqual(NI5, 5)
Serhiy Storchakae50e7802015-03-31 16:56:49 +03001127 test_pickle_dump_load(self.assertEqual, NI5, 5)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001128 self.assertEqual(NEI.y.value, 2)
Serhiy Storchakae50e7802015-03-31 16:56:49 +03001129 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001130 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001131
1132 def test_subclasses_with_reduce(self):
1133 class NamedInt(int):
1134 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1135 def __new__(cls, *args):
1136 _args = args
1137 name, *args = args
1138 if len(args) == 0:
1139 raise TypeError("name and value must be specified")
1140 self = int.__new__(cls, *args)
1141 self._intname = name
1142 self._args = _args
1143 return self
1144 def __reduce__(self):
1145 return self.__class__, self._args
1146 @property
1147 def __name__(self):
1148 return self._intname
1149 def __repr__(self):
1150 # repr() is updated to include the name and type info
1151 return "{}({!r}, {})".format(type(self).__name__,
1152 self.__name__,
1153 int.__repr__(self))
1154 def __str__(self):
1155 # str() is unchanged, even if it relies on the repr() fallback
1156 base = int
1157 base_str = base.__str__
1158 if base_str.__objclass__ is object:
1159 return base.__repr__(self)
1160 return base_str(self)
1161 # for simplicity, we only define one operator that
1162 # propagates expressions
1163 def __add__(self, other):
1164 temp = int(self) + int( other)
1165 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1166 return NamedInt(
1167 '({0} + {1})'.format(self.__name__, other.__name__),
1168 temp )
1169 else:
1170 return temp
1171
1172 class NEI(NamedInt, Enum):
1173 __qualname__ = 'NEI' # needed for pickle protocol 4
1174 x = ('the-x', 1)
1175 y = ('the-y', 2)
1176
1177
1178 self.assertIs(NEI.__new__, Enum.__new__)
1179 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1180 globals()['NamedInt'] = NamedInt
1181 globals()['NEI'] = NEI
1182 NI5 = NamedInt('test', 5)
1183 self.assertEqual(NI5, 5)
1184 test_pickle_dump_load(self.assertEqual, NI5, 5)
1185 self.assertEqual(NEI.y.value, 2)
1186 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001187 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001188
1189 def test_subclasses_with_reduce_ex(self):
1190 class NamedInt(int):
1191 __qualname__ = 'NamedInt' # needed for pickle protocol 4
1192 def __new__(cls, *args):
1193 _args = args
1194 name, *args = args
1195 if len(args) == 0:
1196 raise TypeError("name and value must be specified")
1197 self = int.__new__(cls, *args)
1198 self._intname = name
1199 self._args = _args
1200 return self
1201 def __reduce_ex__(self, proto):
1202 return self.__class__, self._args
1203 @property
1204 def __name__(self):
1205 return self._intname
1206 def __repr__(self):
1207 # repr() is updated to include the name and type info
1208 return "{}({!r}, {})".format(type(self).__name__,
1209 self.__name__,
1210 int.__repr__(self))
1211 def __str__(self):
1212 # str() is unchanged, even if it relies on the repr() fallback
1213 base = int
1214 base_str = base.__str__
1215 if base_str.__objclass__ is object:
1216 return base.__repr__(self)
1217 return base_str(self)
1218 # for simplicity, we only define one operator that
1219 # propagates expressions
1220 def __add__(self, other):
1221 temp = int(self) + int( other)
1222 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1223 return NamedInt(
1224 '({0} + {1})'.format(self.__name__, other.__name__),
1225 temp )
1226 else:
1227 return temp
1228
1229 class NEI(NamedInt, Enum):
1230 __qualname__ = 'NEI' # needed for pickle protocol 4
1231 x = ('the-x', 1)
1232 y = ('the-y', 2)
1233
1234
1235 self.assertIs(NEI.__new__, Enum.__new__)
1236 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1237 globals()['NamedInt'] = NamedInt
1238 globals()['NEI'] = NEI
1239 NI5 = NamedInt('test', 5)
1240 self.assertEqual(NI5, 5)
1241 test_pickle_dump_load(self.assertEqual, NI5, 5)
1242 self.assertEqual(NEI.y.value, 2)
1243 test_pickle_dump_load(self.assertIs, NEI.y)
Ethan Furmandc870522014-02-18 12:37:12 -08001244 test_pickle_dump_load(self.assertIs, NEI)
Ethan Furmanca1b7942014-02-08 11:36:27 -08001245
Ethan Furmandc870522014-02-18 12:37:12 -08001246 def test_subclasses_without_direct_pickle_support(self):
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001247 class NamedInt(int):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001248 __qualname__ = 'NamedInt'
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001249 def __new__(cls, *args):
1250 _args = args
1251 name, *args = args
1252 if len(args) == 0:
1253 raise TypeError("name and value must be specified")
1254 self = int.__new__(cls, *args)
1255 self._intname = name
1256 self._args = _args
1257 return self
1258 @property
1259 def __name__(self):
1260 return self._intname
1261 def __repr__(self):
1262 # repr() is updated to include the name and type info
1263 return "{}({!r}, {})".format(type(self).__name__,
1264 self.__name__,
1265 int.__repr__(self))
1266 def __str__(self):
1267 # str() is unchanged, even if it relies on the repr() fallback
1268 base = int
1269 base_str = base.__str__
1270 if base_str.__objclass__ is object:
1271 return base.__repr__(self)
1272 return base_str(self)
1273 # for simplicity, we only define one operator that
1274 # propagates expressions
1275 def __add__(self, other):
1276 temp = int(self) + int( other)
1277 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1278 return NamedInt(
1279 '({0} + {1})'.format(self.__name__, other.__name__),
1280 temp )
1281 else:
1282 return temp
1283
1284 class NEI(NamedInt, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001285 __qualname__ = 'NEI'
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001286 x = ('the-x', 1)
1287 y = ('the-y', 2)
1288
1289 self.assertIs(NEI.__new__, Enum.__new__)
1290 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1291 globals()['NamedInt'] = NamedInt
1292 globals()['NEI'] = NEI
1293 NI5 = NamedInt('test', 5)
1294 self.assertEqual(NI5, 5)
1295 self.assertEqual(NEI.y.value, 2)
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001296 test_pickle_exception(self.assertRaises, TypeError, NEI.x)
1297 test_pickle_exception(self.assertRaises, PicklingError, NEI)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001298
Ethan Furmandc870522014-02-18 12:37:12 -08001299 def test_subclasses_without_direct_pickle_support_using_name(self):
1300 class NamedInt(int):
1301 __qualname__ = 'NamedInt'
1302 def __new__(cls, *args):
1303 _args = args
1304 name, *args = args
1305 if len(args) == 0:
1306 raise TypeError("name and value must be specified")
1307 self = int.__new__(cls, *args)
1308 self._intname = name
1309 self._args = _args
1310 return self
1311 @property
1312 def __name__(self):
1313 return self._intname
1314 def __repr__(self):
1315 # repr() is updated to include the name and type info
1316 return "{}({!r}, {})".format(type(self).__name__,
1317 self.__name__,
1318 int.__repr__(self))
1319 def __str__(self):
1320 # str() is unchanged, even if it relies on the repr() fallback
1321 base = int
1322 base_str = base.__str__
1323 if base_str.__objclass__ is object:
1324 return base.__repr__(self)
1325 return base_str(self)
1326 # for simplicity, we only define one operator that
1327 # propagates expressions
1328 def __add__(self, other):
1329 temp = int(self) + int( other)
1330 if isinstance(self, NamedInt) and isinstance(other, NamedInt):
1331 return NamedInt(
1332 '({0} + {1})'.format(self.__name__, other.__name__),
1333 temp )
1334 else:
1335 return temp
1336
1337 class NEI(NamedInt, Enum):
1338 __qualname__ = 'NEI'
1339 x = ('the-x', 1)
1340 y = ('the-y', 2)
1341 def __reduce_ex__(self, proto):
1342 return getattr, (self.__class__, self._name_)
1343
1344 self.assertIs(NEI.__new__, Enum.__new__)
1345 self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")
1346 globals()['NamedInt'] = NamedInt
1347 globals()['NEI'] = NEI
1348 NI5 = NamedInt('test', 5)
1349 self.assertEqual(NI5, 5)
1350 self.assertEqual(NEI.y.value, 2)
1351 test_pickle_dump_load(self.assertIs, NEI.y)
1352 test_pickle_dump_load(self.assertIs, NEI)
1353
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001354 def test_tuple_subclass(self):
1355 class SomeTuple(tuple, Enum):
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001356 __qualname__ = 'SomeTuple' # needed for pickle protocol 4
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001357 first = (1, 'for the money')
1358 second = (2, 'for the show')
1359 third = (3, 'for the music')
1360 self.assertIs(type(SomeTuple.first), SomeTuple)
1361 self.assertIsInstance(SomeTuple.second, tuple)
1362 self.assertEqual(SomeTuple.third, (3, 'for the music'))
1363 globals()['SomeTuple'] = SomeTuple
Ethan Furman2ddb39a2014-02-06 17:28:50 -08001364 test_pickle_dump_load(self.assertIs, SomeTuple.first)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001365
1366 def test_duplicate_values_give_unique_enum_items(self):
1367 class AutoNumber(Enum):
1368 first = ()
1369 second = ()
1370 third = ()
1371 def __new__(cls):
1372 value = len(cls.__members__) + 1
1373 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001374 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001375 return obj
1376 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001377 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001378 self.assertEqual(
1379 list(AutoNumber),
1380 [AutoNumber.first, AutoNumber.second, AutoNumber.third],
1381 )
1382 self.assertEqual(int(AutoNumber.second), 2)
Ethan Furman2aa27322013-07-19 19:35:56 -07001383 self.assertEqual(AutoNumber.third.value, 3)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001384 self.assertIs(AutoNumber(1), AutoNumber.first)
1385
1386 def test_inherited_new_from_enhanced_enum(self):
1387 class AutoNumber(Enum):
1388 def __new__(cls):
1389 value = len(cls.__members__) + 1
1390 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001391 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001392 return obj
1393 def __int__(self):
Ethan Furman520ad572013-07-19 19:47:21 -07001394 return int(self._value_)
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001395 class Color(AutoNumber):
1396 red = ()
1397 green = ()
1398 blue = ()
1399 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1400 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1401
1402 def test_inherited_new_from_mixed_enum(self):
1403 class AutoNumber(IntEnum):
1404 def __new__(cls):
1405 value = len(cls.__members__) + 1
1406 obj = int.__new__(cls, value)
Ethan Furman520ad572013-07-19 19:47:21 -07001407 obj._value_ = value
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001408 return obj
1409 class Color(AutoNumber):
1410 red = ()
1411 green = ()
1412 blue = ()
1413 self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])
1414 self.assertEqual(list(map(int, Color)), [1, 2, 3])
1415
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001416 def test_equality(self):
1417 class AlwaysEqual:
1418 def __eq__(self, other):
1419 return True
1420 class OrdinaryEnum(Enum):
1421 a = 1
1422 self.assertEqual(AlwaysEqual(), OrdinaryEnum.a)
1423 self.assertEqual(OrdinaryEnum.a, AlwaysEqual())
1424
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001425 def test_ordered_mixin(self):
1426 class OrderedEnum(Enum):
1427 def __ge__(self, other):
1428 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001429 return self._value_ >= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001430 return NotImplemented
1431 def __gt__(self, other):
1432 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001433 return self._value_ > other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001434 return NotImplemented
1435 def __le__(self, other):
1436 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001437 return self._value_ <= other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001438 return NotImplemented
1439 def __lt__(self, other):
1440 if self.__class__ is other.__class__:
Ethan Furman520ad572013-07-19 19:47:21 -07001441 return self._value_ < other._value_
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001442 return NotImplemented
1443 class Grade(OrderedEnum):
1444 A = 5
1445 B = 4
1446 C = 3
1447 D = 2
1448 F = 1
1449 self.assertGreater(Grade.A, Grade.B)
1450 self.assertLessEqual(Grade.F, Grade.C)
1451 self.assertLess(Grade.D, Grade.A)
1452 self.assertGreaterEqual(Grade.B, Grade.B)
Ethan Furmanbe3c2fe2013-11-13 14:25:45 -08001453 self.assertEqual(Grade.B, Grade.B)
1454 self.assertNotEqual(Grade.C, Grade.D)
Ethan Furman520ad572013-07-19 19:47:21 -07001455
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001456 def test_extending2(self):
1457 class Shade(Enum):
1458 def shade(self):
1459 print(self.name)
1460 class Color(Shade):
1461 red = 1
1462 green = 2
1463 blue = 3
1464 with self.assertRaises(TypeError):
1465 class MoreColor(Color):
1466 cyan = 4
1467 magenta = 5
1468 yellow = 6
1469
1470 def test_extending3(self):
1471 class Shade(Enum):
1472 def shade(self):
1473 return self.name
1474 class Color(Shade):
1475 def hex(self):
1476 return '%s hexlified!' % self.value
1477 class MoreColor(Color):
1478 cyan = 4
1479 magenta = 5
1480 yellow = 6
1481 self.assertEqual(MoreColor.magenta.hex(), '5 hexlified!')
1482
1483
1484 def test_no_duplicates(self):
1485 class UniqueEnum(Enum):
1486 def __init__(self, *args):
1487 cls = self.__class__
1488 if any(self.value == e.value for e in cls):
1489 a = self.name
1490 e = cls(self.value).name
1491 raise ValueError(
1492 "aliases not allowed in UniqueEnum: %r --> %r"
1493 % (a, e)
1494 )
1495 class Color(UniqueEnum):
1496 red = 1
1497 green = 2
1498 blue = 3
1499 with self.assertRaises(ValueError):
1500 class Color(UniqueEnum):
1501 red = 1
1502 green = 2
1503 blue = 3
1504 grene = 2
1505
1506 def test_init(self):
1507 class Planet(Enum):
1508 MERCURY = (3.303e+23, 2.4397e6)
1509 VENUS = (4.869e+24, 6.0518e6)
1510 EARTH = (5.976e+24, 6.37814e6)
1511 MARS = (6.421e+23, 3.3972e6)
1512 JUPITER = (1.9e+27, 7.1492e7)
1513 SATURN = (5.688e+26, 6.0268e7)
1514 URANUS = (8.686e+25, 2.5559e7)
1515 NEPTUNE = (1.024e+26, 2.4746e7)
1516 def __init__(self, mass, radius):
1517 self.mass = mass # in kilograms
1518 self.radius = radius # in meters
1519 @property
1520 def surface_gravity(self):
1521 # universal gravitational constant (m3 kg-1 s-2)
1522 G = 6.67300E-11
1523 return G * self.mass / (self.radius * self.radius)
1524 self.assertEqual(round(Planet.EARTH.surface_gravity, 2), 9.80)
1525 self.assertEqual(Planet.EARTH.value, (5.976e+24, 6.37814e6))
1526
Ethan Furman2aa27322013-07-19 19:35:56 -07001527 def test_nonhash_value(self):
1528 class AutoNumberInAList(Enum):
1529 def __new__(cls):
1530 value = [len(cls.__members__) + 1]
1531 obj = object.__new__(cls)
Ethan Furman520ad572013-07-19 19:47:21 -07001532 obj._value_ = value
Ethan Furman2aa27322013-07-19 19:35:56 -07001533 return obj
1534 class ColorInAList(AutoNumberInAList):
1535 red = ()
1536 green = ()
1537 blue = ()
1538 self.assertEqual(list(ColorInAList), [ColorInAList.red, ColorInAList.green, ColorInAList.blue])
Ethan Furman1a162882013-10-16 19:09:31 -07001539 for enum, value in zip(ColorInAList, range(3)):
1540 value += 1
1541 self.assertEqual(enum.value, [value])
1542 self.assertIs(ColorInAList([value]), enum)
Ethan Furman2aa27322013-07-19 19:35:56 -07001543
Ethan Furmanb41803e2013-07-25 13:50:45 -07001544 def test_conflicting_types_resolved_in_new(self):
1545 class LabelledIntEnum(int, Enum):
1546 def __new__(cls, *args):
1547 value, label = args
1548 obj = int.__new__(cls, value)
1549 obj.label = label
1550 obj._value_ = value
1551 return obj
1552
1553 class LabelledList(LabelledIntEnum):
1554 unprocessed = (1, "Unprocessed")
1555 payment_complete = (2, "Payment Complete")
1556
1557 self.assertEqual(list(LabelledList), [LabelledList.unprocessed, LabelledList.payment_complete])
1558 self.assertEqual(LabelledList.unprocessed, 1)
1559 self.assertEqual(LabelledList(1), LabelledList.unprocessed)
Ethan Furman2aa27322013-07-19 19:35:56 -07001560
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001561
Ethan Furmanf24bb352013-07-18 17:05:39 -07001562class TestUnique(unittest.TestCase):
1563
1564 def test_unique_clean(self):
1565 @unique
1566 class Clean(Enum):
1567 one = 1
1568 two = 'dos'
1569 tres = 4.0
1570 @unique
1571 class Cleaner(IntEnum):
1572 single = 1
1573 double = 2
1574 triple = 3
1575
1576 def test_unique_dirty(self):
1577 with self.assertRaisesRegex(ValueError, 'tres.*one'):
1578 @unique
1579 class Dirty(Enum):
1580 one = 1
1581 two = 'dos'
1582 tres = 1
1583 with self.assertRaisesRegex(
1584 ValueError,
1585 'double.*single.*turkey.*triple',
1586 ):
1587 @unique
1588 class Dirtier(IntEnum):
1589 single = 1
1590 double = 1
1591 triple = 3
1592 turkey = 3
1593
1594
Ethan Furman3323da92015-04-11 09:39:59 -07001595expected_help_output_with_docs = """\
Ethan Furman5875d742013-10-21 20:45:55 -07001596Help on class Color in module %s:
1597
1598class Color(enum.Enum)
Ethan Furman48a724f2015-04-11 23:23:06 -07001599 | An enumeration.
Serhiy Storchakab599ca82015-04-04 12:48:04 +03001600 |\x20\x20
Ethan Furman5875d742013-10-21 20:45:55 -07001601 | Method resolution order:
1602 | Color
1603 | enum.Enum
1604 | builtins.object
1605 |\x20\x20
1606 | Data and other attributes defined here:
1607 |\x20\x20
1608 | blue = <Color.blue: 3>
1609 |\x20\x20
1610 | green = <Color.green: 2>
1611 |\x20\x20
1612 | red = <Color.red: 1>
1613 |\x20\x20
1614 | ----------------------------------------------------------------------
1615 | Data descriptors inherited from enum.Enum:
1616 |\x20\x20
1617 | name
1618 | The name of the Enum member.
1619 |\x20\x20
1620 | value
1621 | The value of the Enum member.
1622 |\x20\x20
1623 | ----------------------------------------------------------------------
1624 | Data descriptors inherited from enum.EnumMeta:
1625 |\x20\x20
1626 | __members__
1627 | Returns a mapping of member name->value.
1628 |\x20\x20\x20\x20\x20\x20
1629 | This mapping lists all enum members, including aliases. Note that this
Ethan Furman3323da92015-04-11 09:39:59 -07001630 | is a read-only view of the internal mapping."""
1631
1632expected_help_output_without_docs = """\
1633Help on class Color in module %s:
1634
1635class Color(enum.Enum)
1636 | Method resolution order:
1637 | Color
1638 | enum.Enum
1639 | builtins.object
1640 |\x20\x20
1641 | Data and other attributes defined here:
1642 |\x20\x20
1643 | blue = <Color.blue: 3>
1644 |\x20\x20
1645 | green = <Color.green: 2>
1646 |\x20\x20
1647 | red = <Color.red: 1>
1648 |\x20\x20
1649 | ----------------------------------------------------------------------
1650 | Data descriptors inherited from enum.Enum:
1651 |\x20\x20
1652 | name
1653 |\x20\x20
1654 | value
1655 |\x20\x20
1656 | ----------------------------------------------------------------------
1657 | Data descriptors inherited from enum.EnumMeta:
1658 |\x20\x20
1659 | __members__"""
Ethan Furman5875d742013-10-21 20:45:55 -07001660
1661class TestStdLib(unittest.TestCase):
1662
Ethan Furman48a724f2015-04-11 23:23:06 -07001663 maxDiff = None
1664
Ethan Furman5875d742013-10-21 20:45:55 -07001665 class Color(Enum):
1666 red = 1
1667 green = 2
1668 blue = 3
1669
1670 def test_pydoc(self):
1671 # indirectly test __objclass__
Ethan Furman3323da92015-04-11 09:39:59 -07001672 if StrEnum.__doc__ is None:
1673 expected_text = expected_help_output_without_docs % __name__
1674 else:
1675 expected_text = expected_help_output_with_docs % __name__
Ethan Furman5875d742013-10-21 20:45:55 -07001676 output = StringIO()
1677 helper = pydoc.Helper(output=output)
1678 helper(self.Color)
1679 result = output.getvalue().strip()
Victor Stinner4b0432d2014-06-16 22:48:43 +02001680 self.assertEqual(result, expected_text)
Ethan Furman5875d742013-10-21 20:45:55 -07001681
1682 def test_inspect_getmembers(self):
1683 values = dict((
1684 ('__class__', EnumMeta),
Ethan Furman48a724f2015-04-11 23:23:06 -07001685 ('__doc__', 'An enumeration.'),
Ethan Furman5875d742013-10-21 20:45:55 -07001686 ('__members__', self.Color.__members__),
1687 ('__module__', __name__),
1688 ('blue', self.Color.blue),
1689 ('green', self.Color.green),
1690 ('name', Enum.__dict__['name']),
1691 ('red', self.Color.red),
1692 ('value', Enum.__dict__['value']),
1693 ))
1694 result = dict(inspect.getmembers(self.Color))
1695 self.assertEqual(values.keys(), result.keys())
1696 failed = False
1697 for k in values.keys():
1698 if result[k] != values[k]:
1699 print()
1700 print('\n%s\n key: %s\n result: %s\nexpected: %s\n%s\n' %
1701 ('=' * 75, k, result[k], values[k], '=' * 75), sep='')
1702 failed = True
1703 if failed:
1704 self.fail("result does not equal expected, see print above")
1705
1706 def test_inspect_classify_class_attrs(self):
1707 # indirectly test __objclass__
1708 from inspect import Attribute
1709 values = [
1710 Attribute(name='__class__', kind='data',
1711 defining_class=object, object=EnumMeta),
1712 Attribute(name='__doc__', kind='data',
Ethan Furman48a724f2015-04-11 23:23:06 -07001713 defining_class=self.Color, object='An enumeration.'),
Ethan Furman5875d742013-10-21 20:45:55 -07001714 Attribute(name='__members__', kind='property',
1715 defining_class=EnumMeta, object=EnumMeta.__members__),
1716 Attribute(name='__module__', kind='data',
1717 defining_class=self.Color, object=__name__),
1718 Attribute(name='blue', kind='data',
1719 defining_class=self.Color, object=self.Color.blue),
1720 Attribute(name='green', kind='data',
1721 defining_class=self.Color, object=self.Color.green),
1722 Attribute(name='red', kind='data',
1723 defining_class=self.Color, object=self.Color.red),
1724 Attribute(name='name', kind='data',
1725 defining_class=Enum, object=Enum.__dict__['name']),
1726 Attribute(name='value', kind='data',
1727 defining_class=Enum, object=Enum.__dict__['value']),
1728 ]
1729 values.sort(key=lambda item: item.name)
1730 result = list(inspect.classify_class_attrs(self.Color))
1731 result.sort(key=lambda item: item.name)
1732 failed = False
1733 for v, r in zip(values, result):
1734 if r != v:
1735 print('\n%s\n%s\n%s\n%s\n' % ('=' * 75, r, v, '=' * 75), sep='')
1736 failed = True
1737 if failed:
1738 self.fail("result does not equal expected, see print above")
1739
Martin Panter19e69c52015-11-14 12:46:42 +00001740
1741class MiscTestCase(unittest.TestCase):
1742 def test__all__(self):
1743 support.check__all__(self, enum)
1744
1745
Ethan Furman6b3d64a2013-06-14 16:55:46 -07001746if __name__ == '__main__':
1747 unittest.main()