test_errors.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # This file is part of h5py, a Python interface to the HDF5 library.
  2. #
  3. # http://www.h5py.org
  4. #
  5. # Copyright 2008-2013 Andrew Collette and contributors
  6. #
  7. # License: Standard 3-clause BSD; see "license.txt" for full license terms
  8. # and contributor agreement.
  9. """
  10. Tests the h5py.File object.
  11. """
  12. import threading
  13. import pytest
  14. import h5py
  15. from .common import make_name
  16. def _access_not_existing_object(filename):
  17. """Create a file and access not existing key"""
  18. with h5py.File(filename, 'w') as newfile:
  19. try:
  20. doesnt_exist = newfile['doesnt_exist'].value
  21. except KeyError:
  22. pass
  23. @pytest.mark.thread_unsafe(reason="Changes global state")
  24. def test_unsilence_errors(tmp_path, capfd):
  25. """Check that HDF5 errors can be muted/unmuted from h5py"""
  26. filename = tmp_path / 'test.h5'
  27. # Unmute HDF5 errors
  28. try:
  29. h5py._errors.unsilence_errors()
  30. _access_not_existing_object(filename)
  31. captured = capfd.readouterr()
  32. assert captured.err != ''
  33. assert captured.out == ''
  34. # Mute HDF5 errors
  35. finally:
  36. h5py._errors.silence_errors()
  37. _access_not_existing_object(filename)
  38. captured = capfd.readouterr()
  39. assert captured.err == ''
  40. assert captured.out == ''
  41. def test_thread_hdf5_silence_error_membership(tmp_path, capfd):
  42. """Verify the error printing is squashed in all threads.
  43. No console messages should be shown from membership tests
  44. """
  45. th = threading.Thread(target=_access_not_existing_object,
  46. args=(tmp_path / make_name("{}.h5"),))
  47. th.start()
  48. th.join()
  49. captured = capfd.readouterr()
  50. assert captured.err == ''
  51. assert captured.out == ''
  52. def test_thread_hdf5_silence_error_attr(tmp_path, capfd):
  53. """Verify the error printing is squashed in all threads.
  54. No console messages should be shown for non-existing attributes
  55. """
  56. def test():
  57. with h5py.File(tmp_path/make_name("{}.h5"), 'w') as newfile:
  58. newfile['newdata'] = [1, 2, 3]
  59. try:
  60. nonexistent_attr = newfile['newdata'].attrs['nonexistent_attr']
  61. except KeyError:
  62. pass
  63. th = threading.Thread(target=test)
  64. th.start()
  65. th.join()
  66. captured = capfd.readouterr()
  67. assert captured.err == ''
  68. assert captured.out == ''