Like override_settings, but makes it possible to append, prepend, or remove items instead of redefining the entire list.
| 566 | |
| 567 | |
| 568 | class modify_settings(override_settings): |
| 569 | """ |
| 570 | Like override_settings, but makes it possible to append, prepend, or remove |
| 571 | items instead of redefining the entire list. |
| 572 | """ |
| 573 | |
| 574 | def __init__(self, *args, **kwargs): |
| 575 | if args: |
| 576 | # Hack used when instantiating from SimpleTestCase.setUpClass. |
| 577 | assert not kwargs |
| 578 | self.operations = args[0] |
| 579 | else: |
| 580 | assert not args |
| 581 | self.operations = list(kwargs.items()) |
| 582 | super(override_settings, self).__init__() |
| 583 | |
| 584 | def save_options(self, test_func): |
| 585 | if test_func._modified_settings is None: |
| 586 | test_func._modified_settings = self.operations |
| 587 | else: |
| 588 | # Duplicate list to prevent subclasses from altering their parent. |
| 589 | test_func._modified_settings = ( |
| 590 | list(test_func._modified_settings) + self.operations |
| 591 | ) |
| 592 | |
| 593 | def enable(self): |
| 594 | self.options = {} |
| 595 | for name, operations in self.operations: |
| 596 | try: |
| 597 | # When called from SimpleTestCase.setUpClass, values may be |
| 598 | # overridden several times; cumulate changes. |
| 599 | value = self.options[name] |
| 600 | except KeyError: |
| 601 | value = list(getattr(settings, name, [])) |
| 602 | for action, items in operations.items(): |
| 603 | # items may be a single value or an iterable. |
| 604 | if isinstance(items, str): |
| 605 | items = [items] |
| 606 | if action == "append": |
| 607 | value += [item for item in items if item not in value] |
| 608 | elif action == "prepend": |
| 609 | value = [item for item in items if item not in value] + value |
| 610 | elif action == "remove": |
| 611 | value = [item for item in value if item not in items] |
| 612 | else: |
| 613 | raise ValueError("Unsupported action: %s" % action) |
| 614 | self.options[name] = value |
| 615 | super().enable() |
| 616 | |
| 617 | |
| 618 | class override_system_checks(TestContextDecorator): |
no outgoing calls