stream_fluent_test.cxx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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::ElementsAreArray;
  12. using ::testing::Eq;
  13. TEST(FluentStreamTest, CollectToObjectPreservesElements) {
  14. std::vector<int> input{1, 2, 3, 4, 5};
  15. auto s = stream::make_stream(input);
  16. std::set<int> out{};
  17. EXPECT_THAT(s > out, ElementsAreArray(input));
  18. }
  19. TEST(FluentStreamTest, MapToSelfIsSelfs) {
  20. std::vector<int> input{1, 2, 3, 4, 5};
  21. auto identity = [](int i) { return i; };
  22. auto s = stream::make_stream(input) | identity;
  23. EXPECT_THAT(s.collect(), Eq(input));
  24. }
  25. TEST(FluentStreamTest, MapCanAlterValues) {
  26. std::vector<int> input{1, 2, 3, 4, 5};
  27. std::vector<int> expected{3, 5, 7, 9, 11};
  28. auto fmap = [](int i) { return 2 * i + 1; };
  29. auto s = stream::make_stream(input) | fmap;
  30. EXPECT_THAT(s.collect(), Eq(expected));
  31. }
  32. TEST(FluentStreamTest, NoOpFilterReturnOriginal) {
  33. std::vector<int> input{1, 2, 3, 4, 5};
  34. auto pass = [](int) { return true; };
  35. auto s = stream::make_stream(input) | pass;
  36. EXPECT_THAT(s.collect(), Eq(input));
  37. }
  38. TEST(FluentStreamTest, CanFilterOutElements) {
  39. std::vector<int> input{1, 2, 3, 4, 5};
  40. std::vector<int> expected{2, 4};
  41. auto even = [](int i) { return i % 2 == 0; };
  42. auto s = stream::make_stream(input) | even;
  43. EXPECT_THAT(s.collect(), Eq(expected));
  44. }
  45. TEST(FluentStreamTest, AccumulateDefaultsToAdd) {
  46. std::vector<int> input{1, 2, 3, 4, 5};
  47. auto even = [](int i) { return i % 2 == 0; };
  48. auto sum = [](int lhs, int rhs) { return lhs + rhs; };
  49. auto s = stream::make_stream(input) | even;
  50. EXPECT_THAT(s > sum, Eq(6));
  51. }
  52. TEST(FluentStreamTest, FlatmapJoinsIterableOutputs) {
  53. std::vector<int> vv{1, 2, 3, 4, 5};
  54. auto next3 = [](int i) { return std::vector<int>{i, i + 1, i + 2}; };
  55. std::vector<int> expected{1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7};
  56. auto s = stream::make_stream(vv) || next3;
  57. EXPECT_THAT(s.collect(), Eq(expected));
  58. }