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