Skip to content

Instantly share code, notes, and snippets.

@guoqiao
Created August 18, 2017 03:11
Show Gist options
  • Save guoqiao/d2e5e9d76af92da38b9ddf944f08b963 to your computer and use it in GitHub Desktop.
Save guoqiao/d2e5e9d76af92da38b9ddf944f08b963 to your computer and use it in GitHub Desktop.
Use contextmanager to set attrs for object temporarily
from contextlib import contextmanager
@contextmanager
def temporarily(obj, **kwargs):
original_values = {k: getattr(obj, k) for k in kwargs}
for k, v in kwargs.items():
setattr(obj, k, v)
obj.save(update_fields=kwargs.keys())
try:
yield
finally:
for k, v in original_values.items():
setattr(obj, k, v)
obj.save(update_fields=original_values.keys())
def test_should_not_send_notification(self):
with temporarily(
user_account.feature_set,
can_pay_with_credit_card=True,
can_receive_notifications=False,
):
pay_with_credit_card(user_account, 100)
self.assertEquals(len(outbox), 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment