Files
defer.hpp/untests/defer_tests.cpp
2023-01-05 09:37:11 +07:00

137 lines
3.2 KiB
C++

/*******************************************************************************
* This file is part of the "https://github.com/blackmatov/defer.hpp"
* For conditions of distribution and use, see copyright notice in LICENSE.md
* Copyright (C) 2020-2023, by Matvey Cherevko (blackmatov@gmail.com)
******************************************************************************/
#include <defer.hpp/defer.hpp>
#include <doctest/doctest.h>
#include <functional>
TEST_CASE("defer") {
SUBCASE("simple") {
int i = 0;
{
DEFER_HPP([&i]{ ++i; });
REQUIRE(i == 0);
}
REQUIRE(i == 1);
}
SUBCASE("simple_with_arg") {
int i = 0;
{
DEFER_HPP([](int& ni){ ++ni; }, std::ref(i));
REQUIRE(i == 0);
}
REQUIRE(i == 1);
}
SUBCASE("simple_with_args") {
int i = 0, j = 0;
{
DEFER_HPP([](int& ni, int& nj){ ++ni; nj += 2; }, std::ref(i), std::ref(j));
REQUIRE(i == 0);
REQUIRE(j == 0);
}
REQUIRE(i == 1);
REQUIRE(j == 2);
}
SUBCASE("simple_with_exception") {
int i = 0;
try {
DEFER_HPP([&i]{ ++i; });
REQUIRE(i == 0);
throw std::exception();
} catch (...) {
}
REQUIRE(i == 1);
}
}
TEST_CASE("error_defer") {
SUBCASE("simple") {
int i = 0;
{
ERROR_DEFER_HPP([&i]{ ++i; });
REQUIRE(i == 0);
}
REQUIRE(i == 0);
}
SUBCASE("simple_with_arg") {
int i = 0;
{
ERROR_DEFER_HPP([](int& ni){ ++ni; }, std::ref(i));
REQUIRE(i == 0);
}
REQUIRE(i == 0);
}
SUBCASE("simple_with_args") {
int i = 0, j = 0;
{
ERROR_DEFER_HPP([](int& ni, int& nj){ ++ni; nj += 2; }, std::ref(i), std::ref(j));
REQUIRE(i == 0);
REQUIRE(j == 0);
}
REQUIRE(i == 0);
REQUIRE(j == 0);
}
SUBCASE("simple_with_exception") {
int i = 0;
try {
ERROR_DEFER_HPP([&i]{ ++i; });
REQUIRE(i == 0);
throw std::exception();
} catch (...) {
}
REQUIRE(i == 1);
}
}
TEST_CASE("return_defer") {
SUBCASE("simple") {
int i = 0;
{
RETURN_DEFER_HPP([&i]{ ++i; });
REQUIRE(i == 0);
}
REQUIRE(i == 1);
}
SUBCASE("simple_with_arg") {
int i = 0;
{
RETURN_DEFER_HPP([](int& ni){ ++ni; }, std::ref(i));
REQUIRE(i == 0);
}
REQUIRE(i == 1);
}
SUBCASE("simple_with_args") {
int i = 0, j = 0;
{
RETURN_DEFER_HPP([](int& ni, int& nj){ ++ni; nj += 2; }, std::ref(i), std::ref(j));
REQUIRE(i == 0);
REQUIRE(j == 0);
}
REQUIRE(i == 1);
REQUIRE(j == 2);
}
SUBCASE("simple_with_exception") {
int i = 0;
try {
RETURN_DEFER_HPP([&i]{ ++i; });
REQUIRE(i == 0);
throw std::exception();
} catch (...) {
}
REQUIRE(i == 0);
}
}