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