ObjectPoolTests.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include "tests/ObjectPoolTests.h"
  2. #include "tests/Test.h"
  3. #include "memory/ObjectPool.h"
  4. struct A {
  5. static int instances;
  6. int a;
  7. A(int a) : a(a) {
  8. instances += a;
  9. }
  10. ~A() {
  11. instances -= a;
  12. }
  13. };
  14. int A::instances = 0;
  15. static void testAllocateAndFree(Test& test) {
  16. ObjectPool<A, 3> pool;
  17. int a = pool.allocate(1);
  18. int b = pool.allocate(2);
  19. int c = pool.allocate(3);
  20. int d = pool.allocate(4);
  21. int e = pool.allocate(5);
  22. test.checkEqual(0, a, "int pointer allocate 1");
  23. test.checkEqual(1, b, "int pointer allocate 2");
  24. test.checkEqual(2, c, "int pointer allocate 3");
  25. test.checkEqual(-1, d, "int pointer allocate 4");
  26. test.checkEqual(-1, e, "int pointer allocate 5");
  27. pool.free(a);
  28. pool.free(b);
  29. pool.free(c);
  30. test.checkEqual(0, A::instances, "all destructors are called 1");
  31. }
  32. static void testAllocateAfterFree(Test& test) {
  33. ObjectPool<A, 3> pool;
  34. int a = pool.allocate(1);
  35. int b = pool.allocate(2);
  36. int c = pool.allocate(3);
  37. pool.free(b);
  38. b = pool.allocate(7);
  39. test.checkEqual(1, b, "int pointer allocate after free 1");
  40. pool.free(c);
  41. c = pool.allocate(9);
  42. test.checkEqual(2, c, "int pointer allocate after free 2");
  43. pool.free(a);
  44. a = pool.allocate(11);
  45. test.checkEqual(0, a, "int pointer allocate after free 3");
  46. pool.free(a);
  47. pool.free(b);
  48. b = pool.allocate(23);
  49. a = pool.allocate(17);
  50. test.checkEqual(0, a, "int pointer allocate after free 4");
  51. test.checkEqual(1, b, "int pointer allocate after free 5");
  52. test.checkEqual(-1, pool.allocate(50), "int pointer allocate after free 6");
  53. pool.free(a);
  54. pool.free(b);
  55. pool.free(c);
  56. test.checkEqual(0, A::instances, "all destructors are called 2");
  57. }
  58. void ObjectPoolTests::test() {
  59. Test test("ObjectPool");
  60. testAllocateAndFree(test);
  61. testAllocateAfterFree(test);
  62. test.finalize();
  63. }