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