(self)
| 3286 | ) |
| 3287 | |
| 3288 | def test_invalid_registrations(self): |
| 3289 | msg_prefix = "Invalid first argument to `register()`: " |
| 3290 | msg_suffix = ( |
| 3291 | ". Use either `@register(some_class)` or plain `@register` on an " |
| 3292 | "annotated function." |
| 3293 | ) |
| 3294 | @functools.singledispatch |
| 3295 | def i(arg): |
| 3296 | return "base" |
| 3297 | with self.assertRaises(TypeError) as exc: |
| 3298 | @i.register(42) |
| 3299 | def _(arg): |
| 3300 | return "I annotated with a non-type" |
| 3301 | self.assertStartsWith(str(exc.exception), msg_prefix + "42") |
| 3302 | self.assertEndsWith(str(exc.exception), msg_suffix) |
| 3303 | with self.assertRaises(TypeError) as exc: |
| 3304 | @i.register |
| 3305 | def _(arg): |
| 3306 | return "I forgot to annotate" |
| 3307 | self.assertStartsWith(str(exc.exception), msg_prefix + |
| 3308 | "<function TestSingleDispatch.test_invalid_registrations.<locals>._" |
| 3309 | ) |
| 3310 | self.assertEndsWith(str(exc.exception), msg_suffix) |
| 3311 | |
| 3312 | with self.assertRaises(TypeError) as exc: |
| 3313 | @i.register |
| 3314 | def _(arg: typing.Iterable[str]): |
| 3315 | # At runtime, dispatching on generics is impossible. |
| 3316 | # When registering implementations with singledispatch, avoid |
| 3317 | # types from `typing`. Instead, annotate with regular types |
| 3318 | # or ABCs. |
| 3319 | return "I annotated with a generic collection" |
| 3320 | self.assertStartsWith(str(exc.exception), |
| 3321 | "Invalid annotation for 'arg'." |
| 3322 | ) |
| 3323 | self.assertEndsWith(str(exc.exception), |
| 3324 | 'typing.Iterable[str] is not a class.' |
| 3325 | ) |
| 3326 | |
| 3327 | with self.assertRaises(TypeError) as exc: |
| 3328 | @i.register |
| 3329 | def _(arg: typing.Union[int, typing.Iterable[str]]): |
| 3330 | return "Invalid Union" |
| 3331 | self.assertStartsWith(str(exc.exception), |
| 3332 | "Invalid annotation for 'arg'." |
| 3333 | ) |
| 3334 | self.assertEndsWith(str(exc.exception), |
| 3335 | 'int | typing.Iterable[str] not all arguments are classes.' |
| 3336 | ) |
| 3337 | |
| 3338 | def test_invalid_positional_argument(self): |
| 3339 | @functools.singledispatch |
nothing calls this directly
no test coverage detected