test_module.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/env python
  2. #
  3. # Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
  4. # Copyright (c) 2008-2016 California Institute of Technology.
  5. # Copyright (c) 2016-2024 The Uncertainty Quantification Foundation.
  6. # License: 3-clause BSD. The full license text is available at:
  7. # - https://github.com/uqfoundation/dill/blob/master/LICENSE
  8. import sys
  9. import dill
  10. import test_mixins as module
  11. from importlib import reload
  12. dill.settings['recurse'] = True
  13. cached = (module.__cached__ if hasattr(module, "__cached__")
  14. else module.__file__.split(".", 1)[0] + ".pyc")
  15. module.a = 1234
  16. pik_mod = dill.dumps(module)
  17. module.a = 0
  18. # remove module
  19. del sys.modules[module.__name__]
  20. del module
  21. module = dill.loads(pik_mod)
  22. def test_attributes():
  23. #assert hasattr(module, "a") and module.a == 1234 #FIXME: -m dill.tests
  24. assert module.double_add(1, 2, 3) == 2 * module.fx
  25. # Restart, and test use_diff
  26. reload(module)
  27. try:
  28. dill.use_diff()
  29. module.a = 1234
  30. pik_mod = dill.dumps(module)
  31. module.a = 0
  32. # remove module
  33. del sys.modules[module.__name__]
  34. del module
  35. module = dill.loads(pik_mod)
  36. def test_diff_attributes():
  37. assert hasattr(module, "a") and module.a == 1234
  38. assert module.double_add(1, 2, 3) == 2 * module.fx
  39. except AttributeError:
  40. def test_diff_attributes():
  41. pass
  42. # clean up
  43. import os
  44. if os.path.exists(cached):
  45. os.remove(cached)
  46. pycache = os.path.join(os.path.dirname(module.__file__), "__pycache__")
  47. if os.path.exists(pycache) and not os.listdir(pycache):
  48. os.removedirs(pycache)
  49. # test when module is None
  50. import math
  51. def get_lambda(str, **kwarg):
  52. return eval(str, kwarg, None)
  53. obj = get_lambda('lambda x: math.exp(x)', math=math)
  54. def test_module_is_none():
  55. assert obj.__module__ is None
  56. assert dill.copy(obj)(3) == obj(3)
  57. if __name__ == '__main__':
  58. test_attributes()
  59. test_diff_attributes()
  60. test_module_is_none()