Files
defer.hpp/untests/defer_examples.cpp
2020-10-29 04:58:07 +07:00

63 lines
2.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, by Matvey Cherevko (blackmatov@gmail.com)
******************************************************************************/
#define CATCH_CONFIG_FAST_COMPILE
#include <catch2/catch.hpp>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <defer.hpp/defer.hpp>
TEST_CASE("examples") {
SECTION("basic_defer") {
if ( FILE *file = std::fopen("output.txt", "a") ) {
// defer will close the file after scope or on exception
DEFER_HPP([file]{ std::fclose(file); });
const char buffer[] = "hello world\n";
if ( 12 != std::fwrite(buffer, sizeof(buffer[0]), std::strlen(buffer), file) ) {
throw std::runtime_error("some exception");
}
}
}
SECTION("error_defer") {
if ( FILE *file = std::fopen("output.txt", "a") ) {
// defer will close the file after scope or on exception
DEFER_HPP([file]{ std::fclose(file); });
// error defer will be called on exception
ERROR_DEFER_HPP([]{
std::cerr << "there is something wrong" << std::endl;
});
const char buffer[] = "hello world\n";
if ( 12 != std::fwrite(buffer, sizeof(buffer[0]), std::strlen(buffer), file) ) {
throw std::runtime_error("some exception");
}
}
}
SECTION("return_defer") {
if ( FILE *file = std::fopen("output.txt", "a") ) {
// defer will close the file after scope or on exception
DEFER_HPP([file]{ std::fclose(file); });
// return defer will be called on successful scope exit
RETURN_DEFER_HPP([]{
std::cout << "all is ok!" << std::endl;
});
const char buffer[] = "hello world\n";
if ( 12 != std::fwrite(buffer, sizeof(buffer[0]), std::strlen(buffer), file) ) {
throw std::runtime_error("some exception");
}
}
}
}