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.
 
 
 

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