// // 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 int_t = int const &; 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_t 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_t 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_t 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_t 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_t i) { return i%2 == 0; }; auto sum =[](int_t lhs, int_t rhs) { return lhs + rhs; }; auto s = stream::make_stream(v).filter( even ); TS_ASSERT_EQUALS( 6 , s.accumulate(sum, 0) ); } void test_flatmap_joins_lists() { vec_t vv{1, 2, 3, 4, 5}; auto next3 = [](int_t i) { return vec_t{i, i+1, i+2}; }; vec_t expected{1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7}; auto s = stream::make_stream(vv).flatmap( next3 ); vec_t o{s.begin(), s.end()}; TS_ASSERT_EQUALS(expected, o); } };