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.
 
 
 

111 lines
2.7 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. import inspect
  11. err = cStringIO.StringIO()
  12. @nilmdb.utils.must_close(errorfile = err)
  13. class Foo:
  14. def __init__(self, arg):
  15. fprintf(err, "Init %s\n", arg)
  16. def __del__(self):
  17. fprintf(err, "Deleting\n")
  18. def close(self):
  19. fprintf(err, "Closing\n")
  20. @nilmdb.utils.must_close(errorfile = err, wrap_verify = True)
  21. class Bar:
  22. def __init__(self):
  23. fprintf(err, "Init\n")
  24. def __del__(self):
  25. fprintf(err, "Deleting\n")
  26. def close(self):
  27. fprintf(err, "Closing\n")
  28. def blah(self, arg):
  29. fprintf(err, "Blah %s\n", arg)
  30. @nilmdb.utils.must_close(errorfile = err)
  31. class Baz:
  32. pass
  33. class TestMustClose(object):
  34. def test(self):
  35. # Note: this test might fail if the Python interpreter doesn't
  36. # garbage collect the object (and call its __del__ function)
  37. # right after a "del x".
  38. # Trigger error
  39. err.truncate()
  40. x = Foo("hi")
  41. # Verify that the arg spec was maintained
  42. eq_(inspect.getargspec(x.__init__),
  43. inspect.ArgSpec(args = ['self', 'arg'],
  44. varargs = None, keywords = None, defaults = None))
  45. del x
  46. gc.collect()
  47. eq_(err.getvalue(),
  48. "Init hi\n"
  49. "error: Foo.close() wasn't called!\n"
  50. "Deleting\n")
  51. # No error
  52. err.truncate(0)
  53. y = Foo("bye")
  54. y.close()
  55. del y
  56. gc.collect()
  57. eq_(err.getvalue(),
  58. "Init bye\n"
  59. "Closing\n"
  60. "Deleting\n")
  61. # Verify function calls when wrap_verify is True
  62. err.truncate(0)
  63. z = Bar()
  64. eq_(inspect.getargspec(z.blah),
  65. inspect.ArgSpec(args = ['self', 'arg'],
  66. varargs = None, keywords = None, defaults = None))
  67. z.blah("boo")
  68. z.close()
  69. with assert_raises(AssertionError) as e:
  70. z.blah("hello")
  71. in_("called <function blah at 0x", str(e.exception))
  72. in_("> after close", str(e.exception))
  73. # Since the most recent assertion references 'z',
  74. # we need to raise another assertion here so that
  75. # 'z' will get properly deleted.
  76. with assert_raises(AssertionError):
  77. raise AssertionError()
  78. del z
  79. gc.collect()
  80. eq_(err.getvalue(),
  81. "Init\n"
  82. "Blah boo\n"
  83. "Closing\n"
  84. "Deleting\n")
  85. # Class with missing methods
  86. err.truncate(0)
  87. w = Baz()
  88. w.close()
  89. del w
  90. eq_(err.getvalue(), "")