StackTests.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include "tests/StackTests.h"
  2. #include "tests/Test.h"
  3. #include "utils/StringBuffer.h"
  4. #include "utils/Stack.h"
  5. typedef Stack<int, 10> IntStack;
  6. typedef StringBuffer<50> String;
  7. static void testPushPopPeek(Test& test) {
  8. IntStack stack;
  9. stack.push(1);
  10. stack.push(2);
  11. stack.push(3);
  12. test.checkEqual(3, stack.peek(), "push pop peek 1");
  13. test.checkEqual(false, stack.pop(), "pop without error 1");
  14. test.checkEqual(2, stack.peek(), "push pop peek 2");
  15. test.checkEqual(false, stack.pop(), "pop without error 2");
  16. test.checkEqual(1, stack.peek(), "push pop peek 3");
  17. test.checkEqual(false, stack.pop(), "pop without error 3");
  18. test.checkEqual(true, stack.isEmpty(), "empty after popping all");
  19. }
  20. static void testOverflow(Test& test) {
  21. IntStack stack;
  22. for(int i = 0; i < 10; i++) {
  23. test.checkEqual(false, stack.push(i), "push returns false without overflow");
  24. }
  25. for(int i = 0; i < 1000000; i++) {
  26. test.checkEqual(true, stack.push(i), "push returns true with overflow");
  27. }
  28. test.checkEqual(true, true, "survives overflow");
  29. }
  30. static void testToString1(Test& test) {
  31. IntStack stack;
  32. stack.push(1);
  33. stack.push(243);
  34. stack.push(-423);
  35. test.checkEqual(String("[1, 243, -423]"), String(stack), "to string 1");
  36. }
  37. static void testToString2(Test& test) {
  38. IntStack stack;
  39. stack.push(1);
  40. test.checkEqual(String("[1]"), String(stack), "to string 2");
  41. }
  42. static void testToString3(Test& test) {
  43. IntStack stack;
  44. test.checkEqual(String("[]"), String(stack), "to string 3");
  45. }
  46. static void testPop(Test& test) {
  47. IntStack stack;
  48. for(int i = 0; i < 1000000; i++) {
  49. test.checkEqual(true, stack.pop(), "popping empty stack is safe");
  50. }
  51. }
  52. void StackTests::test() {
  53. Test test("Stack");
  54. testPushPopPeek(test);
  55. testOverflow(test);
  56. testToString1(test);
  57. testToString2(test);
  58. testToString3(test);
  59. testPop(test);
  60. test.finalize();
  61. }