stream_fluent_test.cxx 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //
  2. // stream_fluent.t.h
  3. // stream
  4. //
  5. // Created by Sam Jaffe on 1/28/17.
  6. //
  7. #include <gmock/gmock.h>
  8. #include <vector>
  9. #include "stream/streams.hpp"
  10. #include "stream/streams/fluent.hpp"
  11. using ::testing::Eq;
  12. using int_t = int const &;
  13. TEST(FluentStreamTest, CollectToObjectPreservesElements) {
  14. std::vector<int> v{1, 2, 3, 4, 5};
  15. auto s = stream::make_stream(v);
  16. std::set<int> o{};
  17. s > o;
  18. for (int i : v ) {
  19. EXPECT_THAT(o.count(i), Eq(1));
  20. }
  21. }
  22. TEST(FluentStreamTest, MapToSelfIsSelfs) {
  23. std::vector<int> v{1, 2, 3, 4, 5};
  24. auto identity = [](int_t i) { return i; };
  25. auto s = stream::make_stream(v) | identity;
  26. std::vector<int> o{s.begin(), s.end()};
  27. EXPECT_THAT(o, Eq(v));
  28. }
  29. TEST(FluentStreamTest, MapCanAlterValues) {
  30. std::vector<int> v{1, 2, 3, 4, 5};
  31. std::vector<int> expected{3, 5, 7, 9, 11};
  32. auto fmap = [](int_t i) { return 2*i+1; };
  33. auto s = stream::make_stream(v) | fmap;
  34. std::vector<int> o{s.begin(), s.end()};
  35. EXPECT_THAT(o, Eq(expected));
  36. }
  37. TEST(FluentStreamTest, NoOpFilterReturnOriginal) {
  38. std::vector<int> v{1, 2, 3, 4, 5};
  39. auto pass = [](int_t) { return true; };
  40. auto s = stream::make_stream(v) | pass;
  41. std::vector<int> o{s.begin(), s.end()};
  42. EXPECT_THAT(o, Eq(v));
  43. }
  44. TEST(FluentStreamTest, CanFilterOutElements) {
  45. std::vector<int> v{1, 2, 3, 4, 5};
  46. std::vector<int> expected{2, 4};
  47. auto even = [](int_t i) { return i%2 == 0; };
  48. auto s = stream::make_stream(v) | even;
  49. std::vector<int> o{s.begin(), s.end()};
  50. EXPECT_THAT(o, Eq(expected));
  51. }
  52. TEST(FluentStreamTest, AccumulateDefaultsToAdd) {
  53. std::vector<int> v{1, 2, 3, 4, 5};
  54. auto even = [](int_t i) { return i%2 == 0; };
  55. auto sum = [](int_t lhs, int_t rhs) { return lhs + rhs; };
  56. auto s = stream::make_stream(v) | even;
  57. EXPECT_THAT(s > sum, Eq(6));
  58. }
  59. TEST(FluentStreamTest, FlatmapJoinsIterableOutputs) {
  60. std::vector<int> vv{1, 2, 3, 4, 5};
  61. auto next3 = [](int_t i) { return std::vector<int>{i, i+1, i+2}; };
  62. std::vector<int> expected{1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7};
  63. auto s = stream::make_stream(vv) || next3;
  64. std::vector<int> o{s.begin(), s.end()};
  65. EXPECT_THAT(o, Eq(expected));
  66. }