Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Create by Brice PARENT, for whoever it could help (so, just me right now)
- # Do whatever you want with it, and don't hesitate to drop a not here if
- # it helped you, or if you have anything to say about it. Also, I'm not
- # providing any support for it, so use at your own risk (but I might help
- # if I've got some time) !
- # When using unittest.setUpTestData to prefetch some data in the db, we should
- # always take extra care when modify this data, as it will not be refreshed
- # before the next tests.
- # If we have to modify it, we have to re-set it manually before the end of the
- # test (and in some cases, if we exit the test prematurely, the data will stay
- # modified, potentially causing many side effects to future tests.
- # Or we can use this context manager, which will operate the value change, and
- # reverse it at the end (even if the test is exited prematurely).
- # Usage :
- # self.assertEqual(book.title, "My book's title") # Initial title of the book
- # with TestDataTempChange(book, "title", "My temporary title"):
- # self.assertEqual(book.title, "My temporary title") # Your test here
- #
- # self.assertEqual(book.title, "My book's title") # Back to initial title
- class TestDataTempChange:
- def __init__(self, obj, prop, val):
- self.obj = obj
- self.prop = prop
- self.val = val
- def __enter__(self):
- # saving initial value
- self.init_val = getattr(self.obj, self.prop)
- # updating the object with new value
- setattr(self.obj, self.prop, self.val)
- self.obj.save()
- def __exit__(self, type_, value, traceback):
- # reverting the object's value to its initial value
- setattr(self.obj, self.prop, self.init_val)
- self.obj.save()
Add Comment
Please, Sign In to add comment