Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
| Download
code directory
Project: CubicBraidGroup
Views: 5048import enum1import sys2import unittest3from enum import Enum, IntEnum, unique, EnumMeta4from pickle import dumps, loads, PicklingError, HIGHEST_PROTOCOL56pyver = float('%s.%s' % sys.version_info[:2])78try:9any10except NameError:11def any(iterable):12for element in iterable:13if element:14return True15return False1617try:18unicode19except NameError:20unicode = str2122try:23from collections import OrderedDict24except ImportError:25OrderedDict = None2627# for pickle tests28try:29class Stooges(Enum):30LARRY = 131CURLY = 232MOE = 333except Exception:34Stooges = sys.exc_info()[1]3536try:37class IntStooges(int, Enum):38LARRY = 139CURLY = 240MOE = 341except Exception:42IntStooges = sys.exc_info()[1]4344try:45class FloatStooges(float, Enum):46LARRY = 1.3947CURLY = 2.7248MOE = 3.14259649except Exception:50FloatStooges = sys.exc_info()[1]5152# for pickle test and subclass tests53try:54class StrEnum(str, Enum):55'accepts only string values'56class Name(StrEnum):57BDFL = 'Guido van Rossum'58FLUFL = 'Barry Warsaw'59except Exception:60Name = sys.exc_info()[1]6162try:63Question = Enum('Question', 'who what when where why', module=__name__)64except Exception:65Question = sys.exc_info()[1]6667try:68Answer = Enum('Answer', 'him this then there because')69except Exception:70Answer = sys.exc_info()[1]7172try:73Theory = Enum('Theory', 'rule law supposition', qualname='spanish_inquisition')74except Exception:75Theory = sys.exc_info()[1]7677# for doctests78try:79class Fruit(Enum):80tomato = 181banana = 282cherry = 383except Exception:84pass8586def test_pickle_dump_load(assertion, source, target=None,87protocol=(0, HIGHEST_PROTOCOL)):88start, stop = protocol89failures = []90for protocol in range(start, stop+1):91try:92if target is None:93assertion(loads(dumps(source, protocol=protocol)) is source)94else:95assertion(loads(dumps(source, protocol=protocol)), target)96except Exception:97exc, tb = sys.exc_info()[1:]98failures.append('%2d: %s' %(protocol, exc))99if failures:100raise ValueError('Failed with protocols: %s' % ', '.join(failures))101102def test_pickle_exception(assertion, exception, obj,103protocol=(0, HIGHEST_PROTOCOL)):104start, stop = protocol105failures = []106for protocol in range(start, stop+1):107try:108assertion(exception, dumps, obj, protocol=protocol)109except Exception:110exc = sys.exc_info()[1]111failures.append('%d: %s %s' % (protocol, exc.__class__.__name__, exc))112if failures:113raise ValueError('Failed with protocols: %s' % ', '.join(failures))114115116class TestHelpers(unittest.TestCase):117# _is_descriptor, _is_sunder, _is_dunder118119def test_is_descriptor(self):120class foo:121pass122for attr in ('__get__','__set__','__delete__'):123obj = foo()124self.assertFalse(enum._is_descriptor(obj))125setattr(obj, attr, 1)126self.assertTrue(enum._is_descriptor(obj))127128def test_is_sunder(self):129for s in ('_a_', '_aa_'):130self.assertTrue(enum._is_sunder(s))131132for s in ('a', 'a_', '_a', '__a', 'a__', '__a__', '_a__', '__a_', '_',133'__', '___', '____', '_____',):134self.assertFalse(enum._is_sunder(s))135136def test_is_dunder(self):137for s in ('__a__', '__aa__'):138self.assertTrue(enum._is_dunder(s))139for s in ('a', 'a_', '_a', '__a', 'a__', '_a_', '_a__', '__a_', '_',140'__', '___', '____', '_____',):141self.assertFalse(enum._is_dunder(s))142143144class TestEnum(unittest.TestCase):145def setUp(self):146class Season(Enum):147SPRING = 1148SUMMER = 2149AUTUMN = 3150WINTER = 4151self.Season = Season152153class Konstants(float, Enum):154E = 2.7182818155PI = 3.1415926156TAU = 2 * PI157self.Konstants = Konstants158159class Grades(IntEnum):160A = 5161B = 4162C = 3163D = 2164F = 0165self.Grades = Grades166167class Directional(str, Enum):168EAST = 'east'169WEST = 'west'170NORTH = 'north'171SOUTH = 'south'172self.Directional = Directional173174from datetime import date175class Holiday(date, Enum):176NEW_YEAR = 2013, 1, 1177IDES_OF_MARCH = 2013, 3, 15178self.Holiday = Holiday179180if pyver >= 3.0: # do not specify custom `dir` on previous versions181def test_dir_on_class(self):182Season = self.Season183self.assertEqual(184set(dir(Season)),185set(['__class__', '__doc__', '__members__', '__module__',186'SPRING', 'SUMMER', 'AUTUMN', 'WINTER']),187)188189def test_dir_on_item(self):190Season = self.Season191self.assertEqual(192set(dir(Season.WINTER)),193set(['__class__', '__doc__', '__module__', 'name', 'value']),194)195196def test_dir_with_added_behavior(self):197class Test(Enum):198this = 'that'199these = 'those'200def wowser(self):201return ("Wowser! I'm %s!" % self.name)202self.assertEqual(203set(dir(Test)),204set(['__class__', '__doc__', '__members__', '__module__', 'this', 'these']),205)206self.assertEqual(207set(dir(Test.this)),208set(['__class__', '__doc__', '__module__', 'name', 'value', 'wowser']),209)210211def test_dir_on_sub_with_behavior_on_super(self):212# see issue22506213class SuperEnum(Enum):214def invisible(self):215return "did you see me?"216class SubEnum(SuperEnum):217sample = 5218self.assertEqual(219set(dir(SubEnum.sample)),220set(['__class__', '__doc__', '__module__', 'name', 'value', 'invisible']),221)222223if pyver >= 2.7: # OrderedDict first available here224def test_members_is_ordereddict_if_ordered(self):225class Ordered(Enum):226__order__ = 'first second third'227first = 'bippity'228second = 'boppity'229third = 'boo'230self.assertTrue(type(Ordered.__members__) is OrderedDict)231232def test_members_is_ordereddict_if_not_ordered(self):233class Unordered(Enum):234this = 'that'235these = 'those'236self.assertTrue(type(Unordered.__members__) is OrderedDict)237238if pyver >= 3.0: # all objects are ordered in Python 2.x239def test_members_is_always_ordered(self):240class AlwaysOrdered(Enum):241first = 1242second = 2243third = 3244self.assertTrue(type(AlwaysOrdered.__members__) is OrderedDict)245246def test_comparisons(self):247def bad_compare():248Season.SPRING > 4249Season = self.Season250self.assertNotEqual(Season.SPRING, 1)251self.assertRaises(TypeError, bad_compare)252253class Part(Enum):254SPRING = 1255CLIP = 2256BARREL = 3257258self.assertNotEqual(Season.SPRING, Part.SPRING)259def bad_compare():260Season.SPRING < Part.CLIP261self.assertRaises(TypeError, bad_compare)262263def test_enum_in_enum_out(self):264Season = self.Season265self.assertTrue(Season(Season.WINTER) is Season.WINTER)266267def test_enum_value(self):268Season = self.Season269self.assertEqual(Season.SPRING.value, 1)270271def test_intenum_value(self):272self.assertEqual(IntStooges.CURLY.value, 2)273274def test_enum(self):275Season = self.Season276lst = list(Season)277self.assertEqual(len(lst), len(Season))278self.assertEqual(len(Season), 4, Season)279self.assertEqual(280[Season.SPRING, Season.SUMMER, Season.AUTUMN, Season.WINTER], lst)281282for i, season in enumerate('SPRING SUMMER AUTUMN WINTER'.split()):283i += 1284e = Season(i)285self.assertEqual(e, getattr(Season, season))286self.assertEqual(e.value, i)287self.assertNotEqual(e, i)288self.assertEqual(e.name, season)289self.assertTrue(e in Season)290self.assertTrue(type(e) is Season)291self.assertTrue(isinstance(e, Season))292self.assertEqual(str(e), 'Season.' + season)293self.assertEqual(294repr(e),295'<Season.%s: %s>' % (season, i),296)297298def test_value_name(self):299Season = self.Season300self.assertEqual(Season.SPRING.name, 'SPRING')301self.assertEqual(Season.SPRING.value, 1)302def set_name(obj, new_value):303obj.name = new_value304def set_value(obj, new_value):305obj.value = new_value306self.assertRaises(AttributeError, set_name, Season.SPRING, 'invierno', )307self.assertRaises(AttributeError, set_value, Season.SPRING, 2)308309def test_attribute_deletion(self):310class Season(Enum):311SPRING = 1312SUMMER = 2313AUTUMN = 3314WINTER = 4315316def spam(cls):317pass318319self.assertTrue(hasattr(Season, 'spam'))320del Season.spam321self.assertFalse(hasattr(Season, 'spam'))322323self.assertRaises(AttributeError, delattr, Season, 'SPRING')324self.assertRaises(AttributeError, delattr, Season, 'DRY')325self.assertRaises(AttributeError, delattr, Season.SPRING, 'name')326327def test_invalid_names(self):328def create_bad_class_1():329class Wrong(Enum):330mro = 9331def create_bad_class_2():332class Wrong(Enum):333_reserved_ = 3334self.assertRaises(ValueError, create_bad_class_1)335self.assertRaises(ValueError, create_bad_class_2)336337# TODO: enable when Python 3.6 is released338# def test_bool(self):339# class Logic(Enum):340# true = True341# false = False342# self.assertTrue(Logic.true)343# self.assertFalse(Logic.false)344345def test_contains(self):346Season = self.Season347self.assertTrue(Season.AUTUMN in Season)348self.assertTrue(3 not in Season)349350val = Season(3)351self.assertTrue(val in Season)352353class OtherEnum(Enum):354one = 1; two = 2355self.assertTrue(OtherEnum.two not in Season)356357if pyver >= 2.6: # when `format` came into being358359def test_format_enum(self):360Season = self.Season361self.assertEqual('{0}'.format(Season.SPRING),362'{0}'.format(str(Season.SPRING)))363self.assertEqual( '{0:}'.format(Season.SPRING),364'{0:}'.format(str(Season.SPRING)))365self.assertEqual('{0:20}'.format(Season.SPRING),366'{0:20}'.format(str(Season.SPRING)))367self.assertEqual('{0:^20}'.format(Season.SPRING),368'{0:^20}'.format(str(Season.SPRING)))369self.assertEqual('{0:>20}'.format(Season.SPRING),370'{0:>20}'.format(str(Season.SPRING)))371self.assertEqual('{0:<20}'.format(Season.SPRING),372'{0:<20}'.format(str(Season.SPRING)))373374def test_format_enum_custom(self):375class TestFloat(float, Enum):376one = 1.0377two = 2.0378def __format__(self, spec):379return 'TestFloat success!'380self.assertEqual('{0}'.format(TestFloat.one), 'TestFloat success!')381382def assertFormatIsValue(self, spec, member):383self.assertEqual(spec.format(member), spec.format(member.value))384385def test_format_enum_date(self):386Holiday = self.Holiday387self.assertFormatIsValue('{0}', Holiday.IDES_OF_MARCH)388self.assertFormatIsValue('{0:}', Holiday.IDES_OF_MARCH)389self.assertFormatIsValue('{0:20}', Holiday.IDES_OF_MARCH)390self.assertFormatIsValue('{0:^20}', Holiday.IDES_OF_MARCH)391self.assertFormatIsValue('{0:>20}', Holiday.IDES_OF_MARCH)392self.assertFormatIsValue('{0:<20}', Holiday.IDES_OF_MARCH)393self.assertFormatIsValue('{0:%Y %m}', Holiday.IDES_OF_MARCH)394self.assertFormatIsValue('{0:%Y %m %M:00}', Holiday.IDES_OF_MARCH)395396def test_format_enum_float(self):397Konstants = self.Konstants398self.assertFormatIsValue('{0}', Konstants.TAU)399self.assertFormatIsValue('{0:}', Konstants.TAU)400self.assertFormatIsValue('{0:20}', Konstants.TAU)401self.assertFormatIsValue('{0:^20}', Konstants.TAU)402self.assertFormatIsValue('{0:>20}', Konstants.TAU)403self.assertFormatIsValue('{0:<20}', Konstants.TAU)404self.assertFormatIsValue('{0:n}', Konstants.TAU)405self.assertFormatIsValue('{0:5.2}', Konstants.TAU)406self.assertFormatIsValue('{0:f}', Konstants.TAU)407408def test_format_enum_int(self):409Grades = self.Grades410self.assertFormatIsValue('{0}', Grades.C)411self.assertFormatIsValue('{0:}', Grades.C)412self.assertFormatIsValue('{0:20}', Grades.C)413self.assertFormatIsValue('{0:^20}', Grades.C)414self.assertFormatIsValue('{0:>20}', Grades.C)415self.assertFormatIsValue('{0:<20}', Grades.C)416self.assertFormatIsValue('{0:+}', Grades.C)417self.assertFormatIsValue('{0:08X}', Grades.C)418self.assertFormatIsValue('{0:b}', Grades.C)419420def test_format_enum_str(self):421Directional = self.Directional422self.assertFormatIsValue('{0}', Directional.WEST)423self.assertFormatIsValue('{0:}', Directional.WEST)424self.assertFormatIsValue('{0:20}', Directional.WEST)425self.assertFormatIsValue('{0:^20}', Directional.WEST)426self.assertFormatIsValue('{0:>20}', Directional.WEST)427self.assertFormatIsValue('{0:<20}', Directional.WEST)428429def test_hash(self):430Season = self.Season431dates = {}432dates[Season.WINTER] = '1225'433dates[Season.SPRING] = '0315'434dates[Season.SUMMER] = '0704'435dates[Season.AUTUMN] = '1031'436self.assertEqual(dates[Season.AUTUMN], '1031')437438def test_enum_duplicates(self):439__order__ = "SPRING SUMMER AUTUMN WINTER"440class Season(Enum):441SPRING = 1442SUMMER = 2443AUTUMN = FALL = 3444WINTER = 4445ANOTHER_SPRING = 1446lst = list(Season)447self.assertEqual(448lst,449[Season.SPRING, Season.SUMMER,450Season.AUTUMN, Season.WINTER,451])452self.assertTrue(Season.FALL is Season.AUTUMN)453self.assertEqual(Season.FALL.value, 3)454self.assertEqual(Season.AUTUMN.value, 3)455self.assertTrue(Season(3) is Season.AUTUMN)456self.assertTrue(Season(1) is Season.SPRING)457self.assertEqual(Season.FALL.name, 'AUTUMN')458self.assertEqual(459set([k for k,v in Season.__members__.items() if v.name != k]),460set(['FALL', 'ANOTHER_SPRING']),461)462463if pyver >= 3.0:464cls = vars()465result = {'Enum':Enum}466exec("""def test_duplicate_name(self):467with self.assertRaises(TypeError):468class Color(Enum):469red = 1470green = 2471blue = 3472red = 4473474with self.assertRaises(TypeError):475class Color(Enum):476red = 1477green = 2478blue = 3479def red(self):480return 'red'481482with self.assertRaises(TypeError):483class Color(Enum):484@property485486def red(self):487return 'redder'488red = 1489green = 2490blue = 3""",491result)492cls['test_duplicate_name'] = result['test_duplicate_name']493494def test_enum_with_value_name(self):495class Huh(Enum):496name = 1497value = 2498self.assertEqual(499list(Huh),500[Huh.name, Huh.value],501)502self.assertTrue(type(Huh.name) is Huh)503self.assertEqual(Huh.name.name, 'name')504self.assertEqual(Huh.name.value, 1)505506def test_intenum_from_scratch(self):507class phy(int, Enum):508pi = 3509tau = 2 * pi510self.assertTrue(phy.pi < phy.tau)511512def test_intenum_inherited(self):513class IntEnum(int, Enum):514pass515class phy(IntEnum):516pi = 3517tau = 2 * pi518self.assertTrue(phy.pi < phy.tau)519520def test_floatenum_from_scratch(self):521class phy(float, Enum):522pi = 3.1415926523tau = 2 * pi524self.assertTrue(phy.pi < phy.tau)525526def test_floatenum_inherited(self):527class FloatEnum(float, Enum):528pass529class phy(FloatEnum):530pi = 3.1415926531tau = 2 * pi532self.assertTrue(phy.pi < phy.tau)533534def test_strenum_from_scratch(self):535class phy(str, Enum):536pi = 'Pi'537tau = 'Tau'538self.assertTrue(phy.pi < phy.tau)539540def test_strenum_inherited(self):541class StrEnum(str, Enum):542pass543class phy(StrEnum):544pi = 'Pi'545tau = 'Tau'546self.assertTrue(phy.pi < phy.tau)547548def test_intenum(self):549class WeekDay(IntEnum):550SUNDAY = 1551MONDAY = 2552TUESDAY = 3553WEDNESDAY = 4554THURSDAY = 5555FRIDAY = 6556SATURDAY = 7557558self.assertEqual(['a', 'b', 'c'][WeekDay.MONDAY], 'c')559self.assertEqual([i for i in range(WeekDay.TUESDAY)], [0, 1, 2])560561lst = list(WeekDay)562self.assertEqual(len(lst), len(WeekDay))563self.assertEqual(len(WeekDay), 7)564target = 'SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY'565target = target.split()566for i, weekday in enumerate(target):567i += 1568e = WeekDay(i)569self.assertEqual(e, i)570self.assertEqual(int(e), i)571self.assertEqual(e.name, weekday)572self.assertTrue(e in WeekDay)573self.assertEqual(lst.index(e)+1, i)574self.assertTrue(0 < e < 8)575self.assertTrue(type(e) is WeekDay)576self.assertTrue(isinstance(e, int))577self.assertTrue(isinstance(e, Enum))578579def test_intenum_duplicates(self):580class WeekDay(IntEnum):581__order__ = 'SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY'582SUNDAY = 1583MONDAY = 2584TUESDAY = TEUSDAY = 3585WEDNESDAY = 4586THURSDAY = 5587FRIDAY = 6588SATURDAY = 7589self.assertTrue(WeekDay.TEUSDAY is WeekDay.TUESDAY)590self.assertEqual(WeekDay(3).name, 'TUESDAY')591self.assertEqual([k for k,v in WeekDay.__members__.items()592if v.name != k], ['TEUSDAY', ])593594def test_pickle_enum(self):595if isinstance(Stooges, Exception):596raise Stooges597test_pickle_dump_load(self.assertTrue, Stooges.CURLY)598test_pickle_dump_load(self.assertTrue, Stooges)599600def test_pickle_int(self):601if isinstance(IntStooges, Exception):602raise IntStooges603test_pickle_dump_load(self.assertTrue, IntStooges.CURLY)604test_pickle_dump_load(self.assertTrue, IntStooges)605606def test_pickle_float(self):607if isinstance(FloatStooges, Exception):608raise FloatStooges609test_pickle_dump_load(self.assertTrue, FloatStooges.CURLY)610test_pickle_dump_load(self.assertTrue, FloatStooges)611612def test_pickle_enum_function(self):613if isinstance(Answer, Exception):614raise Answer615test_pickle_dump_load(self.assertTrue, Answer.him)616test_pickle_dump_load(self.assertTrue, Answer)617618def test_pickle_enum_function_with_module(self):619if isinstance(Question, Exception):620raise Question621test_pickle_dump_load(self.assertTrue, Question.who)622test_pickle_dump_load(self.assertTrue, Question)623624if pyver == 3.4:625def test_class_nested_enum_and_pickle_protocol_four(self):626# would normally just have this directly in the class namespace627class NestedEnum(Enum):628twigs = 'common'629shiny = 'rare'630631self.__class__.NestedEnum = NestedEnum632self.NestedEnum.__qualname__ = '%s.NestedEnum' % self.__class__.__name__633test_pickle_exception(634self.assertRaises, PicklingError, self.NestedEnum.twigs,635protocol=(0, 3))636test_pickle_dump_load(self.assertTrue, self.NestedEnum.twigs,637protocol=(4, HIGHEST_PROTOCOL))638639elif pyver == 3.5:640def test_class_nested_enum_and_pickle_protocol_four(self):641# would normally just have this directly in the class namespace642class NestedEnum(Enum):643twigs = 'common'644shiny = 'rare'645646self.__class__.NestedEnum = NestedEnum647self.NestedEnum.__qualname__ = '%s.NestedEnum' % self.__class__.__name__648test_pickle_dump_load(self.assertTrue, self.NestedEnum.twigs,649protocol=(0, HIGHEST_PROTOCOL))650651def test_exploding_pickle(self):652BadPickle = Enum('BadPickle', 'dill sweet bread-n-butter')653enum._make_class_unpicklable(BadPickle)654globals()['BadPickle'] = BadPickle655test_pickle_exception(self.assertRaises, TypeError, BadPickle.dill)656test_pickle_exception(self.assertRaises, PicklingError, BadPickle)657658def test_string_enum(self):659class SkillLevel(str, Enum):660master = 'what is the sound of one hand clapping?'661journeyman = 'why did the chicken cross the road?'662apprentice = 'knock, knock!'663self.assertEqual(SkillLevel.apprentice, 'knock, knock!')664665def test_getattr_getitem(self):666class Period(Enum):667morning = 1668noon = 2669evening = 3670night = 4671self.assertTrue(Period(2) is Period.noon)672self.assertTrue(getattr(Period, 'night') is Period.night)673self.assertTrue(Period['morning'] is Period.morning)674675def test_getattr_dunder(self):676Season = self.Season677self.assertTrue(getattr(Season, '__hash__'))678679def test_iteration_order(self):680class Season(Enum):681__order__ = 'SUMMER WINTER AUTUMN SPRING'682SUMMER = 2683WINTER = 4684AUTUMN = 3685SPRING = 1686self.assertEqual(687list(Season),688[Season.SUMMER, Season.WINTER, Season.AUTUMN, Season.SPRING],689)690691def test_iteration_order_reversed(self):692self.assertEqual(693list(reversed(self.Season)),694[self.Season.WINTER, self.Season.AUTUMN, self.Season.SUMMER,695self.Season.SPRING]696)697698def test_iteration_order_with_unorderable_values(self):699class Complex(Enum):700a = complex(7, 9)701b = complex(3.14, 2)702c = complex(1, -1)703d = complex(-77, 32)704self.assertEqual(705list(Complex),706[Complex.a, Complex.b, Complex.c, Complex.d],707)708709def test_programatic_function_string(self):710SummerMonth = Enum('SummerMonth', 'june july august')711lst = list(SummerMonth)712self.assertEqual(len(lst), len(SummerMonth))713self.assertEqual(len(SummerMonth), 3, SummerMonth)714self.assertEqual(715[SummerMonth.june, SummerMonth.july, SummerMonth.august],716lst,717)718for i, month in enumerate('june july august'.split()):719i += 1720e = SummerMonth(i)721self.assertEqual(int(e.value), i)722self.assertNotEqual(e, i)723self.assertEqual(e.name, month)724self.assertTrue(e in SummerMonth)725self.assertTrue(type(e) is SummerMonth)726727def test_programatic_function_string_with_start(self):728SummerMonth = Enum('SummerMonth', 'june july august', start=10)729lst = list(SummerMonth)730self.assertEqual(len(lst), len(SummerMonth))731self.assertEqual(len(SummerMonth), 3, SummerMonth)732self.assertEqual(733[SummerMonth.june, SummerMonth.july, SummerMonth.august],734lst,735)736for i, month in enumerate('june july august'.split(), 10):737e = SummerMonth(i)738self.assertEqual(int(e.value), i)739self.assertNotEqual(e, i)740self.assertEqual(e.name, month)741self.assertTrue(e in SummerMonth)742self.assertTrue(type(e) is SummerMonth)743744def test_programatic_function_string_list(self):745SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'])746lst = list(SummerMonth)747self.assertEqual(len(lst), len(SummerMonth))748self.assertEqual(len(SummerMonth), 3, SummerMonth)749self.assertEqual(750[SummerMonth.june, SummerMonth.july, SummerMonth.august],751lst,752)753for i, month in enumerate('june july august'.split()):754i += 1755e = SummerMonth(i)756self.assertEqual(int(e.value), i)757self.assertNotEqual(e, i)758self.assertEqual(e.name, month)759self.assertTrue(e in SummerMonth)760self.assertTrue(type(e) is SummerMonth)761762def test_programatic_function_string_list_with_start(self):763SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'], start=20)764lst = list(SummerMonth)765self.assertEqual(len(lst), len(SummerMonth))766self.assertEqual(len(SummerMonth), 3, SummerMonth)767self.assertEqual(768[SummerMonth.june, SummerMonth.july, SummerMonth.august],769lst,770)771for i, month in enumerate('june july august'.split(), 20):772e = SummerMonth(i)773self.assertEqual(int(e.value), i)774self.assertNotEqual(e, i)775self.assertEqual(e.name, month)776self.assertTrue(e in SummerMonth)777self.assertTrue(type(e) is SummerMonth)778779def test_programatic_function_iterable(self):780SummerMonth = Enum(781'SummerMonth',782(('june', 1), ('july', 2), ('august', 3))783)784lst = list(SummerMonth)785self.assertEqual(len(lst), len(SummerMonth))786self.assertEqual(len(SummerMonth), 3, SummerMonth)787self.assertEqual(788[SummerMonth.june, SummerMonth.july, SummerMonth.august],789lst,790)791for i, month in enumerate('june july august'.split()):792i += 1793e = SummerMonth(i)794self.assertEqual(int(e.value), i)795self.assertNotEqual(e, i)796self.assertEqual(e.name, month)797self.assertTrue(e in SummerMonth)798self.assertTrue(type(e) is SummerMonth)799800def test_programatic_function_from_dict(self):801SummerMonth = Enum(802'SummerMonth',803dict((('june', 1), ('july', 2), ('august', 3)))804)805lst = list(SummerMonth)806self.assertEqual(len(lst), len(SummerMonth))807self.assertEqual(len(SummerMonth), 3, SummerMonth)808if pyver < 3.0:809self.assertEqual(810[SummerMonth.june, SummerMonth.july, SummerMonth.august],811lst,812)813for i, month in enumerate('june july august'.split()):814i += 1815e = SummerMonth(i)816self.assertEqual(int(e.value), i)817self.assertNotEqual(e, i)818self.assertEqual(e.name, month)819self.assertTrue(e in SummerMonth)820self.assertTrue(type(e) is SummerMonth)821822def test_programatic_function_type(self):823SummerMonth = Enum('SummerMonth', 'june july august', type=int)824lst = list(SummerMonth)825self.assertEqual(len(lst), len(SummerMonth))826self.assertEqual(len(SummerMonth), 3, SummerMonth)827self.assertEqual(828[SummerMonth.june, SummerMonth.july, SummerMonth.august],829lst,830)831for i, month in enumerate('june july august'.split()):832i += 1833e = SummerMonth(i)834self.assertEqual(e, i)835self.assertEqual(e.name, month)836self.assertTrue(e in SummerMonth)837self.assertTrue(type(e) is SummerMonth)838839def test_programatic_function_type_with_start(self):840SummerMonth = Enum('SummerMonth', 'june july august', type=int, start=30)841lst = list(SummerMonth)842self.assertEqual(len(lst), len(SummerMonth))843self.assertEqual(len(SummerMonth), 3, SummerMonth)844self.assertEqual(845[SummerMonth.june, SummerMonth.july, SummerMonth.august],846lst,847)848for i, month in enumerate('june july august'.split(), 30):849e = SummerMonth(i)850self.assertEqual(e, i)851self.assertEqual(e.name, month)852self.assertTrue(e in SummerMonth)853self.assertTrue(type(e) is SummerMonth)854855def test_programatic_function_type_from_subclass(self):856SummerMonth = IntEnum('SummerMonth', 'june july august')857lst = list(SummerMonth)858self.assertEqual(len(lst), len(SummerMonth))859self.assertEqual(len(SummerMonth), 3, SummerMonth)860self.assertEqual(861[SummerMonth.june, SummerMonth.july, SummerMonth.august],862lst,863)864for i, month in enumerate('june july august'.split()):865i += 1866e = SummerMonth(i)867self.assertEqual(e, i)868self.assertEqual(e.name, month)869self.assertTrue(e in SummerMonth)870self.assertTrue(type(e) is SummerMonth)871872def test_programatic_function_type_from_subclass_with_start(self):873SummerMonth = IntEnum('SummerMonth', 'june july august', start=40)874lst = list(SummerMonth)875self.assertEqual(len(lst), len(SummerMonth))876self.assertEqual(len(SummerMonth), 3, SummerMonth)877self.assertEqual(878[SummerMonth.june, SummerMonth.july, SummerMonth.august],879lst,880)881for i, month in enumerate('june july august'.split(), 40):882e = SummerMonth(i)883self.assertEqual(e, i)884self.assertEqual(e.name, month)885self.assertTrue(e in SummerMonth)886self.assertTrue(type(e) is SummerMonth)887888def test_programatic_function_unicode(self):889SummerMonth = Enum('SummerMonth', unicode('june july august'))890lst = list(SummerMonth)891self.assertEqual(len(lst), len(SummerMonth))892self.assertEqual(len(SummerMonth), 3, SummerMonth)893self.assertEqual(894[SummerMonth.june, SummerMonth.july, SummerMonth.august],895lst,896)897for i, month in enumerate(unicode('june july august').split()):898i += 1899e = SummerMonth(i)900self.assertEqual(int(e.value), i)901self.assertNotEqual(e, i)902self.assertEqual(e.name, month)903self.assertTrue(e in SummerMonth)904self.assertTrue(type(e) is SummerMonth)905906def test_programatic_function_unicode_list(self):907SummerMonth = Enum('SummerMonth', [unicode('june'), unicode('july'), unicode('august')])908lst = list(SummerMonth)909self.assertEqual(len(lst), len(SummerMonth))910self.assertEqual(len(SummerMonth), 3, SummerMonth)911self.assertEqual(912[SummerMonth.june, SummerMonth.july, SummerMonth.august],913lst,914)915for i, month in enumerate(unicode('june july august').split()):916i += 1917e = SummerMonth(i)918self.assertEqual(int(e.value), i)919self.assertNotEqual(e, i)920self.assertEqual(e.name, month)921self.assertTrue(e in SummerMonth)922self.assertTrue(type(e) is SummerMonth)923924def test_programatic_function_unicode_iterable(self):925SummerMonth = Enum(926'SummerMonth',927((unicode('june'), 1), (unicode('july'), 2), (unicode('august'), 3))928)929lst = list(SummerMonth)930self.assertEqual(len(lst), len(SummerMonth))931self.assertEqual(len(SummerMonth), 3, SummerMonth)932self.assertEqual(933[SummerMonth.june, SummerMonth.july, SummerMonth.august],934lst,935)936for i, month in enumerate(unicode('june july august').split()):937i += 1938e = SummerMonth(i)939self.assertEqual(int(e.value), i)940self.assertNotEqual(e, i)941self.assertEqual(e.name, month)942self.assertTrue(e in SummerMonth)943self.assertTrue(type(e) is SummerMonth)944945def test_programatic_function_from_unicode_dict(self):946SummerMonth = Enum(947'SummerMonth',948dict(((unicode('june'), 1), (unicode('july'), 2), (unicode('august'), 3)))949)950lst = list(SummerMonth)951self.assertEqual(len(lst), len(SummerMonth))952self.assertEqual(len(SummerMonth), 3, SummerMonth)953if pyver < 3.0:954self.assertEqual(955[SummerMonth.june, SummerMonth.july, SummerMonth.august],956lst,957)958for i, month in enumerate(unicode('june july august').split()):959i += 1960e = SummerMonth(i)961self.assertEqual(int(e.value), i)962self.assertNotEqual(e, i)963self.assertEqual(e.name, month)964self.assertTrue(e in SummerMonth)965self.assertTrue(type(e) is SummerMonth)966967def test_programatic_function_unicode_type(self):968SummerMonth = Enum('SummerMonth', unicode('june july august'), type=int)969lst = list(SummerMonth)970self.assertEqual(len(lst), len(SummerMonth))971self.assertEqual(len(SummerMonth), 3, SummerMonth)972self.assertEqual(973[SummerMonth.june, SummerMonth.july, SummerMonth.august],974lst,975)976for i, month in enumerate(unicode('june july august').split()):977i += 1978e = SummerMonth(i)979self.assertEqual(e, i)980self.assertEqual(e.name, month)981self.assertTrue(e in SummerMonth)982self.assertTrue(type(e) is SummerMonth)983984def test_programatic_function_unicode_type_from_subclass(self):985SummerMonth = IntEnum('SummerMonth', unicode('june july august'))986lst = list(SummerMonth)987self.assertEqual(len(lst), len(SummerMonth))988self.assertEqual(len(SummerMonth), 3, SummerMonth)989self.assertEqual(990[SummerMonth.june, SummerMonth.july, SummerMonth.august],991lst,992)993for i, month in enumerate(unicode('june july august').split()):994i += 1995e = SummerMonth(i)996self.assertEqual(e, i)997self.assertEqual(e.name, month)998self.assertTrue(e in SummerMonth)999self.assertTrue(type(e) is SummerMonth)10001001def test_programmatic_function_unicode_class(self):1002if pyver < 3.0:1003class_names = unicode('SummerMonth'), 'S\xfcmm\xe9rM\xf6nth'.decode('latin1')1004else:1005class_names = 'SummerMonth', 'S\xfcmm\xe9rM\xf6nth'1006for i, class_name in enumerate(class_names):1007if pyver < 3.0 and i == 1:1008self.assertRaises(TypeError, Enum, class_name, unicode('june july august'))1009else:1010SummerMonth = Enum(class_name, unicode('june july august'))1011lst = list(SummerMonth)1012self.assertEqual(len(lst), len(SummerMonth))1013self.assertEqual(len(SummerMonth), 3, SummerMonth)1014self.assertEqual(1015[SummerMonth.june, SummerMonth.july, SummerMonth.august],1016lst,1017)1018for i, month in enumerate(unicode('june july august').split()):1019i += 11020e = SummerMonth(i)1021self.assertEqual(e.value, i)1022self.assertEqual(e.name, month)1023self.assertTrue(e in SummerMonth)1024self.assertTrue(type(e) is SummerMonth)10251026def test_subclassing(self):1027if isinstance(Name, Exception):1028raise Name1029self.assertEqual(Name.BDFL, 'Guido van Rossum')1030self.assertTrue(Name.BDFL, Name('Guido van Rossum'))1031self.assertTrue(Name.BDFL is getattr(Name, 'BDFL'))1032test_pickle_dump_load(self.assertTrue, Name.BDFL)10331034def test_extending(self):1035def bad_extension():1036class Color(Enum):1037red = 11038green = 21039blue = 31040class MoreColor(Color):1041cyan = 41042magenta = 51043yellow = 61044self.assertRaises(TypeError, bad_extension)10451046def test_exclude_methods(self):1047class whatever(Enum):1048this = 'that'1049these = 'those'1050def really(self):1051return 'no, not %s' % self.value1052self.assertFalse(type(whatever.really) is whatever)1053self.assertEqual(whatever.this.really(), 'no, not that')10541055def test_wrong_inheritance_order(self):1056def wrong_inherit():1057class Wrong(Enum, str):1058NotHere = 'error before this point'1059self.assertRaises(TypeError, wrong_inherit)10601061def test_intenum_transitivity(self):1062class number(IntEnum):1063one = 11064two = 21065three = 31066class numero(IntEnum):1067uno = 11068dos = 21069tres = 31070self.assertEqual(number.one, numero.uno)1071self.assertEqual(number.two, numero.dos)1072self.assertEqual(number.three, numero.tres)10731074def test_introspection(self):1075class Number(IntEnum):1076one = 1001077two = 2001078self.assertTrue(Number.one._member_type_ is int)1079self.assertTrue(Number._member_type_ is int)1080class String(str, Enum):1081yarn = 'soft'1082rope = 'rough'1083wire = 'hard'1084self.assertTrue(String.yarn._member_type_ is str)1085self.assertTrue(String._member_type_ is str)1086class Plain(Enum):1087vanilla = 'white'1088one = 11089self.assertTrue(Plain.vanilla._member_type_ is object)1090self.assertTrue(Plain._member_type_ is object)10911092def test_wrong_enum_in_call(self):1093class Monochrome(Enum):1094black = 01095white = 11096class Gender(Enum):1097male = 01098female = 11099self.assertRaises(ValueError, Monochrome, Gender.male)11001101def test_wrong_enum_in_mixed_call(self):1102class Monochrome(IntEnum):1103black = 01104white = 11105class Gender(Enum):1106male = 01107female = 11108self.assertRaises(ValueError, Monochrome, Gender.male)11091110def test_mixed_enum_in_call_1(self):1111class Monochrome(IntEnum):1112black = 01113white = 11114class Gender(IntEnum):1115male = 01116female = 11117self.assertTrue(Monochrome(Gender.female) is Monochrome.white)11181119def test_mixed_enum_in_call_2(self):1120class Monochrome(Enum):1121black = 01122white = 11123class Gender(IntEnum):1124male = 01125female = 11126self.assertTrue(Monochrome(Gender.male) is Monochrome.black)11271128def test_flufl_enum(self):1129class Fluflnum(Enum):1130def __int__(self):1131return int(self.value)1132class MailManOptions(Fluflnum):1133option1 = 11134option2 = 21135option3 = 31136self.assertEqual(int(MailManOptions.option1), 1)11371138def test_no_such_enum_member(self):1139class Color(Enum):1140red = 11141green = 21142blue = 31143self.assertRaises(ValueError, Color, 4)1144self.assertRaises(KeyError, Color.__getitem__, 'chartreuse')11451146def test_new_repr(self):1147class Color(Enum):1148red = 11149green = 21150blue = 31151def __repr__(self):1152return "don't you just love shades of %s?" % self.name1153self.assertEqual(1154repr(Color.blue),1155"don't you just love shades of blue?",1156)11571158def test_inherited_repr(self):1159class MyEnum(Enum):1160def __repr__(self):1161return "My name is %s." % self.name1162class MyIntEnum(int, MyEnum):1163this = 11164that = 21165theother = 31166self.assertEqual(repr(MyIntEnum.that), "My name is that.")11671168def test_multiple_mixin_mro(self):1169class auto_enum(EnumMeta):1170def __new__(metacls, cls, bases, classdict):1171original_dict = classdict1172classdict = enum._EnumDict()1173for k, v in original_dict.items():1174classdict[k] = v1175temp = type(classdict)()1176names = set(classdict._member_names)1177i = 01178for k in classdict._member_names:1179v = classdict[k]1180if v == ():1181v = i1182else:1183i = v1184i += 11185temp[k] = v1186for k, v in classdict.items():1187if k not in names:1188temp[k] = v1189return super(auto_enum, metacls).__new__(1190metacls, cls, bases, temp)11911192AutoNumberedEnum = auto_enum('AutoNumberedEnum', (Enum,), {})11931194AutoIntEnum = auto_enum('AutoIntEnum', (IntEnum,), {})11951196class TestAutoNumber(AutoNumberedEnum):1197a = ()1198b = 31199c = ()12001201class TestAutoInt(AutoIntEnum):1202a = ()1203b = 31204c = ()12051206def test_subclasses_with_getnewargs(self):1207class NamedInt(int):1208__qualname__ = 'NamedInt' # needed for pickle protocol 41209def __new__(cls, *args):1210_args = args1211if len(args) < 1:1212raise TypeError("name and value must be specified")1213name, args = args[0], args[1:]1214self = int.__new__(cls, *args)1215self._intname = name1216self._args = _args1217return self1218def __getnewargs__(self):1219return self._args1220@property1221def __name__(self):1222return self._intname1223def __repr__(self):1224# repr() is updated to include the name and type info1225return "%s(%r, %s)" % (type(self).__name__,1226self.__name__,1227int.__repr__(self))1228def __str__(self):1229# str() is unchanged, even if it relies on the repr() fallback1230base = int1231base_str = base.__str__1232if base_str.__objclass__ is object:1233return base.__repr__(self)1234return base_str(self)1235# for simplicity, we only define one operator that1236# propagates expressions1237def __add__(self, other):1238temp = int(self) + int( other)1239if isinstance(self, NamedInt) and isinstance(other, NamedInt):1240return NamedInt(1241'(%s + %s)' % (self.__name__, other.__name__),1242temp )1243else:1244return temp12451246class NEI(NamedInt, Enum):1247__qualname__ = 'NEI' # needed for pickle protocol 41248x = ('the-x', 1)1249y = ('the-y', 2)12501251self.assertTrue(NEI.__new__ is Enum.__new__)1252self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")1253globals()['NamedInt'] = NamedInt1254globals()['NEI'] = NEI1255NI5 = NamedInt('test', 5)1256self.assertEqual(NI5, 5)1257test_pickle_dump_load(self.assertTrue, NI5, 5)1258self.assertEqual(NEI.y.value, 2)1259test_pickle_dump_load(self.assertTrue, NEI.y)12601261if pyver >= 3.4:1262def test_subclasses_with_getnewargs_ex(self):1263class NamedInt(int):1264__qualname__ = 'NamedInt' # needed for pickle protocol 41265def __new__(cls, *args):1266_args = args1267if len(args) < 2:1268raise TypeError("name and value must be specified")1269name, args = args[0], args[1:]1270self = int.__new__(cls, *args)1271self._intname = name1272self._args = _args1273return self1274def __getnewargs_ex__(self):1275return self._args, {}1276@property1277def __name__(self):1278return self._intname1279def __repr__(self):1280# repr() is updated to include the name and type info1281return "{}({!r}, {})".format(type(self).__name__,1282self.__name__,1283int.__repr__(self))1284def __str__(self):1285# str() is unchanged, even if it relies on the repr() fallback1286base = int1287base_str = base.__str__1288if base_str.__objclass__ is object:1289return base.__repr__(self)1290return base_str(self)1291# for simplicity, we only define one operator that1292# propagates expressions1293def __add__(self, other):1294temp = int(self) + int( other)1295if isinstance(self, NamedInt) and isinstance(other, NamedInt):1296return NamedInt(1297'({0} + {1})'.format(self.__name__, other.__name__),1298temp )1299else:1300return temp13011302class NEI(NamedInt, Enum):1303__qualname__ = 'NEI' # needed for pickle protocol 41304x = ('the-x', 1)1305y = ('the-y', 2)130613071308self.assertIs(NEI.__new__, Enum.__new__)1309self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")1310globals()['NamedInt'] = NamedInt1311globals()['NEI'] = NEI1312NI5 = NamedInt('test', 5)1313self.assertEqual(NI5, 5)1314test_pickle_dump_load(self.assertEqual, NI5, 5, protocol=(4, HIGHEST_PROTOCOL))1315self.assertEqual(NEI.y.value, 2)1316test_pickle_dump_load(self.assertTrue, NEI.y, protocol=(4, HIGHEST_PROTOCOL))13171318def test_subclasses_with_reduce(self):1319class NamedInt(int):1320__qualname__ = 'NamedInt' # needed for pickle protocol 41321def __new__(cls, *args):1322_args = args1323if len(args) < 1:1324raise TypeError("name and value must be specified")1325name, args = args[0], args[1:]1326self = int.__new__(cls, *args)1327self._intname = name1328self._args = _args1329return self1330def __reduce__(self):1331return self.__class__, self._args1332@property1333def __name__(self):1334return self._intname1335def __repr__(self):1336# repr() is updated to include the name and type info1337return "%s(%r, %s)" % (type(self).__name__,1338self.__name__,1339int.__repr__(self))1340def __str__(self):1341# str() is unchanged, even if it relies on the repr() fallback1342base = int1343base_str = base.__str__1344if base_str.__objclass__ is object:1345return base.__repr__(self)1346return base_str(self)1347# for simplicity, we only define one operator that1348# propagates expressions1349def __add__(self, other):1350temp = int(self) + int( other)1351if isinstance(self, NamedInt) and isinstance(other, NamedInt):1352return NamedInt(1353'(%s + %s)' % (self.__name__, other.__name__),1354temp )1355else:1356return temp13571358class NEI(NamedInt, Enum):1359__qualname__ = 'NEI' # needed for pickle protocol 41360x = ('the-x', 1)1361y = ('the-y', 2)136213631364self.assertTrue(NEI.__new__ is Enum.__new__)1365self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")1366globals()['NamedInt'] = NamedInt1367globals()['NEI'] = NEI1368NI5 = NamedInt('test', 5)1369self.assertEqual(NI5, 5)1370test_pickle_dump_load(self.assertEqual, NI5, 5)1371self.assertEqual(NEI.y.value, 2)1372test_pickle_dump_load(self.assertTrue, NEI.y)13731374def test_subclasses_with_reduce_ex(self):1375class NamedInt(int):1376__qualname__ = 'NamedInt' # needed for pickle protocol 41377def __new__(cls, *args):1378_args = args1379if len(args) < 1:1380raise TypeError("name and value must be specified")1381name, args = args[0], args[1:]1382self = int.__new__(cls, *args)1383self._intname = name1384self._args = _args1385return self1386def __reduce_ex__(self, proto):1387return self.__class__, self._args1388@property1389def __name__(self):1390return self._intname1391def __repr__(self):1392# repr() is updated to include the name and type info1393return "%s(%r, %s)" % (type(self).__name__,1394self.__name__,1395int.__repr__(self))1396def __str__(self):1397# str() is unchanged, even if it relies on the repr() fallback1398base = int1399base_str = base.__str__1400if base_str.__objclass__ is object:1401return base.__repr__(self)1402return base_str(self)1403# for simplicity, we only define one operator that1404# propagates expressions1405def __add__(self, other):1406temp = int(self) + int( other)1407if isinstance(self, NamedInt) and isinstance(other, NamedInt):1408return NamedInt(1409'(%s + %s)' % (self.__name__, other.__name__),1410temp )1411else:1412return temp14131414class NEI(NamedInt, Enum):1415__qualname__ = 'NEI' # needed for pickle protocol 41416x = ('the-x', 1)1417y = ('the-y', 2)141814191420self.assertTrue(NEI.__new__ is Enum.__new__)1421self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")1422globals()['NamedInt'] = NamedInt1423globals()['NEI'] = NEI1424NI5 = NamedInt('test', 5)1425self.assertEqual(NI5, 5)1426test_pickle_dump_load(self.assertEqual, NI5, 5)1427self.assertEqual(NEI.y.value, 2)1428test_pickle_dump_load(self.assertTrue, NEI.y)14291430def test_subclasses_without_direct_pickle_support(self):1431class NamedInt(int):1432__qualname__ = 'NamedInt'1433def __new__(cls, *args):1434_args = args1435name, args = args[0], args[1:]1436if len(args) == 0:1437raise TypeError("name and value must be specified")1438self = int.__new__(cls, *args)1439self._intname = name1440self._args = _args1441return self1442@property1443def __name__(self):1444return self._intname1445def __repr__(self):1446# repr() is updated to include the name and type info1447return "%s(%r, %s)" % (type(self).__name__,1448self.__name__,1449int.__repr__(self))1450def __str__(self):1451# str() is unchanged, even if it relies on the repr() fallback1452base = int1453base_str = base.__str__1454if base_str.__objclass__ is object:1455return base.__repr__(self)1456return base_str(self)1457# for simplicity, we only define one operator that1458# propagates expressions1459def __add__(self, other):1460temp = int(self) + int( other)1461if isinstance(self, NamedInt) and isinstance(other, NamedInt):1462return NamedInt(1463'(%s + %s)' % (self.__name__, other.__name__),1464temp )1465else:1466return temp14671468class NEI(NamedInt, Enum):1469__qualname__ = 'NEI'1470x = ('the-x', 1)1471y = ('the-y', 2)14721473self.assertTrue(NEI.__new__ is Enum.__new__)1474self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")1475globals()['NamedInt'] = NamedInt1476globals()['NEI'] = NEI1477NI5 = NamedInt('test', 5)1478self.assertEqual(NI5, 5)1479self.assertEqual(NEI.y.value, 2)1480test_pickle_exception(self.assertRaises, TypeError, NEI.x)1481test_pickle_exception(self.assertRaises, PicklingError, NEI)14821483def test_subclasses_without_direct_pickle_support_using_name(self):1484class NamedInt(int):1485__qualname__ = 'NamedInt'1486def __new__(cls, *args):1487_args = args1488name, args = args[0], args[1:]1489if len(args) == 0:1490raise TypeError("name and value must be specified")1491self = int.__new__(cls, *args)1492self._intname = name1493self._args = _args1494return self1495@property1496def __name__(self):1497return self._intname1498def __repr__(self):1499# repr() is updated to include the name and type info1500return "%s(%r, %s)" % (type(self).__name__,1501self.__name__,1502int.__repr__(self))1503def __str__(self):1504# str() is unchanged, even if it relies on the repr() fallback1505base = int1506base_str = base.__str__1507if base_str.__objclass__ is object:1508return base.__repr__(self)1509return base_str(self)1510# for simplicity, we only define one operator that1511# propagates expressions1512def __add__(self, other):1513temp = int(self) + int( other)1514if isinstance(self, NamedInt) and isinstance(other, NamedInt):1515return NamedInt(1516'(%s + %s)' % (self.__name__, other.__name__),1517temp )1518else:1519return temp15201521class NEI(NamedInt, Enum):1522__qualname__ = 'NEI'1523x = ('the-x', 1)1524y = ('the-y', 2)1525def __reduce_ex__(self, proto):1526return getattr, (self.__class__, self._name_)15271528self.assertTrue(NEI.__new__ is Enum.__new__)1529self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)")1530globals()['NamedInt'] = NamedInt1531globals()['NEI'] = NEI1532NI5 = NamedInt('test', 5)1533self.assertEqual(NI5, 5)1534self.assertEqual(NEI.y.value, 2)1535test_pickle_dump_load(self.assertTrue, NEI.y)1536test_pickle_dump_load(self.assertTrue, NEI)15371538def test_tuple_subclass(self):1539class SomeTuple(tuple, Enum):1540__qualname__ = 'SomeTuple'1541first = (1, 'for the money')1542second = (2, 'for the show')1543third = (3, 'for the music')1544self.assertTrue(type(SomeTuple.first) is SomeTuple)1545self.assertTrue(isinstance(SomeTuple.second, tuple))1546self.assertEqual(SomeTuple.third, (3, 'for the music'))1547globals()['SomeTuple'] = SomeTuple1548test_pickle_dump_load(self.assertTrue, SomeTuple.first)15491550def test_duplicate_values_give_unique_enum_items(self):1551class AutoNumber(Enum):1552__order__ = 'enum_m enum_d enum_y'1553enum_m = ()1554enum_d = ()1555enum_y = ()1556def __new__(cls):1557value = len(cls.__members__) + 11558obj = object.__new__(cls)1559obj._value_ = value1560return obj1561def __int__(self):1562return int(self._value_)1563self.assertEqual(int(AutoNumber.enum_d), 2)1564self.assertEqual(AutoNumber.enum_y.value, 3)1565self.assertTrue(AutoNumber(1) is AutoNumber.enum_m)1566self.assertEqual(1567list(AutoNumber),1568[AutoNumber.enum_m, AutoNumber.enum_d, AutoNumber.enum_y],1569)15701571def test_inherited_new_from_enhanced_enum(self):1572class AutoNumber2(Enum):1573def __new__(cls):1574value = len(cls.__members__) + 11575obj = object.__new__(cls)1576obj._value_ = value1577return obj1578def __int__(self):1579return int(self._value_)1580class Color(AutoNumber2):1581__order__ = 'red green blue'1582red = ()1583green = ()1584blue = ()1585self.assertEqual(len(Color), 3, "wrong number of elements: %d (should be %d)" % (len(Color), 3))1586self.assertEqual(list(Color), [Color.red, Color.green, Color.blue])1587if pyver >= 3.0:1588self.assertEqual(list(map(int, Color)), [1, 2, 3])15891590def test_inherited_new_from_mixed_enum(self):1591class AutoNumber3(IntEnum):1592def __new__(cls):1593value = len(cls.__members__) + 11594obj = int.__new__(cls, value)1595obj._value_ = value1596return obj1597class Color(AutoNumber3):1598red = ()1599green = ()1600blue = ()1601self.assertEqual(len(Color), 3, "wrong number of elements: %d (should be %d)" % (len(Color), 3))1602Color.red1603Color.green1604Color.blue16051606def test_equality(self):1607class AlwaysEqual:1608def __eq__(self, other):1609return True1610class OrdinaryEnum(Enum):1611a = 11612self.assertEqual(AlwaysEqual(), OrdinaryEnum.a)1613self.assertEqual(OrdinaryEnum.a, AlwaysEqual())16141615def test_ordered_mixin(self):1616class OrderedEnum(Enum):1617def __ge__(self, other):1618if self.__class__ is other.__class__:1619return self._value_ >= other._value_1620return NotImplemented1621def __gt__(self, other):1622if self.__class__ is other.__class__:1623return self._value_ > other._value_1624return NotImplemented1625def __le__(self, other):1626if self.__class__ is other.__class__:1627return self._value_ <= other._value_1628return NotImplemented1629def __lt__(self, other):1630if self.__class__ is other.__class__:1631return self._value_ < other._value_1632return NotImplemented1633class Grade(OrderedEnum):1634__order__ = 'A B C D F'1635A = 51636B = 41637C = 31638D = 21639F = 11640self.assertEqual(list(Grade), [Grade.A, Grade.B, Grade.C, Grade.D, Grade.F])1641self.assertTrue(Grade.A > Grade.B)1642self.assertTrue(Grade.F <= Grade.C)1643self.assertTrue(Grade.D < Grade.A)1644self.assertTrue(Grade.B >= Grade.B)16451646def test_extending2(self):1647def bad_extension():1648class Shade(Enum):1649def shade(self):1650print(self.name)1651class Color(Shade):1652red = 11653green = 21654blue = 31655class MoreColor(Color):1656cyan = 41657magenta = 51658yellow = 61659self.assertRaises(TypeError, bad_extension)16601661def test_extending3(self):1662class Shade(Enum):1663def shade(self):1664return self.name1665class Color(Shade):1666def hex(self):1667return '%s hexlified!' % self.value1668class MoreColor(Color):1669cyan = 41670magenta = 51671yellow = 61672self.assertEqual(MoreColor.magenta.hex(), '5 hexlified!')16731674def test_no_duplicates(self):1675def bad_duplicates():1676class UniqueEnum(Enum):1677def __init__(self, *args):1678cls = self.__class__1679if any(self.value == e.value for e in cls):1680a = self.name1681e = cls(self.value).name1682raise ValueError(1683"aliases not allowed in UniqueEnum: %r --> %r"1684% (a, e)1685)1686class Color(UniqueEnum):1687red = 11688green = 21689blue = 31690class Color(UniqueEnum):1691red = 11692green = 21693blue = 31694grene = 21695self.assertRaises(ValueError, bad_duplicates)16961697def test_init(self):1698class Planet(Enum):1699MERCURY = (3.303e+23, 2.4397e6)1700VENUS = (4.869e+24, 6.0518e6)1701EARTH = (5.976e+24, 6.37814e6)1702MARS = (6.421e+23, 3.3972e6)1703JUPITER = (1.9e+27, 7.1492e7)1704SATURN = (5.688e+26, 6.0268e7)1705URANUS = (8.686e+25, 2.5559e7)1706NEPTUNE = (1.024e+26, 2.4746e7)1707def __init__(self, mass, radius):1708self.mass = mass # in kilograms1709self.radius = radius # in meters1710@property1711def surface_gravity(self):1712# universal gravitational constant (m3 kg-1 s-2)1713G = 6.67300E-111714return G * self.mass / (self.radius * self.radius)1715self.assertEqual(round(Planet.EARTH.surface_gravity, 2), 9.80)1716self.assertEqual(Planet.EARTH.value, (5.976e+24, 6.37814e6))17171718def test_nonhash_value(self):1719class AutoNumberInAList(Enum):1720def __new__(cls):1721value = [len(cls.__members__) + 1]1722obj = object.__new__(cls)1723obj._value_ = value1724return obj1725class ColorInAList(AutoNumberInAList):1726__order__ = 'red green blue'1727red = ()1728green = ()1729blue = ()1730self.assertEqual(list(ColorInAList), [ColorInAList.red, ColorInAList.green, ColorInAList.blue])1731self.assertEqual(ColorInAList.red.value, [1])1732self.assertEqual(ColorInAList([1]), ColorInAList.red)17331734def test_conflicting_types_resolved_in_new(self):1735class LabelledIntEnum(int, Enum):1736def __new__(cls, *args):1737value, label = args1738obj = int.__new__(cls, value)1739obj.label = label1740obj._value_ = value1741return obj17421743class LabelledList(LabelledIntEnum):1744unprocessed = (1, "Unprocessed")1745payment_complete = (2, "Payment Complete")17461747self.assertEqual(list(LabelledList), [LabelledList.unprocessed, LabelledList.payment_complete])1748self.assertEqual(LabelledList.unprocessed, 1)1749self.assertEqual(LabelledList(1), LabelledList.unprocessed)17501751def test_empty_with_functional_api(self):1752empty = enum.IntEnum('Foo', {})1753self.assertEqual(len(empty), 0)175417551756class TestUnique(unittest.TestCase):1757"""2.4 doesn't allow class decorators, use function syntax."""17581759def test_unique_clean(self):1760class Clean(Enum):1761one = 11762two = 'dos'1763tres = 4.01764unique(Clean)1765class Cleaner(IntEnum):1766single = 11767double = 21768triple = 31769unique(Cleaner)17701771def test_unique_dirty(self):1772try:1773class Dirty(Enum):1774__order__ = 'one two tres'1775one = 11776two = 'dos'1777tres = 11778unique(Dirty)1779except ValueError:1780exc = sys.exc_info()[1]1781message = exc.args[0]1782self.assertTrue('tres -> one' in message)17831784try:1785class Dirtier(IntEnum):1786__order__ = 'single double triple turkey'1787single = 11788double = 11789triple = 31790turkey = 31791unique(Dirtier)1792except ValueError:1793exc = sys.exc_info()[1]1794message = exc.args[0]1795self.assertTrue('double -> single' in message)1796self.assertTrue('turkey -> triple' in message)179717981799class TestMe(unittest.TestCase):18001801pass18021803if __name__ == '__main__':1804unittest.main()180518061807