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.
 
 
 

87 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. import threading
  7. import time
  8. from testutil.helpers import *
  9. class Foo(object):
  10. val = 0
  11. def __init__(self, asdf = "asdf"):
  12. self.init_thread = threading.current_thread().name
  13. @classmethod
  14. def foo(self):
  15. pass
  16. def fail(self):
  17. raise Exception("you asked me to do this")
  18. def test(self, debug = False):
  19. self.tester(debug)
  20. def t(self):
  21. pass
  22. def tester(self, debug = False):
  23. # purposely not thread-safe
  24. self.test_thread = threading.current_thread().name
  25. oldval = self.val
  26. newval = oldval + 1
  27. time.sleep(0.05)
  28. self.val = newval
  29. if debug:
  30. printf("[%s] value changed: %d -> %d\n",
  31. threading.current_thread().name, oldval, newval)
  32. class Base(object):
  33. def test_wrapping(self):
  34. self.foo.test()
  35. with assert_raises(Exception):
  36. self.foo.fail()
  37. def test_threaded(self):
  38. def func(foo):
  39. foo.test()
  40. threads = []
  41. for i in xrange(20):
  42. threads.append(threading.Thread(target = func, args = (self.foo,)))
  43. for t in threads:
  44. t.start()
  45. for t in threads:
  46. t.join()
  47. self.verify_result()
  48. def verify_result(self):
  49. eq_(self.foo.val, 20)
  50. eq_(self.foo.init_thread, self.foo.test_thread)
  51. class TestUnserialized(Base):
  52. def setUp(self):
  53. self.foo = Foo()
  54. def verify_result(self):
  55. # This should have failed to increment properly
  56. ne_(self.foo.val, 20)
  57. # Init and tests ran in different threads
  58. ne_(self.foo.init_thread, self.foo.test_thread)
  59. class TestSerializer(Base):
  60. def setUp(self):
  61. self.foo = nilmdb.utils.serializer_proxy(Foo)("qwer")
  62. def test_multi(self):
  63. sp = nilmdb.utils.serializer_proxy
  64. sp(Foo("x")).t()
  65. sp(sp(Foo)("x")).t()
  66. sp(sp(Foo))("x").t()
  67. sp(sp(Foo("x"))).t()
  68. sp(sp(Foo)("x")).t()
  69. sp(sp(Foo))("x").t()