test_warnings.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # This file is dual licensed under the terms of the Apache License, Version
  2. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  3. # for complete details.
  4. import sys
  5. import types
  6. import typing
  7. import warnings
  8. import pytest
  9. from cryptography.utils import deprecated
  10. class TestDeprecated:
  11. @typing.no_type_check
  12. def test_deprecated(self, monkeypatch):
  13. mod = types.ModuleType("TestDeprecated/test_deprecated")
  14. monkeypatch.setitem(sys.modules, mod.__name__, mod)
  15. deprecated(
  16. name="X",
  17. value=1,
  18. module_name=mod.__name__,
  19. message="deprecated message text",
  20. warning_class=DeprecationWarning,
  21. )
  22. mod.Y = deprecated(
  23. value=2,
  24. module_name=mod.__name__,
  25. message="more deprecated text",
  26. warning_class=PendingDeprecationWarning,
  27. )
  28. mod = sys.modules[mod.__name__]
  29. mod.Z = 3
  30. with warnings.catch_warnings(record=True) as log:
  31. warnings.simplefilter("always", PendingDeprecationWarning)
  32. warnings.simplefilter("always", DeprecationWarning)
  33. assert mod.X == 1
  34. assert mod.Y == 2
  35. assert mod.Z == 3
  36. [msg1, msg2] = log
  37. assert msg1.category is DeprecationWarning
  38. assert msg1.message.args == ("deprecated message text",)
  39. assert msg2.category is PendingDeprecationWarning
  40. assert msg2.message.args == ("more deprecated text",)
  41. assert "Y" in dir(mod)
  42. @typing.no_type_check
  43. def test_deleting_deprecated_members(self, monkeypatch):
  44. mod = types.ModuleType("TestDeprecated/test_deprecated")
  45. monkeypatch.setitem(sys.modules, mod.__name__, mod)
  46. deprecated(
  47. name="X",
  48. value=1,
  49. module_name=mod.__name__,
  50. message="deprecated message text",
  51. warning_class=DeprecationWarning,
  52. )
  53. mod.Y = deprecated(
  54. value=2,
  55. module_name=mod.__name__,
  56. message="more deprecated text",
  57. warning_class=PendingDeprecationWarning,
  58. )
  59. mod = sys.modules[mod.__name__]
  60. mod.Z = 3
  61. with warnings.catch_warnings(record=True) as log:
  62. warnings.simplefilter("always", PendingDeprecationWarning)
  63. warnings.simplefilter("always", DeprecationWarning)
  64. del mod.X
  65. del mod.Y
  66. del mod.Z
  67. [msg1, msg2] = log
  68. assert msg1.category is DeprecationWarning
  69. assert msg1.message.args == ("deprecated message text",)
  70. assert msg2.category is PendingDeprecationWarning
  71. assert msg2.message.args == ("more deprecated text",)
  72. assert "X" not in dir(mod)
  73. assert "Y" not in dir(mod)
  74. assert "Z" not in dir(mod)
  75. with pytest.raises(AttributeError):
  76. del mod.X