mirror of
https://github.com/EQEmu/Server.git
synced 2026-09-02 08:26:36 +00:00
EQStream abstraction layer
This commit is contained in:
@@ -0,0 +1,157 @@
|
||||
#------------------------------------------------------------------------------
|
||||
# Build the google test library
|
||||
|
||||
# We compile Google Test ourselves instead of using pre-compiled libraries.
|
||||
# See the Google Test FAQ "Why is it not recommended to install a
|
||||
# pre-compiled copy of Google Test (for example, into /usr/local)?"
|
||||
# at http://code.google.com/p/googletest/wiki/FAQ for more details.
|
||||
add_library(gmock STATIC
|
||||
gmock-gtest-all.cc gmock/gmock.h gtest/gtest.h gtest/gtest-spi.h)
|
||||
target_compile_options(gmock PUBLIC ${CPP11_FLAG})
|
||||
target_compile_definitions(gmock PUBLIC GTEST_HAS_STD_WSTRING=1)
|
||||
target_include_directories(gmock PUBLIC .)
|
||||
|
||||
find_package(Threads)
|
||||
if (Threads_FOUND)
|
||||
target_link_libraries(gmock ${CMAKE_THREAD_LIBS_INIT})
|
||||
else ()
|
||||
target_compile_definitions(gmock PUBLIC GTEST_HAS_PTHREAD=0)
|
||||
endif ()
|
||||
|
||||
if (NOT SUPPORTS_VARIADIC_TEMPLATES OR NOT SUPPORTS_INITIALIZER_LIST)
|
||||
target_compile_definitions(gmock PUBLIC GTEST_LANG_CXX11=0)
|
||||
endif ()
|
||||
|
||||
# Workaround a bug in implementation of variadic templates in MSVC11.
|
||||
if (MSVC)
|
||||
target_compile_definitions(gmock PUBLIC _VARIADIC_MAX=10)
|
||||
endif ()
|
||||
|
||||
# GTest doesn't detect <tuple> with clang.
|
||||
if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
|
||||
target_compile_definitions(gmock PUBLIC GTEST_USE_OWN_TR1_TUPLE=1)
|
||||
endif ()
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
# Build the actual library tests
|
||||
|
||||
set(TEST_MAIN_SRC test-main.cc gtest-extra.cc gtest-extra.h util.cc)
|
||||
add_library(test-main STATIC ${TEST_MAIN_SRC})
|
||||
target_compile_definitions(test-main PUBLIC
|
||||
FMT_USE_FILE_DESCRIPTORS=$<BOOL:${HAVE_OPEN}>)
|
||||
target_link_libraries(test-main gmock fmt)
|
||||
|
||||
include(CheckCXXCompilerFlag)
|
||||
|
||||
# Workaround GTest bug https://github.com/google/googletest/issues/705.
|
||||
check_cxx_compiler_flag(
|
||||
-fno-delete-null-pointer-checks HAVE_FNO_DELETE_NULL_POINTER_CHECKS)
|
||||
if (HAVE_FNO_DELETE_NULL_POINTER_CHECKS)
|
||||
target_compile_options(test-main PUBLIC -fno-delete-null-pointer-checks)
|
||||
endif ()
|
||||
|
||||
# Use less strict pedantic flags for the tests because GMock doesn't compile
|
||||
# cleanly with -pedantic and -std=c++98.
|
||||
if (CMAKE_COMPILER_IS_GNUCXX OR (CMAKE_CXX_COMPILER_ID MATCHES "Clang"))
|
||||
set(PEDANTIC_COMPILE_FLAGS -Wall -Wextra -Wno-long-long -Wno-variadic-macros)
|
||||
endif ()
|
||||
|
||||
# Adds a test.
|
||||
# Usage: add_fmt_test(name srcs...)
|
||||
function(add_fmt_test name)
|
||||
add_executable(${name} ${name}.cc ${ARGN})
|
||||
target_link_libraries(${name} test-main)
|
||||
# define if certain c++ features can be used
|
||||
target_compile_definitions(${name} PRIVATE
|
||||
FMT_USE_TYPE_TRAITS=$<BOOL:${SUPPORTS_TYPE_TRAITS}>
|
||||
FMT_USE_ENUM_BASE=$<BOOL:${SUPPORTS_ENUM_BASE}>)
|
||||
if (FMT_PEDANTIC)
|
||||
target_compile_options(${name} PRIVATE ${PEDANTIC_COMPILE_FLAGS})
|
||||
endif ()
|
||||
add_test(NAME ${name} COMMAND ${name})
|
||||
endfunction()
|
||||
|
||||
add_fmt_test(assert-test)
|
||||
add_fmt_test(gtest-extra-test)
|
||||
add_fmt_test(format-test)
|
||||
add_fmt_test(format-impl-test)
|
||||
add_fmt_test(ostream-test)
|
||||
add_fmt_test(printf-test)
|
||||
add_fmt_test(util-test mock-allocator.h)
|
||||
add_fmt_test(macro-test)
|
||||
|
||||
# Enable stricter options for one test to make sure that the header is free of
|
||||
# warnings.
|
||||
if (FMT_PEDANTIC AND MSVC)
|
||||
target_compile_options(format-test PRIVATE /W4)
|
||||
endif ()
|
||||
|
||||
if (HAVE_OPEN)
|
||||
add_executable(posix-mock-test posix-mock-test.cc ../fmt/format.cc ${TEST_MAIN_SRC})
|
||||
target_include_directories(posix-mock-test PRIVATE ${PROJECT_SOURCE_DIR})
|
||||
target_compile_definitions(posix-mock-test PRIVATE FMT_USE_FILE_DESCRIPTORS=1)
|
||||
target_link_libraries(posix-mock-test gmock)
|
||||
add_test(NAME posix-mock-test COMMAND posix-mock-test)
|
||||
add_fmt_test(posix-test)
|
||||
endif ()
|
||||
|
||||
add_executable(header-only-test
|
||||
header-only-test.cc header-only-test2.cc test-main.cc)
|
||||
target_link_libraries(header-only-test gmock)
|
||||
if (TARGET fmt-header-only)
|
||||
target_link_libraries(header-only-test fmt-header-only)
|
||||
else ()
|
||||
target_include_directories(header-only-test PRIVATE ${PROJECT_SOURCE_DIR})
|
||||
target_compile_definitions(header-only-test PRIVATE FMT_HEADER_ONLY=1)
|
||||
endif ()
|
||||
|
||||
# Test that the library can be compiled with exceptions disabled.
|
||||
check_cxx_compiler_flag(-fno-exceptions HAVE_FNO_EXCEPTIONS_FLAG)
|
||||
if (HAVE_FNO_EXCEPTIONS_FLAG)
|
||||
add_library(noexception-test ../fmt/format.cc)
|
||||
target_compile_options(noexception-test PRIVATE -fno-exceptions)
|
||||
endif ()
|
||||
|
||||
if (FMT_PEDANTIC)
|
||||
# Test that the library compiles without windows.h.
|
||||
if (CMAKE_SYSTEM_NAME STREQUAL "Windows")
|
||||
add_library(no-windows-h-test ../fmt/format.cc)
|
||||
target_compile_definitions(no-windows-h-test PRIVATE FMT_USE_WINDOWS_H=0)
|
||||
endif ()
|
||||
|
||||
add_test(compile-test ${CMAKE_CTEST_COMMAND}
|
||||
--build-and-test
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/compile-test"
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/compile-test"
|
||||
--build-generator ${CMAKE_GENERATOR}
|
||||
--build-makeprogram ${CMAKE_MAKE_PROGRAM}
|
||||
--build-options
|
||||
"-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}"
|
||||
"-DCPP11_FLAG=${CPP11_FLAG}"
|
||||
"-DSUPPORTS_USER_DEFINED_LITERALS=${SUPPORTS_USER_DEFINED_LITERALS}")
|
||||
|
||||
# test if the targets are findable from the build directory
|
||||
add_test(find-package-test ${CMAKE_CTEST_COMMAND}
|
||||
-C ${CMAKE_BUILD_TYPE}
|
||||
--build-and-test
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/find-package-test"
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/find-package-test"
|
||||
--build-generator ${CMAKE_GENERATOR}
|
||||
--build-makeprogram ${CMAKE_MAKE_PROGRAM}
|
||||
--build-options
|
||||
"-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}"
|
||||
"-DFMT_DIR=${PROJECT_BINARY_DIR}"
|
||||
"-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}")
|
||||
|
||||
# test if the targets are findable when add_subdirectory is used
|
||||
add_test(add-subdirectory-test ${CMAKE_CTEST_COMMAND}
|
||||
-C ${CMAKE_BUILD_TYPE}
|
||||
--build-and-test
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/add-subdirectory-test"
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/add-subdirectory-test"
|
||||
--build-generator ${CMAKE_GENERATOR}
|
||||
--build-makeprogram ${CMAKE_MAKE_PROGRAM}
|
||||
--build-options
|
||||
"-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}"
|
||||
"-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}")
|
||||
endif ()
|
||||
@@ -0,0 +1,13 @@
|
||||
cmake_minimum_required(VERSION 2.8.12)
|
||||
|
||||
project(fmt-test)
|
||||
|
||||
add_subdirectory(../.. fmt)
|
||||
|
||||
add_executable(library-test "main.cc")
|
||||
target_link_libraries(library-test fmt)
|
||||
|
||||
if (TARGET fmt-header-only)
|
||||
add_executable(header-only-test "main.cc")
|
||||
target_link_libraries(header-only-test fmt-header-only)
|
||||
endif ()
|
||||
@@ -0,0 +1,6 @@
|
||||
#include "fmt/format.h"
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
for(int i = 0; i < argc; ++i)
|
||||
fmt::print("{}: {}\n", i, argv[i]);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
Assertion tests
|
||||
|
||||
Copyright (c) 2015, Victor Zverovich
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include "fmt/format.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#if GTEST_HAS_DEATH_TEST
|
||||
# define EXPECT_DEBUG_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
EXPECT_DEBUG_DEATH(statement, regex)
|
||||
#else
|
||||
# define EXPECT_DEBUG_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, )
|
||||
#endif
|
||||
|
||||
TEST(AssertTest, Fail) {
|
||||
EXPECT_DEBUG_DEATH_IF_SUPPORTED(FMT_ASSERT(false, "don't panic!"), "don't panic!");
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
# Test if compile errors are produced where necessary.
|
||||
|
||||
cmake_minimum_required(VERSION 2.8)
|
||||
|
||||
include(CheckCXXSourceCompiles)
|
||||
set(CMAKE_REQUIRED_INCLUDES ${CMAKE_CURRENT_SOURCE_DIR}/../..)
|
||||
set(CMAKE_REQUIRED_FLAGS ${CPP11_FLAG})
|
||||
|
||||
function (generate_source result fragment)
|
||||
set(${result} "
|
||||
#define FMT_HEADER_ONLY 1
|
||||
#include \"fmt/posix.h\"
|
||||
int main() {
|
||||
${fragment}
|
||||
}
|
||||
" PARENT_SCOPE)
|
||||
endfunction ()
|
||||
|
||||
function (expect_compile code)
|
||||
generate_source(source "${code}")
|
||||
check_cxx_source_compiles("${source}" compiles)
|
||||
if (NOT compiles)
|
||||
set(error_msg "Compile error for: ${code}")
|
||||
endif ()
|
||||
# Unset the CMake cache variable compiles. Otherwise the compile test will
|
||||
# just use cached information next time it runs.
|
||||
unset(compiles CACHE)
|
||||
if (error_msg)
|
||||
message(FATAL_ERROR ${error_msg})
|
||||
endif ()
|
||||
endfunction ()
|
||||
|
||||
function (expect_compile_error code)
|
||||
generate_source(source "${code}")
|
||||
check_cxx_source_compiles("${source}" compiles)
|
||||
if (compiles)
|
||||
set(error_msg "No compile error for: ${code}")
|
||||
endif ()
|
||||
# Unset the CMake cache variable compiles. Otherwise the compile test will
|
||||
# just use cached information next time it runs.
|
||||
unset(compiles CACHE)
|
||||
if (error_msg)
|
||||
message(FATAL_ERROR ${error_msg})
|
||||
endif ()
|
||||
endfunction ()
|
||||
|
||||
# check if the source file skeleton compiles
|
||||
expect_compile("")
|
||||
|
||||
# MakeArg doesn't accept [const] volatile char *.
|
||||
expect_compile_error("volatile char s[] = \"test\"; (fmt::internal::MakeArg<char>)(s);")
|
||||
expect_compile_error("const volatile char s[] = \"test\"; (fmt::internal::MakeArg<char>)(s);")
|
||||
|
||||
# MakeArg<char> doesn't accept wchar_t.
|
||||
expect_compile_error("fmt::internal::MakeValue<char>(L'a');")
|
||||
expect_compile_error("fmt::internal::MakeValue<char>(L\"test\");")
|
||||
|
||||
# Writing a wide character to a character stream Writer is forbidden.
|
||||
expect_compile_error("fmt::MemoryWriter() << L'a';")
|
||||
expect_compile_error("fmt::MemoryWriter() << fmt::pad(\"abc\", 5, L' ');")
|
||||
expect_compile_error("fmt::MemoryWriter() << fmt::pad(42, 5, L' ');")
|
||||
|
||||
# Formatting a wide character with a narrow format string is forbidden.
|
||||
expect_compile_error("fmt::format(\"{}\", L'a';")
|
||||
|
||||
expect_compile("FMT_STATIC_ASSERT(true, \"this should never happen\");")
|
||||
expect_compile_error("FMT_STATIC_ASSERT(0 > 1, \"oops\");")
|
||||
|
||||
# Make sure that compiler features detected in the header
|
||||
# match the features detected in CMake.
|
||||
if (SUPPORTS_USER_DEFINED_LITERALS)
|
||||
set(supports_udl 1)
|
||||
else ()
|
||||
set(supports_udl 0)
|
||||
endif ()
|
||||
expect_compile("#if FMT_USE_USER_DEFINED_LITERALS != ${supports_udl}
|
||||
# error
|
||||
#endif")
|
||||
@@ -0,0 +1,13 @@
|
||||
cmake_minimum_required(VERSION 2.8.12)
|
||||
|
||||
project(fmt-test)
|
||||
|
||||
find_package(FMT REQUIRED)
|
||||
|
||||
add_executable(library-test main.cc)
|
||||
target_link_libraries(library-test fmt)
|
||||
|
||||
if (TARGET fmt-header-only)
|
||||
add_executable(header-only-test main.cc)
|
||||
target_link_libraries(header-only-test fmt-header-only)
|
||||
endif ()
|
||||
@@ -0,0 +1,6 @@
|
||||
#include "fmt/format.h"
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
for(int i = 0; i < argc; ++i)
|
||||
fmt::print("{}: {}\n", i, argv[i]);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
/*
|
||||
Formatting library implementation tests.
|
||||
|
||||
Copyright (c) 2012-2014, Victor Zverovich
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#define FMT_NOEXCEPT
|
||||
#include "test-assert.h"
|
||||
|
||||
// Include format.cc instead of format.h to test implementation-specific stuff.
|
||||
#include "fmt/format.cc"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
|
||||
#include "gmock/gmock.h"
|
||||
#include "gtest-extra.h"
|
||||
#include "util.h"
|
||||
|
||||
#undef min
|
||||
#undef max
|
||||
|
||||
TEST(FormatTest, ArgConverter) {
|
||||
using fmt::internal::Arg;
|
||||
Arg arg = Arg();
|
||||
arg.type = Arg::LONG_LONG;
|
||||
arg.long_long_value = std::numeric_limits<fmt::LongLong>::max();
|
||||
fmt::ArgConverter<fmt::LongLong>(arg, 'd').visit(arg);
|
||||
EXPECT_EQ(Arg::LONG_LONG, arg.type);
|
||||
}
|
||||
|
||||
TEST(FormatTest, FormatNegativeNaN) {
|
||||
double nan = std::numeric_limits<double>::quiet_NaN();
|
||||
if (fmt::internal::FPUtil::isnegative(-nan))
|
||||
EXPECT_EQ("-nan", fmt::format("{}", -nan));
|
||||
else
|
||||
fmt::print("Warning: compiler doesn't handle negative NaN correctly");
|
||||
}
|
||||
|
||||
TEST(FormatTest, StrError) {
|
||||
char *message = 0;
|
||||
char buffer[BUFFER_SIZE];
|
||||
EXPECT_ASSERT(fmt::safe_strerror(EDOM, message = 0, 0), "invalid buffer");
|
||||
EXPECT_ASSERT(fmt::safe_strerror(EDOM, message = buffer, 0),
|
||||
"invalid buffer");
|
||||
buffer[0] = 'x';
|
||||
#if defined(_GNU_SOURCE) && !defined(__COVERITY__)
|
||||
// Use invalid error code to make sure that safe_strerror returns an error
|
||||
// message in the buffer rather than a pointer to a static string.
|
||||
int error_code = -1;
|
||||
#else
|
||||
int error_code = EDOM;
|
||||
#endif
|
||||
|
||||
int result = fmt::safe_strerror(error_code, message = buffer, BUFFER_SIZE);
|
||||
EXPECT_EQ(0, result);
|
||||
std::size_t message_size = std::strlen(message);
|
||||
EXPECT_GE(BUFFER_SIZE - 1u, message_size);
|
||||
EXPECT_EQ(get_system_error(error_code), message);
|
||||
|
||||
// safe_strerror never uses buffer on MinGW.
|
||||
#ifndef __MINGW32__
|
||||
result = fmt::safe_strerror(error_code, message = buffer, message_size);
|
||||
EXPECT_EQ(ERANGE, result);
|
||||
result = fmt::safe_strerror(error_code, message = buffer, 1);
|
||||
EXPECT_EQ(buffer, message); // Message should point to buffer.
|
||||
EXPECT_EQ(ERANGE, result);
|
||||
EXPECT_STREQ("", message);
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST(FormatTest, FormatErrorCode) {
|
||||
std::string msg = "error 42", sep = ": ";
|
||||
{
|
||||
fmt::MemoryWriter w;
|
||||
w << "garbage";
|
||||
fmt::format_error_code(w, 42, "test");
|
||||
EXPECT_EQ("test: " + msg, w.str());
|
||||
}
|
||||
{
|
||||
fmt::MemoryWriter w;
|
||||
std::string prefix(
|
||||
fmt::internal::INLINE_BUFFER_SIZE - msg.size() - sep.size() + 1, 'x');
|
||||
fmt::format_error_code(w, 42, prefix);
|
||||
EXPECT_EQ(msg, w.str());
|
||||
}
|
||||
int codes[] = {42, -1};
|
||||
for (std::size_t i = 0, n = sizeof(codes) / sizeof(*codes); i < n; ++i) {
|
||||
// Test maximum buffer size.
|
||||
msg = fmt::format("error {}", codes[i]);
|
||||
fmt::MemoryWriter w;
|
||||
std::string prefix(
|
||||
fmt::internal::INLINE_BUFFER_SIZE - msg.size() - sep.size(), 'x');
|
||||
fmt::format_error_code(w, codes[i], prefix);
|
||||
EXPECT_EQ(prefix + sep + msg, w.str());
|
||||
std::size_t size = fmt::internal::INLINE_BUFFER_SIZE;
|
||||
EXPECT_EQ(size, w.size());
|
||||
w.clear();
|
||||
// Test with a message that doesn't fit into the buffer.
|
||||
prefix += 'x';
|
||||
fmt::format_error_code(w, codes[i], prefix);
|
||||
EXPECT_EQ(msg, w.str());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,433 @@
|
||||
/*
|
||||
Tests of custom Google Test assertions.
|
||||
|
||||
Copyright (c) 2012-2014, Victor Zverovich
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include "gtest-extra.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <algorithm>
|
||||
#include <stdexcept>
|
||||
#include <gtest/gtest-spi.h>
|
||||
|
||||
#if defined(_WIN32) && !defined(__MINGW32__)
|
||||
# include <crtdbg.h> // for _CrtSetReportMode
|
||||
#endif // _WIN32
|
||||
|
||||
#include "util.h"
|
||||
|
||||
using testing::internal::scoped_ptr;
|
||||
|
||||
namespace {
|
||||
|
||||
// This is used to suppress coverity warnings about untrusted values.
|
||||
std::string sanitize(const std::string &s) {
|
||||
std::string result;
|
||||
for (std::string::const_iterator i = s.begin(), end = s.end(); i != end; ++i)
|
||||
result.push_back(static_cast<char>(*i & 0xff));
|
||||
return result;
|
||||
}
|
||||
|
||||
// Tests that assertion macros evaluate their arguments exactly once.
|
||||
class SingleEvaluationTest : public ::testing::Test {
|
||||
protected:
|
||||
SingleEvaluationTest() {
|
||||
p_ = s_;
|
||||
a_ = 0;
|
||||
b_ = 0;
|
||||
}
|
||||
|
||||
static const char* const s_;
|
||||
static const char* p_;
|
||||
|
||||
static int a_;
|
||||
static int b_;
|
||||
};
|
||||
|
||||
const char* const SingleEvaluationTest::s_ = "01234";
|
||||
const char* SingleEvaluationTest::p_;
|
||||
int SingleEvaluationTest::a_;
|
||||
int SingleEvaluationTest::b_;
|
||||
|
||||
void do_nothing() {}
|
||||
|
||||
void throw_exception() {
|
||||
throw std::runtime_error("test");
|
||||
}
|
||||
|
||||
void throw_system_error() {
|
||||
throw fmt::SystemError(EDOM, "test");
|
||||
}
|
||||
|
||||
// Tests that when EXPECT_THROW_MSG fails, it evaluates its message argument
|
||||
// exactly once.
|
||||
TEST_F(SingleEvaluationTest, FailedEXPECT_THROW_MSG) {
|
||||
EXPECT_NONFATAL_FAILURE(
|
||||
EXPECT_THROW_MSG(throw_exception(), std::exception, p_++), "01234");
|
||||
EXPECT_EQ(s_ + 1, p_);
|
||||
}
|
||||
|
||||
// Tests that when EXPECT_SYSTEM_ERROR fails, it evaluates its message argument
|
||||
// exactly once.
|
||||
TEST_F(SingleEvaluationTest, FailedEXPECT_SYSTEM_ERROR) {
|
||||
EXPECT_NONFATAL_FAILURE(
|
||||
EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, p_++), "01234");
|
||||
EXPECT_EQ(s_ + 1, p_);
|
||||
}
|
||||
|
||||
// Tests that when EXPECT_WRITE fails, it evaluates its message argument
|
||||
// exactly once.
|
||||
TEST_F(SingleEvaluationTest, FailedEXPECT_WRITE) {
|
||||
EXPECT_NONFATAL_FAILURE(
|
||||
EXPECT_WRITE(stdout, std::printf("test"), p_++), "01234");
|
||||
EXPECT_EQ(s_ + 1, p_);
|
||||
}
|
||||
|
||||
// Tests that assertion arguments are evaluated exactly once.
|
||||
TEST_F(SingleEvaluationTest, ExceptionTests) {
|
||||
// successful EXPECT_THROW_MSG
|
||||
EXPECT_THROW_MSG({ // NOLINT
|
||||
a_++;
|
||||
throw_exception();
|
||||
}, std::exception, (b_++, "test"));
|
||||
EXPECT_EQ(1, a_);
|
||||
EXPECT_EQ(1, b_);
|
||||
|
||||
// failed EXPECT_THROW_MSG, throws different type
|
||||
EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG({ // NOLINT
|
||||
a_++;
|
||||
throw_exception();
|
||||
}, std::logic_error, (b_++, "test")), "throws a different type");
|
||||
EXPECT_EQ(2, a_);
|
||||
EXPECT_EQ(2, b_);
|
||||
|
||||
// failed EXPECT_THROW_MSG, throws an exception with different message
|
||||
EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG({ // NOLINT
|
||||
a_++;
|
||||
throw_exception();
|
||||
}, std::exception, (b_++, "other")),
|
||||
"throws an exception with a different message");
|
||||
EXPECT_EQ(3, a_);
|
||||
EXPECT_EQ(3, b_);
|
||||
|
||||
// failed EXPECT_THROW_MSG, throws nothing
|
||||
EXPECT_NONFATAL_FAILURE(
|
||||
EXPECT_THROW_MSG(a_++, std::exception, (b_++, "test")), "throws nothing");
|
||||
EXPECT_EQ(4, a_);
|
||||
EXPECT_EQ(4, b_);
|
||||
}
|
||||
|
||||
TEST_F(SingleEvaluationTest, SystemErrorTests) {
|
||||
// successful EXPECT_SYSTEM_ERROR
|
||||
EXPECT_SYSTEM_ERROR({ // NOLINT
|
||||
a_++;
|
||||
throw_system_error();
|
||||
}, EDOM, (b_++, "test"));
|
||||
EXPECT_EQ(1, a_);
|
||||
EXPECT_EQ(1, b_);
|
||||
|
||||
// failed EXPECT_SYSTEM_ERROR, throws different type
|
||||
EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR({ // NOLINT
|
||||
a_++;
|
||||
throw_exception();
|
||||
}, EDOM, (b_++, "test")), "throws a different type");
|
||||
EXPECT_EQ(2, a_);
|
||||
EXPECT_EQ(2, b_);
|
||||
|
||||
// failed EXPECT_SYSTEM_ERROR, throws an exception with different message
|
||||
EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR({ // NOLINT
|
||||
a_++;
|
||||
throw_system_error();
|
||||
}, EDOM, (b_++, "other")),
|
||||
"throws an exception with a different message");
|
||||
EXPECT_EQ(3, a_);
|
||||
EXPECT_EQ(3, b_);
|
||||
|
||||
// failed EXPECT_SYSTEM_ERROR, throws nothing
|
||||
EXPECT_NONFATAL_FAILURE(
|
||||
EXPECT_SYSTEM_ERROR(a_++, EDOM, (b_++, "test")), "throws nothing");
|
||||
EXPECT_EQ(4, a_);
|
||||
EXPECT_EQ(4, b_);
|
||||
}
|
||||
|
||||
// Tests that assertion arguments are evaluated exactly once.
|
||||
TEST_F(SingleEvaluationTest, WriteTests) {
|
||||
// successful EXPECT_WRITE
|
||||
EXPECT_WRITE(stdout, { // NOLINT
|
||||
a_++;
|
||||
std::printf("test");
|
||||
}, (b_++, "test"));
|
||||
EXPECT_EQ(1, a_);
|
||||
EXPECT_EQ(1, b_);
|
||||
|
||||
// failed EXPECT_WRITE
|
||||
EXPECT_NONFATAL_FAILURE(EXPECT_WRITE(stdout, { // NOLINT
|
||||
a_++;
|
||||
std::printf("test");
|
||||
}, (b_++, "other")), "Actual: test");
|
||||
EXPECT_EQ(2, a_);
|
||||
EXPECT_EQ(2, b_);
|
||||
}
|
||||
|
||||
// Tests that the compiler will not complain about unreachable code in the
|
||||
// EXPECT_THROW_MSG macro.
|
||||
TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
|
||||
int n = 0;
|
||||
using std::runtime_error;
|
||||
EXPECT_THROW_MSG(throw runtime_error(""), runtime_error, "");
|
||||
EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(n++, runtime_error, ""), "");
|
||||
EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(throw 1, runtime_error, ""), "");
|
||||
EXPECT_NONFATAL_FAILURE(EXPECT_THROW_MSG(
|
||||
throw runtime_error("a"), runtime_error, "b"), "");
|
||||
}
|
||||
|
||||
// Tests that the compiler will not complain about unreachable code in the
|
||||
// EXPECT_SYSTEM_ERROR macro.
|
||||
TEST(ExpectSystemErrorTest, DoesNotGenerateUnreachableCodeWarning) {
|
||||
int n = 0;
|
||||
EXPECT_SYSTEM_ERROR(throw fmt::SystemError(EDOM, "test"), EDOM, "test");
|
||||
EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(n++, EDOM, ""), "");
|
||||
EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(throw 1, EDOM, ""), "");
|
||||
EXPECT_NONFATAL_FAILURE(EXPECT_SYSTEM_ERROR(
|
||||
throw fmt::SystemError(EDOM, "aaa"), EDOM, "bbb"), "");
|
||||
}
|
||||
|
||||
TEST(AssertionSyntaxTest, ExceptionAssertionBehavesLikeSingleStatement) {
|
||||
if (::testing::internal::AlwaysFalse())
|
||||
EXPECT_THROW_MSG(do_nothing(), std::exception, "");
|
||||
|
||||
if (::testing::internal::AlwaysTrue())
|
||||
EXPECT_THROW_MSG(throw_exception(), std::exception, "test");
|
||||
else
|
||||
do_nothing();
|
||||
}
|
||||
|
||||
TEST(AssertionSyntaxTest, SystemErrorAssertionBehavesLikeSingleStatement) {
|
||||
if (::testing::internal::AlwaysFalse())
|
||||
EXPECT_SYSTEM_ERROR(do_nothing(), EDOM, "");
|
||||
|
||||
if (::testing::internal::AlwaysTrue())
|
||||
EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "test");
|
||||
else
|
||||
do_nothing();
|
||||
}
|
||||
|
||||
TEST(AssertionSyntaxTest, WriteAssertionBehavesLikeSingleStatement) {
|
||||
if (::testing::internal::AlwaysFalse())
|
||||
EXPECT_WRITE(stdout, std::printf("x"), "x");
|
||||
|
||||
if (::testing::internal::AlwaysTrue())
|
||||
EXPECT_WRITE(stdout, std::printf("x"), "x");
|
||||
else
|
||||
do_nothing();
|
||||
}
|
||||
|
||||
// Tests EXPECT_THROW_MSG.
|
||||
TEST(ExpectTest, EXPECT_THROW_MSG) {
|
||||
EXPECT_THROW_MSG(throw_exception(), std::exception, "test");
|
||||
EXPECT_NONFATAL_FAILURE(
|
||||
EXPECT_THROW_MSG(throw_exception(), std::logic_error, "test"),
|
||||
"Expected: throw_exception() throws an exception of "
|
||||
"type std::logic_error.\n Actual: it throws a different type.");
|
||||
EXPECT_NONFATAL_FAILURE(
|
||||
EXPECT_THROW_MSG(do_nothing(), std::exception, "test"),
|
||||
"Expected: do_nothing() throws an exception of type std::exception.\n"
|
||||
" Actual: it throws nothing.");
|
||||
EXPECT_NONFATAL_FAILURE(
|
||||
EXPECT_THROW_MSG(throw_exception(), std::exception, "other"),
|
||||
"throw_exception() throws an exception with a different message.\n"
|
||||
"Expected: other\n"
|
||||
" Actual: test");
|
||||
}
|
||||
|
||||
// Tests EXPECT_SYSTEM_ERROR.
|
||||
TEST(ExpectTest, EXPECT_SYSTEM_ERROR) {
|
||||
EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "test");
|
||||
EXPECT_NONFATAL_FAILURE(
|
||||
EXPECT_SYSTEM_ERROR(throw_exception(), EDOM, "test"),
|
||||
"Expected: throw_exception() throws an exception of "
|
||||
"type fmt::SystemError.\n Actual: it throws a different type.");
|
||||
EXPECT_NONFATAL_FAILURE(
|
||||
EXPECT_SYSTEM_ERROR(do_nothing(), EDOM, "test"),
|
||||
"Expected: do_nothing() throws an exception of type fmt::SystemError.\n"
|
||||
" Actual: it throws nothing.");
|
||||
EXPECT_NONFATAL_FAILURE(
|
||||
EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "other"),
|
||||
fmt::format(
|
||||
"throw_system_error() throws an exception with a different message.\n"
|
||||
"Expected: {}\n"
|
||||
" Actual: {}",
|
||||
format_system_error(EDOM, "other"),
|
||||
format_system_error(EDOM, "test")));
|
||||
}
|
||||
|
||||
// Tests EXPECT_WRITE.
|
||||
TEST(ExpectTest, EXPECT_WRITE) {
|
||||
EXPECT_WRITE(stdout, do_nothing(), "");
|
||||
EXPECT_WRITE(stdout, std::printf("test"), "test");
|
||||
EXPECT_WRITE(stderr, std::fprintf(stderr, "test"), "test");
|
||||
EXPECT_NONFATAL_FAILURE(
|
||||
EXPECT_WRITE(stdout, std::printf("that"), "this"),
|
||||
"Expected: this\n"
|
||||
" Actual: that");
|
||||
}
|
||||
|
||||
TEST(StreamingAssertionsTest, EXPECT_THROW_MSG) {
|
||||
EXPECT_THROW_MSG(throw_exception(), std::exception, "test")
|
||||
<< "unexpected failure";
|
||||
EXPECT_NONFATAL_FAILURE(
|
||||
EXPECT_THROW_MSG(throw_exception(), std::exception, "other")
|
||||
<< "expected failure", "expected failure");
|
||||
}
|
||||
|
||||
TEST(StreamingAssertionsTest, EXPECT_SYSTEM_ERROR) {
|
||||
EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "test")
|
||||
<< "unexpected failure";
|
||||
EXPECT_NONFATAL_FAILURE(
|
||||
EXPECT_SYSTEM_ERROR(throw_system_error(), EDOM, "other")
|
||||
<< "expected failure", "expected failure");
|
||||
}
|
||||
|
||||
TEST(StreamingAssertionsTest, EXPECT_WRITE) {
|
||||
EXPECT_WRITE(stdout, std::printf("test"), "test")
|
||||
<< "unexpected failure";
|
||||
EXPECT_NONFATAL_FAILURE(
|
||||
EXPECT_WRITE(stdout, std::printf("test"), "other")
|
||||
<< "expected failure", "expected failure");
|
||||
}
|
||||
|
||||
TEST(UtilTest, FormatSystemError) {
|
||||
fmt::MemoryWriter out;
|
||||
fmt::internal::format_system_error(out, EDOM, "test message");
|
||||
EXPECT_EQ(out.str(), format_system_error(EDOM, "test message"));
|
||||
}
|
||||
|
||||
#if FMT_USE_FILE_DESCRIPTORS
|
||||
|
||||
using fmt::BufferedFile;
|
||||
using fmt::ErrorCode;
|
||||
using fmt::File;
|
||||
|
||||
TEST(ErrorCodeTest, Ctor) {
|
||||
EXPECT_EQ(0, ErrorCode().get());
|
||||
EXPECT_EQ(42, ErrorCode(42).get());
|
||||
}
|
||||
|
||||
TEST(OutputRedirectTest, ScopedRedirect) {
|
||||
File read_end, write_end;
|
||||
File::pipe(read_end, write_end);
|
||||
{
|
||||
BufferedFile file(write_end.fdopen("w"));
|
||||
std::fprintf(file.get(), "[[[");
|
||||
{
|
||||
OutputRedirect redir(file.get());
|
||||
std::fprintf(file.get(), "censored");
|
||||
}
|
||||
std::fprintf(file.get(), "]]]");
|
||||
}
|
||||
EXPECT_READ(read_end, "[[[]]]");
|
||||
}
|
||||
|
||||
// Test that OutputRedirect handles errors in flush correctly.
|
||||
TEST(OutputRedirectTest, FlushErrorInCtor) {
|
||||
File read_end, write_end;
|
||||
File::pipe(read_end, write_end);
|
||||
int write_fd = write_end.descriptor();
|
||||
File write_copy = write_end.dup(write_fd);
|
||||
BufferedFile f = write_end.fdopen("w");
|
||||
// Put a character in a file buffer.
|
||||
EXPECT_EQ('x', fputc('x', f.get()));
|
||||
FMT_POSIX(close(write_fd));
|
||||
scoped_ptr<OutputRedirect> redir;
|
||||
EXPECT_SYSTEM_ERROR_NOASSERT(redir.reset(new OutputRedirect(f.get())),
|
||||
EBADF, "cannot flush stream");
|
||||
redir.reset();
|
||||
write_copy.dup2(write_fd); // "undo" close or dtor will fail
|
||||
}
|
||||
|
||||
TEST(OutputRedirectTest, DupErrorInCtor) {
|
||||
BufferedFile f = open_buffered_file();
|
||||
int fd = (f.fileno)();
|
||||
File copy = File::dup(fd);
|
||||
FMT_POSIX(close(fd));
|
||||
scoped_ptr<OutputRedirect> redir;
|
||||
EXPECT_SYSTEM_ERROR_NOASSERT(redir.reset(new OutputRedirect(f.get())),
|
||||
EBADF, fmt::format("cannot duplicate file descriptor {}", fd));
|
||||
copy.dup2(fd); // "undo" close or dtor will fail
|
||||
}
|
||||
|
||||
TEST(OutputRedirectTest, RestoreAndRead) {
|
||||
File read_end, write_end;
|
||||
File::pipe(read_end, write_end);
|
||||
BufferedFile file(write_end.fdopen("w"));
|
||||
std::fprintf(file.get(), "[[[");
|
||||
OutputRedirect redir(file.get());
|
||||
std::fprintf(file.get(), "censored");
|
||||
EXPECT_EQ("censored", sanitize(redir.restore_and_read()));
|
||||
EXPECT_EQ("", sanitize(redir.restore_and_read()));
|
||||
std::fprintf(file.get(), "]]]");
|
||||
file = BufferedFile();
|
||||
EXPECT_READ(read_end, "[[[]]]");
|
||||
}
|
||||
|
||||
// Test that OutputRedirect handles errors in flush correctly.
|
||||
TEST(OutputRedirectTest, FlushErrorInRestoreAndRead) {
|
||||
File read_end, write_end;
|
||||
File::pipe(read_end, write_end);
|
||||
int write_fd = write_end.descriptor();
|
||||
File write_copy = write_end.dup(write_fd);
|
||||
BufferedFile f = write_end.fdopen("w");
|
||||
OutputRedirect redir(f.get());
|
||||
// Put a character in a file buffer.
|
||||
EXPECT_EQ('x', fputc('x', f.get()));
|
||||
FMT_POSIX(close(write_fd));
|
||||
EXPECT_SYSTEM_ERROR_NOASSERT(redir.restore_and_read(),
|
||||
EBADF, "cannot flush stream");
|
||||
write_copy.dup2(write_fd); // "undo" close or dtor will fail
|
||||
}
|
||||
|
||||
TEST(OutputRedirectTest, ErrorInDtor) {
|
||||
File read_end, write_end;
|
||||
File::pipe(read_end, write_end);
|
||||
int write_fd = write_end.descriptor();
|
||||
File write_copy = write_end.dup(write_fd);
|
||||
BufferedFile f = write_end.fdopen("w");
|
||||
scoped_ptr<OutputRedirect> redir(new OutputRedirect(f.get()));
|
||||
// Put a character in a file buffer.
|
||||
EXPECT_EQ('x', fputc('x', f.get()));
|
||||
EXPECT_WRITE(stderr, {
|
||||
// The close function must be called inside EXPECT_WRITE, otherwise
|
||||
// the system may recycle closed file descriptor when redirecting the
|
||||
// output in EXPECT_STDERR and the second close will break output
|
||||
// redirection.
|
||||
FMT_POSIX(close(write_fd));
|
||||
SUPPRESS_ASSERT(redir.reset());
|
||||
}, format_system_error(EBADF, "cannot flush stream"));
|
||||
write_copy.dup2(write_fd); // "undo" close or dtor of BufferedFile will fail
|
||||
}
|
||||
|
||||
#endif // FMT_USE_FILE_DESCRIPTORS
|
||||
|
||||
} // namespace
|
||||
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
Custom Google Test assertions.
|
||||
|
||||
Copyright (c) 2012-2014, Victor Zverovich
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include "gtest-extra.h"
|
||||
|
||||
#if FMT_USE_FILE_DESCRIPTORS
|
||||
|
||||
using fmt::File;
|
||||
|
||||
void OutputRedirect::flush() {
|
||||
#if EOF != -1
|
||||
# error "FMT_RETRY assumes return value of -1 indicating failure"
|
||||
#endif
|
||||
int result = 0;
|
||||
FMT_RETRY(result, fflush(file_));
|
||||
if (result != 0)
|
||||
throw fmt::SystemError(errno, "cannot flush stream");
|
||||
}
|
||||
|
||||
void OutputRedirect::restore() {
|
||||
if (original_.descriptor() == -1)
|
||||
return; // Already restored.
|
||||
flush();
|
||||
// Restore the original file.
|
||||
original_.dup2(FMT_POSIX(fileno(file_)));
|
||||
original_.close();
|
||||
}
|
||||
|
||||
OutputRedirect::OutputRedirect(FILE *file) : file_(file) {
|
||||
flush();
|
||||
int fd = FMT_POSIX(fileno(file));
|
||||
// Create a File object referring to the original file.
|
||||
original_ = File::dup(fd);
|
||||
// Create a pipe.
|
||||
File write_end;
|
||||
File::pipe(read_end_, write_end);
|
||||
// Connect the passed FILE object to the write end of the pipe.
|
||||
write_end.dup2(fd);
|
||||
}
|
||||
|
||||
OutputRedirect::~OutputRedirect() FMT_NOEXCEPT {
|
||||
try {
|
||||
restore();
|
||||
} catch (const std::exception &e) {
|
||||
std::fputs(e.what(), stderr);
|
||||
}
|
||||
}
|
||||
|
||||
std::string OutputRedirect::restore_and_read() {
|
||||
// Restore output.
|
||||
restore();
|
||||
|
||||
// Read everything from the pipe.
|
||||
std::string content;
|
||||
if (read_end_.descriptor() == -1)
|
||||
return content; // Already read.
|
||||
enum { BUFFER_SIZE = 4096 };
|
||||
char buffer[BUFFER_SIZE];
|
||||
std::size_t count = 0;
|
||||
do {
|
||||
count = read_end_.read(buffer, BUFFER_SIZE);
|
||||
content.append(buffer, count);
|
||||
} while (count != 0);
|
||||
read_end_.close();
|
||||
return content;
|
||||
}
|
||||
|
||||
std::string read(File &f, std::size_t count) {
|
||||
std::string buffer(count, '\0');
|
||||
std::size_t n = 0, offset = 0;
|
||||
do {
|
||||
n = f.read(&buffer[offset], count - offset);
|
||||
// We can't read more than size_t bytes since count has type size_t.
|
||||
offset += static_cast<std::size_t>(n);
|
||||
} while (offset < count && n != 0);
|
||||
buffer.resize(offset);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
#endif // FMT_USE_FILE_DESCRIPTORS
|
||||
|
||||
std::string format_system_error(int error_code, fmt::StringRef message) {
|
||||
fmt::MemoryWriter out;
|
||||
fmt::internal::format_system_error(out, error_code, message);
|
||||
return out.str();
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
/*
|
||||
Custom Google Test assertions.
|
||||
|
||||
Copyright (c) 2012-2014, Victor Zverovich
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef FMT_GTEST_EXTRA_H_
|
||||
#define FMT_GTEST_EXTRA_H_
|
||||
|
||||
#include <string>
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "fmt/format.h"
|
||||
|
||||
#ifndef FMT_USE_FILE_DESCRIPTORS
|
||||
# define FMT_USE_FILE_DESCRIPTORS 0
|
||||
#endif
|
||||
|
||||
#if FMT_USE_FILE_DESCRIPTORS
|
||||
# include "fmt/posix.h"
|
||||
#endif
|
||||
|
||||
#define FMT_TEST_THROW_(statement, expected_exception, expected_message, fail) \
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
|
||||
if (::testing::AssertionResult gtest_ar = ::testing::AssertionSuccess()) { \
|
||||
std::string gtest_expected_message = expected_message; \
|
||||
bool gtest_caught_expected = false; \
|
||||
try { \
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
|
||||
} \
|
||||
catch (expected_exception const& e) { \
|
||||
if (gtest_expected_message != e.what()) { \
|
||||
gtest_ar \
|
||||
<< #statement " throws an exception with a different message.\n" \
|
||||
<< "Expected: " << gtest_expected_message << "\n" \
|
||||
<< " Actual: " << e.what(); \
|
||||
goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
|
||||
} \
|
||||
gtest_caught_expected = true; \
|
||||
} \
|
||||
catch (...) { \
|
||||
gtest_ar << \
|
||||
"Expected: " #statement " throws an exception of type " \
|
||||
#expected_exception ".\n Actual: it throws a different type."; \
|
||||
goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
|
||||
} \
|
||||
if (!gtest_caught_expected) { \
|
||||
gtest_ar << \
|
||||
"Expected: " #statement " throws an exception of type " \
|
||||
#expected_exception ".\n Actual: it throws nothing."; \
|
||||
goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
|
||||
} \
|
||||
} else \
|
||||
GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \
|
||||
fail(gtest_ar.failure_message())
|
||||
|
||||
// Tests that the statement throws the expected exception and the exception's
|
||||
// what() method returns expected message.
|
||||
#define EXPECT_THROW_MSG(statement, expected_exception, expected_message) \
|
||||
FMT_TEST_THROW_(statement, expected_exception, \
|
||||
expected_message, GTEST_NONFATAL_FAILURE_)
|
||||
|
||||
std::string format_system_error(int error_code, fmt::StringRef message);
|
||||
|
||||
#define EXPECT_SYSTEM_ERROR(statement, error_code, message) \
|
||||
EXPECT_THROW_MSG(statement, fmt::SystemError, \
|
||||
format_system_error(error_code, message))
|
||||
|
||||
#if FMT_USE_FILE_DESCRIPTORS
|
||||
|
||||
// Captures file output by redirecting it to a pipe.
|
||||
// The output it can handle is limited by the pipe capacity.
|
||||
class OutputRedirect {
|
||||
private:
|
||||
FILE *file_;
|
||||
fmt::File original_; // Original file passed to redirector.
|
||||
fmt::File read_end_; // Read end of the pipe where the output is redirected.
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(OutputRedirect);
|
||||
|
||||
void flush();
|
||||
void restore();
|
||||
|
||||
public:
|
||||
explicit OutputRedirect(FILE *file);
|
||||
~OutputRedirect() FMT_NOEXCEPT;
|
||||
|
||||
// Restores the original file, reads output from the pipe into a string
|
||||
// and returns it.
|
||||
std::string restore_and_read();
|
||||
};
|
||||
|
||||
#define FMT_TEST_WRITE_(statement, expected_output, file, fail) \
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
|
||||
if (::testing::AssertionResult gtest_ar = ::testing::AssertionSuccess()) { \
|
||||
std::string gtest_expected_output = expected_output; \
|
||||
OutputRedirect gtest_redir(file); \
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
|
||||
std::string gtest_output = gtest_redir.restore_and_read(); \
|
||||
if (gtest_output != gtest_expected_output) { \
|
||||
gtest_ar \
|
||||
<< #statement " produces different output.\n" \
|
||||
<< "Expected: " << gtest_expected_output << "\n" \
|
||||
<< " Actual: " << gtest_output; \
|
||||
goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
|
||||
} \
|
||||
} else \
|
||||
GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \
|
||||
fail(gtest_ar.failure_message())
|
||||
|
||||
// Tests that the statement writes the expected output to file.
|
||||
#define EXPECT_WRITE(file, statement, expected_output) \
|
||||
FMT_TEST_WRITE_(statement, expected_output, file, GTEST_NONFATAL_FAILURE_)
|
||||
|
||||
#ifdef _MSC_VER
|
||||
|
||||
// Suppresses Windows assertions on invalid file descriptors, making
|
||||
// POSIX functions return proper error codes instead of crashing on Windows.
|
||||
class SuppressAssert {
|
||||
private:
|
||||
_invalid_parameter_handler original_handler_;
|
||||
int original_report_mode_;
|
||||
|
||||
static void handle_invalid_parameter(const wchar_t *,
|
||||
const wchar_t *, const wchar_t *, unsigned , uintptr_t) {}
|
||||
|
||||
public:
|
||||
SuppressAssert()
|
||||
: original_handler_(_set_invalid_parameter_handler(handle_invalid_parameter)),
|
||||
original_report_mode_(_CrtSetReportMode(_CRT_ASSERT, 0)) {
|
||||
}
|
||||
~SuppressAssert() {
|
||||
_set_invalid_parameter_handler(original_handler_);
|
||||
_CrtSetReportMode(_CRT_ASSERT, original_report_mode_);
|
||||
}
|
||||
};
|
||||
|
||||
# define SUPPRESS_ASSERT(statement) { SuppressAssert sa; statement; }
|
||||
#else
|
||||
# define SUPPRESS_ASSERT(statement) statement
|
||||
#endif // _MSC_VER
|
||||
|
||||
#define EXPECT_SYSTEM_ERROR_NOASSERT(statement, error_code, message) \
|
||||
EXPECT_SYSTEM_ERROR(SUPPRESS_ASSERT(statement), error_code, message)
|
||||
|
||||
// Attempts to read count characters from a file.
|
||||
std::string read(fmt::File &f, std::size_t count);
|
||||
|
||||
#define EXPECT_READ(file, expected_content) \
|
||||
EXPECT_EQ(expected_content, read(file, std::strlen(expected_content)))
|
||||
|
||||
#endif // FMT_USE_FILE_DESCRIPTORS
|
||||
|
||||
#endif // FMT_GTEST_EXTRA_H_
|
||||
@@ -0,0 +1,232 @@
|
||||
// Copyright 2007, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
//
|
||||
// Utilities for testing Google Test itself and code that uses Google Test
|
||||
// (e.g. frameworks built on top of Google Test).
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace testing {
|
||||
|
||||
// This helper class can be used to mock out Google Test failure reporting
|
||||
// so that we can test Google Test or code that builds on Google Test.
|
||||
//
|
||||
// An object of this class appends a TestPartResult object to the
|
||||
// TestPartResultArray object given in the constructor whenever a Google Test
|
||||
// failure is reported. It can either intercept only failures that are
|
||||
// generated in the same thread that created this object or it can intercept
|
||||
// all generated failures. The scope of this mock object can be controlled with
|
||||
// the second argument to the two arguments constructor.
|
||||
class GTEST_API_ ScopedFakeTestPartResultReporter
|
||||
: public TestPartResultReporterInterface {
|
||||
public:
|
||||
// The two possible mocking modes of this object.
|
||||
enum InterceptMode {
|
||||
INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
|
||||
INTERCEPT_ALL_THREADS // Intercepts all failures.
|
||||
};
|
||||
|
||||
// The c'tor sets this object as the test part result reporter used
|
||||
// by Google Test. The 'result' parameter specifies where to report the
|
||||
// results. This reporter will only catch failures generated in the current
|
||||
// thread. DEPRECATED
|
||||
explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
|
||||
|
||||
// Same as above, but you can choose the interception scope of this object.
|
||||
ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
|
||||
TestPartResultArray* result);
|
||||
|
||||
// The d'tor restores the previous test part result reporter.
|
||||
virtual ~ScopedFakeTestPartResultReporter();
|
||||
|
||||
// Appends the TestPartResult object to the TestPartResultArray
|
||||
// received in the constructor.
|
||||
//
|
||||
// This method is from the TestPartResultReporterInterface
|
||||
// interface.
|
||||
virtual void ReportTestPartResult(const TestPartResult& result);
|
||||
private:
|
||||
void Init();
|
||||
|
||||
const InterceptMode intercept_mode_;
|
||||
TestPartResultReporterInterface* old_reporter_;
|
||||
TestPartResultArray* const result_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
|
||||
};
|
||||
|
||||
namespace internal {
|
||||
|
||||
// A helper class for implementing EXPECT_FATAL_FAILURE() and
|
||||
// EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
|
||||
// TestPartResultArray contains exactly one failure that has the given
|
||||
// type and contains the given substring. If that's not the case, a
|
||||
// non-fatal failure will be generated.
|
||||
class GTEST_API_ SingleFailureChecker {
|
||||
public:
|
||||
// The constructor remembers the arguments.
|
||||
SingleFailureChecker(const TestPartResultArray* results,
|
||||
TestPartResult::Type type,
|
||||
const string& substr);
|
||||
~SingleFailureChecker();
|
||||
private:
|
||||
const TestPartResultArray* const results_;
|
||||
const TestPartResult::Type type_;
|
||||
const string substr_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
|
||||
};
|
||||
|
||||
} // namespace internal
|
||||
|
||||
} // namespace testing
|
||||
|
||||
// A set of macros for testing Google Test assertions or code that's expected
|
||||
// to generate Google Test fatal failures. It verifies that the given
|
||||
// statement will cause exactly one fatal Google Test failure with 'substr'
|
||||
// being part of the failure message.
|
||||
//
|
||||
// There are two different versions of this macro. EXPECT_FATAL_FAILURE only
|
||||
// affects and considers failures generated in the current thread and
|
||||
// EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
|
||||
//
|
||||
// The verification of the assertion is done correctly even when the statement
|
||||
// throws an exception or aborts the current function.
|
||||
//
|
||||
// Known restrictions:
|
||||
// - 'statement' cannot reference local non-static variables or
|
||||
// non-static members of the current object.
|
||||
// - 'statement' cannot return a value.
|
||||
// - You cannot stream a failure message to this macro.
|
||||
//
|
||||
// Note that even though the implementations of the following two
|
||||
// macros are much alike, we cannot refactor them to use a common
|
||||
// helper macro, due to some peculiarity in how the preprocessor
|
||||
// works. The AcceptsMacroThatExpandsToUnprotectedComma test in
|
||||
// gtest_unittest.cc will fail to compile if we do that.
|
||||
#define EXPECT_FATAL_FAILURE(statement, substr) \
|
||||
do { \
|
||||
class GTestExpectFatalFailureHelper {\
|
||||
public:\
|
||||
static void Execute() { statement; }\
|
||||
};\
|
||||
::testing::TestPartResultArray gtest_failures;\
|
||||
::testing::internal::SingleFailureChecker gtest_checker(\
|
||||
>est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
|
||||
{\
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
|
||||
::testing::ScopedFakeTestPartResultReporter:: \
|
||||
INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
|
||||
GTestExpectFatalFailureHelper::Execute();\
|
||||
}\
|
||||
} while (::testing::internal::AlwaysFalse())
|
||||
|
||||
#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
|
||||
do { \
|
||||
class GTestExpectFatalFailureHelper {\
|
||||
public:\
|
||||
static void Execute() { statement; }\
|
||||
};\
|
||||
::testing::TestPartResultArray gtest_failures;\
|
||||
::testing::internal::SingleFailureChecker gtest_checker(\
|
||||
>est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
|
||||
{\
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
|
||||
::testing::ScopedFakeTestPartResultReporter:: \
|
||||
INTERCEPT_ALL_THREADS, >est_failures);\
|
||||
GTestExpectFatalFailureHelper::Execute();\
|
||||
}\
|
||||
} while (::testing::internal::AlwaysFalse())
|
||||
|
||||
// A macro for testing Google Test assertions or code that's expected to
|
||||
// generate Google Test non-fatal failures. It asserts that the given
|
||||
// statement will cause exactly one non-fatal Google Test failure with 'substr'
|
||||
// being part of the failure message.
|
||||
//
|
||||
// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
|
||||
// affects and considers failures generated in the current thread and
|
||||
// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
|
||||
//
|
||||
// 'statement' is allowed to reference local variables and members of
|
||||
// the current object.
|
||||
//
|
||||
// The verification of the assertion is done correctly even when the statement
|
||||
// throws an exception or aborts the current function.
|
||||
//
|
||||
// Known restrictions:
|
||||
// - You cannot stream a failure message to this macro.
|
||||
//
|
||||
// Note that even though the implementations of the following two
|
||||
// macros are much alike, we cannot refactor them to use a common
|
||||
// helper macro, due to some peculiarity in how the preprocessor
|
||||
// works. If we do that, the code won't compile when the user gives
|
||||
// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
|
||||
// expands to code containing an unprotected comma. The
|
||||
// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
|
||||
// catches that.
|
||||
//
|
||||
// For the same reason, we have to write
|
||||
// if (::testing::internal::AlwaysTrue()) { statement; }
|
||||
// instead of
|
||||
// GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
|
||||
// to avoid an MSVC warning on unreachable code.
|
||||
#define EXPECT_NONFATAL_FAILURE(statement, substr) \
|
||||
do {\
|
||||
::testing::TestPartResultArray gtest_failures;\
|
||||
::testing::internal::SingleFailureChecker gtest_checker(\
|
||||
>est_failures, ::testing::TestPartResult::kNonFatalFailure, \
|
||||
(substr));\
|
||||
{\
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
|
||||
::testing::ScopedFakeTestPartResultReporter:: \
|
||||
INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
|
||||
if (::testing::internal::AlwaysTrue()) { statement; }\
|
||||
}\
|
||||
} while (::testing::internal::AlwaysFalse())
|
||||
|
||||
#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
|
||||
do {\
|
||||
::testing::TestPartResultArray gtest_failures;\
|
||||
::testing::internal::SingleFailureChecker gtest_checker(\
|
||||
>est_failures, ::testing::TestPartResult::kNonFatalFailure, \
|
||||
(substr));\
|
||||
{\
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
|
||||
::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
|
||||
>est_failures);\
|
||||
if (::testing::internal::AlwaysTrue()) { statement; }\
|
||||
}\
|
||||
} while (::testing::internal::AlwaysFalse())
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,3 @@
|
||||
// Header-only configuration test
|
||||
|
||||
#include "fmt/format.h"
|
||||
@@ -0,0 +1,3 @@
|
||||
// Additional translation unit for the header-only configuration test
|
||||
|
||||
#include "fmt/format.h"
|
||||
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
Tests of variadic function emulation macros.
|
||||
|
||||
Copyright (c) 2012-2014, Victor Zverovich
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <utility>
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#define FMT_USE_VARIADIC_TEMPLATES 0
|
||||
#include "fmt/format.h"
|
||||
|
||||
#define IDENTITY(x) x
|
||||
|
||||
TEST(UtilTest, Gen) {
|
||||
int values[] = {FMT_GEN(10, IDENTITY)};
|
||||
for (int i = 0; i < 10; ++i)
|
||||
EXPECT_EQ(i, values[i]);
|
||||
}
|
||||
|
||||
#define MAKE_PAIR(x, y) std::make_pair(x, y)
|
||||
|
||||
TEST(UtilTest, ForEach) {
|
||||
std::pair<char, int> values[] = {
|
||||
FMT_FOR_EACH10(MAKE_PAIR, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j')
|
||||
};
|
||||
for (int i = 0; i < 10; ++i) {
|
||||
EXPECT_EQ('a' + i, values[i].first);
|
||||
EXPECT_EQ(i, values[i].second);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(UtilTest, NArg) {
|
||||
EXPECT_EQ(1, FMT_NARG(a));
|
||||
EXPECT_EQ(2, FMT_NARG(a, b));
|
||||
EXPECT_EQ(3, FMT_NARG(a, b, c));
|
||||
EXPECT_EQ(4, FMT_NARG(a, b, c, d));
|
||||
EXPECT_EQ(5, FMT_NARG(a, b, c, d, e));
|
||||
EXPECT_EQ(6, FMT_NARG(a, b, c, d, e, f));
|
||||
EXPECT_EQ(7, FMT_NARG(a, b, c, d, e, f, g));
|
||||
EXPECT_EQ(8, FMT_NARG(a, b, c, d, e, f, g, h));
|
||||
EXPECT_EQ(9, FMT_NARG(a, b, c, d, e, f, g, h, i));
|
||||
EXPECT_EQ(10, FMT_NARG(a, b, c, d, e, f, g, h, i, j));
|
||||
}
|
||||
|
||||
int result;
|
||||
|
||||
#define MAKE_TEST(func) \
|
||||
void func(const char *, const fmt::ArgList &args) { \
|
||||
result = 0; \
|
||||
for (unsigned i = 0; args[i].type; ++i) \
|
||||
result += args[i].int_value; \
|
||||
}
|
||||
|
||||
MAKE_TEST(test_func)
|
||||
|
||||
typedef char Char;
|
||||
FMT_WRAP1(test_func, const char *, 1)
|
||||
|
||||
TEST(UtilTest, Wrap1) {
|
||||
result = 0;
|
||||
test_func("", 42);
|
||||
EXPECT_EQ(42, result);
|
||||
}
|
||||
|
||||
MAKE_TEST(test_variadic_void)
|
||||
FMT_VARIADIC_VOID(test_variadic_void, const char *)
|
||||
|
||||
TEST(UtilTest, VariadicVoid) {
|
||||
result = 0;
|
||||
test_variadic_void("", 10, 20, 30, 40, 50, 60, 70, 80, 90, 100);
|
||||
EXPECT_EQ(550, result);
|
||||
}
|
||||
|
||||
template <int>
|
||||
struct S {};
|
||||
|
||||
#define GET_TYPE(n) S<n>
|
||||
|
||||
int test_variadic(FMT_GEN(10, GET_TYPE), const fmt::ArgList &args) { \
|
||||
int result = 0; \
|
||||
for (unsigned i = 0; args[i].type; ++i) \
|
||||
result += args[i].int_value; \
|
||||
return result;
|
||||
}
|
||||
FMT_VARIADIC(int, test_variadic,
|
||||
S<0>, S<1>, S<2>, S<3>, S<4>, S<5>, S<6>, S<7>, S<8>, S<9>)
|
||||
|
||||
#define MAKE_ARG(n) S<n>()
|
||||
|
||||
TEST(UtilTest, Variadic) {
|
||||
EXPECT_EQ(550, test_variadic(FMT_GEN(10, MAKE_ARG),
|
||||
10, 20, 30, 40, 50, 60, 70, 80, 90, 100));
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
Mock allocator.
|
||||
|
||||
Copyright (c) 2014, Victor Zverovich
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef FMT_MOCK_ALLOCATOR_H_
|
||||
#define FMT_MOCK_ALLOCATOR_H_
|
||||
|
||||
#include "gmock/gmock.h"
|
||||
|
||||
template <typename T>
|
||||
class MockAllocator {
|
||||
public:
|
||||
MockAllocator() {}
|
||||
MockAllocator(const MockAllocator &) {}
|
||||
typedef T value_type;
|
||||
MOCK_METHOD1_T(allocate, T* (std::size_t n));
|
||||
MOCK_METHOD2_T(deallocate, void (T* p, std::size_t n));
|
||||
};
|
||||
|
||||
template <typename Allocator>
|
||||
class AllocatorRef {
|
||||
private:
|
||||
Allocator *alloc_;
|
||||
|
||||
public:
|
||||
typedef typename Allocator::value_type value_type;
|
||||
|
||||
explicit AllocatorRef(Allocator *alloc = 0) : alloc_(alloc) {}
|
||||
|
||||
AllocatorRef(const AllocatorRef &other) : alloc_(other.alloc_) {}
|
||||
|
||||
AllocatorRef& operator=(const AllocatorRef &other) {
|
||||
alloc_ = other.alloc_;
|
||||
return *this;
|
||||
}
|
||||
|
||||
#if FMT_USE_RVALUE_REFERENCES
|
||||
private:
|
||||
void move(AllocatorRef &other) {
|
||||
alloc_ = other.alloc_;
|
||||
other.alloc_ = 0;
|
||||
}
|
||||
|
||||
public:
|
||||
AllocatorRef(AllocatorRef &&other) {
|
||||
move(other);
|
||||
}
|
||||
|
||||
AllocatorRef& operator=(AllocatorRef &&other) {
|
||||
assert(this != &other);
|
||||
move(other);
|
||||
return *this;
|
||||
}
|
||||
#endif
|
||||
|
||||
Allocator *get() const { return alloc_; }
|
||||
|
||||
value_type* allocate(std::size_t n) { return alloc_->allocate(n); }
|
||||
void deallocate(value_type* p, std::size_t n) { alloc_->deallocate(p, n); }
|
||||
};
|
||||
|
||||
#endif // FMT_MOCK_ALLOCATOR_H_
|
||||
@@ -0,0 +1,192 @@
|
||||
/*
|
||||
std::ostream support tests
|
||||
|
||||
Copyright (c) 2012-2016, Victor Zverovich
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include "fmt/ostream.cc"
|
||||
|
||||
#include <sstream>
|
||||
#include "gmock/gmock.h"
|
||||
#include "gtest-extra.h"
|
||||
#include "util.h"
|
||||
|
||||
using fmt::format;
|
||||
using fmt::FormatError;
|
||||
|
||||
template <typename Char>
|
||||
std::basic_ostream<Char> &operator<<(
|
||||
std::basic_ostream<Char> &os, const BasicTestString<Char> &s) {
|
||||
os << s.value();
|
||||
return os;
|
||||
}
|
||||
|
||||
std::ostream &operator<<(std::ostream &os, const Date &d) {
|
||||
os << d.year() << '-' << d.month() << '-' << d.day();
|
||||
return os;
|
||||
}
|
||||
|
||||
std::wostream &operator<<(std::wostream &os, const Date &d) {
|
||||
os << d.year() << L'-' << d.month() << L'-' << d.day();
|
||||
return os;
|
||||
}
|
||||
|
||||
enum TestEnum {};
|
||||
std::ostream &operator<<(std::ostream &os, TestEnum) {
|
||||
return os << "TestEnum";
|
||||
}
|
||||
|
||||
enum TestEnum2 {A};
|
||||
|
||||
TEST(OStreamTest, Enum) {
|
||||
EXPECT_FALSE(fmt::internal::ConvertToInt<TestEnum>::value);
|
||||
EXPECT_EQ("TestEnum", fmt::format("{}", TestEnum()));
|
||||
EXPECT_EQ("0", fmt::format("{}", A));
|
||||
}
|
||||
|
||||
struct TestArgFormatter : fmt::BasicArgFormatter<TestArgFormatter, char> {
|
||||
TestArgFormatter(fmt::BasicFormatter<char, TestArgFormatter> &f,
|
||||
fmt::FormatSpec &s, const char *fmt)
|
||||
: fmt::BasicArgFormatter<TestArgFormatter, char>(f, s, fmt) {}
|
||||
};
|
||||
|
||||
TEST(OStreamTest, CustomArg) {
|
||||
fmt::MemoryWriter writer;
|
||||
typedef fmt::BasicFormatter<char, TestArgFormatter> Formatter;
|
||||
Formatter formatter(fmt::ArgList(), writer);
|
||||
fmt::FormatSpec spec;
|
||||
TestArgFormatter af(formatter, spec, "}");
|
||||
af.visit(fmt::internal::MakeArg<Formatter>(TestEnum()));
|
||||
EXPECT_EQ("TestEnum", writer.str());
|
||||
}
|
||||
|
||||
TEST(OStreamTest, Format) {
|
||||
EXPECT_EQ("a string", format("{0}", TestString("a string")));
|
||||
std::string s = format("The date is {0}", Date(2012, 12, 9));
|
||||
EXPECT_EQ("The date is 2012-12-9", s);
|
||||
Date date(2012, 12, 9);
|
||||
EXPECT_EQ(L"The date is 2012-12-9",
|
||||
format(L"The date is {0}", Date(2012, 12, 9)));
|
||||
}
|
||||
|
||||
TEST(OStreamTest, FormatSpecs) {
|
||||
EXPECT_EQ("def ", format("{0:<5}", TestString("def")));
|
||||
EXPECT_EQ(" def", format("{0:>5}", TestString("def")));
|
||||
EXPECT_THROW_MSG(format("{0:=5}", TestString("def")),
|
||||
FormatError, "format specifier '=' requires numeric argument");
|
||||
EXPECT_EQ(" def ", format("{0:^5}", TestString("def")));
|
||||
EXPECT_EQ("def**", format("{0:*<5}", TestString("def")));
|
||||
EXPECT_THROW_MSG(format("{0:+}", TestString()),
|
||||
FormatError, "format specifier '+' requires numeric argument");
|
||||
EXPECT_THROW_MSG(format("{0:-}", TestString()),
|
||||
FormatError, "format specifier '-' requires numeric argument");
|
||||
EXPECT_THROW_MSG(format("{0: }", TestString()),
|
||||
FormatError, "format specifier ' ' requires numeric argument");
|
||||
EXPECT_THROW_MSG(format("{0:#}", TestString()),
|
||||
FormatError, "format specifier '#' requires numeric argument");
|
||||
EXPECT_THROW_MSG(format("{0:05}", TestString()),
|
||||
FormatError, "format specifier '0' requires numeric argument");
|
||||
EXPECT_EQ("test ", format("{0:13}", TestString("test")));
|
||||
EXPECT_EQ("test ", format("{0:{1}}", TestString("test"), 13));
|
||||
EXPECT_EQ("te", format("{0:.2}", TestString("test")));
|
||||
EXPECT_EQ("te", format("{0:.{1}}", TestString("test"), 2));
|
||||
}
|
||||
|
||||
struct EmptyTest {};
|
||||
std::ostream &operator<<(std::ostream &os, EmptyTest) {
|
||||
return os << "";
|
||||
}
|
||||
|
||||
TEST(OStreamTest, EmptyCustomOutput) {
|
||||
EXPECT_EQ("", fmt::format("{}", EmptyTest()));
|
||||
}
|
||||
|
||||
TEST(OStreamTest, Print) {
|
||||
std::ostringstream os;
|
||||
fmt::print(os, "Don't {}!", "panic");
|
||||
EXPECT_EQ("Don't panic!", os.str());
|
||||
}
|
||||
|
||||
TEST(OStreamTest, PrintfCustom) {
|
||||
EXPECT_EQ("abc", fmt::sprintf("%s", TestString("abc")));
|
||||
}
|
||||
|
||||
TEST(OStreamTest, FPrintf) {
|
||||
std::ostringstream os;
|
||||
int ret = fmt::fprintf(os, "Don't %s!", "panic");
|
||||
EXPECT_EQ("Don't panic!", os.str());
|
||||
EXPECT_EQ(12, ret);
|
||||
}
|
||||
|
||||
TEST(OStreamTest, WriteToOStream) {
|
||||
std::ostringstream os;
|
||||
fmt::MemoryWriter w;
|
||||
w << "foo";
|
||||
fmt::write(os, w);
|
||||
EXPECT_EQ("foo", os.str());
|
||||
}
|
||||
|
||||
TEST(OStreamTest, WriteToOStreamMaxSize) {
|
||||
std::size_t max_size = std::numeric_limits<std::size_t>::max();
|
||||
std::streamsize max_streamsize = std::numeric_limits<std::streamsize>::max();
|
||||
if (max_size <= fmt::internal::to_unsigned(max_streamsize))
|
||||
return;
|
||||
|
||||
class TestWriter : public fmt::BasicWriter<char> {
|
||||
private:
|
||||
struct TestBuffer : fmt::Buffer<char> {
|
||||
explicit TestBuffer(std::size_t size) { size_ = size; }
|
||||
void grow(std::size_t) {}
|
||||
} buffer_;
|
||||
public:
|
||||
explicit TestWriter(std::size_t size)
|
||||
: fmt::BasicWriter<char>(buffer_), buffer_(size) {}
|
||||
} w(max_size);
|
||||
|
||||
struct MockStreamBuf : std::streambuf {
|
||||
MOCK_METHOD2(xsputn, std::streamsize (const void *s, std::streamsize n));
|
||||
std::streamsize xsputn(const char *s, std::streamsize n) {
|
||||
const void *v = s;
|
||||
return xsputn(v, n);
|
||||
}
|
||||
} buffer;
|
||||
|
||||
struct TestOStream : std::ostream {
|
||||
explicit TestOStream(MockStreamBuf &buffer) : std::ostream(&buffer) {}
|
||||
} os(buffer);
|
||||
|
||||
testing::InSequence sequence;
|
||||
const char *data = 0;
|
||||
std::size_t size = max_size;
|
||||
do {
|
||||
typedef fmt::internal::MakeUnsigned<std::streamsize>::Type UStreamSize;
|
||||
UStreamSize n = std::min<UStreamSize>(
|
||||
size, fmt::internal::to_unsigned(max_streamsize));
|
||||
EXPECT_CALL(buffer, xsputn(data, static_cast<std::streamsize>(n)))
|
||||
.WillOnce(testing::Return(max_streamsize));
|
||||
data += n;
|
||||
size -= static_cast<std::size_t>(n);
|
||||
} while (size != 0);
|
||||
fmt::write(os, w);
|
||||
}
|
||||
@@ -0,0 +1,560 @@
|
||||
/*
|
||||
Tests of the C++ interface to POSIX functions that require mocks
|
||||
|
||||
Copyright (c) 2012-2015, Victor Zverovich
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
// Disable bogus MSVC warnings.
|
||||
#define _CRT_SECURE_NO_WARNINGS
|
||||
|
||||
#include "posix-mock.h"
|
||||
#include "fmt/posix.cc"
|
||||
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <climits>
|
||||
|
||||
#ifdef _WIN32
|
||||
# include <io.h>
|
||||
# undef max
|
||||
# undef ERROR
|
||||
#endif
|
||||
|
||||
#include "gmock/gmock.h"
|
||||
#include "gtest-extra.h"
|
||||
#include "util.h"
|
||||
|
||||
using fmt::BufferedFile;
|
||||
using fmt::ErrorCode;
|
||||
using fmt::File;
|
||||
|
||||
using testing::internal::scoped_ptr;
|
||||
using testing::_;
|
||||
using testing::StrEq;
|
||||
using testing::Return;
|
||||
|
||||
namespace {
|
||||
int open_count;
|
||||
int close_count;
|
||||
int dup_count;
|
||||
int dup2_count;
|
||||
int fdopen_count;
|
||||
int read_count;
|
||||
int write_count;
|
||||
int pipe_count;
|
||||
int fopen_count;
|
||||
int fclose_count;
|
||||
int fileno_count;
|
||||
std::size_t read_nbyte;
|
||||
std::size_t write_nbyte;
|
||||
bool sysconf_error;
|
||||
|
||||
enum FStatSimulation { NONE, MAX_SIZE, ERROR } fstat_sim;
|
||||
}
|
||||
|
||||
#define EMULATE_EINTR(func, error_result) \
|
||||
if (func##_count != 0) { \
|
||||
if (func##_count++ != 3) { \
|
||||
errno = EINTR; \
|
||||
return error_result; \
|
||||
} \
|
||||
}
|
||||
|
||||
#ifndef _MSC_VER
|
||||
int test::open(const char *path, int oflag, int mode) {
|
||||
EMULATE_EINTR(open, -1);
|
||||
return ::open(path, oflag, mode);
|
||||
}
|
||||
#else
|
||||
errno_t test::sopen_s(
|
||||
int* pfh, const char *filename, int oflag, int shflag, int pmode) {
|
||||
EMULATE_EINTR(open, EINTR);
|
||||
return _sopen_s(pfh, filename, oflag, shflag, pmode);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef _WIN32
|
||||
|
||||
long test::sysconf(int name) {
|
||||
long result = ::sysconf(name);
|
||||
if (!sysconf_error)
|
||||
return result;
|
||||
// Simulate an error.
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static off_t max_file_size() { return std::numeric_limits<off_t>::max(); }
|
||||
|
||||
int test::fstat(int fd, struct stat *buf) {
|
||||
int result = ::fstat(fd, buf);
|
||||
if (fstat_sim == MAX_SIZE)
|
||||
buf->st_size = max_file_size();
|
||||
return result;
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
static LONGLONG max_file_size() { return std::numeric_limits<LONGLONG>::max(); }
|
||||
|
||||
DWORD test::GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh) {
|
||||
if (fstat_sim == ERROR) {
|
||||
SetLastError(ERROR_ACCESS_DENIED);
|
||||
return INVALID_FILE_SIZE;
|
||||
}
|
||||
if (fstat_sim == MAX_SIZE) {
|
||||
DWORD max = std::numeric_limits<DWORD>::max();
|
||||
*lpFileSizeHigh = max >> 1;
|
||||
return max;
|
||||
}
|
||||
return ::GetFileSize(hFile, lpFileSizeHigh);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
int test::close(int fildes) {
|
||||
// Close the file first because close shouldn't be retried.
|
||||
int result = ::FMT_POSIX(close(fildes));
|
||||
EMULATE_EINTR(close, -1);
|
||||
return result;
|
||||
}
|
||||
|
||||
int test::dup(int fildes) {
|
||||
EMULATE_EINTR(dup, -1);
|
||||
return ::FMT_POSIX(dup(fildes));
|
||||
}
|
||||
|
||||
int test::dup2(int fildes, int fildes2) {
|
||||
EMULATE_EINTR(dup2, -1);
|
||||
return ::FMT_POSIX(dup2(fildes, fildes2));
|
||||
}
|
||||
|
||||
FILE *test::fdopen(int fildes, const char *mode) {
|
||||
EMULATE_EINTR(fdopen, 0);
|
||||
return ::FMT_POSIX(fdopen(fildes, mode));
|
||||
}
|
||||
|
||||
test::ssize_t test::read(int fildes, void *buf, test::size_t nbyte) {
|
||||
read_nbyte = nbyte;
|
||||
EMULATE_EINTR(read, -1);
|
||||
return ::FMT_POSIX(read(fildes, buf, nbyte));
|
||||
}
|
||||
|
||||
test::ssize_t test::write(int fildes, const void *buf, test::size_t nbyte) {
|
||||
write_nbyte = nbyte;
|
||||
EMULATE_EINTR(write, -1);
|
||||
return ::FMT_POSIX(write(fildes, buf, nbyte));
|
||||
}
|
||||
|
||||
#ifndef _WIN32
|
||||
int test::pipe(int fildes[2]) {
|
||||
EMULATE_EINTR(pipe, -1);
|
||||
return ::pipe(fildes);
|
||||
}
|
||||
#else
|
||||
int test::pipe(int *pfds, unsigned psize, int textmode) {
|
||||
EMULATE_EINTR(pipe, -1);
|
||||
return _pipe(pfds, psize, textmode);
|
||||
}
|
||||
#endif
|
||||
|
||||
FILE *test::fopen(const char *filename, const char *mode) {
|
||||
EMULATE_EINTR(fopen, 0);
|
||||
return ::fopen(filename, mode);
|
||||
}
|
||||
|
||||
int test::fclose(FILE *stream) {
|
||||
EMULATE_EINTR(fclose, EOF);
|
||||
return ::fclose(stream);
|
||||
}
|
||||
|
||||
int (test::fileno)(FILE *stream) {
|
||||
EMULATE_EINTR(fileno, -1);
|
||||
#ifdef fileno
|
||||
return FMT_POSIX(fileno(stream));
|
||||
#else
|
||||
return ::FMT_POSIX(fileno(stream));
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifndef _WIN32
|
||||
# define EXPECT_RETRY(statement, func, message) \
|
||||
func##_count = 1; \
|
||||
statement; \
|
||||
EXPECT_EQ(4, func##_count); \
|
||||
func##_count = 0;
|
||||
# define EXPECT_EQ_POSIX(expected, actual) EXPECT_EQ(expected, actual)
|
||||
#else
|
||||
# define EXPECT_RETRY(statement, func, message) \
|
||||
func##_count = 1; \
|
||||
EXPECT_SYSTEM_ERROR(statement, EINTR, message); \
|
||||
func##_count = 0;
|
||||
# define EXPECT_EQ_POSIX(expected, actual)
|
||||
#endif
|
||||
|
||||
void write_file(fmt::CStringRef filename, fmt::StringRef content) {
|
||||
fmt::BufferedFile f(filename, "w");
|
||||
f.print("{}", content);
|
||||
}
|
||||
|
||||
TEST(UtilTest, StaticAssert) {
|
||||
FMT_STATIC_ASSERT(true, "success");
|
||||
// Static assertion failure is tested in compile-test because it causes
|
||||
// a compile-time error.
|
||||
}
|
||||
|
||||
TEST(UtilTest, GetPageSize) {
|
||||
#ifdef _WIN32
|
||||
SYSTEM_INFO si = {};
|
||||
GetSystemInfo(&si);
|
||||
EXPECT_EQ(si.dwPageSize, fmt::getpagesize());
|
||||
#else
|
||||
EXPECT_EQ(sysconf(_SC_PAGESIZE), fmt::getpagesize());
|
||||
sysconf_error = true;
|
||||
EXPECT_SYSTEM_ERROR(
|
||||
fmt::getpagesize(), EINVAL, "cannot get memory page size");
|
||||
sysconf_error = false;
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST(FileTest, OpenRetry) {
|
||||
write_file("test", "there must be something here");
|
||||
scoped_ptr<File> f;
|
||||
EXPECT_RETRY(f.reset(new File("test", File::RDONLY)),
|
||||
open, "cannot open file test");
|
||||
#ifndef _WIN32
|
||||
char c = 0;
|
||||
f->read(&c, 1);
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST(FileTest, CloseNoRetryInDtor) {
|
||||
File read_end, write_end;
|
||||
File::pipe(read_end, write_end);
|
||||
scoped_ptr<File> f(new File(std::move(read_end)));
|
||||
int saved_close_count = 0;
|
||||
EXPECT_WRITE(stderr, {
|
||||
close_count = 1;
|
||||
f.reset();
|
||||
saved_close_count = close_count;
|
||||
close_count = 0;
|
||||
}, format_system_error(EINTR, "cannot close file") + "\n");
|
||||
EXPECT_EQ(2, saved_close_count);
|
||||
}
|
||||
|
||||
TEST(FileTest, CloseNoRetry) {
|
||||
File read_end, write_end;
|
||||
File::pipe(read_end, write_end);
|
||||
close_count = 1;
|
||||
EXPECT_SYSTEM_ERROR(read_end.close(), EINTR, "cannot close file");
|
||||
EXPECT_EQ(2, close_count);
|
||||
close_count = 0;
|
||||
}
|
||||
|
||||
TEST(FileTest, Size) {
|
||||
std::string content = "top secret, destroy before reading";
|
||||
write_file("test", content);
|
||||
File f("test", File::RDONLY);
|
||||
EXPECT_GE(f.size(), 0);
|
||||
EXPECT_EQ(content.size(), static_cast<fmt::ULongLong>(f.size()));
|
||||
#ifdef _WIN32
|
||||
fmt::MemoryWriter message;
|
||||
fmt::internal::format_windows_error(
|
||||
message, ERROR_ACCESS_DENIED, "cannot get file size");
|
||||
fstat_sim = ERROR;
|
||||
EXPECT_THROW_MSG(f.size(), fmt::WindowsError, message.str());
|
||||
fstat_sim = NONE;
|
||||
#else
|
||||
f.close();
|
||||
EXPECT_SYSTEM_ERROR(f.size(), EBADF, "cannot get file attributes");
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST(FileTest, MaxSize) {
|
||||
write_file("test", "");
|
||||
File f("test", File::RDONLY);
|
||||
fstat_sim = MAX_SIZE;
|
||||
EXPECT_GE(f.size(), 0);
|
||||
EXPECT_EQ(max_file_size(), f.size());
|
||||
fstat_sim = NONE;
|
||||
}
|
||||
|
||||
TEST(FileTest, ReadRetry) {
|
||||
File read_end, write_end;
|
||||
File::pipe(read_end, write_end);
|
||||
enum { SIZE = 4 };
|
||||
write_end.write("test", SIZE);
|
||||
write_end.close();
|
||||
char buffer[SIZE];
|
||||
std::size_t count = 0;
|
||||
EXPECT_RETRY(count = read_end.read(buffer, SIZE),
|
||||
read, "cannot read from file");
|
||||
EXPECT_EQ_POSIX(static_cast<std::streamsize>(SIZE), count);
|
||||
}
|
||||
|
||||
TEST(FileTest, WriteRetry) {
|
||||
File read_end, write_end;
|
||||
File::pipe(read_end, write_end);
|
||||
enum { SIZE = 4 };
|
||||
std::size_t count = 0;
|
||||
EXPECT_RETRY(count = write_end.write("test", SIZE),
|
||||
write, "cannot write to file");
|
||||
write_end.close();
|
||||
#ifndef _WIN32
|
||||
EXPECT_EQ(static_cast<std::streamsize>(SIZE), count);
|
||||
char buffer[SIZE + 1];
|
||||
read_end.read(buffer, SIZE);
|
||||
buffer[SIZE] = '\0';
|
||||
EXPECT_STREQ("test", buffer);
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
TEST(FileTest, ConvertReadCount) {
|
||||
File read_end, write_end;
|
||||
File::pipe(read_end, write_end);
|
||||
char c;
|
||||
std::size_t size = UINT_MAX;
|
||||
if (sizeof(unsigned) != sizeof(std::size_t))
|
||||
++size;
|
||||
read_count = 1;
|
||||
read_nbyte = 0;
|
||||
EXPECT_THROW(read_end.read(&c, size), fmt::SystemError);
|
||||
read_count = 0;
|
||||
EXPECT_EQ(UINT_MAX, read_nbyte);
|
||||
}
|
||||
|
||||
TEST(FileTest, ConvertWriteCount) {
|
||||
File read_end, write_end;
|
||||
File::pipe(read_end, write_end);
|
||||
char c;
|
||||
std::size_t size = UINT_MAX;
|
||||
if (sizeof(unsigned) != sizeof(std::size_t))
|
||||
++size;
|
||||
write_count = 1;
|
||||
write_nbyte = 0;
|
||||
EXPECT_THROW(write_end.write(&c, size), fmt::SystemError);
|
||||
write_count = 0;
|
||||
EXPECT_EQ(UINT_MAX, write_nbyte);
|
||||
}
|
||||
#endif
|
||||
|
||||
TEST(FileTest, DupNoRetry) {
|
||||
int stdout_fd = FMT_POSIX(fileno(stdout));
|
||||
dup_count = 1;
|
||||
EXPECT_SYSTEM_ERROR(File::dup(stdout_fd), EINTR,
|
||||
fmt::format("cannot duplicate file descriptor {}", stdout_fd));
|
||||
dup_count = 0;
|
||||
}
|
||||
|
||||
TEST(FileTest, Dup2Retry) {
|
||||
int stdout_fd = FMT_POSIX(fileno(stdout));
|
||||
File f1 = File::dup(stdout_fd), f2 = File::dup(stdout_fd);
|
||||
EXPECT_RETRY(f1.dup2(f2.descriptor()), dup2,
|
||||
fmt::format("cannot duplicate file descriptor {} to {}",
|
||||
f1.descriptor(), f2.descriptor()));
|
||||
}
|
||||
|
||||
TEST(FileTest, Dup2NoExceptRetry) {
|
||||
int stdout_fd = FMT_POSIX(fileno(stdout));
|
||||
File f1 = File::dup(stdout_fd), f2 = File::dup(stdout_fd);
|
||||
ErrorCode ec;
|
||||
dup2_count = 1;
|
||||
f1.dup2(f2.descriptor(), ec);
|
||||
#ifndef _WIN32
|
||||
EXPECT_EQ(4, dup2_count);
|
||||
#else
|
||||
EXPECT_EQ(EINTR, ec.get());
|
||||
#endif
|
||||
dup2_count = 0;
|
||||
}
|
||||
|
||||
TEST(FileTest, PipeNoRetry) {
|
||||
File read_end, write_end;
|
||||
pipe_count = 1;
|
||||
EXPECT_SYSTEM_ERROR(
|
||||
File::pipe(read_end, write_end), EINTR, "cannot create pipe");
|
||||
pipe_count = 0;
|
||||
}
|
||||
|
||||
TEST(FileTest, FdopenNoRetry) {
|
||||
File read_end, write_end;
|
||||
File::pipe(read_end, write_end);
|
||||
fdopen_count = 1;
|
||||
EXPECT_SYSTEM_ERROR(read_end.fdopen("r"),
|
||||
EINTR, "cannot associate stream with file descriptor");
|
||||
fdopen_count = 0;
|
||||
}
|
||||
|
||||
TEST(BufferedFileTest, OpenRetry) {
|
||||
write_file("test", "there must be something here");
|
||||
scoped_ptr<BufferedFile> f;
|
||||
EXPECT_RETRY(f.reset(new BufferedFile("test", "r")),
|
||||
fopen, "cannot open file test");
|
||||
#ifndef _WIN32
|
||||
char c = 0;
|
||||
if (fread(&c, 1, 1, f->get()) < 1)
|
||||
throw fmt::SystemError(errno, "fread failed");
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST(BufferedFileTest, CloseNoRetryInDtor) {
|
||||
File read_end, write_end;
|
||||
File::pipe(read_end, write_end);
|
||||
scoped_ptr<BufferedFile> f(new BufferedFile(read_end.fdopen("r")));
|
||||
int saved_fclose_count = 0;
|
||||
EXPECT_WRITE(stderr, {
|
||||
fclose_count = 1;
|
||||
f.reset();
|
||||
saved_fclose_count = fclose_count;
|
||||
fclose_count = 0;
|
||||
}, format_system_error(EINTR, "cannot close file") + "\n");
|
||||
EXPECT_EQ(2, saved_fclose_count);
|
||||
}
|
||||
|
||||
TEST(BufferedFileTest, CloseNoRetry) {
|
||||
File read_end, write_end;
|
||||
File::pipe(read_end, write_end);
|
||||
BufferedFile f = read_end.fdopen("r");
|
||||
fclose_count = 1;
|
||||
EXPECT_SYSTEM_ERROR(f.close(), EINTR, "cannot close file");
|
||||
EXPECT_EQ(2, fclose_count);
|
||||
fclose_count = 0;
|
||||
}
|
||||
|
||||
TEST(BufferedFileTest, FilenoNoRetry) {
|
||||
File read_end, write_end;
|
||||
File::pipe(read_end, write_end);
|
||||
BufferedFile f = read_end.fdopen("r");
|
||||
fileno_count = 1;
|
||||
EXPECT_SYSTEM_ERROR((f.fileno)(), EINTR, "cannot get file descriptor");
|
||||
EXPECT_EQ(2, fileno_count);
|
||||
fileno_count = 0;
|
||||
}
|
||||
|
||||
template <typename Mock>
|
||||
struct ScopedMock : testing::StrictMock<Mock> {
|
||||
ScopedMock() { Mock::instance = this; }
|
||||
~ScopedMock() { Mock::instance = 0; }
|
||||
};
|
||||
|
||||
struct TestMock {
|
||||
static TestMock *instance;
|
||||
} *TestMock::instance;
|
||||
|
||||
TEST(ScopedMock, Scope) {
|
||||
{
|
||||
ScopedMock<TestMock> mock;
|
||||
EXPECT_EQ(&mock, TestMock::instance);
|
||||
TestMock © = mock;
|
||||
}
|
||||
EXPECT_EQ(0, TestMock::instance);
|
||||
}
|
||||
|
||||
#ifdef FMT_LOCALE
|
||||
|
||||
typedef fmt::Locale::Type LocaleType;
|
||||
|
||||
struct LocaleMock {
|
||||
static LocaleMock *instance;
|
||||
MOCK_METHOD3(newlocale, LocaleType (int category_mask, const char *locale,
|
||||
LocaleType base));
|
||||
MOCK_METHOD1(freelocale, void (LocaleType locale));
|
||||
|
||||
MOCK_METHOD3(strtod_l, double (const char *nptr, char **endptr,
|
||||
LocaleType locale));
|
||||
} *LocaleMock::instance;
|
||||
|
||||
#ifdef _MSC_VER
|
||||
# pragma warning(push)
|
||||
# pragma warning(disable: 4273)
|
||||
|
||||
_locale_t _create_locale(int category, const char *locale) {
|
||||
return LocaleMock::instance->newlocale(category, locale, 0);
|
||||
}
|
||||
|
||||
void _free_locale(_locale_t locale) {
|
||||
LocaleMock::instance->freelocale(locale);
|
||||
}
|
||||
|
||||
double _strtod_l(const char *nptr, char **endptr, _locale_t locale) {
|
||||
return LocaleMock::instance->strtod_l(nptr, endptr, locale);
|
||||
}
|
||||
# pragma warning(pop)
|
||||
#endif
|
||||
|
||||
LocaleType newlocale(int category_mask, const char *locale, LocaleType base) {
|
||||
return LocaleMock::instance->newlocale(category_mask, locale, base);
|
||||
}
|
||||
|
||||
#ifdef __APPLE__
|
||||
typedef int FreeLocaleResult;
|
||||
#else
|
||||
typedef void FreeLocaleResult;
|
||||
#endif
|
||||
|
||||
FreeLocaleResult freelocale(LocaleType locale) {
|
||||
LocaleMock::instance->freelocale(locale);
|
||||
return FreeLocaleResult();
|
||||
}
|
||||
|
||||
double strtod_l(const char *nptr, char **endptr, LocaleType locale) {
|
||||
return LocaleMock::instance->strtod_l(nptr, endptr, locale);
|
||||
}
|
||||
|
||||
TEST(LocaleTest, LocaleMock) {
|
||||
ScopedMock<LocaleMock> mock;
|
||||
LocaleType locale = reinterpret_cast<LocaleType>(11);
|
||||
EXPECT_CALL(mock, newlocale(222, StrEq("foo"), locale));
|
||||
newlocale(222, "foo", locale);
|
||||
}
|
||||
|
||||
TEST(LocaleTest, Locale) {
|
||||
#ifndef LC_NUMERIC_MASK
|
||||
enum { LC_NUMERIC_MASK = LC_NUMERIC };
|
||||
#endif
|
||||
ScopedMock<LocaleMock> mock;
|
||||
LocaleType impl = reinterpret_cast<LocaleType>(42);
|
||||
EXPECT_CALL(mock, newlocale(LC_NUMERIC_MASK, StrEq("C"), 0))
|
||||
.WillOnce(Return(impl));
|
||||
EXPECT_CALL(mock, freelocale(impl));
|
||||
fmt::Locale locale;
|
||||
EXPECT_EQ(impl, locale.get());
|
||||
}
|
||||
|
||||
TEST(LocaleTest, Strtod) {
|
||||
ScopedMock<LocaleMock> mock;
|
||||
EXPECT_CALL(mock, newlocale(_, _, _))
|
||||
.WillOnce(Return(reinterpret_cast<LocaleType>(42)));
|
||||
EXPECT_CALL(mock, freelocale(_));
|
||||
fmt::Locale locale;
|
||||
const char *str = "4.2";
|
||||
char end = 'x';
|
||||
EXPECT_CALL(mock, strtod_l(str, _, locale.get()))
|
||||
.WillOnce(testing::DoAll(testing::SetArgPointee<1>(&end), Return(777)));
|
||||
EXPECT_EQ(777, locale.strtod(str));
|
||||
EXPECT_EQ(&end, str);
|
||||
}
|
||||
|
||||
#endif // FMT_LOCALE
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
Mocks of POSIX functions
|
||||
|
||||
Copyright (c) 2012-2015, Victor Zverovich
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef FMT_POSIX_TEST_H
|
||||
#define FMT_POSIX_TEST_H
|
||||
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
# include <windows.h>
|
||||
#else
|
||||
# include <sys/types.h> // for ssize_t
|
||||
#endif
|
||||
|
||||
#ifndef _MSC_VER
|
||||
struct stat;
|
||||
#endif
|
||||
|
||||
namespace test {
|
||||
|
||||
#ifndef _MSC_VER
|
||||
// Size type for read and write.
|
||||
typedef size_t size_t;
|
||||
typedef ssize_t ssize_t;
|
||||
int open(const char *path, int oflag, int mode);
|
||||
int fstat(int fd, struct stat *buf);
|
||||
#else
|
||||
typedef unsigned size_t;
|
||||
typedef int ssize_t;
|
||||
errno_t sopen_s(
|
||||
int* pfh, const char *filename, int oflag, int shflag, int pmode);
|
||||
#endif
|
||||
|
||||
#ifndef _WIN32
|
||||
long sysconf(int name);
|
||||
#else
|
||||
DWORD GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh);
|
||||
#endif
|
||||
|
||||
int close(int fildes);
|
||||
|
||||
int dup(int fildes);
|
||||
int dup2(int fildes, int fildes2);
|
||||
|
||||
FILE *fdopen(int fildes, const char *mode);
|
||||
|
||||
ssize_t read(int fildes, void *buf, size_t nbyte);
|
||||
ssize_t write(int fildes, const void *buf, size_t nbyte);
|
||||
|
||||
#ifndef _WIN32
|
||||
int pipe(int fildes[2]);
|
||||
#else
|
||||
int pipe(int *pfds, unsigned psize, int textmode);
|
||||
#endif
|
||||
|
||||
FILE *fopen(const char *filename, const char *mode);
|
||||
int fclose(FILE *stream);
|
||||
int (fileno)(FILE *stream);
|
||||
} // namespace test
|
||||
|
||||
#define FMT_SYSTEM(call) test::call
|
||||
|
||||
#endif // FMT_POSIX_TEST_H
|
||||
@@ -0,0 +1,398 @@
|
||||
/*
|
||||
Tests of the C++ interface to POSIX functions
|
||||
|
||||
Copyright (c) 2015, Victor Zverovich
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <cstdlib> // std::exit
|
||||
#include <cstring>
|
||||
|
||||
#include "fmt/posix.h"
|
||||
#include "gtest-extra.h"
|
||||
#include "util.h"
|
||||
|
||||
#ifdef fileno
|
||||
# undef fileno
|
||||
#endif
|
||||
|
||||
using fmt::BufferedFile;
|
||||
using fmt::ErrorCode;
|
||||
using fmt::File;
|
||||
|
||||
using testing::internal::scoped_ptr;
|
||||
|
||||
// Checks if the file is open by reading one character from it.
|
||||
bool isopen(int fd) {
|
||||
char buffer;
|
||||
return FMT_POSIX(read(fd, &buffer, 1)) == 1;
|
||||
}
|
||||
|
||||
bool isclosed(int fd) {
|
||||
char buffer;
|
||||
std::streamsize result = 0;
|
||||
SUPPRESS_ASSERT(result = FMT_POSIX(read(fd, &buffer, 1)));
|
||||
return result == -1 && errno == EBADF;
|
||||
}
|
||||
|
||||
// Opens a file for reading.
|
||||
File open_file() {
|
||||
File read_end, write_end;
|
||||
File::pipe(read_end, write_end);
|
||||
write_end.write(FILE_CONTENT, std::strlen(FILE_CONTENT));
|
||||
write_end.close();
|
||||
return read_end;
|
||||
}
|
||||
|
||||
// Attempts to write a string to a file.
|
||||
void write(File &f, fmt::StringRef s) {
|
||||
std::size_t num_chars_left = s.size();
|
||||
const char *ptr = s.data();
|
||||
do {
|
||||
std::size_t count = f.write(ptr, num_chars_left);
|
||||
ptr += count;
|
||||
// We can't write more than size_t bytes since num_chars_left
|
||||
// has type size_t.
|
||||
num_chars_left -= static_cast<std::size_t>(count);
|
||||
} while (num_chars_left != 0);
|
||||
}
|
||||
|
||||
TEST(BufferedFileTest, DefaultCtor) {
|
||||
BufferedFile f;
|
||||
EXPECT_TRUE(f.get() == 0);
|
||||
}
|
||||
|
||||
TEST(BufferedFileTest, MoveCtor) {
|
||||
BufferedFile bf = open_buffered_file();
|
||||
FILE *fp = bf.get();
|
||||
EXPECT_TRUE(fp != 0);
|
||||
BufferedFile bf2(std::move(bf));
|
||||
EXPECT_EQ(fp, bf2.get());
|
||||
EXPECT_TRUE(bf.get() == 0);
|
||||
}
|
||||
|
||||
TEST(BufferedFileTest, MoveAssignment) {
|
||||
BufferedFile bf = open_buffered_file();
|
||||
FILE *fp = bf.get();
|
||||
EXPECT_TRUE(fp != 0);
|
||||
BufferedFile bf2;
|
||||
bf2 = std::move(bf);
|
||||
EXPECT_EQ(fp, bf2.get());
|
||||
EXPECT_TRUE(bf.get() == 0);
|
||||
}
|
||||
|
||||
TEST(BufferedFileTest, MoveAssignmentClosesFile) {
|
||||
BufferedFile bf = open_buffered_file();
|
||||
BufferedFile bf2 = open_buffered_file();
|
||||
int old_fd = bf2.fileno();
|
||||
bf2 = std::move(bf);
|
||||
EXPECT_TRUE(isclosed(old_fd));
|
||||
}
|
||||
|
||||
TEST(BufferedFileTest, MoveFromTemporaryInCtor) {
|
||||
FILE *fp = 0;
|
||||
BufferedFile f(open_buffered_file(&fp));
|
||||
EXPECT_EQ(fp, f.get());
|
||||
}
|
||||
|
||||
TEST(BufferedFileTest, MoveFromTemporaryInAssignment) {
|
||||
FILE *fp = 0;
|
||||
BufferedFile f;
|
||||
f = open_buffered_file(&fp);
|
||||
EXPECT_EQ(fp, f.get());
|
||||
}
|
||||
|
||||
TEST(BufferedFileTest, MoveFromTemporaryInAssignmentClosesFile) {
|
||||
BufferedFile f = open_buffered_file();
|
||||
int old_fd = f.fileno();
|
||||
f = open_buffered_file();
|
||||
EXPECT_TRUE(isclosed(old_fd));
|
||||
}
|
||||
|
||||
TEST(BufferedFileTest, CloseFileInDtor) {
|
||||
int fd = 0;
|
||||
{
|
||||
BufferedFile f = open_buffered_file();
|
||||
fd = f.fileno();
|
||||
}
|
||||
EXPECT_TRUE(isclosed(fd));
|
||||
}
|
||||
|
||||
TEST(BufferedFileTest, CloseErrorInDtor) {
|
||||
scoped_ptr<BufferedFile> f(new BufferedFile(open_buffered_file()));
|
||||
EXPECT_WRITE(stderr, {
|
||||
// The close function must be called inside EXPECT_WRITE, otherwise
|
||||
// the system may recycle closed file descriptor when redirecting the
|
||||
// output in EXPECT_STDERR and the second close will break output
|
||||
// redirection.
|
||||
FMT_POSIX(close(f->fileno()));
|
||||
SUPPRESS_ASSERT(f.reset());
|
||||
}, format_system_error(EBADF, "cannot close file") + "\n");
|
||||
}
|
||||
|
||||
TEST(BufferedFileTest, Close) {
|
||||
BufferedFile f = open_buffered_file();
|
||||
int fd = f.fileno();
|
||||
f.close();
|
||||
EXPECT_TRUE(f.get() == 0);
|
||||
EXPECT_TRUE(isclosed(fd));
|
||||
}
|
||||
|
||||
TEST(BufferedFileTest, CloseError) {
|
||||
BufferedFile f = open_buffered_file();
|
||||
FMT_POSIX(close(f.fileno()));
|
||||
EXPECT_SYSTEM_ERROR_NOASSERT(f.close(), EBADF, "cannot close file");
|
||||
EXPECT_TRUE(f.get() == 0);
|
||||
}
|
||||
|
||||
TEST(BufferedFileTest, Fileno) {
|
||||
BufferedFile f;
|
||||
#ifndef __COVERITY__
|
||||
// fileno on a null FILE pointer either crashes or returns an error.
|
||||
// Disable Coverity because this is intentional.
|
||||
EXPECT_DEATH_IF_SUPPORTED({
|
||||
try {
|
||||
f.fileno();
|
||||
} catch (fmt::SystemError) {
|
||||
std::exit(1);
|
||||
}
|
||||
}, "");
|
||||
#endif
|
||||
f = open_buffered_file();
|
||||
EXPECT_TRUE(f.fileno() != -1);
|
||||
File copy = File::dup(f.fileno());
|
||||
EXPECT_READ(copy, FILE_CONTENT);
|
||||
}
|
||||
|
||||
TEST(FileTest, DefaultCtor) {
|
||||
File f;
|
||||
EXPECT_EQ(-1, f.descriptor());
|
||||
}
|
||||
|
||||
TEST(FileTest, OpenBufferedFileInCtor) {
|
||||
FILE *fp = safe_fopen("test-file", "w");
|
||||
std::fputs(FILE_CONTENT, fp);
|
||||
std::fclose(fp);
|
||||
File f("test-file", File::RDONLY);
|
||||
ASSERT_TRUE(isopen(f.descriptor()));
|
||||
}
|
||||
|
||||
TEST(FileTest, OpenBufferedFileError) {
|
||||
EXPECT_SYSTEM_ERROR(File("nonexistent", File::RDONLY),
|
||||
ENOENT, "cannot open file nonexistent");
|
||||
}
|
||||
|
||||
TEST(FileTest, MoveCtor) {
|
||||
File f = open_file();
|
||||
int fd = f.descriptor();
|
||||
EXPECT_NE(-1, fd);
|
||||
File f2(std::move(f));
|
||||
EXPECT_EQ(fd, f2.descriptor());
|
||||
EXPECT_EQ(-1, f.descriptor());
|
||||
}
|
||||
|
||||
TEST(FileTest, MoveAssignment) {
|
||||
File f = open_file();
|
||||
int fd = f.descriptor();
|
||||
EXPECT_NE(-1, fd);
|
||||
File f2;
|
||||
f2 = std::move(f);
|
||||
EXPECT_EQ(fd, f2.descriptor());
|
||||
EXPECT_EQ(-1, f.descriptor());
|
||||
}
|
||||
|
||||
TEST(FileTest, MoveAssignmentClosesFile) {
|
||||
File f = open_file();
|
||||
File f2 = open_file();
|
||||
int old_fd = f2.descriptor();
|
||||
f2 = std::move(f);
|
||||
EXPECT_TRUE(isclosed(old_fd));
|
||||
}
|
||||
|
||||
File OpenBufferedFile(int &fd) {
|
||||
File f = open_file();
|
||||
fd = f.descriptor();
|
||||
return std::move(f);
|
||||
}
|
||||
|
||||
TEST(FileTest, MoveFromTemporaryInCtor) {
|
||||
int fd = 0xdead;
|
||||
File f(OpenBufferedFile(fd));
|
||||
EXPECT_EQ(fd, f.descriptor());
|
||||
}
|
||||
|
||||
TEST(FileTest, MoveFromTemporaryInAssignment) {
|
||||
int fd = 0xdead;
|
||||
File f;
|
||||
f = OpenBufferedFile(fd);
|
||||
EXPECT_EQ(fd, f.descriptor());
|
||||
}
|
||||
|
||||
TEST(FileTest, MoveFromTemporaryInAssignmentClosesFile) {
|
||||
int fd = 0xdead;
|
||||
File f = open_file();
|
||||
int old_fd = f.descriptor();
|
||||
f = OpenBufferedFile(fd);
|
||||
EXPECT_TRUE(isclosed(old_fd));
|
||||
}
|
||||
|
||||
TEST(FileTest, CloseFileInDtor) {
|
||||
int fd = 0;
|
||||
{
|
||||
File f = open_file();
|
||||
fd = f.descriptor();
|
||||
}
|
||||
EXPECT_TRUE(isclosed(fd));
|
||||
}
|
||||
|
||||
TEST(FileTest, CloseErrorInDtor) {
|
||||
scoped_ptr<File> f(new File(open_file()));
|
||||
EXPECT_WRITE(stderr, {
|
||||
// The close function must be called inside EXPECT_WRITE, otherwise
|
||||
// the system may recycle closed file descriptor when redirecting the
|
||||
// output in EXPECT_STDERR and the second close will break output
|
||||
// redirection.
|
||||
FMT_POSIX(close(f->descriptor()));
|
||||
SUPPRESS_ASSERT(f.reset());
|
||||
}, format_system_error(EBADF, "cannot close file") + "\n");
|
||||
}
|
||||
|
||||
TEST(FileTest, Close) {
|
||||
File f = open_file();
|
||||
int fd = f.descriptor();
|
||||
f.close();
|
||||
EXPECT_EQ(-1, f.descriptor());
|
||||
EXPECT_TRUE(isclosed(fd));
|
||||
}
|
||||
|
||||
TEST(FileTest, CloseError) {
|
||||
File f = open_file();
|
||||
FMT_POSIX(close(f.descriptor()));
|
||||
EXPECT_SYSTEM_ERROR_NOASSERT(f.close(), EBADF, "cannot close file");
|
||||
EXPECT_EQ(-1, f.descriptor());
|
||||
}
|
||||
|
||||
TEST(FileTest, Read) {
|
||||
File f = open_file();
|
||||
EXPECT_READ(f, FILE_CONTENT);
|
||||
}
|
||||
|
||||
TEST(FileTest, ReadError) {
|
||||
File f("test-file", File::WRONLY);
|
||||
char buf;
|
||||
// We intentionally read from a file opened in the write-only mode to
|
||||
// cause error.
|
||||
EXPECT_SYSTEM_ERROR(f.read(&buf, 1), EBADF, "cannot read from file");
|
||||
}
|
||||
|
||||
TEST(FileTest, Write) {
|
||||
File read_end, write_end;
|
||||
File::pipe(read_end, write_end);
|
||||
write(write_end, "test");
|
||||
write_end.close();
|
||||
EXPECT_READ(read_end, "test");
|
||||
}
|
||||
|
||||
TEST(FileTest, WriteError) {
|
||||
File f("test-file", File::RDONLY);
|
||||
// We intentionally write to a file opened in the read-only mode to
|
||||
// cause error.
|
||||
EXPECT_SYSTEM_ERROR(f.write(" ", 1), EBADF, "cannot write to file");
|
||||
}
|
||||
|
||||
TEST(FileTest, Dup) {
|
||||
File f = open_file();
|
||||
File copy = File::dup(f.descriptor());
|
||||
EXPECT_NE(f.descriptor(), copy.descriptor());
|
||||
EXPECT_EQ(FILE_CONTENT, read(copy, std::strlen(FILE_CONTENT)));
|
||||
}
|
||||
|
||||
#ifndef __COVERITY__
|
||||
TEST(FileTest, DupError) {
|
||||
int value = -1;
|
||||
EXPECT_SYSTEM_ERROR_NOASSERT(File::dup(value),
|
||||
EBADF, "cannot duplicate file descriptor -1");
|
||||
}
|
||||
#endif
|
||||
|
||||
TEST(FileTest, Dup2) {
|
||||
File f = open_file();
|
||||
File copy = open_file();
|
||||
f.dup2(copy.descriptor());
|
||||
EXPECT_NE(f.descriptor(), copy.descriptor());
|
||||
EXPECT_READ(copy, FILE_CONTENT);
|
||||
}
|
||||
|
||||
TEST(FileTest, Dup2Error) {
|
||||
File f = open_file();
|
||||
EXPECT_SYSTEM_ERROR_NOASSERT(f.dup2(-1), EBADF,
|
||||
fmt::format("cannot duplicate file descriptor {} to -1", f.descriptor()));
|
||||
}
|
||||
|
||||
TEST(FileTest, Dup2NoExcept) {
|
||||
File f = open_file();
|
||||
File copy = open_file();
|
||||
ErrorCode ec;
|
||||
f.dup2(copy.descriptor(), ec);
|
||||
EXPECT_EQ(0, ec.get());
|
||||
EXPECT_NE(f.descriptor(), copy.descriptor());
|
||||
EXPECT_READ(copy, FILE_CONTENT);
|
||||
}
|
||||
|
||||
TEST(FileTest, Dup2NoExceptError) {
|
||||
File f = open_file();
|
||||
ErrorCode ec;
|
||||
SUPPRESS_ASSERT(f.dup2(-1, ec));
|
||||
EXPECT_EQ(EBADF, ec.get());
|
||||
}
|
||||
|
||||
TEST(FileTest, Pipe) {
|
||||
File read_end, write_end;
|
||||
File::pipe(read_end, write_end);
|
||||
EXPECT_NE(-1, read_end.descriptor());
|
||||
EXPECT_NE(-1, write_end.descriptor());
|
||||
write(write_end, "test");
|
||||
EXPECT_READ(read_end, "test");
|
||||
}
|
||||
|
||||
TEST(FileTest, Fdopen) {
|
||||
File read_end, write_end;
|
||||
File::pipe(read_end, write_end);
|
||||
int read_fd = read_end.descriptor();
|
||||
EXPECT_EQ(read_fd, FMT_POSIX(fileno(read_end.fdopen("r").get())));
|
||||
}
|
||||
|
||||
TEST(FileTest, FdopenError) {
|
||||
File f;
|
||||
EXPECT_SYSTEM_ERROR_NOASSERT(
|
||||
f.fdopen("r"), EBADF, "cannot associate stream with file descriptor");
|
||||
}
|
||||
|
||||
#ifdef FMT_LOCALE
|
||||
TEST(LocaleTest, Strtod) {
|
||||
fmt::Locale locale;
|
||||
const char *start = "4.2", *ptr = start;
|
||||
EXPECT_EQ(4.2, locale.strtod(ptr));
|
||||
EXPECT_EQ(start + 3, ptr);
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,479 @@
|
||||
/*
|
||||
printf tests.
|
||||
|
||||
Copyright (c) 2012-2014, Victor Zverovich
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <cctype>
|
||||
#include <climits>
|
||||
#include <cstring>
|
||||
|
||||
#include "fmt/format.h"
|
||||
#include "gtest-extra.h"
|
||||
#include "util.h"
|
||||
|
||||
using fmt::format;
|
||||
using fmt::FormatError;
|
||||
|
||||
const unsigned BIG_NUM = INT_MAX + 1u;
|
||||
|
||||
// Makes format string argument positional.
|
||||
std::string make_positional(fmt::StringRef format) {
|
||||
std::string s(format.to_string());
|
||||
s.replace(s.find('%'), 1, "%1$");
|
||||
return s;
|
||||
}
|
||||
|
||||
#define EXPECT_PRINTF(expected_output, format, arg) \
|
||||
EXPECT_EQ(expected_output, fmt::sprintf(format, arg)) \
|
||||
<< "format: " << format; \
|
||||
EXPECT_EQ(expected_output, fmt::sprintf(make_positional(format), arg))
|
||||
|
||||
TEST(PrintfTest, NoArgs) {
|
||||
EXPECT_EQ("test", fmt::sprintf("test"));
|
||||
}
|
||||
|
||||
TEST(PrintfTest, Escape) {
|
||||
EXPECT_EQ("%", fmt::sprintf("%%"));
|
||||
EXPECT_EQ("before %", fmt::sprintf("before %%"));
|
||||
EXPECT_EQ("% after", fmt::sprintf("%% after"));
|
||||
EXPECT_EQ("before % after", fmt::sprintf("before %% after"));
|
||||
EXPECT_EQ("%s", fmt::sprintf("%%s"));
|
||||
}
|
||||
|
||||
TEST(PrintfTest, PositionalArgs) {
|
||||
EXPECT_EQ("42", fmt::sprintf("%1$d", 42));
|
||||
EXPECT_EQ("before 42", fmt::sprintf("before %1$d", 42));
|
||||
EXPECT_EQ("42 after", fmt::sprintf("%1$d after",42));
|
||||
EXPECT_EQ("before 42 after", fmt::sprintf("before %1$d after", 42));
|
||||
EXPECT_EQ("answer = 42", fmt::sprintf("%1$s = %2$d", "answer", 42));
|
||||
EXPECT_EQ("42 is the answer",
|
||||
fmt::sprintf("%2$d is the %1$s", "answer", 42));
|
||||
EXPECT_EQ("abracadabra", fmt::sprintf("%1$s%2$s%1$s", "abra", "cad"));
|
||||
}
|
||||
|
||||
TEST(PrintfTest, AutomaticArgIndexing) {
|
||||
EXPECT_EQ("abc", fmt::sprintf("%c%c%c", 'a', 'b', 'c'));
|
||||
}
|
||||
|
||||
TEST(PrintfTest, NumberIsTooBigInArgIndex) {
|
||||
EXPECT_THROW_MSG(fmt::sprintf(format("%{}$", BIG_NUM)),
|
||||
FormatError, "number is too big");
|
||||
EXPECT_THROW_MSG(fmt::sprintf(format("%{}$d", BIG_NUM)),
|
||||
FormatError, "number is too big");
|
||||
}
|
||||
|
||||
TEST(PrintfTest, SwitchArgIndexing) {
|
||||
EXPECT_THROW_MSG(fmt::sprintf("%1$d%", 1, 2),
|
||||
FormatError, "invalid format string");
|
||||
EXPECT_THROW_MSG(fmt::sprintf(format("%1$d%{}d", BIG_NUM), 1, 2),
|
||||
FormatError, "number is too big");
|
||||
EXPECT_THROW_MSG(fmt::sprintf("%1$d%d", 1, 2),
|
||||
FormatError, "cannot switch from manual to automatic argument indexing");
|
||||
|
||||
EXPECT_THROW_MSG(fmt::sprintf("%d%1$", 1, 2),
|
||||
FormatError, "invalid format string");
|
||||
EXPECT_THROW_MSG(fmt::sprintf(format("%d%{}$d", BIG_NUM), 1, 2),
|
||||
FormatError, "number is too big");
|
||||
EXPECT_THROW_MSG(fmt::sprintf("%d%1$d", 1, 2),
|
||||
FormatError, "cannot switch from automatic to manual argument indexing");
|
||||
|
||||
// Indexing errors override width errors.
|
||||
EXPECT_THROW_MSG(fmt::sprintf(format("%d%1${}d", BIG_NUM), 1, 2),
|
||||
FormatError, "number is too big");
|
||||
EXPECT_THROW_MSG(fmt::sprintf(format("%1$d%{}d", BIG_NUM), 1, 2),
|
||||
FormatError, "number is too big");
|
||||
}
|
||||
|
||||
TEST(PrintfTest, InvalidArgIndex) {
|
||||
EXPECT_THROW_MSG(fmt::sprintf("%0$d", 42), FormatError,
|
||||
"argument index out of range");
|
||||
EXPECT_THROW_MSG(fmt::sprintf("%2$d", 42), FormatError,
|
||||
"argument index out of range");
|
||||
EXPECT_THROW_MSG(fmt::sprintf(format("%{}$d", INT_MAX), 42),
|
||||
FormatError, "argument index out of range");
|
||||
|
||||
EXPECT_THROW_MSG(fmt::sprintf("%2$", 42),
|
||||
FormatError, "invalid format string");
|
||||
EXPECT_THROW_MSG(fmt::sprintf(format("%{}$d", BIG_NUM), 42),
|
||||
FormatError, "number is too big");
|
||||
}
|
||||
|
||||
TEST(PrintfTest, DefaultAlignRight) {
|
||||
EXPECT_PRINTF(" 42", "%5d", 42);
|
||||
EXPECT_PRINTF(" abc", "%5s", "abc");
|
||||
}
|
||||
|
||||
TEST(PrintfTest, ZeroFlag) {
|
||||
EXPECT_PRINTF("00042", "%05d", 42);
|
||||
EXPECT_PRINTF("-0042", "%05d", -42);
|
||||
|
||||
EXPECT_PRINTF("00042", "%05d", 42);
|
||||
EXPECT_PRINTF("-0042", "%05d", -42);
|
||||
EXPECT_PRINTF("-004.2", "%06g", -4.2);
|
||||
|
||||
EXPECT_PRINTF("+00042", "%00+6d", 42);
|
||||
|
||||
// '0' flag is ignored for non-numeric types.
|
||||
EXPECT_PRINTF(" x", "%05c", 'x');
|
||||
}
|
||||
|
||||
TEST(PrintfTest, PlusFlag) {
|
||||
EXPECT_PRINTF("+42", "%+d", 42);
|
||||
EXPECT_PRINTF("-42", "%+d", -42);
|
||||
EXPECT_PRINTF("+0042", "%+05d", 42);
|
||||
EXPECT_PRINTF("+0042", "%0++5d", 42);
|
||||
|
||||
// '+' flag is ignored for non-numeric types.
|
||||
EXPECT_PRINTF("x", "%+c", 'x');
|
||||
}
|
||||
|
||||
TEST(PrintfTest, MinusFlag) {
|
||||
EXPECT_PRINTF("abc ", "%-5s", "abc");
|
||||
EXPECT_PRINTF("abc ", "%0--5s", "abc");
|
||||
}
|
||||
|
||||
TEST(PrintfTest, SpaceFlag) {
|
||||
EXPECT_PRINTF(" 42", "% d", 42);
|
||||
EXPECT_PRINTF("-42", "% d", -42);
|
||||
EXPECT_PRINTF(" 0042", "% 05d", 42);
|
||||
EXPECT_PRINTF(" 0042", "%0 5d", 42);
|
||||
|
||||
// ' ' flag is ignored for non-numeric types.
|
||||
EXPECT_PRINTF("x", "% c", 'x');
|
||||
}
|
||||
|
||||
TEST(PrintfTest, HashFlag) {
|
||||
EXPECT_PRINTF("042", "%#o", 042);
|
||||
EXPECT_PRINTF(fmt::format("0{:o}", static_cast<unsigned>(-042)), "%#o", -042);
|
||||
EXPECT_PRINTF("0", "%#o", 0);
|
||||
|
||||
EXPECT_PRINTF("0x42", "%#x", 0x42);
|
||||
EXPECT_PRINTF("0X42", "%#X", 0x42);
|
||||
EXPECT_PRINTF(
|
||||
fmt::format("0x{:x}", static_cast<unsigned>(-0x42)), "%#x", -0x42);
|
||||
EXPECT_PRINTF("0", "%#x", 0);
|
||||
|
||||
EXPECT_PRINTF("0x0042", "%#06x", 0x42);
|
||||
EXPECT_PRINTF("0x0042", "%0##6x", 0x42);
|
||||
|
||||
EXPECT_PRINTF("-42.000000", "%#f", -42.0);
|
||||
EXPECT_PRINTF("-42.000000", "%#F", -42.0);
|
||||
|
||||
char buffer[BUFFER_SIZE];
|
||||
safe_sprintf(buffer, "%#e", -42.0);
|
||||
EXPECT_PRINTF(buffer, "%#e", -42.0);
|
||||
safe_sprintf(buffer, "%#E", -42.0);
|
||||
EXPECT_PRINTF(buffer, "%#E", -42.0);
|
||||
|
||||
EXPECT_PRINTF("-42.0000", "%#g", -42.0);
|
||||
EXPECT_PRINTF("-42.0000", "%#G", -42.0);
|
||||
|
||||
safe_sprintf(buffer, "%#a", 16.0);
|
||||
EXPECT_PRINTF(buffer, "%#a", 16.0);
|
||||
safe_sprintf(buffer, "%#A", 16.0);
|
||||
EXPECT_PRINTF(buffer, "%#A", 16.0);
|
||||
|
||||
// '#' flag is ignored for non-numeric types.
|
||||
EXPECT_PRINTF("x", "%#c", 'x');
|
||||
}
|
||||
|
||||
TEST(PrintfTest, Width) {
|
||||
EXPECT_PRINTF(" abc", "%5s", "abc");
|
||||
|
||||
// Width cannot be specified twice.
|
||||
EXPECT_THROW_MSG(fmt::sprintf("%5-5d", 42), FormatError,
|
||||
"unknown format code '-' for integer");
|
||||
|
||||
EXPECT_THROW_MSG(fmt::sprintf(format("%{}d", BIG_NUM), 42),
|
||||
FormatError, "number is too big");
|
||||
EXPECT_THROW_MSG(fmt::sprintf(format("%1${}d", BIG_NUM), 42),
|
||||
FormatError, "number is too big");
|
||||
}
|
||||
|
||||
TEST(PrintfTest, DynamicWidth) {
|
||||
EXPECT_EQ(" 42", fmt::sprintf("%*d", 5, 42));
|
||||
EXPECT_EQ("42 ", fmt::sprintf("%*d", -5, 42));
|
||||
EXPECT_THROW_MSG(fmt::sprintf("%*d", 5.0, 42), FormatError,
|
||||
"width is not integer");
|
||||
EXPECT_THROW_MSG(fmt::sprintf("%*d"), FormatError,
|
||||
"argument index out of range");
|
||||
EXPECT_THROW_MSG(fmt::sprintf("%*d", BIG_NUM, 42), FormatError,
|
||||
"number is too big");
|
||||
}
|
||||
|
||||
TEST(PrintfTest, IntPrecision) {
|
||||
EXPECT_PRINTF("00042", "%.5d", 42);
|
||||
EXPECT_PRINTF("-00042", "%.5d", -42);
|
||||
EXPECT_PRINTF("00042", "%.5x", 0x42);
|
||||
EXPECT_PRINTF("0x00042", "%#.5x", 0x42);
|
||||
EXPECT_PRINTF("00042", "%.5o", 042);
|
||||
EXPECT_PRINTF("00042", "%#.5o", 042);
|
||||
|
||||
EXPECT_PRINTF(" 00042", "%7.5d", 42);
|
||||
EXPECT_PRINTF(" 00042", "%7.5x", 0x42);
|
||||
EXPECT_PRINTF(" 0x00042", "%#10.5x", 0x42);
|
||||
EXPECT_PRINTF(" 00042", "%7.5o", 042);
|
||||
EXPECT_PRINTF(" 00042", "%#10.5o", 042);
|
||||
|
||||
EXPECT_PRINTF("00042 ", "%-7.5d", 42);
|
||||
EXPECT_PRINTF("00042 ", "%-7.5x", 0x42);
|
||||
EXPECT_PRINTF("0x00042 ", "%-#10.5x", 0x42);
|
||||
EXPECT_PRINTF("00042 ", "%-7.5o", 042);
|
||||
EXPECT_PRINTF("00042 ", "%-#10.5o", 042);
|
||||
}
|
||||
|
||||
TEST(PrintfTest, FloatPrecision) {
|
||||
char buffer[BUFFER_SIZE];
|
||||
safe_sprintf(buffer, "%.3e", 1234.5678);
|
||||
EXPECT_PRINTF(buffer, "%.3e", 1234.5678);
|
||||
EXPECT_PRINTF("1234.568", "%.3f", 1234.5678);
|
||||
safe_sprintf(buffer, "%.3g", 1234.5678);
|
||||
EXPECT_PRINTF(buffer, "%.3g", 1234.5678);
|
||||
safe_sprintf(buffer, "%.3a", 1234.5678);
|
||||
EXPECT_PRINTF(buffer, "%.3a", 1234.5678);
|
||||
}
|
||||
|
||||
TEST(PrintfTest, IgnorePrecisionForNonNumericArg) {
|
||||
EXPECT_PRINTF("abc", "%.5s", "abc");
|
||||
}
|
||||
|
||||
TEST(PrintfTest, DynamicPrecision) {
|
||||
EXPECT_EQ("00042", fmt::sprintf("%.*d", 5, 42));
|
||||
EXPECT_EQ("42", fmt::sprintf("%.*d", -5, 42));
|
||||
EXPECT_THROW_MSG(fmt::sprintf("%.*d", 5.0, 42), FormatError,
|
||||
"precision is not integer");
|
||||
EXPECT_THROW_MSG(fmt::sprintf("%.*d"), FormatError,
|
||||
"argument index out of range");
|
||||
EXPECT_THROW_MSG(fmt::sprintf("%.*d", BIG_NUM, 42), FormatError,
|
||||
"number is too big");
|
||||
if (sizeof(fmt::LongLong) != sizeof(int)) {
|
||||
fmt::LongLong prec = static_cast<fmt::LongLong>(INT_MIN) - 1;
|
||||
EXPECT_THROW_MSG(fmt::sprintf("%.*d", prec, 42), FormatError,
|
||||
"number is too big");
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
struct MakeSigned { typedef T Type; };
|
||||
|
||||
#define SPECIALIZE_MAKE_SIGNED(T, S) \
|
||||
template <> \
|
||||
struct MakeSigned<T> { typedef S Type; }
|
||||
|
||||
SPECIALIZE_MAKE_SIGNED(char, signed char);
|
||||
SPECIALIZE_MAKE_SIGNED(unsigned char, signed char);
|
||||
SPECIALIZE_MAKE_SIGNED(unsigned short, short);
|
||||
SPECIALIZE_MAKE_SIGNED(unsigned, int);
|
||||
SPECIALIZE_MAKE_SIGNED(unsigned long, long);
|
||||
SPECIALIZE_MAKE_SIGNED(fmt::ULongLong, fmt::LongLong);
|
||||
|
||||
// Test length format specifier ``length_spec``.
|
||||
template <typename T, typename U>
|
||||
void TestLength(const char *length_spec, U value) {
|
||||
fmt::LongLong signed_value = 0;
|
||||
fmt::ULongLong unsigned_value = 0;
|
||||
// Apply integer promotion to the argument.
|
||||
fmt::ULongLong max = std::numeric_limits<U>::max();
|
||||
using fmt::internal::check;
|
||||
if (check(max <= static_cast<unsigned>(std::numeric_limits<int>::max()))) {
|
||||
signed_value = static_cast<int>(value);
|
||||
unsigned_value = static_cast<unsigned>(value);
|
||||
} else if (check(max <= std::numeric_limits<unsigned>::max())) {
|
||||
signed_value = static_cast<unsigned>(value);
|
||||
unsigned_value = static_cast<unsigned>(value);
|
||||
}
|
||||
using fmt::internal::MakeUnsigned;
|
||||
if (sizeof(U) <= sizeof(int) && sizeof(int) < sizeof(T)) {
|
||||
signed_value = static_cast<fmt::LongLong>(value);
|
||||
unsigned_value = static_cast<typename MakeUnsigned<unsigned>::Type>(value);
|
||||
} else {
|
||||
signed_value = static_cast<typename MakeSigned<T>::Type>(value);
|
||||
unsigned_value = static_cast<typename MakeUnsigned<T>::Type>(value);
|
||||
}
|
||||
std::ostringstream os;
|
||||
os << signed_value;
|
||||
EXPECT_PRINTF(os.str(), fmt::format("%{}d", length_spec), value);
|
||||
EXPECT_PRINTF(os.str(), fmt::format("%{}i", length_spec), value);
|
||||
os.str("");
|
||||
os << unsigned_value;
|
||||
EXPECT_PRINTF(os.str(), fmt::format("%{}u", length_spec), value);
|
||||
os.str("");
|
||||
os << std::oct << unsigned_value;
|
||||
EXPECT_PRINTF(os.str(), fmt::format("%{}o", length_spec), value);
|
||||
os.str("");
|
||||
os << std::hex << unsigned_value;
|
||||
EXPECT_PRINTF(os.str(), fmt::format("%{}x", length_spec), value);
|
||||
os.str("");
|
||||
os << std::hex << std::uppercase << unsigned_value;
|
||||
EXPECT_PRINTF(os.str(), fmt::format("%{}X", length_spec), value);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void TestLength(const char *length_spec) {
|
||||
T min = std::numeric_limits<T>::min(), max = std::numeric_limits<T>::max();
|
||||
TestLength<T>(length_spec, 42);
|
||||
TestLength<T>(length_spec, -42);
|
||||
TestLength<T>(length_spec, min);
|
||||
TestLength<T>(length_spec, max);
|
||||
TestLength<T>(length_spec, fmt::LongLong(min) - 1);
|
||||
fmt::ULongLong long_long_max = std::numeric_limits<fmt::LongLong>::max();
|
||||
if (static_cast<fmt::ULongLong>(max) < long_long_max)
|
||||
TestLength<T>(length_spec, fmt::LongLong(max) + 1);
|
||||
TestLength<T>(length_spec, std::numeric_limits<short>::min());
|
||||
TestLength<T>(length_spec, std::numeric_limits<unsigned short>::max());
|
||||
TestLength<T>(length_spec, std::numeric_limits<int>::min());
|
||||
TestLength<T>(length_spec, std::numeric_limits<int>::max());
|
||||
TestLength<T>(length_spec, std::numeric_limits<unsigned>::min());
|
||||
TestLength<T>(length_spec, std::numeric_limits<unsigned>::max());
|
||||
TestLength<T>(length_spec, std::numeric_limits<fmt::LongLong>::min());
|
||||
TestLength<T>(length_spec, std::numeric_limits<fmt::LongLong>::max());
|
||||
TestLength<T>(length_spec, std::numeric_limits<fmt::ULongLong>::min());
|
||||
TestLength<T>(length_spec, std::numeric_limits<fmt::ULongLong>::max());
|
||||
}
|
||||
|
||||
TEST(PrintfTest, Length) {
|
||||
TestLength<char>("hh");
|
||||
TestLength<signed char>("hh");
|
||||
TestLength<unsigned char>("hh");
|
||||
TestLength<short>("h");
|
||||
TestLength<unsigned short>("h");
|
||||
TestLength<long>("l");
|
||||
TestLength<unsigned long>("l");
|
||||
TestLength<fmt::LongLong>("ll");
|
||||
TestLength<fmt::ULongLong>("ll");
|
||||
TestLength<intmax_t>("j");
|
||||
TestLength<std::size_t>("z");
|
||||
TestLength<std::ptrdiff_t>("t");
|
||||
long double max = std::numeric_limits<long double>::max();
|
||||
EXPECT_PRINTF(fmt::format("{}", max), "%g", max);
|
||||
EXPECT_PRINTF(fmt::format("{}", max), "%Lg", max);
|
||||
}
|
||||
|
||||
TEST(PrintfTest, Bool) {
|
||||
EXPECT_PRINTF("1", "%d", true);
|
||||
EXPECT_PRINTF("true", "%s", true);
|
||||
}
|
||||
|
||||
TEST(PrintfTest, Int) {
|
||||
EXPECT_PRINTF("-42", "%d", -42);
|
||||
EXPECT_PRINTF("-42", "%i", -42);
|
||||
unsigned u = 0 - 42u;
|
||||
EXPECT_PRINTF(fmt::format("{}", u), "%u", -42);
|
||||
EXPECT_PRINTF(fmt::format("{:o}", u), "%o", -42);
|
||||
EXPECT_PRINTF(fmt::format("{:x}", u), "%x", -42);
|
||||
EXPECT_PRINTF(fmt::format("{:X}", u), "%X", -42);
|
||||
}
|
||||
|
||||
TEST(PrintfTest, LongLong) {
|
||||
// fmt::printf allows passing long long arguments to %d without length
|
||||
// specifiers.
|
||||
fmt::LongLong max = std::numeric_limits<fmt::LongLong>::max();
|
||||
EXPECT_PRINTF(fmt::format("{}", max), "%d", max);
|
||||
}
|
||||
|
||||
TEST(PrintfTest, Float) {
|
||||
EXPECT_PRINTF("392.650000", "%f", 392.65);
|
||||
EXPECT_PRINTF("392.650000", "%F", 392.65);
|
||||
char buffer[BUFFER_SIZE];
|
||||
safe_sprintf(buffer, "%e", 392.65);
|
||||
EXPECT_PRINTF(buffer, "%e", 392.65);
|
||||
safe_sprintf(buffer, "%E", 392.65);
|
||||
EXPECT_PRINTF(buffer, "%E", 392.65);
|
||||
EXPECT_PRINTF("392.65", "%g", 392.65);
|
||||
EXPECT_PRINTF("392.65", "%G", 392.65);
|
||||
safe_sprintf(buffer, "%a", -392.65);
|
||||
EXPECT_EQ(buffer, format("{:a}", -392.65));
|
||||
safe_sprintf(buffer, "%A", -392.65);
|
||||
EXPECT_EQ(buffer, format("{:A}", -392.65));
|
||||
}
|
||||
|
||||
TEST(PrintfTest, Inf) {
|
||||
double inf = std::numeric_limits<double>::infinity();
|
||||
for (const char* type = "fega"; *type; ++type) {
|
||||
EXPECT_PRINTF("inf", fmt::format("%{}", *type), inf);
|
||||
char upper = std::toupper(*type);
|
||||
EXPECT_PRINTF("INF", fmt::format("%{}", upper), inf);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(PrintfTest, Char) {
|
||||
EXPECT_PRINTF("x", "%c", 'x');
|
||||
int max = std::numeric_limits<int>::max();
|
||||
EXPECT_PRINTF(fmt::format("{}", static_cast<char>(max)), "%c", max);
|
||||
//EXPECT_PRINTF("x", "%lc", L'x');
|
||||
// TODO: test wchar_t
|
||||
}
|
||||
|
||||
TEST(PrintfTest, String) {
|
||||
EXPECT_PRINTF("abc", "%s", "abc");
|
||||
const char *null_str = 0;
|
||||
EXPECT_PRINTF("(null)", "%s", null_str);
|
||||
EXPECT_PRINTF(" (null)", "%10s", null_str);
|
||||
// TODO: wide string
|
||||
}
|
||||
|
||||
TEST(PrintfTest, Pointer) {
|
||||
int n;
|
||||
void *p = &n;
|
||||
EXPECT_PRINTF(fmt::format("{}", p), "%p", p);
|
||||
p = 0;
|
||||
EXPECT_PRINTF("(nil)", "%p", p);
|
||||
EXPECT_PRINTF(" (nil)", "%10p", p);
|
||||
const char *s = "test";
|
||||
EXPECT_PRINTF(fmt::format("{:p}", s), "%p", s);
|
||||
const char *null_str = 0;
|
||||
EXPECT_PRINTF("(nil)", "%p", null_str);
|
||||
}
|
||||
|
||||
TEST(PrintfTest, Location) {
|
||||
// TODO: test %n
|
||||
}
|
||||
|
||||
enum E { A = 42 };
|
||||
|
||||
TEST(PrintfTest, Enum) {
|
||||
EXPECT_PRINTF("42", "%d", A);
|
||||
}
|
||||
|
||||
#if FMT_USE_FILE_DESCRIPTORS
|
||||
TEST(PrintfTest, Examples) {
|
||||
const char *weekday = "Thursday";
|
||||
const char *month = "August";
|
||||
int day = 21;
|
||||
EXPECT_WRITE(stdout, fmt::printf("%1$s, %3$d %2$s", weekday, month, day),
|
||||
"Thursday, 21 August");
|
||||
}
|
||||
|
||||
TEST(PrintfTest, PrintfError) {
|
||||
fmt::File read_end, write_end;
|
||||
fmt::File::pipe(read_end, write_end);
|
||||
int result = fmt::fprintf(read_end.fdopen("r").get(), "test");
|
||||
EXPECT_LT(result, 0);
|
||||
}
|
||||
#endif
|
||||
|
||||
TEST(PrintfTest, WideString) {
|
||||
EXPECT_EQ(L"abc", fmt::sprintf(L"%s", L"abc"));
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
Test version of FMT_ASSERT
|
||||
|
||||
Copyright (c) 2015, Victor Zverovich
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef FMT_TEST_ASSERT_H
|
||||
#define FMT_TEST_ASSERT_H
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
class AssertionFailure : public std::logic_error {
|
||||
public:
|
||||
explicit AssertionFailure(const char *message) : std::logic_error(message) {}
|
||||
};
|
||||
|
||||
#define FMT_ASSERT(condition, message) \
|
||||
if (!(condition)) throw AssertionFailure(message);
|
||||
|
||||
#include "gtest-extra.h"
|
||||
|
||||
// Expects an assertion failure.
|
||||
#define EXPECT_ASSERT(stmt, message) \
|
||||
EXPECT_THROW_MSG(stmt, AssertionFailure, message)
|
||||
|
||||
#endif // FMT_TEST_ASSERT_H
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
Test main function.
|
||||
|
||||
Copyright (c) 2012-2014, Victor Zverovich
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <cstdlib>
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
# include <windows.h>
|
||||
#endif
|
||||
|
||||
#ifdef _MSC_VER
|
||||
# include <crtdbg.h>
|
||||
#else
|
||||
# define _CrtSetReportFile(a, b)
|
||||
# define _CrtSetReportMode(a, b)
|
||||
#endif
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
#ifdef _WIN32
|
||||
// Don't display any error dialogs. This also suppresses message boxes
|
||||
// on assertion failures in MinGW where _set_error_mode/CrtSetReportMode
|
||||
// doesn't help.
|
||||
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
|
||||
SEM_NOOPENFILEERRORBOX);
|
||||
#endif
|
||||
// Disable message boxes on assertion failures.
|
||||
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
|
||||
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
|
||||
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
|
||||
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
|
||||
try {
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
} catch (...) {
|
||||
// Catch all exceptions to make Coverity happy.
|
||||
}
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
@@ -0,0 +1,958 @@
|
||||
/*
|
||||
Utility tests.
|
||||
|
||||
Copyright (c) 2012-2014, Victor Zverovich
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include "test-assert.h"
|
||||
|
||||
#include <cfloat>
|
||||
#include <climits>
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
#include <limits>
|
||||
|
||||
#if FMT_USE_TYPE_TRAITS
|
||||
# include <type_traits>
|
||||
#endif
|
||||
|
||||
#include "gmock/gmock.h"
|
||||
#include "gtest-extra.h"
|
||||
#include "mock-allocator.h"
|
||||
#include "util.h"
|
||||
|
||||
// Check if format.h compiles with windows.h included.
|
||||
#ifdef _WIN32
|
||||
# include <windows.h>
|
||||
#endif
|
||||
|
||||
#include "fmt/format.h"
|
||||
|
||||
#undef max
|
||||
|
||||
using fmt::StringRef;
|
||||
using fmt::internal::Arg;
|
||||
using fmt::Buffer;
|
||||
using fmt::internal::MemoryBuffer;
|
||||
|
||||
using testing::Return;
|
||||
using testing::StrictMock;
|
||||
|
||||
namespace {
|
||||
|
||||
struct Test {};
|
||||
|
||||
template <typename Char>
|
||||
void format(fmt::BasicFormatter<Char> &f, const Char *, Test) {
|
||||
f.writer() << "test";
|
||||
}
|
||||
|
||||
template <typename Char, typename T>
|
||||
Arg make_arg(const T &value) {
|
||||
typedef fmt::internal::MakeValue< fmt::BasicFormatter<Char> > MakeValue;
|
||||
Arg arg = MakeValue(value);
|
||||
arg.type = static_cast<Arg::Type>(MakeValue::type(value));
|
||||
return arg;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void CheckForwarding(
|
||||
MockAllocator<int> &alloc, AllocatorRef< MockAllocator<int> > &ref) {
|
||||
int mem;
|
||||
// Check if value_type is properly defined.
|
||||
AllocatorRef< MockAllocator<int> >::value_type *ptr = &mem;
|
||||
// Check forwarding.
|
||||
EXPECT_CALL(alloc, allocate(42)).WillOnce(Return(ptr));
|
||||
ref.allocate(42);
|
||||
EXPECT_CALL(alloc, deallocate(ptr, 42));
|
||||
ref.deallocate(ptr, 42);
|
||||
}
|
||||
|
||||
TEST(AllocatorTest, AllocatorRef) {
|
||||
StrictMock< MockAllocator<int> > alloc;
|
||||
typedef AllocatorRef< MockAllocator<int> > TestAllocatorRef;
|
||||
TestAllocatorRef ref(&alloc);
|
||||
// Check if AllocatorRef forwards to the underlying allocator.
|
||||
CheckForwarding(alloc, ref);
|
||||
TestAllocatorRef ref2(ref);
|
||||
CheckForwarding(alloc, ref2);
|
||||
TestAllocatorRef ref3;
|
||||
EXPECT_EQ(0, ref3.get());
|
||||
ref3 = ref;
|
||||
CheckForwarding(alloc, ref3);
|
||||
}
|
||||
|
||||
#if FMT_USE_TYPE_TRAITS
|
||||
TEST(BufferTest, Noncopyable) {
|
||||
EXPECT_FALSE(std::is_copy_constructible<Buffer<char> >::value);
|
||||
EXPECT_FALSE(std::is_copy_assignable<Buffer<char> >::value);
|
||||
}
|
||||
|
||||
TEST(BufferTest, Nonmoveable) {
|
||||
EXPECT_FALSE(std::is_move_constructible<Buffer<char> >::value);
|
||||
EXPECT_FALSE(std::is_move_assignable<Buffer<char> >::value);
|
||||
}
|
||||
#endif
|
||||
|
||||
// A test buffer with a dummy grow method.
|
||||
template <typename T>
|
||||
struct TestBuffer : Buffer<T> {
|
||||
void grow(std::size_t size) { this->capacity_ = size; }
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct MockBuffer : Buffer<T> {
|
||||
MOCK_METHOD1(do_grow, void (std::size_t size));
|
||||
|
||||
void grow(std::size_t size) {
|
||||
this->capacity_ = size;
|
||||
do_grow(size);
|
||||
}
|
||||
|
||||
MockBuffer() {}
|
||||
MockBuffer(T *ptr) : Buffer<T>(ptr) {}
|
||||
MockBuffer(T *ptr, std::size_t capacity) : Buffer<T>(ptr, capacity) {}
|
||||
};
|
||||
|
||||
TEST(BufferTest, Ctor) {
|
||||
{
|
||||
MockBuffer<int> buffer;
|
||||
EXPECT_EQ(0, &buffer[0]);
|
||||
EXPECT_EQ(0u, buffer.size());
|
||||
EXPECT_EQ(0u, buffer.capacity());
|
||||
}
|
||||
{
|
||||
int dummy;
|
||||
MockBuffer<int> buffer(&dummy);
|
||||
EXPECT_EQ(&dummy, &buffer[0]);
|
||||
EXPECT_EQ(0u, buffer.size());
|
||||
EXPECT_EQ(0u, buffer.capacity());
|
||||
}
|
||||
{
|
||||
int dummy;
|
||||
std::size_t capacity = std::numeric_limits<std::size_t>::max();
|
||||
MockBuffer<int> buffer(&dummy, capacity);
|
||||
EXPECT_EQ(&dummy, &buffer[0]);
|
||||
EXPECT_EQ(0u, buffer.size());
|
||||
EXPECT_EQ(capacity, buffer.capacity());
|
||||
}
|
||||
}
|
||||
|
||||
struct DyingBuffer : TestBuffer<int> {
|
||||
MOCK_METHOD0(die, void());
|
||||
~DyingBuffer() { die(); }
|
||||
};
|
||||
|
||||
TEST(BufferTest, VirtualDtor) {
|
||||
typedef StrictMock<DyingBuffer> StictMockBuffer;
|
||||
StictMockBuffer *mock_buffer = new StictMockBuffer();
|
||||
EXPECT_CALL(*mock_buffer, die());
|
||||
Buffer<int> *buffer = mock_buffer;
|
||||
delete buffer;
|
||||
}
|
||||
|
||||
TEST(BufferTest, Access) {
|
||||
char data[10];
|
||||
MockBuffer<char> buffer(data, sizeof(data));
|
||||
buffer[0] = 11;
|
||||
EXPECT_EQ(11, buffer[0]);
|
||||
buffer[3] = 42;
|
||||
EXPECT_EQ(42, *(&buffer[0] + 3));
|
||||
const Buffer<char> &const_buffer = buffer;
|
||||
EXPECT_EQ(42, const_buffer[3]);
|
||||
}
|
||||
|
||||
TEST(BufferTest, Resize) {
|
||||
char data[123];
|
||||
MockBuffer<char> buffer(data, sizeof(data));
|
||||
buffer[10] = 42;
|
||||
EXPECT_EQ(42, buffer[10]);
|
||||
buffer.resize(20);
|
||||
EXPECT_EQ(20u, buffer.size());
|
||||
EXPECT_EQ(123u, buffer.capacity());
|
||||
EXPECT_EQ(42, buffer[10]);
|
||||
buffer.resize(5);
|
||||
EXPECT_EQ(5u, buffer.size());
|
||||
EXPECT_EQ(123u, buffer.capacity());
|
||||
EXPECT_EQ(42, buffer[10]);
|
||||
// Check if resize calls grow.
|
||||
EXPECT_CALL(buffer, do_grow(124));
|
||||
buffer.resize(124);
|
||||
EXPECT_CALL(buffer, do_grow(200));
|
||||
buffer.resize(200);
|
||||
}
|
||||
|
||||
TEST(BufferTest, Clear) {
|
||||
TestBuffer<char> buffer;
|
||||
buffer.resize(20);
|
||||
buffer.clear();
|
||||
EXPECT_EQ(0u, buffer.size());
|
||||
EXPECT_EQ(20u, buffer.capacity());
|
||||
}
|
||||
|
||||
TEST(BufferTest, PushBack) {
|
||||
int data[15];
|
||||
MockBuffer<int> buffer(data, 10);
|
||||
buffer.push_back(11);
|
||||
EXPECT_EQ(11, buffer[0]);
|
||||
EXPECT_EQ(1u, buffer.size());
|
||||
buffer.resize(10);
|
||||
EXPECT_CALL(buffer, do_grow(11));
|
||||
buffer.push_back(22);
|
||||
EXPECT_EQ(22, buffer[10]);
|
||||
EXPECT_EQ(11u, buffer.size());
|
||||
}
|
||||
|
||||
TEST(BufferTest, Append) {
|
||||
char data[15];
|
||||
MockBuffer<char> buffer(data, 10);
|
||||
const char *test = "test";
|
||||
buffer.append(test, test + 5);
|
||||
EXPECT_STREQ(test, &buffer[0]);
|
||||
EXPECT_EQ(5u, buffer.size());
|
||||
buffer.resize(10);
|
||||
EXPECT_CALL(buffer, do_grow(12));
|
||||
buffer.append(test, test + 2);
|
||||
EXPECT_EQ('t', buffer[10]);
|
||||
EXPECT_EQ('e', buffer[11]);
|
||||
EXPECT_EQ(12u, buffer.size());
|
||||
}
|
||||
|
||||
TEST(BufferTest, AppendAllocatesEnoughStorage) {
|
||||
char data[19];
|
||||
MockBuffer<char> buffer(data, 10);
|
||||
const char *test = "abcdefgh";
|
||||
buffer.resize(10);
|
||||
EXPECT_CALL(buffer, do_grow(19));
|
||||
buffer.append(test, test + 9);
|
||||
}
|
||||
|
||||
TEST(MemoryBufferTest, Ctor) {
|
||||
MemoryBuffer<char, 123> buffer;
|
||||
EXPECT_EQ(0u, buffer.size());
|
||||
EXPECT_EQ(123u, buffer.capacity());
|
||||
}
|
||||
|
||||
#if FMT_USE_RVALUE_REFERENCES
|
||||
|
||||
typedef AllocatorRef< std::allocator<char> > TestAllocator;
|
||||
|
||||
void check_move_buffer(const char *str,
|
||||
MemoryBuffer<char, 5, TestAllocator> &buffer) {
|
||||
std::allocator<char> *alloc = buffer.get_allocator().get();
|
||||
MemoryBuffer<char, 5, TestAllocator> buffer2(std::move(buffer));
|
||||
// Move shouldn't destroy the inline content of the first buffer.
|
||||
EXPECT_EQ(str, std::string(&buffer[0], buffer.size()));
|
||||
EXPECT_EQ(str, std::string(&buffer2[0], buffer2.size()));
|
||||
EXPECT_EQ(5u, buffer2.capacity());
|
||||
// Move should transfer allocator.
|
||||
EXPECT_EQ(0, buffer.get_allocator().get());
|
||||
EXPECT_EQ(alloc, buffer2.get_allocator().get());
|
||||
}
|
||||
|
||||
TEST(MemoryBufferTest, MoveCtor) {
|
||||
std::allocator<char> alloc;
|
||||
MemoryBuffer<char, 5, TestAllocator> buffer((TestAllocator(&alloc)));
|
||||
const char test[] = "test";
|
||||
buffer.append(test, test + 4);
|
||||
check_move_buffer("test", buffer);
|
||||
// Adding one more character fills the inline buffer, but doesn't cause
|
||||
// dynamic allocation.
|
||||
buffer.push_back('a');
|
||||
check_move_buffer("testa", buffer);
|
||||
const char *inline_buffer_ptr = &buffer[0];
|
||||
// Adding one more character causes the content to move from the inline to
|
||||
// a dynamically allocated buffer.
|
||||
buffer.push_back('b');
|
||||
MemoryBuffer<char, 5, TestAllocator> buffer2(std::move(buffer));
|
||||
// Move should rip the guts of the first buffer.
|
||||
EXPECT_EQ(inline_buffer_ptr, &buffer[0]);
|
||||
EXPECT_EQ("testab", std::string(&buffer2[0], buffer2.size()));
|
||||
EXPECT_GT(buffer2.capacity(), 5u);
|
||||
}
|
||||
|
||||
void check_move_assign_buffer(const char *str, MemoryBuffer<char, 5> &buffer) {
|
||||
MemoryBuffer<char, 5> buffer2;
|
||||
buffer2 = std::move(buffer);
|
||||
// Move shouldn't destroy the inline content of the first buffer.
|
||||
EXPECT_EQ(str, std::string(&buffer[0], buffer.size()));
|
||||
EXPECT_EQ(str, std::string(&buffer2[0], buffer2.size()));
|
||||
EXPECT_EQ(5u, buffer2.capacity());
|
||||
}
|
||||
|
||||
TEST(MemoryBufferTest, MoveAssignment) {
|
||||
MemoryBuffer<char, 5> buffer;
|
||||
const char test[] = "test";
|
||||
buffer.append(test, test + 4);
|
||||
check_move_assign_buffer("test", buffer);
|
||||
// Adding one more character fills the inline buffer, but doesn't cause
|
||||
// dynamic allocation.
|
||||
buffer.push_back('a');
|
||||
check_move_assign_buffer("testa", buffer);
|
||||
const char *inline_buffer_ptr = &buffer[0];
|
||||
// Adding one more character causes the content to move from the inline to
|
||||
// a dynamically allocated buffer.
|
||||
buffer.push_back('b');
|
||||
MemoryBuffer<char, 5> buffer2;
|
||||
buffer2 = std::move(buffer);
|
||||
// Move should rip the guts of the first buffer.
|
||||
EXPECT_EQ(inline_buffer_ptr, &buffer[0]);
|
||||
EXPECT_EQ("testab", std::string(&buffer2[0], buffer2.size()));
|
||||
EXPECT_GT(buffer2.capacity(), 5u);
|
||||
}
|
||||
|
||||
#endif // FMT_USE_RVALUE_REFERENCES
|
||||
|
||||
TEST(MemoryBufferTest, Grow) {
|
||||
typedef AllocatorRef< MockAllocator<int> > Allocator;
|
||||
typedef MemoryBuffer<int, 10, Allocator> Base;
|
||||
MockAllocator<int> alloc;
|
||||
struct TestMemoryBuffer : Base {
|
||||
TestMemoryBuffer(Allocator alloc) : Base(alloc) {}
|
||||
void grow(std::size_t size) { Base::grow(size); }
|
||||
} buffer((Allocator(&alloc)));
|
||||
buffer.resize(7);
|
||||
using fmt::internal::to_unsigned;
|
||||
for (int i = 0; i < 7; ++i)
|
||||
buffer[to_unsigned(i)] = i * i;
|
||||
EXPECT_EQ(10u, buffer.capacity());
|
||||
int mem[20];
|
||||
mem[7] = 0xdead;
|
||||
EXPECT_CALL(alloc, allocate(20)).WillOnce(Return(mem));
|
||||
buffer.grow(20);
|
||||
EXPECT_EQ(20u, buffer.capacity());
|
||||
// Check if size elements have been copied
|
||||
for (int i = 0; i < 7; ++i)
|
||||
EXPECT_EQ(i * i, buffer[to_unsigned(i)]);
|
||||
// and no more than that.
|
||||
EXPECT_EQ(0xdead, buffer[7]);
|
||||
EXPECT_CALL(alloc, deallocate(mem, 20));
|
||||
}
|
||||
|
||||
TEST(MemoryBufferTest, Allocator) {
|
||||
typedef AllocatorRef< MockAllocator<char> > TestAllocator;
|
||||
MemoryBuffer<char, 10, TestAllocator> buffer;
|
||||
EXPECT_EQ(0, buffer.get_allocator().get());
|
||||
StrictMock< MockAllocator<char> > alloc;
|
||||
char mem;
|
||||
{
|
||||
MemoryBuffer<char, 10, TestAllocator> buffer2((TestAllocator(&alloc)));
|
||||
EXPECT_EQ(&alloc, buffer2.get_allocator().get());
|
||||
std::size_t size = 2 * fmt::internal::INLINE_BUFFER_SIZE;
|
||||
EXPECT_CALL(alloc, allocate(size)).WillOnce(Return(&mem));
|
||||
buffer2.reserve(size);
|
||||
EXPECT_CALL(alloc, deallocate(&mem, size));
|
||||
}
|
||||
}
|
||||
|
||||
TEST(MemoryBufferTest, ExceptionInDeallocate) {
|
||||
typedef AllocatorRef< MockAllocator<char> > TestAllocator;
|
||||
StrictMock< MockAllocator<char> > alloc;
|
||||
MemoryBuffer<char, 10, TestAllocator> buffer((TestAllocator(&alloc)));
|
||||
std::size_t size = 2 * fmt::internal::INLINE_BUFFER_SIZE;
|
||||
std::vector<char> mem(size);
|
||||
{
|
||||
EXPECT_CALL(alloc, allocate(size)).WillOnce(Return(&mem[0]));
|
||||
buffer.resize(size);
|
||||
std::fill(&buffer[0], &buffer[0] + size, 'x');
|
||||
}
|
||||
std::vector<char> mem2(2 * size);
|
||||
{
|
||||
EXPECT_CALL(alloc, allocate(2 * size)).WillOnce(Return(&mem2[0]));
|
||||
std::exception e;
|
||||
EXPECT_CALL(alloc, deallocate(&mem[0], size)).WillOnce(testing::Throw(e));
|
||||
EXPECT_THROW(buffer.reserve(2 * size), std::exception);
|
||||
EXPECT_EQ(&mem2[0], &buffer[0]);
|
||||
// Check that the data has been copied.
|
||||
for (std::size_t i = 0; i < size; ++i)
|
||||
EXPECT_EQ('x', buffer[i]);
|
||||
}
|
||||
EXPECT_CALL(alloc, deallocate(&mem2[0], 2 * size));
|
||||
}
|
||||
|
||||
TEST(UtilTest, Increment) {
|
||||
char s[10] = "123";
|
||||
increment(s);
|
||||
EXPECT_STREQ("124", s);
|
||||
s[2] = '8';
|
||||
increment(s);
|
||||
EXPECT_STREQ("129", s);
|
||||
increment(s);
|
||||
EXPECT_STREQ("130", s);
|
||||
s[1] = s[2] = '9';
|
||||
increment(s);
|
||||
EXPECT_STREQ("200", s);
|
||||
}
|
||||
|
||||
template <Arg::Type>
|
||||
struct ArgInfo;
|
||||
|
||||
#define ARG_INFO(type_code, Type, field) \
|
||||
template <> \
|
||||
struct ArgInfo<Arg::type_code> { \
|
||||
static Type get(const Arg &arg) { return arg.field; } \
|
||||
}
|
||||
|
||||
ARG_INFO(INT, int, int_value);
|
||||
ARG_INFO(UINT, unsigned, uint_value);
|
||||
ARG_INFO(LONG_LONG, fmt::LongLong, long_long_value);
|
||||
ARG_INFO(ULONG_LONG, fmt::ULongLong, ulong_long_value);
|
||||
ARG_INFO(BOOL, int, int_value);
|
||||
ARG_INFO(CHAR, int, int_value);
|
||||
ARG_INFO(DOUBLE, double, double_value);
|
||||
ARG_INFO(LONG_DOUBLE, long double, long_double_value);
|
||||
ARG_INFO(CSTRING, const char *, string.value);
|
||||
ARG_INFO(STRING, const char *, string.value);
|
||||
ARG_INFO(WSTRING, const wchar_t *, wstring.value);
|
||||
ARG_INFO(POINTER, const void *, pointer);
|
||||
ARG_INFO(CUSTOM, Arg::CustomValue, custom);
|
||||
|
||||
#define CHECK_ARG_INFO(Type, field, value) { \
|
||||
Arg arg = Arg(); \
|
||||
arg.field = value; \
|
||||
EXPECT_EQ(value, ArgInfo<Arg::Type>::get(arg)); \
|
||||
}
|
||||
|
||||
TEST(ArgTest, ArgInfo) {
|
||||
CHECK_ARG_INFO(INT, int_value, 42);
|
||||
CHECK_ARG_INFO(UINT, uint_value, 42u);
|
||||
CHECK_ARG_INFO(LONG_LONG, long_long_value, 42);
|
||||
CHECK_ARG_INFO(ULONG_LONG, ulong_long_value, 42u);
|
||||
CHECK_ARG_INFO(DOUBLE, double_value, 4.2);
|
||||
CHECK_ARG_INFO(LONG_DOUBLE, long_double_value, 4.2);
|
||||
CHECK_ARG_INFO(CHAR, int_value, 'x');
|
||||
const char STR[] = "abc";
|
||||
CHECK_ARG_INFO(CSTRING, string.value, STR);
|
||||
const wchar_t WSTR[] = L"abc";
|
||||
CHECK_ARG_INFO(WSTRING, wstring.value, WSTR);
|
||||
int p = 0;
|
||||
CHECK_ARG_INFO(POINTER, pointer, &p);
|
||||
Arg arg = Arg();
|
||||
arg.custom.value = &p;
|
||||
EXPECT_EQ(&p, ArgInfo<Arg::CUSTOM>::get(arg).value);
|
||||
}
|
||||
|
||||
#define EXPECT_ARG_(Char, type_code, MakeArgType, ExpectedType, value) { \
|
||||
MakeArgType input = static_cast<MakeArgType>(value); \
|
||||
Arg arg = make_arg<Char>(input); \
|
||||
EXPECT_EQ(Arg::type_code, arg.type); \
|
||||
ExpectedType expected_value = static_cast<ExpectedType>(value); \
|
||||
EXPECT_EQ(expected_value, ArgInfo<Arg::type_code>::get(arg)); \
|
||||
}
|
||||
|
||||
#define EXPECT_ARG(type_code, Type, value) \
|
||||
EXPECT_ARG_(char, type_code, Type, Type, value)
|
||||
|
||||
#define EXPECT_ARGW(type_code, Type, value) \
|
||||
EXPECT_ARG_(wchar_t, type_code, Type, Type, value)
|
||||
|
||||
TEST(ArgTest, MakeArg) {
|
||||
// Test bool.
|
||||
EXPECT_ARG_(char, BOOL, bool, int, true);
|
||||
EXPECT_ARG_(wchar_t, BOOL, bool, int, true);
|
||||
|
||||
// Test char.
|
||||
EXPECT_ARG(CHAR, char, 'a');
|
||||
EXPECT_ARG(CHAR, char, CHAR_MIN);
|
||||
EXPECT_ARG(CHAR, char, CHAR_MAX);
|
||||
|
||||
// Test wchar_t.
|
||||
EXPECT_ARGW(CHAR, wchar_t, L'a');
|
||||
EXPECT_ARGW(CHAR, wchar_t, WCHAR_MIN);
|
||||
EXPECT_ARGW(CHAR, wchar_t, WCHAR_MAX);
|
||||
|
||||
// Test signed/unsigned char.
|
||||
EXPECT_ARG(INT, signed char, 42);
|
||||
EXPECT_ARG(INT, signed char, SCHAR_MIN);
|
||||
EXPECT_ARG(INT, signed char, SCHAR_MAX);
|
||||
EXPECT_ARG(UINT, unsigned char, 42);
|
||||
EXPECT_ARG(UINT, unsigned char, UCHAR_MAX );
|
||||
|
||||
// Test short.
|
||||
EXPECT_ARG(INT, short, 42);
|
||||
EXPECT_ARG(INT, short, SHRT_MIN);
|
||||
EXPECT_ARG(INT, short, SHRT_MAX);
|
||||
EXPECT_ARG(UINT, unsigned short, 42);
|
||||
EXPECT_ARG(UINT, unsigned short, USHRT_MAX);
|
||||
|
||||
// Test int.
|
||||
EXPECT_ARG(INT, int, 42);
|
||||
EXPECT_ARG(INT, int, INT_MIN);
|
||||
EXPECT_ARG(INT, int, INT_MAX);
|
||||
EXPECT_ARG(UINT, unsigned, 42);
|
||||
EXPECT_ARG(UINT, unsigned, UINT_MAX);
|
||||
|
||||
// Test long.
|
||||
#if LONG_MAX == INT_MAX
|
||||
# define LONG INT
|
||||
# define ULONG UINT
|
||||
# define long_value int_value
|
||||
# define ulong_value uint_value
|
||||
#else
|
||||
# define LONG LONG_LONG
|
||||
# define ULONG ULONG_LONG
|
||||
# define long_value long_long_value
|
||||
# define ulong_value ulong_long_value
|
||||
#endif
|
||||
EXPECT_ARG(LONG, long, 42);
|
||||
EXPECT_ARG(LONG, long, LONG_MIN);
|
||||
EXPECT_ARG(LONG, long, LONG_MAX);
|
||||
EXPECT_ARG(ULONG, unsigned long, 42);
|
||||
EXPECT_ARG(ULONG, unsigned long, ULONG_MAX);
|
||||
|
||||
// Test long long.
|
||||
EXPECT_ARG(LONG_LONG, fmt::LongLong, 42);
|
||||
EXPECT_ARG(LONG_LONG, fmt::LongLong, LLONG_MIN);
|
||||
EXPECT_ARG(LONG_LONG, fmt::LongLong, LLONG_MAX);
|
||||
EXPECT_ARG(ULONG_LONG, fmt::ULongLong, 42);
|
||||
EXPECT_ARG(ULONG_LONG, fmt::ULongLong, ULLONG_MAX);
|
||||
|
||||
// Test float.
|
||||
EXPECT_ARG(DOUBLE, float, 4.2);
|
||||
EXPECT_ARG(DOUBLE, float, FLT_MIN);
|
||||
EXPECT_ARG(DOUBLE, float, FLT_MAX);
|
||||
|
||||
// Test double.
|
||||
EXPECT_ARG(DOUBLE, double, 4.2);
|
||||
EXPECT_ARG(DOUBLE, double, DBL_MIN);
|
||||
EXPECT_ARG(DOUBLE, double, DBL_MAX);
|
||||
|
||||
// Test long double.
|
||||
EXPECT_ARG(LONG_DOUBLE, long double, 4.2);
|
||||
EXPECT_ARG(LONG_DOUBLE, long double, LDBL_MIN);
|
||||
EXPECT_ARG(LONG_DOUBLE, long double, LDBL_MAX);
|
||||
|
||||
// Test string.
|
||||
char STR[] = "test";
|
||||
EXPECT_ARG(CSTRING, char*, STR);
|
||||
EXPECT_ARG(CSTRING, const char*, STR);
|
||||
EXPECT_ARG(STRING, std::string, STR);
|
||||
EXPECT_ARG(STRING, fmt::StringRef, STR);
|
||||
|
||||
// Test wide string.
|
||||
wchar_t WSTR[] = L"test";
|
||||
EXPECT_ARGW(WSTRING, wchar_t*, WSTR);
|
||||
EXPECT_ARGW(WSTRING, const wchar_t*, WSTR);
|
||||
EXPECT_ARGW(WSTRING, std::wstring, WSTR);
|
||||
EXPECT_ARGW(WSTRING, fmt::WStringRef, WSTR);
|
||||
|
||||
int n = 42;
|
||||
EXPECT_ARG(POINTER, void*, &n);
|
||||
EXPECT_ARG(POINTER, const void*, &n);
|
||||
|
||||
::Test t;
|
||||
Arg arg = make_arg<char>(t);
|
||||
EXPECT_EQ(fmt::internal::Arg::CUSTOM, arg.type);
|
||||
EXPECT_EQ(&t, arg.custom.value);
|
||||
fmt::MemoryWriter w;
|
||||
fmt::BasicFormatter<char> formatter(fmt::ArgList(), w);
|
||||
const char *s = "}";
|
||||
arg.custom.format(&formatter, &t, &s);
|
||||
EXPECT_EQ("test", w.str());
|
||||
}
|
||||
|
||||
TEST(UtilTest, ArgList) {
|
||||
fmt::ArgList args;
|
||||
EXPECT_EQ(Arg::NONE, args[1].type);
|
||||
}
|
||||
|
||||
struct CustomFormatter {
|
||||
typedef char Char;
|
||||
};
|
||||
|
||||
void format(CustomFormatter &, const char *&s, const Test &) {
|
||||
s = "custom_format";
|
||||
}
|
||||
|
||||
TEST(UtilTest, MakeValueWithCustomFormatter) {
|
||||
::Test t;
|
||||
Arg arg = fmt::internal::MakeValue<CustomFormatter>(t);
|
||||
CustomFormatter formatter;
|
||||
const char *s = "";
|
||||
arg.custom.format(&formatter, &t, &s);
|
||||
EXPECT_STREQ("custom_format", s);
|
||||
}
|
||||
|
||||
struct Result {
|
||||
Arg arg;
|
||||
|
||||
Result() : arg(make_arg<char>(0xdeadbeef)) {}
|
||||
|
||||
template <typename T>
|
||||
Result(const T& value) : arg(make_arg<char>(value)) {}
|
||||
Result(const wchar_t *s) : arg(make_arg<wchar_t>(s)) {}
|
||||
};
|
||||
|
||||
struct TestVisitor : fmt::ArgVisitor<TestVisitor, Result> {
|
||||
Result visit_int(int value) { return value; }
|
||||
Result visit_uint(unsigned value) { return value; }
|
||||
Result visit_long_long(fmt::LongLong value) { return value; }
|
||||
Result visit_ulong_long(fmt::ULongLong value) { return value; }
|
||||
Result visit_double(double value) { return value; }
|
||||
Result visit_long_double(long double value) { return value; }
|
||||
Result visit_char(int value) { return static_cast<char>(value); }
|
||||
Result visit_cstring(const char *s) { return s; }
|
||||
Result visit_string(fmt::internal::Arg::StringValue<char> s) {
|
||||
return s.value;
|
||||
}
|
||||
Result visit_wstring(fmt::internal::Arg::StringValue<wchar_t> s) {
|
||||
return s.value;
|
||||
}
|
||||
Result visit_pointer(const void *p) { return p; }
|
||||
Result visit_custom(fmt::internal::Arg::CustomValue c) {
|
||||
return *static_cast<const ::Test*>(c.value);
|
||||
}
|
||||
};
|
||||
|
||||
#define EXPECT_RESULT_(Char, type_code, value) { \
|
||||
Arg arg = make_arg<Char>(value); \
|
||||
Result result = TestVisitor().visit(arg); \
|
||||
EXPECT_EQ(Arg::type_code, result.arg.type); \
|
||||
EXPECT_EQ(value, ArgInfo<Arg::type_code>::get(result.arg)); \
|
||||
}
|
||||
|
||||
#define EXPECT_RESULT(type_code, value) \
|
||||
EXPECT_RESULT_(char, type_code, value)
|
||||
#define EXPECT_RESULTW(type_code, value) \
|
||||
EXPECT_RESULT_(wchar_t, type_code, value)
|
||||
|
||||
TEST(ArgVisitorTest, VisitAll) {
|
||||
EXPECT_RESULT(INT, 42);
|
||||
EXPECT_RESULT(UINT, 42u);
|
||||
EXPECT_RESULT(LONG_LONG, 42ll);
|
||||
EXPECT_RESULT(ULONG_LONG, 42ull);
|
||||
EXPECT_RESULT(DOUBLE, 4.2);
|
||||
EXPECT_RESULT(LONG_DOUBLE, 4.2l);
|
||||
EXPECT_RESULT(CHAR, 'x');
|
||||
const char STR[] = "abc";
|
||||
EXPECT_RESULT(CSTRING, STR);
|
||||
const wchar_t WSTR[] = L"abc";
|
||||
EXPECT_RESULTW(WSTRING, WSTR);
|
||||
const void *p = STR;
|
||||
EXPECT_RESULT(POINTER, p);
|
||||
::Test t;
|
||||
Result result = TestVisitor().visit(make_arg<char>(t));
|
||||
EXPECT_EQ(Arg::CUSTOM, result.arg.type);
|
||||
EXPECT_EQ(&t, result.arg.custom.value);
|
||||
}
|
||||
|
||||
struct TestAnyVisitor : fmt::ArgVisitor<TestAnyVisitor, Result> {
|
||||
template <typename T>
|
||||
Result visit_any_int(T value) { return value; }
|
||||
|
||||
template <typename T>
|
||||
Result visit_any_double(T value) { return value; }
|
||||
};
|
||||
|
||||
#undef EXPECT_RESULT
|
||||
#define EXPECT_RESULT(type_code, value) { \
|
||||
Result result = TestAnyVisitor().visit(make_arg<char>(value)); \
|
||||
EXPECT_EQ(Arg::type_code, result.arg.type); \
|
||||
EXPECT_EQ(value, ArgInfo<Arg::type_code>::get(result.arg)); \
|
||||
}
|
||||
|
||||
TEST(ArgVisitorTest, VisitAny) {
|
||||
EXPECT_RESULT(INT, 42);
|
||||
EXPECT_RESULT(UINT, 42u);
|
||||
EXPECT_RESULT(LONG_LONG, 42ll);
|
||||
EXPECT_RESULT(ULONG_LONG, 42ull);
|
||||
EXPECT_RESULT(DOUBLE, 4.2);
|
||||
EXPECT_RESULT(LONG_DOUBLE, 4.2l);
|
||||
}
|
||||
|
||||
struct TestUnhandledVisitor :
|
||||
fmt::ArgVisitor<TestUnhandledVisitor, const char *> {
|
||||
const char *visit_unhandled_arg() { return "test"; }
|
||||
};
|
||||
|
||||
#define EXPECT_UNHANDLED(value) \
|
||||
EXPECT_STREQ("test", TestUnhandledVisitor().visit(make_arg<wchar_t>(value)));
|
||||
|
||||
TEST(ArgVisitorTest, VisitUnhandledArg) {
|
||||
EXPECT_UNHANDLED(42);
|
||||
EXPECT_UNHANDLED(42u);
|
||||
EXPECT_UNHANDLED(42ll);
|
||||
EXPECT_UNHANDLED(42ull);
|
||||
EXPECT_UNHANDLED(4.2);
|
||||
EXPECT_UNHANDLED(4.2l);
|
||||
EXPECT_UNHANDLED('x');
|
||||
const char STR[] = "abc";
|
||||
EXPECT_UNHANDLED(STR);
|
||||
const wchar_t WSTR[] = L"abc";
|
||||
EXPECT_UNHANDLED(WSTR);
|
||||
const void *p = STR;
|
||||
EXPECT_UNHANDLED(p);
|
||||
EXPECT_UNHANDLED(::Test());
|
||||
}
|
||||
|
||||
TEST(ArgVisitorTest, VisitInvalidArg) {
|
||||
Arg arg = Arg();
|
||||
arg.type = static_cast<Arg::Type>(Arg::CUSTOM + 1);
|
||||
EXPECT_ASSERT(TestVisitor().visit(arg), "invalid argument type");
|
||||
}
|
||||
|
||||
// Tests fmt::internal::count_digits for integer type Int.
|
||||
template <typename Int>
|
||||
void test_count_digits() {
|
||||
for (Int i = 0; i < 10; ++i)
|
||||
EXPECT_EQ(1u, fmt::internal::count_digits(i));
|
||||
for (Int i = 1, n = 1,
|
||||
end = std::numeric_limits<Int>::max() / 10; n <= end; ++i) {
|
||||
n *= 10;
|
||||
EXPECT_EQ(i, fmt::internal::count_digits(n - 1));
|
||||
EXPECT_EQ(i + 1, fmt::internal::count_digits(n));
|
||||
}
|
||||
}
|
||||
|
||||
TEST(UtilTest, StringRef) {
|
||||
// Test that StringRef::size() returns string length, not buffer size.
|
||||
char str[100] = "some string";
|
||||
EXPECT_EQ(std::strlen(str), StringRef(str).size());
|
||||
EXPECT_LT(std::strlen(str), sizeof(str));
|
||||
}
|
||||
|
||||
// Check StringRef's comparison operator.
|
||||
template <template <typename> class Op>
|
||||
void CheckOp() {
|
||||
const char *inputs[] = {"foo", "fop", "fo"};
|
||||
std::size_t num_inputs = sizeof(inputs) / sizeof(*inputs);
|
||||
for (std::size_t i = 0; i < num_inputs; ++i) {
|
||||
for (std::size_t j = 0; j < num_inputs; ++j) {
|
||||
StringRef lhs(inputs[i]), rhs(inputs[j]);
|
||||
EXPECT_EQ(Op<int>()(lhs.compare(rhs), 0), Op<StringRef>()(lhs, rhs));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(UtilTest, StringRefCompare) {
|
||||
EXPECT_EQ(0, StringRef("foo").compare(StringRef("foo")));
|
||||
EXPECT_GT(StringRef("fop").compare(StringRef("foo")), 0);
|
||||
EXPECT_LT(StringRef("foo").compare(StringRef("fop")), 0);
|
||||
EXPECT_GT(StringRef("foo").compare(StringRef("fo")), 0);
|
||||
EXPECT_LT(StringRef("fo").compare(StringRef("foo")), 0);
|
||||
CheckOp<std::equal_to>();
|
||||
CheckOp<std::not_equal_to>();
|
||||
CheckOp<std::less>();
|
||||
CheckOp<std::less_equal>();
|
||||
CheckOp<std::greater>();
|
||||
CheckOp<std::greater_equal>();
|
||||
}
|
||||
|
||||
TEST(UtilTest, CountDigits) {
|
||||
test_count_digits<uint32_t>();
|
||||
test_count_digits<uint64_t>();
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
TEST(UtilTest, UTF16ToUTF8) {
|
||||
std::string s = "ёжик";
|
||||
fmt::internal::UTF16ToUTF8 u(L"\x0451\x0436\x0438\x043A");
|
||||
EXPECT_EQ(s, u.str());
|
||||
EXPECT_EQ(s.size(), u.size());
|
||||
}
|
||||
|
||||
TEST(UtilTest, UTF8ToUTF16) {
|
||||
std::string s = "лошадка";
|
||||
fmt::internal::UTF8ToUTF16 u(s.c_str());
|
||||
EXPECT_EQ(L"\x043B\x043E\x0448\x0430\x0434\x043A\x0430", u.str());
|
||||
EXPECT_EQ(7, u.size());
|
||||
}
|
||||
|
||||
template <typename Converter, typename Char>
|
||||
void check_utf_conversion_error(
|
||||
const char *message,
|
||||
fmt::BasicStringRef<Char> str = fmt::BasicStringRef<Char>(0, 0)) {
|
||||
fmt::MemoryWriter out;
|
||||
fmt::internal::format_windows_error(out, ERROR_INVALID_PARAMETER, message);
|
||||
fmt::SystemError error(0, "");
|
||||
try {
|
||||
(Converter)(str);
|
||||
} catch (const fmt::SystemError &e) {
|
||||
error = e;
|
||||
}
|
||||
EXPECT_EQ(ERROR_INVALID_PARAMETER, error.error_code());
|
||||
EXPECT_EQ(out.str(), error.what());
|
||||
}
|
||||
|
||||
TEST(UtilTest, UTF16ToUTF8Error) {
|
||||
check_utf_conversion_error<fmt::internal::UTF16ToUTF8, wchar_t>(
|
||||
"cannot convert string from UTF-16 to UTF-8");
|
||||
}
|
||||
|
||||
TEST(UtilTest, UTF8ToUTF16Error) {
|
||||
const char *message = "cannot convert string from UTF-8 to UTF-16";
|
||||
check_utf_conversion_error<fmt::internal::UTF8ToUTF16, char>(message);
|
||||
check_utf_conversion_error<fmt::internal::UTF8ToUTF16, char>(
|
||||
message, fmt::StringRef("foo", INT_MAX + 1u));
|
||||
}
|
||||
|
||||
TEST(UtilTest, UTF16ToUTF8Convert) {
|
||||
fmt::internal::UTF16ToUTF8 u;
|
||||
EXPECT_EQ(ERROR_INVALID_PARAMETER, u.convert(fmt::WStringRef(0, 0)));
|
||||
EXPECT_EQ(ERROR_INVALID_PARAMETER,
|
||||
u.convert(fmt::WStringRef(L"foo", INT_MAX + 1u)));
|
||||
}
|
||||
#endif // _WIN32
|
||||
|
||||
typedef void (*FormatErrorMessage)(
|
||||
fmt::Writer &out, int error_code, StringRef message);
|
||||
|
||||
template <typename Error>
|
||||
void check_throw_error(int error_code, FormatErrorMessage format) {
|
||||
fmt::SystemError error(0, "");
|
||||
try {
|
||||
throw Error(error_code, "test {}", "error");
|
||||
} catch (const fmt::SystemError &e) {
|
||||
error = e;
|
||||
}
|
||||
fmt::MemoryWriter message;
|
||||
format(message, error_code, "test error");
|
||||
EXPECT_EQ(message.str(), error.what());
|
||||
EXPECT_EQ(error_code, error.error_code());
|
||||
}
|
||||
|
||||
TEST(UtilTest, FormatSystemError) {
|
||||
fmt::MemoryWriter message;
|
||||
fmt::internal::format_system_error(message, EDOM, "test");
|
||||
EXPECT_EQ(fmt::format("test: {}", get_system_error(EDOM)), message.str());
|
||||
message.clear();
|
||||
fmt::internal::format_system_error(
|
||||
message, EDOM, fmt::StringRef(0, std::numeric_limits<size_t>::max()));
|
||||
EXPECT_EQ(fmt::format("error {}", EDOM), message.str());
|
||||
}
|
||||
|
||||
TEST(UtilTest, SystemError) {
|
||||
fmt::SystemError e(EDOM, "test");
|
||||
EXPECT_EQ(fmt::format("test: {}", get_system_error(EDOM)), e.what());
|
||||
EXPECT_EQ(EDOM, e.error_code());
|
||||
check_throw_error<fmt::SystemError>(EDOM, fmt::internal::format_system_error);
|
||||
}
|
||||
|
||||
TEST(UtilTest, ReportSystemError) {
|
||||
fmt::MemoryWriter out;
|
||||
fmt::internal::format_system_error(out, EDOM, "test error");
|
||||
out << '\n';
|
||||
EXPECT_WRITE(stderr, fmt::report_system_error(EDOM, "test error"), out.str());
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
|
||||
TEST(UtilTest, FormatWindowsError) {
|
||||
LPWSTR message = 0;
|
||||
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
|
||||
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0,
|
||||
ERROR_FILE_EXISTS, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
|
||||
reinterpret_cast<LPWSTR>(&message), 0, 0);
|
||||
fmt::internal::UTF16ToUTF8 utf8_message(message);
|
||||
LocalFree(message);
|
||||
fmt::MemoryWriter actual_message;
|
||||
fmt::internal::format_windows_error(
|
||||
actual_message, ERROR_FILE_EXISTS, "test");
|
||||
EXPECT_EQ(fmt::format("test: {}", utf8_message.str()),
|
||||
actual_message.str());
|
||||
actual_message.clear();
|
||||
fmt::internal::format_windows_error(
|
||||
actual_message, ERROR_FILE_EXISTS,
|
||||
fmt::StringRef(0, std::numeric_limits<size_t>::max()));
|
||||
EXPECT_EQ(fmt::format("error {}", ERROR_FILE_EXISTS), actual_message.str());
|
||||
}
|
||||
|
||||
TEST(UtilTest, FormatLongWindowsError) {
|
||||
LPWSTR message = 0;
|
||||
// this error code is not available on all Windows platforms and
|
||||
// Windows SDKs, so do not fail the test if the error string cannot
|
||||
// be retrieved.
|
||||
const int provisioning_not_allowed = 0x80284013L /*TBS_E_PROVISIONING_NOT_ALLOWED*/;
|
||||
if (FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
|
||||
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0,
|
||||
provisioning_not_allowed, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
|
||||
reinterpret_cast<LPWSTR>(&message), 0, 0) == 0) {
|
||||
return;
|
||||
}
|
||||
fmt::internal::UTF16ToUTF8 utf8_message(message);
|
||||
LocalFree(message);
|
||||
fmt::MemoryWriter actual_message;
|
||||
fmt::internal::format_windows_error(
|
||||
actual_message, provisioning_not_allowed, "test");
|
||||
EXPECT_EQ(fmt::format("test: {}", utf8_message.str()),
|
||||
actual_message.str());
|
||||
}
|
||||
|
||||
TEST(UtilTest, WindowsError) {
|
||||
check_throw_error<fmt::WindowsError>(
|
||||
ERROR_FILE_EXISTS, fmt::internal::format_windows_error);
|
||||
}
|
||||
|
||||
TEST(UtilTest, ReportWindowsError) {
|
||||
fmt::MemoryWriter out;
|
||||
fmt::internal::format_windows_error(out, ERROR_FILE_EXISTS, "test error");
|
||||
out << '\n';
|
||||
EXPECT_WRITE(stderr,
|
||||
fmt::report_windows_error(ERROR_FILE_EXISTS, "test error"), out.str());
|
||||
}
|
||||
|
||||
#endif // _WIN32
|
||||
|
||||
enum TestEnum2 {};
|
||||
|
||||
TEST(UtilTest, ConvertToInt) {
|
||||
EXPECT_TRUE(fmt::internal::ConvertToInt<char>::enable_conversion);
|
||||
EXPECT_FALSE(fmt::internal::ConvertToInt<const char *>::enable_conversion);
|
||||
EXPECT_TRUE(fmt::internal::ConvertToInt<TestEnum2>::value);
|
||||
}
|
||||
|
||||
#if FMT_USE_ENUM_BASE
|
||||
enum TestEnum : char {TestValue};
|
||||
TEST(UtilTest, IsEnumConvertibleToInt) {
|
||||
EXPECT_TRUE(fmt::internal::ConvertToInt<TestEnum>::enable_conversion);
|
||||
}
|
||||
#endif
|
||||
|
||||
template <typename T>
|
||||
bool check_enable_if(
|
||||
typename fmt::internal::EnableIf<sizeof(T) == sizeof(int), T>::type *) {
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool check_enable_if(
|
||||
typename fmt::internal::EnableIf<sizeof(T) != sizeof(int), T>::type *) {
|
||||
return false;
|
||||
}
|
||||
|
||||
TEST(UtilTest, EnableIf) {
|
||||
int i = 0;
|
||||
EXPECT_TRUE(check_enable_if<int>(&i));
|
||||
char c = 0;
|
||||
EXPECT_FALSE(check_enable_if<char>(&c));
|
||||
}
|
||||
|
||||
TEST(UtilTest, Conditional) {
|
||||
int i = 0;
|
||||
fmt::internal::Conditional<true, int, char>::type *pi = &i;
|
||||
(void)pi;
|
||||
char c = 0;
|
||||
fmt::internal::Conditional<false, int, char>::type *pc = &c;
|
||||
(void)pc;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
Test utilities.
|
||||
|
||||
Copyright (c) 2012-2014, Victor Zverovich
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include "util.h"
|
||||
#include <cstring>
|
||||
|
||||
void increment(char *s) {
|
||||
for (int i = static_cast<int>(std::strlen(s)) - 1; i >= 0; --i) {
|
||||
if (s[i] != '9') {
|
||||
++s[i];
|
||||
break;
|
||||
}
|
||||
s[i] = '0';
|
||||
}
|
||||
}
|
||||
|
||||
std::string get_system_error(int error_code) {
|
||||
#if defined(__MINGW32__) || !defined(_WIN32)
|
||||
return strerror(error_code);
|
||||
#else
|
||||
enum { BUFFER_SIZE = 200 };
|
||||
char buffer[BUFFER_SIZE];
|
||||
if (strerror_s(buffer, BUFFER_SIZE, error_code))
|
||||
throw std::exception("strerror_s failed");
|
||||
return buffer;
|
||||
#endif
|
||||
}
|
||||
|
||||
const char *const FILE_CONTENT = "Don't panic!";
|
||||
|
||||
fmt::BufferedFile open_buffered_file(FILE **fp) {
|
||||
fmt::File read_end, write_end;
|
||||
fmt::File::pipe(read_end, write_end);
|
||||
write_end.write(FILE_CONTENT, std::strlen(FILE_CONTENT));
|
||||
write_end.close();
|
||||
fmt::BufferedFile f = read_end.fdopen("r");
|
||||
if (fp)
|
||||
*fp = f.get();
|
||||
return f;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
/*
|
||||
Test utilities.
|
||||
|
||||
Copyright (c) 2012-2014, Victor Zverovich
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
|
||||
#include "fmt/posix.h"
|
||||
|
||||
enum {BUFFER_SIZE = 256};
|
||||
|
||||
#ifdef _MSC_VER
|
||||
# define FMT_VSNPRINTF vsprintf_s
|
||||
#else
|
||||
# define FMT_VSNPRINTF vsnprintf
|
||||
#endif
|
||||
|
||||
template <std::size_t SIZE>
|
||||
void safe_sprintf(char (&buffer)[SIZE], const char *format, ...) {
|
||||
std::va_list args;
|
||||
va_start(args, format);
|
||||
FMT_VSNPRINTF(buffer, SIZE, format, args);
|
||||
va_end(args);
|
||||
}
|
||||
|
||||
// Increment a number in a string.
|
||||
void increment(char *s);
|
||||
|
||||
std::string get_system_error(int error_code);
|
||||
|
||||
extern const char *const FILE_CONTENT;
|
||||
|
||||
// Opens a buffered file for reading.
|
||||
fmt::BufferedFile open_buffered_file(FILE **fp = 0);
|
||||
|
||||
inline FILE *safe_fopen(const char *filename, const char *mode) {
|
||||
#if defined(_WIN32) && !defined(__MINGW32__)
|
||||
// Fix MSVC warning about "unsafe" fopen.
|
||||
FILE *f = 0;
|
||||
errno = fopen_s(&f, filename, mode);
|
||||
return f;
|
||||
#else
|
||||
return std::fopen(filename, mode);
|
||||
#endif
|
||||
}
|
||||
|
||||
template <typename Char>
|
||||
class BasicTestString {
|
||||
private:
|
||||
std::basic_string<Char> value_;
|
||||
|
||||
static const Char EMPTY[];
|
||||
|
||||
public:
|
||||
explicit BasicTestString(const Char *value = EMPTY) : value_(value) {}
|
||||
|
||||
const std::basic_string<Char> &value() const { return value_; }
|
||||
};
|
||||
|
||||
template <typename Char>
|
||||
const Char BasicTestString<Char>::EMPTY[] = {0};
|
||||
|
||||
typedef BasicTestString<char> TestString;
|
||||
typedef BasicTestString<wchar_t> TestWString;
|
||||
|
||||
class Date {
|
||||
int year_, month_, day_;
|
||||
public:
|
||||
Date(int year, int month, int day) : year_(year), month_(month), day_(day) {}
|
||||
|
||||
int year() const { return year_; }
|
||||
int month() const { return month_; }
|
||||
int day() const { return day_; }
|
||||
};
|
||||
Reference in New Issue
Block a user