// // stream_td.hpp // stream // // Created by Sam Jaffe on 1/28/17. // #pragma once #include #include #include "streams.hpp" class stream_TestSuite : public CxxTest::TestSuite { public: using vec_t = std::vector; public: void test_preserved() { vec_t v{1, 2, 3, 4, 5}; auto s = stream::make_stream(v); vec_t o{s.begin(), s.end()}; TS_ASSERT_EQUALS(v, o); } void test_collect_preserves() { vec_t v{1, 2, 3, 4, 5}; auto s = stream::make_stream(v); vec_t o{s.begin(), s.end()}; vec_t o2{s.collect()}; TS_ASSERT_EQUALS(v, o); TS_ASSERT_EQUALS(v, o2); } void test_collect_arg_preserves() { vec_t v{1, 2, 3, 4, 5}; auto s = stream::make_stream(v); std::set o{}; s.collect(o); for ( int i : v ) { TS_ASSERT_EQUALS(o.count( i ), 1); } } void test_map_identity() { vec_t v{1, 2, 3, 4, 5}; auto identity = [](int const & i) { return i; }; auto s = stream::make_stream(v).map( identity ); vec_t o{s.begin(), s.end()}; TS_ASSERT_EQUALS(v, o); } void test_map_change() { vec_t v{1, 2, 3, 4, 5}; vec_t expected{3, 5, 7, 9, 11}; auto fmap = [](int const & i) { return 2*i+1; }; auto s = stream::make_stream(v).map( fmap ); vec_t o{s.begin(), s.end()}; TS_ASSERT_EQUALS(expected, o); } void test_filter_noop() { vec_t v{1, 2, 3, 4, 5}; auto pass = [](int const & i) { return true; }; auto s = stream::make_stream(v).filter( pass ); vec_t o{s.begin(), s.end()}; TS_ASSERT_EQUALS(v, o); } void test_filter_value() { vec_t v{1, 2, 3, 4, 5}; vec_t expected{2, 4}; auto even = [](int const & i) { return i%2 == 0; }; auto s = stream::make_stream(v).filter( even ); vec_t o{s.begin(), s.end()}; TS_ASSERT_EQUALS(expected, o); } void test_accumulate() { vec_t v{1, 2, 3, 4, 5}; auto even = [](int const & i) { return i%2 == 0; }; auto s = stream::make_stream(v).filter( even ); TS_ASSERT_EQUALS( 6 , s.accumulate([](int const & lhs, int const & rhs) { return lhs + rhs; }, 0) ); } void test_flatmap_joins_lists() { std::vector vv{{1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {4, 5, 6}, {5, 6, 7}}; vec_t expected{1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7}; auto identity = [](int const & i) { return i; }; auto s = stream::make_stream(vv).flatmap( identity ); vec_t o{s.begin(), s.end()}; TS_ASSERT_EQUALS(expected, o); } };