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