stream.t.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. //
  2. // stream_td.hpp
  3. // stream
  4. //
  5. // Created by Sam Jaffe on 1/28/17.
  6. //
  7. #pragma once
  8. #include <cxxtest/TestSuite.h>
  9. #include <vector>
  10. #include "streams.hpp"
  11. class stream_TestSuite : public CxxTest::TestSuite {
  12. public:
  13. using vec_t = std::vector<int>;
  14. public:
  15. void test_preserved() {
  16. vec_t v{1, 2, 3, 4, 5};
  17. auto s = stream::make_stream(v);
  18. vec_t o{s.begin(), s.end()};
  19. TS_ASSERT_EQUALS(v, o);
  20. }
  21. void test_collect_preserves() {
  22. vec_t v{1, 2, 3, 4, 5};
  23. auto s = stream::make_stream(v);
  24. vec_t o{s.begin(), s.end()};
  25. vec_t o2{s.collect()};
  26. TS_ASSERT_EQUALS(v, o);
  27. TS_ASSERT_EQUALS(v, o2);
  28. }
  29. void test_collect_arg_preserves() {
  30. vec_t v{1, 2, 3, 4, 5};
  31. auto s = stream::make_stream(v);
  32. std::set<int> o{};
  33. s.collect(o);
  34. for ( int i : v ) {
  35. TS_ASSERT_EQUALS(o.count( i ), 1);
  36. }
  37. }
  38. void test_map_identity() {
  39. vec_t v{1, 2, 3, 4, 5};
  40. auto identity = [](int const & i) { return i; };
  41. auto s = stream::make_stream(v).map( identity );
  42. vec_t o{s.begin(), s.end()};
  43. TS_ASSERT_EQUALS(v, o);
  44. }
  45. void test_map_change() {
  46. vec_t v{1, 2, 3, 4, 5};
  47. vec_t expected{3, 5, 7, 9, 11};
  48. auto fmap = [](int const & i) { return 2*i+1; };
  49. auto s = stream::make_stream(v).map( fmap );
  50. vec_t o{s.begin(), s.end()};
  51. TS_ASSERT_EQUALS(expected, o);
  52. }
  53. void test_filter_noop() {
  54. vec_t v{1, 2, 3, 4, 5};
  55. auto pass = [](int const & i) { return true; };
  56. auto s = stream::make_stream(v).filter( pass );
  57. vec_t o{s.begin(), s.end()};
  58. TS_ASSERT_EQUALS(v, o);
  59. }
  60. void test_filter_value() {
  61. vec_t v{1, 2, 3, 4, 5};
  62. vec_t expected{2, 4};
  63. auto even = [](int const & i) { return i%2 == 0; };
  64. auto s = stream::make_stream(v).filter( even );
  65. vec_t o{s.begin(), s.end()};
  66. TS_ASSERT_EQUALS(expected, o);
  67. }
  68. void test_accumulate() {
  69. vec_t v{1, 2, 3, 4, 5};
  70. auto even = [](int const & i) { return i%2 == 0; };
  71. auto s = stream::make_stream(v).filter( even );
  72. TS_ASSERT_EQUALS( 6 , s.accumulate([](int const & lhs, int const & rhs) { return lhs + rhs; }, 0) );
  73. }
  74. void test_flatmap_joins_lists() {
  75. std::vector<vec_t> vv{{1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {4, 5, 6}, {5, 6, 7}};
  76. vec_t expected{1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7};
  77. auto identity = [](int const & i) { return i; };
  78. auto s = stream::make_stream(vv).flatmap( identity );
  79. vec_t o{s.begin(), s.end()};
  80. TS_ASSERT_EQUALS(expected, o);
  81. }
  82. };