You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

100 lines
2.1 KiB

  1. import nilmdb
  2. from nilmdb.utils.printf import *
  3. import nose
  4. from nose.tools import *
  5. from nose.tools import assert_raises
  6. from testutil.helpers import *
  7. import sys
  8. import cStringIO
  9. import gc
  10. err = cStringIO.StringIO()
  11. @nilmdb.utils.must_close(errorfile = err)
  12. class Foo:
  13. def __init__(self):
  14. fprintf(err, "Init\n")
  15. def __del__(self):
  16. fprintf(err, "Deleting\n")
  17. def close(self):
  18. fprintf(err, "Closing\n")
  19. @nilmdb.utils.must_close(errorfile = err, wrap_verify = True)
  20. class Bar:
  21. def __init__(self):
  22. fprintf(err, "Init\n")
  23. def __del__(self):
  24. fprintf(err, "Deleting\n")
  25. def close(self):
  26. fprintf(err, "Closing\n")
  27. def blah(self):
  28. fprintf(err, "Blah\n")
  29. @nilmdb.utils.must_close(errorfile = err)
  30. class Baz:
  31. pass
  32. class TestMustClose(object):
  33. def test(self):
  34. # Note: this test might fail if the Python interpreter doesn't
  35. # garbage collect the object (and call its __del__ function)
  36. # right after a "del x".
  37. # Trigger error
  38. err.truncate()
  39. x = Foo()
  40. del x
  41. gc.collect()
  42. eq_(err.getvalue(),
  43. "Init\n"
  44. "error: Foo.close() wasn't called!\n"
  45. "Deleting\n")
  46. # No error
  47. err.truncate(0)
  48. y = Foo()
  49. y.close()
  50. del y
  51. gc.collect()
  52. eq_(err.getvalue(),
  53. "Init\n"
  54. "Closing\n"
  55. "Deleting\n")
  56. # Verify errors
  57. err.truncate(0)
  58. z = Bar()
  59. z.blah()
  60. z.close()
  61. with assert_raises(AssertionError):
  62. z.blah()
  63. # Since the most recent assertion references 'z',
  64. # we need to raise another assertion here so that
  65. # 'z' will get properly deleted.
  66. with assert_raises(AssertionError):
  67. raise AssertionError()
  68. del z
  69. gc.collect()
  70. eq_(err.getvalue(),
  71. "Init\n"
  72. "Blah\n"
  73. "Closing\n"
  74. "Deleting\n")
  75. # Class with missing methods
  76. err.truncate(0)
  77. w = Baz()
  78. w.close()
  79. del w
  80. eq_(err.getvalue(), "")