Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 1 | import enum |
| 2 | import unittest |
| 3 | from collections import OrderedDict |
| 4 | from pickle import dumps, loads, PicklingError |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 5 | from enum import Enum, IntEnum, unique |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 6 | |
| 7 | # for pickle tests |
| 8 | try: |
| 9 | class Stooges(Enum): |
| 10 | LARRY = 1 |
| 11 | CURLY = 2 |
| 12 | MOE = 3 |
| 13 | except Exception as exc: |
| 14 | Stooges = exc |
| 15 | |
| 16 | try: |
| 17 | class IntStooges(int, Enum): |
| 18 | LARRY = 1 |
| 19 | CURLY = 2 |
| 20 | MOE = 3 |
| 21 | except Exception as exc: |
| 22 | IntStooges = exc |
| 23 | |
| 24 | try: |
| 25 | class FloatStooges(float, Enum): |
| 26 | LARRY = 1.39 |
| 27 | CURLY = 2.72 |
| 28 | MOE = 3.142596 |
| 29 | except Exception as exc: |
| 30 | FloatStooges = exc |
| 31 | |
| 32 | # for pickle test and subclass tests |
| 33 | try: |
| 34 | class StrEnum(str, Enum): |
| 35 | 'accepts only string values' |
| 36 | class Name(StrEnum): |
| 37 | BDFL = 'Guido van Rossum' |
| 38 | FLUFL = 'Barry Warsaw' |
| 39 | except Exception as exc: |
| 40 | Name = exc |
| 41 | |
| 42 | try: |
| 43 | Question = Enum('Question', 'who what when where why', module=__name__) |
| 44 | except Exception as exc: |
| 45 | Question = exc |
| 46 | |
| 47 | try: |
| 48 | Answer = Enum('Answer', 'him this then there because') |
| 49 | except Exception as exc: |
| 50 | Answer = exc |
| 51 | |
| 52 | # for doctests |
| 53 | try: |
| 54 | class Fruit(Enum): |
| 55 | tomato = 1 |
| 56 | banana = 2 |
| 57 | cherry = 3 |
| 58 | except Exception: |
| 59 | pass |
| 60 | |
| 61 | class TestEnum(unittest.TestCase): |
| 62 | def setUp(self): |
| 63 | class Season(Enum): |
| 64 | SPRING = 1 |
| 65 | SUMMER = 2 |
| 66 | AUTUMN = 3 |
| 67 | WINTER = 4 |
| 68 | self.Season = Season |
| 69 | |
Ethan Furman | ec15a82 | 2013-08-31 19:17:41 -0700 | [diff] [blame] | 70 | class Konstants(float, Enum): |
| 71 | E = 2.7182818 |
| 72 | PI = 3.1415926 |
| 73 | TAU = 2 * PI |
| 74 | self.Konstants = Konstants |
| 75 | |
| 76 | class Grades(IntEnum): |
| 77 | A = 5 |
| 78 | B = 4 |
| 79 | C = 3 |
| 80 | D = 2 |
| 81 | F = 0 |
| 82 | self.Grades = Grades |
| 83 | |
| 84 | class Directional(str, Enum): |
| 85 | EAST = 'east' |
| 86 | WEST = 'west' |
| 87 | NORTH = 'north' |
| 88 | SOUTH = 'south' |
| 89 | self.Directional = Directional |
| 90 | |
| 91 | from datetime import date |
| 92 | class Holiday(date, Enum): |
| 93 | NEW_YEAR = 2013, 1, 1 |
| 94 | IDES_OF_MARCH = 2013, 3, 15 |
| 95 | self.Holiday = Holiday |
| 96 | |
Ethan Furman | 388a392 | 2013-08-12 06:51:41 -0700 | [diff] [blame] | 97 | def test_dir_on_class(self): |
| 98 | Season = self.Season |
| 99 | self.assertEqual( |
| 100 | set(dir(Season)), |
| 101 | set(['__class__', '__doc__', '__members__', |
| 102 | 'SPRING', 'SUMMER', 'AUTUMN', 'WINTER']), |
| 103 | ) |
| 104 | |
| 105 | def test_dir_on_item(self): |
| 106 | Season = self.Season |
| 107 | self.assertEqual( |
| 108 | set(dir(Season.WINTER)), |
| 109 | set(['__class__', '__doc__', 'name', 'value']), |
| 110 | ) |
| 111 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 112 | def test_enum_in_enum_out(self): |
| 113 | Season = self.Season |
| 114 | self.assertIs(Season(Season.WINTER), Season.WINTER) |
| 115 | |
| 116 | def test_enum_value(self): |
| 117 | Season = self.Season |
| 118 | self.assertEqual(Season.SPRING.value, 1) |
| 119 | |
| 120 | def test_intenum_value(self): |
| 121 | self.assertEqual(IntStooges.CURLY.value, 2) |
| 122 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 123 | def test_enum(self): |
| 124 | Season = self.Season |
| 125 | lst = list(Season) |
| 126 | self.assertEqual(len(lst), len(Season)) |
| 127 | self.assertEqual(len(Season), 4, Season) |
| 128 | self.assertEqual( |
| 129 | [Season.SPRING, Season.SUMMER, Season.AUTUMN, Season.WINTER], lst) |
| 130 | |
| 131 | for i, season in enumerate('SPRING SUMMER AUTUMN WINTER'.split(), 1): |
| 132 | e = Season(i) |
| 133 | self.assertEqual(e, getattr(Season, season)) |
| 134 | self.assertEqual(e.value, i) |
| 135 | self.assertNotEqual(e, i) |
| 136 | self.assertEqual(e.name, season) |
| 137 | self.assertIn(e, Season) |
| 138 | self.assertIs(type(e), Season) |
| 139 | self.assertIsInstance(e, Season) |
| 140 | self.assertEqual(str(e), 'Season.' + season) |
| 141 | self.assertEqual( |
| 142 | repr(e), |
| 143 | '<Season.{0}: {1}>'.format(season, i), |
| 144 | ) |
| 145 | |
| 146 | def test_value_name(self): |
| 147 | Season = self.Season |
| 148 | self.assertEqual(Season.SPRING.name, 'SPRING') |
| 149 | self.assertEqual(Season.SPRING.value, 1) |
| 150 | with self.assertRaises(AttributeError): |
| 151 | Season.SPRING.name = 'invierno' |
| 152 | with self.assertRaises(AttributeError): |
| 153 | Season.SPRING.value = 2 |
| 154 | |
Ethan Furman | f203f2d | 2013-09-06 07:16:48 -0700 | [diff] [blame] | 155 | def test_changing_member(self): |
| 156 | Season = self.Season |
| 157 | with self.assertRaises(AttributeError): |
| 158 | Season.WINTER = 'really cold' |
| 159 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 160 | def test_invalid_names(self): |
| 161 | with self.assertRaises(ValueError): |
| 162 | class Wrong(Enum): |
| 163 | mro = 9 |
| 164 | with self.assertRaises(ValueError): |
| 165 | class Wrong(Enum): |
| 166 | _create_= 11 |
| 167 | with self.assertRaises(ValueError): |
| 168 | class Wrong(Enum): |
| 169 | _get_mixins_ = 9 |
| 170 | with self.assertRaises(ValueError): |
| 171 | class Wrong(Enum): |
| 172 | _find_new_ = 1 |
| 173 | with self.assertRaises(ValueError): |
| 174 | class Wrong(Enum): |
| 175 | _any_name_ = 9 |
| 176 | |
| 177 | def test_contains(self): |
| 178 | Season = self.Season |
| 179 | self.assertIn(Season.AUTUMN, Season) |
| 180 | self.assertNotIn(3, Season) |
| 181 | |
| 182 | val = Season(3) |
| 183 | self.assertIn(val, Season) |
| 184 | |
| 185 | class OtherEnum(Enum): |
| 186 | one = 1; two = 2 |
| 187 | self.assertNotIn(OtherEnum.two, Season) |
| 188 | |
| 189 | def test_comparisons(self): |
| 190 | Season = self.Season |
| 191 | with self.assertRaises(TypeError): |
| 192 | Season.SPRING < Season.WINTER |
| 193 | with self.assertRaises(TypeError): |
| 194 | Season.SPRING > 4 |
| 195 | |
| 196 | self.assertNotEqual(Season.SPRING, 1) |
| 197 | |
| 198 | class Part(Enum): |
| 199 | SPRING = 1 |
| 200 | CLIP = 2 |
| 201 | BARREL = 3 |
| 202 | |
| 203 | self.assertNotEqual(Season.SPRING, Part.SPRING) |
| 204 | with self.assertRaises(TypeError): |
| 205 | Season.SPRING < Part.CLIP |
| 206 | |
| 207 | def test_enum_duplicates(self): |
| 208 | class Season(Enum): |
| 209 | SPRING = 1 |
| 210 | SUMMER = 2 |
| 211 | AUTUMN = FALL = 3 |
| 212 | WINTER = 4 |
| 213 | ANOTHER_SPRING = 1 |
| 214 | lst = list(Season) |
| 215 | self.assertEqual( |
| 216 | lst, |
| 217 | [Season.SPRING, Season.SUMMER, |
| 218 | Season.AUTUMN, Season.WINTER, |
| 219 | ]) |
| 220 | self.assertIs(Season.FALL, Season.AUTUMN) |
| 221 | self.assertEqual(Season.FALL.value, 3) |
| 222 | self.assertEqual(Season.AUTUMN.value, 3) |
| 223 | self.assertIs(Season(3), Season.AUTUMN) |
| 224 | self.assertIs(Season(1), Season.SPRING) |
| 225 | self.assertEqual(Season.FALL.name, 'AUTUMN') |
| 226 | self.assertEqual( |
| 227 | [k for k,v in Season.__members__.items() if v.name != k], |
| 228 | ['FALL', 'ANOTHER_SPRING'], |
| 229 | ) |
| 230 | |
| 231 | def test_enum_with_value_name(self): |
| 232 | class Huh(Enum): |
| 233 | name = 1 |
| 234 | value = 2 |
| 235 | self.assertEqual( |
| 236 | list(Huh), |
| 237 | [Huh.name, Huh.value], |
| 238 | ) |
| 239 | self.assertIs(type(Huh.name), Huh) |
| 240 | self.assertEqual(Huh.name.name, 'name') |
| 241 | self.assertEqual(Huh.name.value, 1) |
Ethan Furman | ec15a82 | 2013-08-31 19:17:41 -0700 | [diff] [blame] | 242 | |
| 243 | def test_format_enum(self): |
| 244 | Season = self.Season |
| 245 | self.assertEqual('{}'.format(Season.SPRING), |
| 246 | '{}'.format(str(Season.SPRING))) |
| 247 | self.assertEqual( '{:}'.format(Season.SPRING), |
| 248 | '{:}'.format(str(Season.SPRING))) |
| 249 | self.assertEqual('{:20}'.format(Season.SPRING), |
| 250 | '{:20}'.format(str(Season.SPRING))) |
| 251 | self.assertEqual('{:^20}'.format(Season.SPRING), |
| 252 | '{:^20}'.format(str(Season.SPRING))) |
| 253 | self.assertEqual('{:>20}'.format(Season.SPRING), |
| 254 | '{:>20}'.format(str(Season.SPRING))) |
| 255 | self.assertEqual('{:<20}'.format(Season.SPRING), |
| 256 | '{:<20}'.format(str(Season.SPRING))) |
| 257 | |
| 258 | def test_format_enum_custom(self): |
| 259 | class TestFloat(float, Enum): |
| 260 | one = 1.0 |
| 261 | two = 2.0 |
| 262 | def __format__(self, spec): |
| 263 | return 'TestFloat success!' |
| 264 | self.assertEqual('{}'.format(TestFloat.one), 'TestFloat success!') |
| 265 | |
| 266 | def assertFormatIsValue(self, spec, member): |
| 267 | self.assertEqual(spec.format(member), spec.format(member.value)) |
| 268 | |
| 269 | def test_format_enum_date(self): |
| 270 | Holiday = self.Holiday |
| 271 | self.assertFormatIsValue('{}', Holiday.IDES_OF_MARCH) |
| 272 | self.assertFormatIsValue('{:}', Holiday.IDES_OF_MARCH) |
| 273 | self.assertFormatIsValue('{:20}', Holiday.IDES_OF_MARCH) |
| 274 | self.assertFormatIsValue('{:^20}', Holiday.IDES_OF_MARCH) |
| 275 | self.assertFormatIsValue('{:>20}', Holiday.IDES_OF_MARCH) |
| 276 | self.assertFormatIsValue('{:<20}', Holiday.IDES_OF_MARCH) |
| 277 | self.assertFormatIsValue('{:%Y %m}', Holiday.IDES_OF_MARCH) |
| 278 | self.assertFormatIsValue('{:%Y %m %M:00}', Holiday.IDES_OF_MARCH) |
| 279 | |
| 280 | def test_format_enum_float(self): |
| 281 | Konstants = self.Konstants |
| 282 | self.assertFormatIsValue('{}', Konstants.TAU) |
| 283 | self.assertFormatIsValue('{:}', Konstants.TAU) |
| 284 | self.assertFormatIsValue('{:20}', Konstants.TAU) |
| 285 | self.assertFormatIsValue('{:^20}', Konstants.TAU) |
| 286 | self.assertFormatIsValue('{:>20}', Konstants.TAU) |
| 287 | self.assertFormatIsValue('{:<20}', Konstants.TAU) |
| 288 | self.assertFormatIsValue('{:n}', Konstants.TAU) |
| 289 | self.assertFormatIsValue('{:5.2}', Konstants.TAU) |
| 290 | self.assertFormatIsValue('{:f}', Konstants.TAU) |
| 291 | |
| 292 | def test_format_enum_int(self): |
| 293 | Grades = self.Grades |
| 294 | self.assertFormatIsValue('{}', Grades.C) |
| 295 | self.assertFormatIsValue('{:}', Grades.C) |
| 296 | self.assertFormatIsValue('{:20}', Grades.C) |
| 297 | self.assertFormatIsValue('{:^20}', Grades.C) |
| 298 | self.assertFormatIsValue('{:>20}', Grades.C) |
| 299 | self.assertFormatIsValue('{:<20}', Grades.C) |
| 300 | self.assertFormatIsValue('{:+}', Grades.C) |
| 301 | self.assertFormatIsValue('{:08X}', Grades.C) |
| 302 | self.assertFormatIsValue('{:b}', Grades.C) |
| 303 | |
| 304 | def test_format_enum_str(self): |
| 305 | Directional = self.Directional |
| 306 | self.assertFormatIsValue('{}', Directional.WEST) |
| 307 | self.assertFormatIsValue('{:}', Directional.WEST) |
| 308 | self.assertFormatIsValue('{:20}', Directional.WEST) |
| 309 | self.assertFormatIsValue('{:^20}', Directional.WEST) |
| 310 | self.assertFormatIsValue('{:>20}', Directional.WEST) |
| 311 | self.assertFormatIsValue('{:<20}', Directional.WEST) |
| 312 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 313 | def test_hash(self): |
| 314 | Season = self.Season |
| 315 | dates = {} |
| 316 | dates[Season.WINTER] = '1225' |
| 317 | dates[Season.SPRING] = '0315' |
| 318 | dates[Season.SUMMER] = '0704' |
| 319 | dates[Season.AUTUMN] = '1031' |
| 320 | self.assertEqual(dates[Season.AUTUMN], '1031') |
| 321 | |
| 322 | def test_intenum_from_scratch(self): |
| 323 | class phy(int, Enum): |
| 324 | pi = 3 |
| 325 | tau = 2 * pi |
| 326 | self.assertTrue(phy.pi < phy.tau) |
| 327 | |
| 328 | def test_intenum_inherited(self): |
| 329 | class IntEnum(int, Enum): |
| 330 | pass |
| 331 | class phy(IntEnum): |
| 332 | pi = 3 |
| 333 | tau = 2 * pi |
| 334 | self.assertTrue(phy.pi < phy.tau) |
| 335 | |
| 336 | def test_floatenum_from_scratch(self): |
| 337 | class phy(float, Enum): |
Ethan Furman | ec15a82 | 2013-08-31 19:17:41 -0700 | [diff] [blame] | 338 | pi = 3.1415926 |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 339 | tau = 2 * pi |
| 340 | self.assertTrue(phy.pi < phy.tau) |
| 341 | |
| 342 | def test_floatenum_inherited(self): |
| 343 | class FloatEnum(float, Enum): |
| 344 | pass |
| 345 | class phy(FloatEnum): |
Ethan Furman | ec15a82 | 2013-08-31 19:17:41 -0700 | [diff] [blame] | 346 | pi = 3.1415926 |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 347 | tau = 2 * pi |
| 348 | self.assertTrue(phy.pi < phy.tau) |
| 349 | |
| 350 | def test_strenum_from_scratch(self): |
| 351 | class phy(str, Enum): |
| 352 | pi = 'Pi' |
| 353 | tau = 'Tau' |
| 354 | self.assertTrue(phy.pi < phy.tau) |
| 355 | |
| 356 | def test_strenum_inherited(self): |
| 357 | class StrEnum(str, Enum): |
| 358 | pass |
| 359 | class phy(StrEnum): |
| 360 | pi = 'Pi' |
| 361 | tau = 'Tau' |
| 362 | self.assertTrue(phy.pi < phy.tau) |
| 363 | |
| 364 | |
| 365 | def test_intenum(self): |
| 366 | class WeekDay(IntEnum): |
| 367 | SUNDAY = 1 |
| 368 | MONDAY = 2 |
| 369 | TUESDAY = 3 |
| 370 | WEDNESDAY = 4 |
| 371 | THURSDAY = 5 |
| 372 | FRIDAY = 6 |
| 373 | SATURDAY = 7 |
| 374 | |
| 375 | self.assertEqual(['a', 'b', 'c'][WeekDay.MONDAY], 'c') |
| 376 | self.assertEqual([i for i in range(WeekDay.TUESDAY)], [0, 1, 2]) |
| 377 | |
| 378 | lst = list(WeekDay) |
| 379 | self.assertEqual(len(lst), len(WeekDay)) |
| 380 | self.assertEqual(len(WeekDay), 7) |
| 381 | target = 'SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY' |
| 382 | target = target.split() |
| 383 | for i, weekday in enumerate(target, 1): |
| 384 | e = WeekDay(i) |
| 385 | self.assertEqual(e, i) |
| 386 | self.assertEqual(int(e), i) |
| 387 | self.assertEqual(e.name, weekday) |
| 388 | self.assertIn(e, WeekDay) |
| 389 | self.assertEqual(lst.index(e)+1, i) |
| 390 | self.assertTrue(0 < e < 8) |
| 391 | self.assertIs(type(e), WeekDay) |
| 392 | self.assertIsInstance(e, int) |
| 393 | self.assertIsInstance(e, Enum) |
| 394 | |
| 395 | def test_intenum_duplicates(self): |
| 396 | class WeekDay(IntEnum): |
| 397 | SUNDAY = 1 |
| 398 | MONDAY = 2 |
| 399 | TUESDAY = TEUSDAY = 3 |
| 400 | WEDNESDAY = 4 |
| 401 | THURSDAY = 5 |
| 402 | FRIDAY = 6 |
| 403 | SATURDAY = 7 |
| 404 | self.assertIs(WeekDay.TEUSDAY, WeekDay.TUESDAY) |
| 405 | self.assertEqual(WeekDay(3).name, 'TUESDAY') |
| 406 | self.assertEqual([k for k,v in WeekDay.__members__.items() |
| 407 | if v.name != k], ['TEUSDAY', ]) |
| 408 | |
| 409 | def test_pickle_enum(self): |
| 410 | if isinstance(Stooges, Exception): |
| 411 | raise Stooges |
| 412 | self.assertIs(Stooges.CURLY, loads(dumps(Stooges.CURLY))) |
| 413 | self.assertIs(Stooges, loads(dumps(Stooges))) |
| 414 | |
| 415 | def test_pickle_int(self): |
| 416 | if isinstance(IntStooges, Exception): |
| 417 | raise IntStooges |
| 418 | self.assertIs(IntStooges.CURLY, loads(dumps(IntStooges.CURLY))) |
| 419 | self.assertIs(IntStooges, loads(dumps(IntStooges))) |
| 420 | |
| 421 | def test_pickle_float(self): |
| 422 | if isinstance(FloatStooges, Exception): |
| 423 | raise FloatStooges |
| 424 | self.assertIs(FloatStooges.CURLY, loads(dumps(FloatStooges.CURLY))) |
| 425 | self.assertIs(FloatStooges, loads(dumps(FloatStooges))) |
| 426 | |
| 427 | def test_pickle_enum_function(self): |
| 428 | if isinstance(Answer, Exception): |
| 429 | raise Answer |
| 430 | self.assertIs(Answer.him, loads(dumps(Answer.him))) |
| 431 | self.assertIs(Answer, loads(dumps(Answer))) |
| 432 | |
| 433 | def test_pickle_enum_function_with_module(self): |
| 434 | if isinstance(Question, Exception): |
| 435 | raise Question |
| 436 | self.assertIs(Question.who, loads(dumps(Question.who))) |
| 437 | self.assertIs(Question, loads(dumps(Question))) |
| 438 | |
| 439 | def test_exploding_pickle(self): |
| 440 | BadPickle = Enum('BadPickle', 'dill sweet bread-n-butter') |
| 441 | enum._make_class_unpicklable(BadPickle) |
| 442 | globals()['BadPickle'] = BadPickle |
| 443 | with self.assertRaises(TypeError): |
| 444 | dumps(BadPickle.dill) |
| 445 | with self.assertRaises(PicklingError): |
| 446 | dumps(BadPickle) |
| 447 | |
| 448 | def test_string_enum(self): |
| 449 | class SkillLevel(str, Enum): |
| 450 | master = 'what is the sound of one hand clapping?' |
| 451 | journeyman = 'why did the chicken cross the road?' |
| 452 | apprentice = 'knock, knock!' |
| 453 | self.assertEqual(SkillLevel.apprentice, 'knock, knock!') |
| 454 | |
| 455 | def test_getattr_getitem(self): |
| 456 | class Period(Enum): |
| 457 | morning = 1 |
| 458 | noon = 2 |
| 459 | evening = 3 |
| 460 | night = 4 |
| 461 | self.assertIs(Period(2), Period.noon) |
| 462 | self.assertIs(getattr(Period, 'night'), Period.night) |
| 463 | self.assertIs(Period['morning'], Period.morning) |
| 464 | |
| 465 | def test_getattr_dunder(self): |
| 466 | Season = self.Season |
| 467 | self.assertTrue(getattr(Season, '__eq__')) |
| 468 | |
| 469 | def test_iteration_order(self): |
| 470 | class Season(Enum): |
| 471 | SUMMER = 2 |
| 472 | WINTER = 4 |
| 473 | AUTUMN = 3 |
| 474 | SPRING = 1 |
| 475 | self.assertEqual( |
| 476 | list(Season), |
| 477 | [Season.SUMMER, Season.WINTER, Season.AUTUMN, Season.SPRING], |
| 478 | ) |
| 479 | |
| 480 | def test_programatic_function_string(self): |
| 481 | SummerMonth = Enum('SummerMonth', 'june july august') |
| 482 | lst = list(SummerMonth) |
| 483 | self.assertEqual(len(lst), len(SummerMonth)) |
| 484 | self.assertEqual(len(SummerMonth), 3, SummerMonth) |
| 485 | self.assertEqual( |
| 486 | [SummerMonth.june, SummerMonth.july, SummerMonth.august], |
| 487 | lst, |
| 488 | ) |
| 489 | for i, month in enumerate('june july august'.split(), 1): |
| 490 | e = SummerMonth(i) |
| 491 | self.assertEqual(int(e.value), i) |
| 492 | self.assertNotEqual(e, i) |
| 493 | self.assertEqual(e.name, month) |
| 494 | self.assertIn(e, SummerMonth) |
| 495 | self.assertIs(type(e), SummerMonth) |
| 496 | |
| 497 | def test_programatic_function_string_list(self): |
| 498 | SummerMonth = Enum('SummerMonth', ['june', 'july', 'august']) |
| 499 | lst = list(SummerMonth) |
| 500 | self.assertEqual(len(lst), len(SummerMonth)) |
| 501 | self.assertEqual(len(SummerMonth), 3, SummerMonth) |
| 502 | self.assertEqual( |
| 503 | [SummerMonth.june, SummerMonth.july, SummerMonth.august], |
| 504 | lst, |
| 505 | ) |
| 506 | for i, month in enumerate('june july august'.split(), 1): |
| 507 | e = SummerMonth(i) |
| 508 | self.assertEqual(int(e.value), i) |
| 509 | self.assertNotEqual(e, i) |
| 510 | self.assertEqual(e.name, month) |
| 511 | self.assertIn(e, SummerMonth) |
| 512 | self.assertIs(type(e), SummerMonth) |
| 513 | |
| 514 | def test_programatic_function_iterable(self): |
| 515 | SummerMonth = Enum( |
| 516 | 'SummerMonth', |
| 517 | (('june', 1), ('july', 2), ('august', 3)) |
| 518 | ) |
| 519 | lst = list(SummerMonth) |
| 520 | self.assertEqual(len(lst), len(SummerMonth)) |
| 521 | self.assertEqual(len(SummerMonth), 3, SummerMonth) |
| 522 | self.assertEqual( |
| 523 | [SummerMonth.june, SummerMonth.july, SummerMonth.august], |
| 524 | lst, |
| 525 | ) |
| 526 | for i, month in enumerate('june july august'.split(), 1): |
| 527 | e = SummerMonth(i) |
| 528 | self.assertEqual(int(e.value), i) |
| 529 | self.assertNotEqual(e, i) |
| 530 | self.assertEqual(e.name, month) |
| 531 | self.assertIn(e, SummerMonth) |
| 532 | self.assertIs(type(e), SummerMonth) |
| 533 | |
| 534 | def test_programatic_function_from_dict(self): |
| 535 | SummerMonth = Enum( |
| 536 | 'SummerMonth', |
| 537 | OrderedDict((('june', 1), ('july', 2), ('august', 3))) |
| 538 | ) |
| 539 | lst = list(SummerMonth) |
| 540 | self.assertEqual(len(lst), len(SummerMonth)) |
| 541 | self.assertEqual(len(SummerMonth), 3, SummerMonth) |
| 542 | self.assertEqual( |
| 543 | [SummerMonth.june, SummerMonth.july, SummerMonth.august], |
| 544 | lst, |
| 545 | ) |
| 546 | for i, month in enumerate('june july august'.split(), 1): |
| 547 | e = SummerMonth(i) |
| 548 | self.assertEqual(int(e.value), i) |
| 549 | self.assertNotEqual(e, i) |
| 550 | self.assertEqual(e.name, month) |
| 551 | self.assertIn(e, SummerMonth) |
| 552 | self.assertIs(type(e), SummerMonth) |
| 553 | |
| 554 | def test_programatic_function_type(self): |
| 555 | SummerMonth = Enum('SummerMonth', 'june july august', type=int) |
| 556 | lst = list(SummerMonth) |
| 557 | self.assertEqual(len(lst), len(SummerMonth)) |
| 558 | self.assertEqual(len(SummerMonth), 3, SummerMonth) |
| 559 | self.assertEqual( |
| 560 | [SummerMonth.june, SummerMonth.july, SummerMonth.august], |
| 561 | lst, |
| 562 | ) |
| 563 | for i, month in enumerate('june july august'.split(), 1): |
| 564 | e = SummerMonth(i) |
| 565 | self.assertEqual(e, i) |
| 566 | self.assertEqual(e.name, month) |
| 567 | self.assertIn(e, SummerMonth) |
| 568 | self.assertIs(type(e), SummerMonth) |
| 569 | |
| 570 | def test_programatic_function_type_from_subclass(self): |
| 571 | SummerMonth = IntEnum('SummerMonth', 'june july august') |
| 572 | lst = list(SummerMonth) |
| 573 | self.assertEqual(len(lst), len(SummerMonth)) |
| 574 | self.assertEqual(len(SummerMonth), 3, SummerMonth) |
| 575 | self.assertEqual( |
| 576 | [SummerMonth.june, SummerMonth.july, SummerMonth.august], |
| 577 | lst, |
| 578 | ) |
| 579 | for i, month in enumerate('june july august'.split(), 1): |
| 580 | e = SummerMonth(i) |
| 581 | self.assertEqual(e, i) |
| 582 | self.assertEqual(e.name, month) |
| 583 | self.assertIn(e, SummerMonth) |
| 584 | self.assertIs(type(e), SummerMonth) |
| 585 | |
| 586 | def test_subclassing(self): |
| 587 | if isinstance(Name, Exception): |
| 588 | raise Name |
| 589 | self.assertEqual(Name.BDFL, 'Guido van Rossum') |
| 590 | self.assertTrue(Name.BDFL, Name('Guido van Rossum')) |
| 591 | self.assertIs(Name.BDFL, getattr(Name, 'BDFL')) |
| 592 | self.assertIs(Name.BDFL, loads(dumps(Name.BDFL))) |
| 593 | |
| 594 | def test_extending(self): |
| 595 | class Color(Enum): |
| 596 | red = 1 |
| 597 | green = 2 |
| 598 | blue = 3 |
| 599 | with self.assertRaises(TypeError): |
| 600 | class MoreColor(Color): |
| 601 | cyan = 4 |
| 602 | magenta = 5 |
| 603 | yellow = 6 |
| 604 | |
| 605 | def test_exclude_methods(self): |
| 606 | class whatever(Enum): |
| 607 | this = 'that' |
| 608 | these = 'those' |
| 609 | def really(self): |
| 610 | return 'no, not %s' % self.value |
| 611 | self.assertIsNot(type(whatever.really), whatever) |
| 612 | self.assertEqual(whatever.this.really(), 'no, not that') |
| 613 | |
| 614 | def test_overwrite_enums(self): |
| 615 | class Why(Enum): |
| 616 | question = 1 |
| 617 | answer = 2 |
| 618 | propisition = 3 |
| 619 | def question(self): |
| 620 | print(42) |
| 621 | self.assertIsNot(type(Why.question), Why) |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 622 | self.assertNotIn(Why.question, Why._member_names_) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 623 | self.assertNotIn(Why.question, Why) |
| 624 | |
| 625 | def test_wrong_inheritance_order(self): |
| 626 | with self.assertRaises(TypeError): |
| 627 | class Wrong(Enum, str): |
| 628 | NotHere = 'error before this point' |
| 629 | |
| 630 | def test_intenum_transitivity(self): |
| 631 | class number(IntEnum): |
| 632 | one = 1 |
| 633 | two = 2 |
| 634 | three = 3 |
| 635 | class numero(IntEnum): |
| 636 | uno = 1 |
| 637 | dos = 2 |
| 638 | tres = 3 |
| 639 | self.assertEqual(number.one, numero.uno) |
| 640 | self.assertEqual(number.two, numero.dos) |
| 641 | self.assertEqual(number.three, numero.tres) |
| 642 | |
| 643 | def test_wrong_enum_in_call(self): |
| 644 | class Monochrome(Enum): |
| 645 | black = 0 |
| 646 | white = 1 |
| 647 | class Gender(Enum): |
| 648 | male = 0 |
| 649 | female = 1 |
| 650 | self.assertRaises(ValueError, Monochrome, Gender.male) |
| 651 | |
| 652 | def test_wrong_enum_in_mixed_call(self): |
| 653 | class Monochrome(IntEnum): |
| 654 | black = 0 |
| 655 | white = 1 |
| 656 | class Gender(Enum): |
| 657 | male = 0 |
| 658 | female = 1 |
| 659 | self.assertRaises(ValueError, Monochrome, Gender.male) |
| 660 | |
| 661 | def test_mixed_enum_in_call_1(self): |
| 662 | class Monochrome(IntEnum): |
| 663 | black = 0 |
| 664 | white = 1 |
| 665 | class Gender(IntEnum): |
| 666 | male = 0 |
| 667 | female = 1 |
| 668 | self.assertIs(Monochrome(Gender.female), Monochrome.white) |
| 669 | |
| 670 | def test_mixed_enum_in_call_2(self): |
| 671 | class Monochrome(Enum): |
| 672 | black = 0 |
| 673 | white = 1 |
| 674 | class Gender(IntEnum): |
| 675 | male = 0 |
| 676 | female = 1 |
| 677 | self.assertIs(Monochrome(Gender.male), Monochrome.black) |
| 678 | |
| 679 | def test_flufl_enum(self): |
| 680 | class Fluflnum(Enum): |
| 681 | def __int__(self): |
| 682 | return int(self.value) |
| 683 | class MailManOptions(Fluflnum): |
| 684 | option1 = 1 |
| 685 | option2 = 2 |
| 686 | option3 = 3 |
| 687 | self.assertEqual(int(MailManOptions.option1), 1) |
| 688 | |
Ethan Furman | 5e5a823 | 2013-08-04 08:42:23 -0700 | [diff] [blame] | 689 | def test_introspection(self): |
| 690 | class Number(IntEnum): |
| 691 | one = 100 |
| 692 | two = 200 |
| 693 | self.assertIs(Number.one._member_type_, int) |
| 694 | self.assertIs(Number._member_type_, int) |
| 695 | class String(str, Enum): |
| 696 | yarn = 'soft' |
| 697 | rope = 'rough' |
| 698 | wire = 'hard' |
| 699 | self.assertIs(String.yarn._member_type_, str) |
| 700 | self.assertIs(String._member_type_, str) |
| 701 | class Plain(Enum): |
| 702 | vanilla = 'white' |
| 703 | one = 1 |
| 704 | self.assertIs(Plain.vanilla._member_type_, object) |
| 705 | self.assertIs(Plain._member_type_, object) |
| 706 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 707 | def test_no_such_enum_member(self): |
| 708 | class Color(Enum): |
| 709 | red = 1 |
| 710 | green = 2 |
| 711 | blue = 3 |
| 712 | with self.assertRaises(ValueError): |
| 713 | Color(4) |
| 714 | with self.assertRaises(KeyError): |
| 715 | Color['chartreuse'] |
| 716 | |
| 717 | def test_new_repr(self): |
| 718 | class Color(Enum): |
| 719 | red = 1 |
| 720 | green = 2 |
| 721 | blue = 3 |
| 722 | def __repr__(self): |
| 723 | return "don't you just love shades of %s?" % self.name |
| 724 | self.assertEqual( |
| 725 | repr(Color.blue), |
| 726 | "don't you just love shades of blue?", |
| 727 | ) |
| 728 | |
| 729 | def test_inherited_repr(self): |
| 730 | class MyEnum(Enum): |
| 731 | def __repr__(self): |
| 732 | return "My name is %s." % self.name |
| 733 | class MyIntEnum(int, MyEnum): |
| 734 | this = 1 |
| 735 | that = 2 |
| 736 | theother = 3 |
| 737 | self.assertEqual(repr(MyIntEnum.that), "My name is that.") |
| 738 | |
| 739 | def test_multiple_mixin_mro(self): |
| 740 | class auto_enum(type(Enum)): |
| 741 | def __new__(metacls, cls, bases, classdict): |
| 742 | temp = type(classdict)() |
| 743 | names = set(classdict._member_names) |
| 744 | i = 0 |
| 745 | for k in classdict._member_names: |
| 746 | v = classdict[k] |
| 747 | if v is Ellipsis: |
| 748 | v = i |
| 749 | else: |
| 750 | i = v |
| 751 | i += 1 |
| 752 | temp[k] = v |
| 753 | for k, v in classdict.items(): |
| 754 | if k not in names: |
| 755 | temp[k] = v |
| 756 | return super(auto_enum, metacls).__new__( |
| 757 | metacls, cls, bases, temp) |
| 758 | |
| 759 | class AutoNumberedEnum(Enum, metaclass=auto_enum): |
| 760 | pass |
| 761 | |
| 762 | class AutoIntEnum(IntEnum, metaclass=auto_enum): |
| 763 | pass |
| 764 | |
| 765 | class TestAutoNumber(AutoNumberedEnum): |
| 766 | a = ... |
| 767 | b = 3 |
| 768 | c = ... |
| 769 | |
| 770 | class TestAutoInt(AutoIntEnum): |
| 771 | a = ... |
| 772 | b = 3 |
| 773 | c = ... |
| 774 | |
| 775 | def test_subclasses_with_getnewargs(self): |
| 776 | class NamedInt(int): |
| 777 | def __new__(cls, *args): |
| 778 | _args = args |
| 779 | name, *args = args |
| 780 | if len(args) == 0: |
| 781 | raise TypeError("name and value must be specified") |
| 782 | self = int.__new__(cls, *args) |
| 783 | self._intname = name |
| 784 | self._args = _args |
| 785 | return self |
| 786 | def __getnewargs__(self): |
| 787 | return self._args |
| 788 | @property |
| 789 | def __name__(self): |
| 790 | return self._intname |
| 791 | def __repr__(self): |
| 792 | # repr() is updated to include the name and type info |
| 793 | return "{}({!r}, {})".format(type(self).__name__, |
| 794 | self.__name__, |
| 795 | int.__repr__(self)) |
| 796 | def __str__(self): |
| 797 | # str() is unchanged, even if it relies on the repr() fallback |
| 798 | base = int |
| 799 | base_str = base.__str__ |
| 800 | if base_str.__objclass__ is object: |
| 801 | return base.__repr__(self) |
| 802 | return base_str(self) |
| 803 | # for simplicity, we only define one operator that |
| 804 | # propagates expressions |
| 805 | def __add__(self, other): |
| 806 | temp = int(self) + int( other) |
| 807 | if isinstance(self, NamedInt) and isinstance(other, NamedInt): |
| 808 | return NamedInt( |
| 809 | '({0} + {1})'.format(self.__name__, other.__name__), |
| 810 | temp ) |
| 811 | else: |
| 812 | return temp |
| 813 | |
| 814 | class NEI(NamedInt, Enum): |
| 815 | x = ('the-x', 1) |
| 816 | y = ('the-y', 2) |
| 817 | |
Ethan Furman | 2aa2732 | 2013-07-19 19:35:56 -0700 | [diff] [blame] | 818 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 819 | self.assertIs(NEI.__new__, Enum.__new__) |
| 820 | self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)") |
| 821 | globals()['NamedInt'] = NamedInt |
| 822 | globals()['NEI'] = NEI |
| 823 | NI5 = NamedInt('test', 5) |
| 824 | self.assertEqual(NI5, 5) |
| 825 | self.assertEqual(loads(dumps(NI5)), 5) |
| 826 | self.assertEqual(NEI.y.value, 2) |
| 827 | self.assertIs(loads(dumps(NEI.y)), NEI.y) |
| 828 | |
| 829 | def test_subclasses_without_getnewargs(self): |
| 830 | class NamedInt(int): |
| 831 | def __new__(cls, *args): |
| 832 | _args = args |
| 833 | name, *args = args |
| 834 | if len(args) == 0: |
| 835 | raise TypeError("name and value must be specified") |
| 836 | self = int.__new__(cls, *args) |
| 837 | self._intname = name |
| 838 | self._args = _args |
| 839 | return self |
| 840 | @property |
| 841 | def __name__(self): |
| 842 | return self._intname |
| 843 | def __repr__(self): |
| 844 | # repr() is updated to include the name and type info |
| 845 | return "{}({!r}, {})".format(type(self).__name__, |
| 846 | self.__name__, |
| 847 | int.__repr__(self)) |
| 848 | def __str__(self): |
| 849 | # str() is unchanged, even if it relies on the repr() fallback |
| 850 | base = int |
| 851 | base_str = base.__str__ |
| 852 | if base_str.__objclass__ is object: |
| 853 | return base.__repr__(self) |
| 854 | return base_str(self) |
| 855 | # for simplicity, we only define one operator that |
| 856 | # propagates expressions |
| 857 | def __add__(self, other): |
| 858 | temp = int(self) + int( other) |
| 859 | if isinstance(self, NamedInt) and isinstance(other, NamedInt): |
| 860 | return NamedInt( |
| 861 | '({0} + {1})'.format(self.__name__, other.__name__), |
| 862 | temp ) |
| 863 | else: |
| 864 | return temp |
| 865 | |
| 866 | class NEI(NamedInt, Enum): |
| 867 | x = ('the-x', 1) |
| 868 | y = ('the-y', 2) |
| 869 | |
| 870 | self.assertIs(NEI.__new__, Enum.__new__) |
| 871 | self.assertEqual(repr(NEI.x + NEI.y), "NamedInt('(the-x + the-y)', 3)") |
| 872 | globals()['NamedInt'] = NamedInt |
| 873 | globals()['NEI'] = NEI |
| 874 | NI5 = NamedInt('test', 5) |
| 875 | self.assertEqual(NI5, 5) |
| 876 | self.assertEqual(NEI.y.value, 2) |
| 877 | with self.assertRaises(TypeError): |
| 878 | dumps(NEI.x) |
| 879 | with self.assertRaises(PicklingError): |
| 880 | dumps(NEI) |
| 881 | |
| 882 | def test_tuple_subclass(self): |
| 883 | class SomeTuple(tuple, Enum): |
| 884 | first = (1, 'for the money') |
| 885 | second = (2, 'for the show') |
| 886 | third = (3, 'for the music') |
| 887 | self.assertIs(type(SomeTuple.first), SomeTuple) |
| 888 | self.assertIsInstance(SomeTuple.second, tuple) |
| 889 | self.assertEqual(SomeTuple.third, (3, 'for the music')) |
| 890 | globals()['SomeTuple'] = SomeTuple |
| 891 | self.assertIs(loads(dumps(SomeTuple.first)), SomeTuple.first) |
| 892 | |
| 893 | def test_duplicate_values_give_unique_enum_items(self): |
| 894 | class AutoNumber(Enum): |
| 895 | first = () |
| 896 | second = () |
| 897 | third = () |
| 898 | def __new__(cls): |
| 899 | value = len(cls.__members__) + 1 |
| 900 | obj = object.__new__(cls) |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 901 | obj._value_ = value |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 902 | return obj |
| 903 | def __int__(self): |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 904 | return int(self._value_) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 905 | self.assertEqual( |
| 906 | list(AutoNumber), |
| 907 | [AutoNumber.first, AutoNumber.second, AutoNumber.third], |
| 908 | ) |
| 909 | self.assertEqual(int(AutoNumber.second), 2) |
Ethan Furman | 2aa2732 | 2013-07-19 19:35:56 -0700 | [diff] [blame] | 910 | self.assertEqual(AutoNumber.third.value, 3) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 911 | self.assertIs(AutoNumber(1), AutoNumber.first) |
| 912 | |
| 913 | def test_inherited_new_from_enhanced_enum(self): |
| 914 | class AutoNumber(Enum): |
| 915 | def __new__(cls): |
| 916 | value = len(cls.__members__) + 1 |
| 917 | obj = object.__new__(cls) |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 918 | obj._value_ = value |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 919 | return obj |
| 920 | def __int__(self): |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 921 | return int(self._value_) |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 922 | class Color(AutoNumber): |
| 923 | red = () |
| 924 | green = () |
| 925 | blue = () |
| 926 | self.assertEqual(list(Color), [Color.red, Color.green, Color.blue]) |
| 927 | self.assertEqual(list(map(int, Color)), [1, 2, 3]) |
| 928 | |
| 929 | def test_inherited_new_from_mixed_enum(self): |
| 930 | class AutoNumber(IntEnum): |
| 931 | def __new__(cls): |
| 932 | value = len(cls.__members__) + 1 |
| 933 | obj = int.__new__(cls, value) |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 934 | obj._value_ = value |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 935 | return obj |
| 936 | class Color(AutoNumber): |
| 937 | red = () |
| 938 | green = () |
| 939 | blue = () |
| 940 | self.assertEqual(list(Color), [Color.red, Color.green, Color.blue]) |
| 941 | self.assertEqual(list(map(int, Color)), [1, 2, 3]) |
| 942 | |
| 943 | def test_ordered_mixin(self): |
| 944 | class OrderedEnum(Enum): |
| 945 | def __ge__(self, other): |
| 946 | if self.__class__ is other.__class__: |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 947 | return self._value_ >= other._value_ |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 948 | return NotImplemented |
| 949 | def __gt__(self, other): |
| 950 | if self.__class__ is other.__class__: |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 951 | return self._value_ > other._value_ |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 952 | return NotImplemented |
| 953 | def __le__(self, other): |
| 954 | if self.__class__ is other.__class__: |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 955 | return self._value_ <= other._value_ |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 956 | return NotImplemented |
| 957 | def __lt__(self, other): |
| 958 | if self.__class__ is other.__class__: |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 959 | return self._value_ < other._value_ |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 960 | return NotImplemented |
| 961 | class Grade(OrderedEnum): |
| 962 | A = 5 |
| 963 | B = 4 |
| 964 | C = 3 |
| 965 | D = 2 |
| 966 | F = 1 |
| 967 | self.assertGreater(Grade.A, Grade.B) |
| 968 | self.assertLessEqual(Grade.F, Grade.C) |
| 969 | self.assertLess(Grade.D, Grade.A) |
| 970 | self.assertGreaterEqual(Grade.B, Grade.B) |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 971 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 972 | def test_extending2(self): |
| 973 | class Shade(Enum): |
| 974 | def shade(self): |
| 975 | print(self.name) |
| 976 | class Color(Shade): |
| 977 | red = 1 |
| 978 | green = 2 |
| 979 | blue = 3 |
| 980 | with self.assertRaises(TypeError): |
| 981 | class MoreColor(Color): |
| 982 | cyan = 4 |
| 983 | magenta = 5 |
| 984 | yellow = 6 |
| 985 | |
| 986 | def test_extending3(self): |
| 987 | class Shade(Enum): |
| 988 | def shade(self): |
| 989 | return self.name |
| 990 | class Color(Shade): |
| 991 | def hex(self): |
| 992 | return '%s hexlified!' % self.value |
| 993 | class MoreColor(Color): |
| 994 | cyan = 4 |
| 995 | magenta = 5 |
| 996 | yellow = 6 |
| 997 | self.assertEqual(MoreColor.magenta.hex(), '5 hexlified!') |
| 998 | |
| 999 | |
| 1000 | def test_no_duplicates(self): |
| 1001 | class UniqueEnum(Enum): |
| 1002 | def __init__(self, *args): |
| 1003 | cls = self.__class__ |
| 1004 | if any(self.value == e.value for e in cls): |
| 1005 | a = self.name |
| 1006 | e = cls(self.value).name |
| 1007 | raise ValueError( |
| 1008 | "aliases not allowed in UniqueEnum: %r --> %r" |
| 1009 | % (a, e) |
| 1010 | ) |
| 1011 | class Color(UniqueEnum): |
| 1012 | red = 1 |
| 1013 | green = 2 |
| 1014 | blue = 3 |
| 1015 | with self.assertRaises(ValueError): |
| 1016 | class Color(UniqueEnum): |
| 1017 | red = 1 |
| 1018 | green = 2 |
| 1019 | blue = 3 |
| 1020 | grene = 2 |
| 1021 | |
| 1022 | def test_init(self): |
| 1023 | class Planet(Enum): |
| 1024 | MERCURY = (3.303e+23, 2.4397e6) |
| 1025 | VENUS = (4.869e+24, 6.0518e6) |
| 1026 | EARTH = (5.976e+24, 6.37814e6) |
| 1027 | MARS = (6.421e+23, 3.3972e6) |
| 1028 | JUPITER = (1.9e+27, 7.1492e7) |
| 1029 | SATURN = (5.688e+26, 6.0268e7) |
| 1030 | URANUS = (8.686e+25, 2.5559e7) |
| 1031 | NEPTUNE = (1.024e+26, 2.4746e7) |
| 1032 | def __init__(self, mass, radius): |
| 1033 | self.mass = mass # in kilograms |
| 1034 | self.radius = radius # in meters |
| 1035 | @property |
| 1036 | def surface_gravity(self): |
| 1037 | # universal gravitational constant (m3 kg-1 s-2) |
| 1038 | G = 6.67300E-11 |
| 1039 | return G * self.mass / (self.radius * self.radius) |
| 1040 | self.assertEqual(round(Planet.EARTH.surface_gravity, 2), 9.80) |
| 1041 | self.assertEqual(Planet.EARTH.value, (5.976e+24, 6.37814e6)) |
| 1042 | |
Ethan Furman | 2aa2732 | 2013-07-19 19:35:56 -0700 | [diff] [blame] | 1043 | def test_nonhash_value(self): |
| 1044 | class AutoNumberInAList(Enum): |
| 1045 | def __new__(cls): |
| 1046 | value = [len(cls.__members__) + 1] |
| 1047 | obj = object.__new__(cls) |
Ethan Furman | 520ad57 | 2013-07-19 19:47:21 -0700 | [diff] [blame] | 1048 | obj._value_ = value |
Ethan Furman | 2aa2732 | 2013-07-19 19:35:56 -0700 | [diff] [blame] | 1049 | return obj |
| 1050 | class ColorInAList(AutoNumberInAList): |
| 1051 | red = () |
| 1052 | green = () |
| 1053 | blue = () |
| 1054 | self.assertEqual(list(ColorInAList), [ColorInAList.red, ColorInAList.green, ColorInAList.blue]) |
| 1055 | self.assertEqual(ColorInAList.red.value, [1]) |
| 1056 | self.assertEqual(ColorInAList([1]), ColorInAList.red) |
| 1057 | |
Ethan Furman | b41803e | 2013-07-25 13:50:45 -0700 | [diff] [blame] | 1058 | def test_conflicting_types_resolved_in_new(self): |
| 1059 | class LabelledIntEnum(int, Enum): |
| 1060 | def __new__(cls, *args): |
| 1061 | value, label = args |
| 1062 | obj = int.__new__(cls, value) |
| 1063 | obj.label = label |
| 1064 | obj._value_ = value |
| 1065 | return obj |
| 1066 | |
| 1067 | class LabelledList(LabelledIntEnum): |
| 1068 | unprocessed = (1, "Unprocessed") |
| 1069 | payment_complete = (2, "Payment Complete") |
| 1070 | |
| 1071 | self.assertEqual(list(LabelledList), [LabelledList.unprocessed, LabelledList.payment_complete]) |
| 1072 | self.assertEqual(LabelledList.unprocessed, 1) |
| 1073 | self.assertEqual(LabelledList(1), LabelledList.unprocessed) |
Ethan Furman | 2aa2732 | 2013-07-19 19:35:56 -0700 | [diff] [blame] | 1074 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 1075 | |
Ethan Furman | f24bb35 | 2013-07-18 17:05:39 -0700 | [diff] [blame] | 1076 | class TestUnique(unittest.TestCase): |
| 1077 | |
| 1078 | def test_unique_clean(self): |
| 1079 | @unique |
| 1080 | class Clean(Enum): |
| 1081 | one = 1 |
| 1082 | two = 'dos' |
| 1083 | tres = 4.0 |
| 1084 | @unique |
| 1085 | class Cleaner(IntEnum): |
| 1086 | single = 1 |
| 1087 | double = 2 |
| 1088 | triple = 3 |
| 1089 | |
| 1090 | def test_unique_dirty(self): |
| 1091 | with self.assertRaisesRegex(ValueError, 'tres.*one'): |
| 1092 | @unique |
| 1093 | class Dirty(Enum): |
| 1094 | one = 1 |
| 1095 | two = 'dos' |
| 1096 | tres = 1 |
| 1097 | with self.assertRaisesRegex( |
| 1098 | ValueError, |
| 1099 | 'double.*single.*turkey.*triple', |
| 1100 | ): |
| 1101 | @unique |
| 1102 | class Dirtier(IntEnum): |
| 1103 | single = 1 |
| 1104 | double = 1 |
| 1105 | triple = 3 |
| 1106 | turkey = 3 |
| 1107 | |
| 1108 | |
Ethan Furman | 6b3d64a | 2013-06-14 16:55:46 -0700 | [diff] [blame] | 1109 | if __name__ == '__main__': |
| 1110 | unittest.main() |