From 0fe488b1c27cd66c91c8e37317a43c644ab7516a Mon Sep 17 00:00:00 2001 From: Deukhoofd Date: Sun, 22 Mar 2020 11:14:47 +0100 Subject: [PATCH] Implements Assert macro. --- src/Assert.hpp | 24 ++++++++++++++++++++++++ tests/AssertTests.cpp | 14 ++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 src/Assert.hpp create mode 100644 tests/AssertTests.cpp diff --git a/src/Assert.hpp b/src/Assert.hpp new file mode 100644 index 0000000..12d568a --- /dev/null +++ b/src/Assert.hpp @@ -0,0 +1,24 @@ +#ifndef ARBUTILS_ASSERT_HPP +#define ARBUTILS_ASSERT_HPP +#include +#include +#include + +#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__) + +#ifndef NO_ASSERT +#define Assert(expr) \ + { \ + if (!expr) { \ + std::stringstream ss; \ + ss << "ASSERTION FAILED: [" << __FILENAME__ << " (" << __LINE__ << ")] \""; \ + ss << #expr << "\""; \ + throw std::logic_error(ss.str()); \ + } \ + } +#else +// Assert is empty if NO_ASSERT is defined. +#define Assert(expr) +#endif + +#endif \ No newline at end of file diff --git a/tests/AssertTests.cpp b/tests/AssertTests.cpp new file mode 100644 index 0000000..bbac7f8 --- /dev/null +++ b/tests/AssertTests.cpp @@ -0,0 +1,14 @@ +#include "../extern/catch.hpp" +#include "../src/Assert.hpp" +void TestWrapper(bool wrapperExpression){Assert(wrapperExpression)} + +TEST_CASE("Assert succeeds if true", "[Utilities]") { + REQUIRE_NOTHROW(TestWrapper(true)); +} + +TEST_CASE("Assert throws if false", "[Utilities]") { REQUIRE_THROWS(TestWrapper(false)); } + +TEST_CASE("Assert throws if false with message", "[Utilities]") { + REQUIRE_THROWS_WITH(TestWrapper(false), + Catch::Matchers::Equals("ASSERTION FAILED: [AssertTests.cpp (3)] \"wrapperExpression\"")); +}