Guest User

Untitled

a guest
Jan 21st, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. # Create by Brice PARENT, for whoever it could help (so, just me right now)
  2. # Do whatever you want with it, and don't hesitate to drop a not here if
  3. # it helped you, or if you have anything to say about it. Also, I'm not
  4. # providing any support for it, so use at your own risk (but I might help
  5. # if I've got some time) !
  6.  
  7. # When using unittest.setUpTestData to prefetch some data in the db, we should
  8. # always take extra care when modify this data, as it will not be refreshed
  9. # before the next tests.
  10. # If we have to modify it, we have to re-set it manually before the end of the
  11. # test (and in some cases, if we exit the test prematurely, the data will stay
  12. # modified, potentially causing many side effects to future tests.
  13. # Or we can use this context manager, which will operate the value change, and
  14. # reverse it at the end (even if the test is exited prematurely).
  15.  
  16. # Usage :
  17. # self.assertEqual(book.title, "My book's title") # Initial title of the book
  18. # with TestDataTempChange(book, "title", "My temporary title"):
  19. # self.assertEqual(book.title, "My temporary title") # Your test here
  20. #
  21. # self.assertEqual(book.title, "My book's title") # Back to initial title
  22.  
  23. class TestDataTempChange:
  24. def __init__(self, obj, prop, val):
  25. self.obj = obj
  26. self.prop = prop
  27. self.val = val
  28.  
  29. def __enter__(self):
  30. # saving initial value
  31. self.init_val = getattr(self.obj, self.prop)
  32. # updating the object with new value
  33. setattr(self.obj, self.prop, self.val)
  34. self.obj.save()
  35.  
  36. def __exit__(self, type_, value, traceback):
  37. # reverting the object's value to its initial value
  38. setattr(self.obj, self.prop, self.init_val)
  39. self.obj.save()
Add Comment
Please, Sign In to add comment