| Conditions | 2 |
| Total Lines | 52 |
| Code Lines | 34 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | import pytest |
||
| 10 | def test_subclass_registry(subclass_registry_metaclass): |
||
| 11 | class ParentClass(metaclass=subclass_registry_metaclass): |
||
| 12 | pass |
||
| 13 | |||
| 14 | assert type(ParentClass) == subclass_registry_metaclass |
||
| 15 | assert hasattr(ParentClass, 'subclasses') |
||
| 16 | assert hasattr(ParentClass, 'create') |
||
| 17 | assert hasattr(ParentClass, 'register_as_subclass') |
||
| 18 | |||
| 19 | assert ParentClass.subclasses == {} |
||
| 20 | |||
| 21 | @ParentClass.register_as_subclass('child1') |
||
| 22 | class Child1(ParentClass): |
||
| 23 | pass |
||
| 24 | |||
| 25 | assert ParentClass.subclasses['child1'] == Child1 |
||
| 26 | |||
| 27 | child1_instance1 = ParentClass.create('child1') |
||
| 28 | |||
| 29 | assert type(child1_instance1) == Child1 |
||
| 30 | assert isinstance(child1_instance1, Child1) |
||
| 31 | assert isinstance(child1_instance1, ParentClass) |
||
| 32 | |||
| 33 | non_existent_identifier = 'child2' |
||
| 34 | |||
| 35 | exception_message_regex = \ |
||
| 36 | f'Bad "{str(ParentClass.__name__)}" subclass request; requested subclass with identifier ' \ |
||
| 37 | f'{non_existent_identifier}, but known identifiers are ' \ |
||
| 38 | rf'\[{", ".join(subclass_identifier for subclass_identifier in ParentClass.subclasses.keys())}\]' |
||
| 39 | |||
| 40 | with pytest.raises(ValueError, match=exception_message_regex): |
||
| 41 | ParentClass.create(non_existent_identifier) |
||
| 42 | |||
| 43 | |||
| 44 | class ParentClass2(metaclass=subclass_registry_metaclass): |
||
| 45 | pass |
||
| 46 | |||
| 47 | assert ParentClass.subclasses['child1'] == Child1 |
||
| 48 | assert ParentClass2.subclasses == {} |
||
| 49 | |||
| 50 | @ParentClass2.register_as_subclass('child2') |
||
| 51 | class Child2: |
||
| 52 | pass |
||
| 53 | |||
| 54 | assert ParentClass.subclasses['child1'] == Child1 |
||
| 55 | assert ParentClass2.subclasses['child2'] == Child2 |
||
| 56 | |||
| 57 | child1_instance2 = ParentClass2.create('child2') |
||
| 58 | |||
| 59 | assert type(child1_instance2) == Child2 |
||
| 60 | assert isinstance(child1_instance2, Child2) |
||
| 61 | assert not isinstance(child1_instance2, ParentClass2) |