Newer
Older
libj / include / j / cppunit / assert.hpp
/**
 * @file assert.hpp
 * @brief J Library Assert ヘッダファイル。
 * @copyright  2001 - 2024  Nomura Kei
 * @depends
 *   j.hpp
 *   j/overload.hpp
 *   j/lang/object.hpp
 *  (j/lang/assertion_error.hpp)
 */
#ifndef J_CPPUNIT_ASSERT_HPP
#define J_CPPUNIT_ASSERT_HPP

#include <sstream>
#include <cmath>

#include <j.hpp>
#include <j/overload.hpp>
#include <j/lang/object.hpp>

namespace j
{
    namespace cppunit
    {
        namespace Assert
        {
            // 汎用, Object を継承したクラスも operator!= により同じ。
            template <typename T>
            void _assertEqualsImpl(const T &expected, const T &actual,
                                   const char *file, const char *func, int line)
            {
                if (expected != actual)
                {
                    std::ostringstream msg;
                    msg << "expected <" << expected << "> but was: <" << actual << ">";
                    throw lang::AssertionError(msg.str(), file, func, line);
                }
            }

            // オーバーロード: const char*
            void _assertEqualsImpl(const char *expected, const char *actual,
                                   const char *file, const char *func, int line);

            // float, double の場合
            void _assertEqualsFloatImpl(const double &expected, const double &actual, const double &delta,
                                        const char *file, const char *func, int line);

            void _assertTrueImpl(bool condition, const char *file, const char *func, int line);
            void _assertFalseImpl(bool condition, const char *file, const char *func, int line);
            void _assertNullImpl(void *obj, const char *file, const char *func, int line);
            void _assertNotNullImpl(void *obj, const char *file, const char *func, int line);
            void _failImpl(const char *file, const char *func, int line);
        }
    } // cppunit
} // namespace j

// __FILE__, __func__, __LINE__ 情報埋め込みマクロ
#define assertEquals(...) J_OVERLOAD(assertEqualsArgs, __VA_ARGS__)
#define assertEqualsArgs2(expected, actual) j::cppunit::Assert::_assertEqualsImpl(expected, actual, __FILE__, __func__, __LINE__)
#define assertEqualsArgs3(expected, actual, delta) j::cppunit::Assert::_assertEqualsFloatImpl(expected, actual, delta, __FILE__, __func__, __LINE__)
#define assertTrue(condition) j::cppunit::Assert::_assertTrueImpl(condition, __FILE__, __func__, __LINE__)
#define assertFalse(condition) j::cppunit::Assert::_assertFalseImpl(condition, __FILE__, __func__, __LINE__)
#define assertNull(obj) j::cppunit::Assert::_assertNullImpl(obj, __FILE__, __func__, __LINE__)
#define assertNotNull(obj) j::cppunit::Assert::_assertNotNullImpl(obj, __FILE__, __func__, __LINE__)
#define fail() j::cppunit::Assert::_failImpl(__FILE__, __func__, __LINE__)

#endif // J_CPPUNIT_ASSERT_HPP