Search code examples
c++booststreamcomparisoncatch-unit-test

Is there a way with catch framework to compare stream or files?


I have seen in the boost testing tools the macro:

BOOST_<level>_EQUAL_COLLECTION(left_begin, left_end, right_begin, right_end)

which can work for streams by using ifstream_iterator.

Does Catch framework provide such a way to compare streams/files?


Solution

  • Not built-in, but then it does not purport to.

    For this you write your own matcher.

    Here's the documentation's example for integer range checking:

    // The matcher class
    class IntRange : public Catch::MatcherBase<int> {
        int m_begin, m_end;
    public:
        IntRange( int begin, int end ) : m_begin( begin ), m_end( end ) {}
    
        // Performs the test for this matcher
        virtual bool match( int const& i ) const override {
            return i >= m_begin && i <= m_end;
        }
    
        // Produces a string describing what this matcher does. It should
        // include any provided data (the begin/ end in this case) and
        // be written as if it were stating a fact (in the output it will be
        // preceded by the value under test).
        virtual std::string describe() const {
            std::ostringstream ss;
            ss << "is between " << m_begin << " and " << m_end;
            return ss.str();
        }
    };
    
    // The builder function
    inline IntRange IsBetween( int begin, int end ) {
        return IntRange( begin, end );
    }
    
    // ...
    
    // Usage
    TEST_CASE("Integers are within a range")
    {
        CHECK_THAT( 3, IsBetween( 1, 10 ) );
        CHECK_THAT( 100, IsBetween( 1, 10 ) );
    }
    

    Clearly you can adapt this to perform any check that you need.