first
This commit is contained in:
parent
c892d32259
commit
66af6e9098
51
.gitignore
vendored
Normal file
51
.gitignore
vendored
Normal file
@ -0,0 +1,51 @@
|
||||
# C++ objects and libs
|
||||
*.slo
|
||||
*.lo
|
||||
*.o
|
||||
*.a
|
||||
*.la
|
||||
*.lai
|
||||
*.so
|
||||
*.dll
|
||||
*.dylib
|
||||
|
||||
# Qt-es
|
||||
object_script.*.Release
|
||||
object_script.*.Debug
|
||||
*_plugin_import.cpp
|
||||
/.qmake.cache
|
||||
/.qmake.stash
|
||||
*.pro.user
|
||||
*.pro.user.*
|
||||
*.qbs.user
|
||||
*.qbs.user.*
|
||||
*.moc
|
||||
moc_*.cpp
|
||||
moc_*.h
|
||||
qrc_*.cpp
|
||||
ui_*.h
|
||||
*.qmlc
|
||||
*.jsc
|
||||
Makefile*
|
||||
*build-*
|
||||
*build_*
|
||||
|
||||
# Qt unit tests
|
||||
target_wrapper.*
|
||||
|
||||
# QtCreator
|
||||
*.autosave
|
||||
|
||||
# QtCreator Qml
|
||||
*.qmlproject.user
|
||||
*.qmlproject.user.*
|
||||
|
||||
# QtCreator CMake
|
||||
CMakeLists.txt.user*
|
||||
|
||||
# My output files
|
||||
build
|
||||
|
||||
# vs
|
||||
.vs
|
||||
.vscode
|
22
3rdparty/capo/make.hpp
vendored
Normal file
22
3rdparty/capo/make.hpp
vendored
Normal file
@ -0,0 +1,22 @@
|
||||
/*
|
||||
The Capo Library
|
||||
Code covered by the MIT License
|
||||
Author: mutouyun (http://orzz.org)
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <type_traits> // std::decay
|
||||
#include <utility> // std::forward
|
||||
|
||||
namespace capo
|
||||
{
|
||||
template <template <typename...> class Ret, typename... T>
|
||||
using return_t = Ret<typename std::decay<T>::type...>;
|
||||
|
||||
template <template <typename...> class Ret, typename... T>
|
||||
inline return_t<Ret, T...> make(T&&... args)
|
||||
{
|
||||
return return_t<Ret, T...>(std::forward<T>(args)...);
|
||||
}
|
||||
}
|
25
3rdparty/capo/noncopyable.hpp
vendored
Normal file
25
3rdparty/capo/noncopyable.hpp
vendored
Normal file
@ -0,0 +1,25 @@
|
||||
/*
|
||||
The Capo Library
|
||||
Code covered by the MIT License
|
||||
Author: mutouyun (http://orzz.org)
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
namespace capo {
|
||||
|
||||
////////////////////////////////////////////////////////////////
|
||||
|
||||
class noncopyable
|
||||
{
|
||||
protected:
|
||||
noncopyable(void) = default;
|
||||
~noncopyable(void) = default;
|
||||
public:
|
||||
noncopyable(const noncopyable&) = delete;
|
||||
noncopyable& operator=(const noncopyable&) = delete;
|
||||
};
|
||||
|
||||
////////////////////////////////////////////////////////////////
|
||||
|
||||
} // namespace capo
|
52
3rdparty/capo/random.hpp
vendored
Normal file
52
3rdparty/capo/random.hpp
vendored
Normal file
@ -0,0 +1,52 @@
|
||||
/*
|
||||
The Capo Library
|
||||
Code covered by the MIT License
|
||||
|
||||
Author: mutouyun (http://orzz.org)
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <random> // std::default_random_engine, std::uniform_int_distribution
|
||||
#include <utility> // std::forward
|
||||
|
||||
namespace capo {
|
||||
|
||||
////////////////////////////////////////////////////////////////
|
||||
/// Simple way of generating random numbers
|
||||
////////////////////////////////////////////////////////////////
|
||||
|
||||
template <class Engine = std::default_random_engine,
|
||||
class Distribution = std::uniform_int_distribution<>>
|
||||
class random : public Distribution
|
||||
{
|
||||
using base_t = Distribution;
|
||||
|
||||
public:
|
||||
using engine_type = Engine;
|
||||
using distribution_type = Distribution;
|
||||
using result_type = typename distribution_type::result_type;
|
||||
using param_type = typename distribution_type::param_type;
|
||||
|
||||
private:
|
||||
engine_type engine_;
|
||||
|
||||
public:
|
||||
template <typename... T>
|
||||
random(T&&... args)
|
||||
: base_t (std::forward<T>(args)...)
|
||||
, engine_(std::random_device{}())
|
||||
{}
|
||||
|
||||
result_type operator()(void)
|
||||
{
|
||||
return base_t::operator()(engine_);
|
||||
}
|
||||
|
||||
result_type operator()(const param_type& parm)
|
||||
{
|
||||
return base_t::operator()(engine_, parm);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace capo
|
103
3rdparty/capo/scope_guard.hpp
vendored
Normal file
103
3rdparty/capo/scope_guard.hpp
vendored
Normal file
@ -0,0 +1,103 @@
|
||||
/*
|
||||
The Capo Library
|
||||
Code covered by the MIT License
|
||||
Author: mutouyun (http://orzz.org)
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "capo/noncopyable.hpp"
|
||||
#include "capo/unused.hpp"
|
||||
#include "capo/make.hpp"
|
||||
|
||||
#include <utility> // std::forward, std::move
|
||||
#include <algorithm> // std::swap
|
||||
#include <functional> // std::function
|
||||
|
||||
namespace capo {
|
||||
|
||||
////////////////////////////////////////////////////////////////
|
||||
/// Execute guard function when the enclosing scope exits
|
||||
////////////////////////////////////////////////////////////////
|
||||
|
||||
template <typename F = std::function<void()>>
|
||||
class scope_guard : capo::noncopyable
|
||||
{
|
||||
F destructor_;
|
||||
mutable bool dismiss_;
|
||||
|
||||
public:
|
||||
template <typename F_>
|
||||
scope_guard(F_&& destructor)
|
||||
: destructor_(std::forward<F_>(destructor))
|
||||
, dismiss_(false)
|
||||
{}
|
||||
|
||||
scope_guard(scope_guard&& rhs)
|
||||
: destructor_(std::move(rhs.destructor_))
|
||||
, dismiss_(true) // dismiss rhs
|
||||
{
|
||||
std::swap(dismiss_, rhs.dismiss_);
|
||||
}
|
||||
|
||||
~scope_guard(void)
|
||||
{
|
||||
try { do_exit(); }
|
||||
/*
|
||||
In the realm of exceptions, it is fundamental that you can do nothing
|
||||
if your "undo/recover" action fails.
|
||||
*/
|
||||
catch(...) { /* Do nothing */ }
|
||||
}
|
||||
|
||||
void dismiss(void) const noexcept
|
||||
{
|
||||
dismiss_ = true;
|
||||
}
|
||||
|
||||
void do_exit(void)
|
||||
{
|
||||
if (!dismiss_)
|
||||
{
|
||||
dismiss_ = true;
|
||||
destructor_();
|
||||
}
|
||||
}
|
||||
|
||||
void swap(scope_guard& rhs)
|
||||
{
|
||||
std::swap(destructor_, rhs.destructor_);
|
||||
std::swap(dismiss_, rhs.dismiss_);
|
||||
}
|
||||
};
|
||||
|
||||
namespace detail_scope_guard {
|
||||
|
||||
struct helper
|
||||
{
|
||||
template <typename F>
|
||||
auto operator=(F&& destructor) -> decltype(capo::make<scope_guard>(std::forward<F>(destructor)))
|
||||
{
|
||||
return capo::make<scope_guard>(std::forward<F>(destructor));
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace detail_scope_guard
|
||||
|
||||
#define CAPO_SCOPE_GUARD_V_(L) CAPO_UNUSED_ scope_guard_##L##__
|
||||
#define CAPO_SCOPE_GUARD_L_(L) auto CAPO_SCOPE_GUARD_V_(L) = capo::detail_scope_guard::helper{}
|
||||
|
||||
/*
|
||||
Do things like this:
|
||||
-->
|
||||
CAPO_SCOPE_GUARD_ = [ptr]
|
||||
{
|
||||
if (ptr) free(ptr);
|
||||
};
|
||||
*/
|
||||
|
||||
#define CAPO_SCOPE_GUARD_ CAPO_SCOPE_GUARD_L_(__LINE__)
|
||||
|
||||
////////////////////////////////////////////////////////////////
|
||||
|
||||
} // namespace capo
|
104
3rdparty/capo/spin_lock.hpp
vendored
Normal file
104
3rdparty/capo/spin_lock.hpp
vendored
Normal file
@ -0,0 +1,104 @@
|
||||
/*
|
||||
The Capo Library
|
||||
Code covered by the MIT License
|
||||
|
||||
Author: mutouyun (http://orzz.org)
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <atomic> // std::atomic_flag, std::atomic_signal_fence
|
||||
#include <thread> // std::this_thread
|
||||
#include <chrono> // std::chrono::milliseconds
|
||||
#if defined(_MSC_VER)
|
||||
#include <windows.h> // YieldProcessor
|
||||
#endif/*_MSC_VER*/
|
||||
|
||||
namespace capo {
|
||||
namespace detail_spin_lock {
|
||||
|
||||
////////////////////////////////////////////////////////////////
|
||||
/// Gives hint to processor that improves performance of spin-wait loops.
|
||||
////////////////////////////////////////////////////////////////
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
/*
|
||||
See: http://msdn.microsoft.com/en-us/library/windows/desktop/ms687419(v=vs.85).aspx
|
||||
Not for intel c++ compiler, so ignore http://software.intel.com/en-us/forums/topic/296168
|
||||
*/
|
||||
# define CAPO_SPIN_LOCK_PAUSE_() YieldProcessor()
|
||||
#elif defined(__GNUC__)
|
||||
#if defined(__i386__) || defined(__x86_64__)
|
||||
/*
|
||||
See: Intel(R) 64 and IA-32 Architectures Software Developer's Manual V2
|
||||
PAUSE-Spin Loop Hint, 4-57
|
||||
http://www.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-software-developer-instruction-set-reference-manual-325383.html?wapkw=instruction+set+reference
|
||||
*/
|
||||
# define CAPO_SPIN_LOCK_PAUSE_() __asm__ __volatile__("pause")
|
||||
#elif defined(__ia64__) || defined(__ia64)
|
||||
/*
|
||||
See: Intel(R) Itanium(R) Architecture Developer's Manual, Vol.3
|
||||
hint - Performance Hint, 3:145
|
||||
http://www.intel.com/content/www/us/en/processors/itanium/itanium-architecture-vol-3-manual.html
|
||||
*/
|
||||
# define CAPO_SPIN_LOCK_PAUSE_() __asm__ __volatile__ ("hint @pause")
|
||||
#elif defined(__arm__)
|
||||
/*
|
||||
See: ARM Architecture Reference Manuals (YIELD)
|
||||
http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.subset.architecture.reference/index.html
|
||||
*/
|
||||
# define CAPO_SPIN_LOCK_PAUSE_() __asm__ __volatile__ ("yield")
|
||||
#endif
|
||||
#endif/*compilers*/
|
||||
|
||||
#if !defined(CAPO_SPIN_LOCK_PAUSE_)
|
||||
/*
|
||||
Just use a compiler fence, prevent compiler from optimizing loop
|
||||
*/
|
||||
# define CAPO_SPIN_LOCK_PAUSE_() std::atomic_signal_fence(std::memory_order_seq_cst)
|
||||
#endif/*!defined(CAPO_SPIN_LOCK_PAUSE_)*/
|
||||
|
||||
////////////////////////////////////////////////////////////////
|
||||
/// Yield to other threads
|
||||
////////////////////////////////////////////////////////////////
|
||||
|
||||
inline void yield(unsigned k)
|
||||
{
|
||||
if (k < 4) { /* Do nothing */ }
|
||||
else
|
||||
if (k < 16) { CAPO_SPIN_LOCK_PAUSE_(); }
|
||||
else
|
||||
if (k < 32) { std::this_thread::yield(); }
|
||||
else
|
||||
{ std::this_thread::sleep_for(std::chrono::milliseconds(1)); }
|
||||
}
|
||||
|
||||
} // namespace detail_spin_lock
|
||||
|
||||
////////////////////////////////////////////////////////////////
|
||||
/// Spinlock
|
||||
////////////////////////////////////////////////////////////////
|
||||
|
||||
class spin_lock
|
||||
{
|
||||
std::atomic_flag lc_ = ATOMIC_FLAG_INIT;
|
||||
|
||||
public:
|
||||
bool try_lock(void)
|
||||
{
|
||||
return !lc_.test_and_set(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
void lock(void)
|
||||
{
|
||||
for (unsigned k = 0; lc_.test_and_set(std::memory_order_acquire); ++k)
|
||||
detail_spin_lock::yield(k);
|
||||
}
|
||||
|
||||
void unlock(void)
|
||||
{
|
||||
lc_.clear(std::memory_order_release);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace capo
|
109
3rdparty/capo/stopwatch.hpp
vendored
Normal file
109
3rdparty/capo/stopwatch.hpp
vendored
Normal file
@ -0,0 +1,109 @@
|
||||
/*
|
||||
The Capo Library
|
||||
Code covered by the MIT License
|
||||
|
||||
Author: mutouyun (http://orzz.org)
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <chrono> // std::chrono
|
||||
#include <array> // std::array
|
||||
#include <utility> // std::pair, std::declval
|
||||
#include <cstddef> // size_t
|
||||
|
||||
namespace capo {
|
||||
|
||||
////////////////////////////////////////////////////////////////
|
||||
/// Stopwatch - can store multiple sets of time
|
||||
////////////////////////////////////////////////////////////////
|
||||
|
||||
template <size_t CountN = 1, class ClockT = std::chrono::steady_clock>
|
||||
class stopwatch : public ClockT
|
||||
{
|
||||
using base_t = ClockT;
|
||||
|
||||
static_assert(CountN > 0, "The count must be greater than 0");
|
||||
|
||||
public:
|
||||
using rep = typename ClockT::rep;
|
||||
using period = typename ClockT::period;
|
||||
using duration = typename ClockT::duration;
|
||||
using time_point = typename ClockT::time_point;
|
||||
|
||||
private:
|
||||
using pair_t = std::pair<time_point/*start*/, time_point/*paused*/>;
|
||||
|
||||
std::array<pair_t, CountN> points_;
|
||||
bool is_stopped_ = true;
|
||||
|
||||
public:
|
||||
stopwatch(bool start_watch = false)
|
||||
{
|
||||
if (start_watch) start();
|
||||
}
|
||||
|
||||
public:
|
||||
bool is_stopped(void) const
|
||||
{
|
||||
return is_stopped_;
|
||||
}
|
||||
|
||||
template <size_t N = 0>
|
||||
bool is_paused(void) const
|
||||
{
|
||||
return (points_[N].second != points_[N].first);
|
||||
}
|
||||
|
||||
template <size_t N = 0>
|
||||
duration elapsed(void)
|
||||
{
|
||||
if (is_stopped())
|
||||
return duration::zero();
|
||||
else
|
||||
if (is_paused<N>())
|
||||
return (points_[N].second - points_[N].first);
|
||||
else
|
||||
return ClockT::now() - points_[N].first;
|
||||
}
|
||||
|
||||
template <typename ToDur, size_t N = 0>
|
||||
auto elapsed(void) -> decltype(std::declval<ToDur>().count())
|
||||
{
|
||||
return std::chrono::duration_cast<ToDur>(elapsed<N>()).count();
|
||||
}
|
||||
|
||||
template <size_t N = 0>
|
||||
void pause(void)
|
||||
{
|
||||
points_[N].second = ClockT::now();
|
||||
}
|
||||
|
||||
template <size_t N = 0>
|
||||
void restart(void)
|
||||
{
|
||||
points_[N].second = points_[N].first =
|
||||
ClockT::now() - (points_[N].second - points_[N].first);
|
||||
}
|
||||
|
||||
void start(void)
|
||||
{
|
||||
time_point now = ClockT::now();
|
||||
for (auto& pt : points_)
|
||||
{
|
||||
pt.second = pt.first = now - (pt.second - pt.first);
|
||||
}
|
||||
is_stopped_ = false;
|
||||
}
|
||||
|
||||
void stop(void)
|
||||
{
|
||||
for (auto& pt : points_)
|
||||
{
|
||||
pt.second = pt.first;
|
||||
}
|
||||
is_stopped_ = true;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace capo
|
320
3rdparty/capo/type_name.hpp
vendored
Normal file
320
3rdparty/capo/type_name.hpp
vendored
Normal file
@ -0,0 +1,320 @@
|
||||
/*
|
||||
The Capo Library
|
||||
Code covered by the MIT License
|
||||
Author: mutouyun (http://orzz.org)
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "capo/scope_guard.hpp"
|
||||
|
||||
#include <typeinfo> // typeid
|
||||
#include <sstream> // std::ostringstream, std::string
|
||||
#include <type_traits> // std::is_array
|
||||
|
||||
#if defined(__GNUC__)
|
||||
# include <cxxabi.h> // abi::__cxa_demangle
|
||||
#endif/*__GNUC__*/
|
||||
|
||||
namespace capo {
|
||||
namespace detail_type_name {
|
||||
|
||||
////////////////////////////////////////////////////////////////
|
||||
/// Ready for output
|
||||
////////////////////////////////////////////////////////////////
|
||||
|
||||
// Forward declarations
|
||||
template <typename T, bool IsBase = false>
|
||||
struct check;
|
||||
|
||||
/*
|
||||
Output state management
|
||||
*/
|
||||
|
||||
class output
|
||||
{
|
||||
bool is_compact_ = true;
|
||||
|
||||
template <typename T>
|
||||
bool check_empty(const T&) { return false; }
|
||||
bool check_empty(const char* val)
|
||||
{
|
||||
return (!val) || (val[0] == 0);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void out(const T& val)
|
||||
{
|
||||
if (check_empty(val)) return;
|
||||
if (!is_compact_) sr_ += " ";
|
||||
std::ostringstream ss;
|
||||
ss << val;
|
||||
sr_ += ss.str();
|
||||
is_compact_ = false;
|
||||
}
|
||||
|
||||
std::string& sr_;
|
||||
|
||||
public:
|
||||
output(std::string& sr) : sr_(sr) {}
|
||||
|
||||
output& operator()(void) { return (*this); }
|
||||
|
||||
template <typename T1, typename... T>
|
||||
output& operator()(const T1& val, const T&... args)
|
||||
{
|
||||
out(val);
|
||||
return operator()(args...);
|
||||
}
|
||||
|
||||
output& compact(void)
|
||||
{
|
||||
is_compact_ = true;
|
||||
return (*this);
|
||||
}
|
||||
};
|
||||
|
||||
// ()
|
||||
|
||||
template <bool>
|
||||
struct bracket
|
||||
{
|
||||
output& out_;
|
||||
|
||||
bracket(output& out, const char* = nullptr) : out_(out)
|
||||
{ out_("(").compact(); }
|
||||
|
||||
~bracket(void)
|
||||
{ out_.compact()(")"); }
|
||||
};
|
||||
|
||||
template <>
|
||||
struct bracket<false>
|
||||
{
|
||||
bracket(output& out, const char* str = nullptr)
|
||||
{ out(str); }
|
||||
};
|
||||
|
||||
// [N]
|
||||
|
||||
template <size_t N = 0>
|
||||
struct bound
|
||||
{
|
||||
output& out_;
|
||||
|
||||
bound(output& out) : out_(out) {}
|
||||
~bound(void)
|
||||
{
|
||||
if (N == 0) out_("[]");
|
||||
else out_("[").compact()
|
||||
( N ).compact()
|
||||
("]");
|
||||
}
|
||||
};
|
||||
|
||||
// (P1, P2, ...)
|
||||
|
||||
template <bool, typename... P>
|
||||
struct parameter;
|
||||
|
||||
template <bool IsStart>
|
||||
struct parameter<IsStart>
|
||||
{
|
||||
output& out_;
|
||||
|
||||
parameter(output& out) : out_(out) {}
|
||||
~parameter(void)
|
||||
{ bracket<IsStart> { out_ }; }
|
||||
};
|
||||
|
||||
template <bool IsStart, typename P1, typename... P>
|
||||
struct parameter<IsStart, P1, P...>
|
||||
{
|
||||
output& out_;
|
||||
|
||||
parameter(output& out) : out_(out) {}
|
||||
~parameter(void)
|
||||
{
|
||||
[this](bracket<IsStart>&&)
|
||||
{
|
||||
check<P1> { out_ };
|
||||
parameter<false, P...> { out_.compact() };
|
||||
} (bracket<IsStart> { out_, "," });
|
||||
}
|
||||
};
|
||||
|
||||
////////////////////////////////////////////////////////////////
|
||||
/// Template specializations for checking
|
||||
////////////////////////////////////////////////////////////////
|
||||
|
||||
/*
|
||||
CV-qualifiers, references, pointers
|
||||
*/
|
||||
|
||||
template <typename T, bool IsBase>
|
||||
struct check
|
||||
{
|
||||
output out_;
|
||||
check(const output& out) : out_(out)
|
||||
{
|
||||
# if defined(__GNUC__)
|
||||
const char* typeid_name = typeid(T).name();
|
||||
char* real_name = abi::__cxa_demangle(typeid_name, nullptr, nullptr, nullptr);
|
||||
CAPO_SCOPE_GUARD_ = [real_name]
|
||||
{
|
||||
if (real_name) ::free(real_name);
|
||||
};
|
||||
out_(real_name ? real_name : typeid_name);
|
||||
# else /*__GNUC__*/
|
||||
out_(typeid(T).name());
|
||||
# endif/*__GNUC__*/
|
||||
}
|
||||
};
|
||||
|
||||
#pragma push_macro("CAPO_CHECK_TYPE__")
|
||||
#undef CAPO_CHECK_TYPE__
|
||||
#define CAPO_CHECK_TYPE__(OPT) \
|
||||
template <typename T, bool IsBase> \
|
||||
struct check<T OPT, IsBase> : check<T, true> \
|
||||
{ \
|
||||
using base_t = check<T, true>; \
|
||||
using base_t::out_; \
|
||||
check(const output& out) : base_t(out) { out_(#OPT); } \
|
||||
};
|
||||
|
||||
CAPO_CHECK_TYPE__(const)
|
||||
CAPO_CHECK_TYPE__(volatile)
|
||||
CAPO_CHECK_TYPE__(const volatile)
|
||||
CAPO_CHECK_TYPE__(&)
|
||||
CAPO_CHECK_TYPE__(&&)
|
||||
CAPO_CHECK_TYPE__(*)
|
||||
|
||||
#pragma pop_macro("CAPO_CHECK_TYPE__")
|
||||
|
||||
/*
|
||||
Arrays
|
||||
*/
|
||||
|
||||
#pragma push_macro("CAPO_CHECK_TYPE_ARRAY__")
|
||||
#pragma push_macro("CAPO_CHECK_TYPE_ARRAY_CV__")
|
||||
#pragma push_macro("CAPO_CHECK_TYPE_PLACEHOLDER__")
|
||||
|
||||
#undef CAPO_CHECK_TYPE_ARRAY__
|
||||
#undef CAPO_CHECK_TYPE_ARRAY_CV__
|
||||
#undef CAPO_CHECK_TYPE_PLACEHOLDER__
|
||||
|
||||
#define CAPO_CHECK_TYPE_ARRAY__(CV_OPT, BOUND_OPT, ...) \
|
||||
template <typename T, bool IsBase __VA_ARGS__> \
|
||||
struct check<T CV_OPT [BOUND_OPT], IsBase> : check<T CV_OPT, !std::is_array<T>::value> \
|
||||
{ \
|
||||
using base_t = check<T CV_OPT, !std::is_array<T>::value>; \
|
||||
using base_t::out_; \
|
||||
\
|
||||
bound<BOUND_OPT> bound_ = out_; \
|
||||
bracket<IsBase> bracket_ = out_; \
|
||||
\
|
||||
check(const output& out) : base_t(out) {} \
|
||||
};
|
||||
|
||||
#define CAPO_CHECK_TYPE_ARRAY_CV__(BOUND_OPT, ...) \
|
||||
CAPO_CHECK_TYPE_ARRAY__(, BOUND_OPT, ,##__VA_ARGS__) \
|
||||
CAPO_CHECK_TYPE_ARRAY__(const, BOUND_OPT, ,##__VA_ARGS__) \
|
||||
CAPO_CHECK_TYPE_ARRAY__(volatile, BOUND_OPT, ,##__VA_ARGS__) \
|
||||
CAPO_CHECK_TYPE_ARRAY__(const volatile, BOUND_OPT, ,##__VA_ARGS__)
|
||||
|
||||
#define CAPO_CHECK_TYPE_PLACEHOLDER__
|
||||
|
||||
CAPO_CHECK_TYPE_ARRAY_CV__(CAPO_CHECK_TYPE_PLACEHOLDER__)
|
||||
#if defined(__GNUC__)
|
||||
CAPO_CHECK_TYPE_ARRAY_CV__(0)
|
||||
#endif/*__GNUC__*/
|
||||
CAPO_CHECK_TYPE_ARRAY_CV__(N, size_t N)
|
||||
|
||||
#pragma pop_macro("CAPO_CHECK_TYPE_PLACEHOLDER__")
|
||||
#pragma pop_macro("CAPO_CHECK_TYPE_ARRAY_CV__")
|
||||
#pragma pop_macro("CAPO_CHECK_TYPE_ARRAY__")
|
||||
|
||||
/*
|
||||
Functions
|
||||
*/
|
||||
|
||||
template <typename T, bool IsBase, typename... P>
|
||||
struct check<T(P...), IsBase> : check<T, true>
|
||||
{
|
||||
using base_t = check<T, true>;
|
||||
using base_t::out_;
|
||||
|
||||
parameter<true, P...> parameter_ = out_;
|
||||
bracket<IsBase> bracket_ = out_;
|
||||
|
||||
check(const output& out) : base_t(out) {}
|
||||
};
|
||||
|
||||
/*
|
||||
Pointers to members
|
||||
*/
|
||||
|
||||
template <typename T, bool IsBase, typename C>
|
||||
struct check<T C::*, IsBase> : check<T, true>
|
||||
{
|
||||
using base_t = check<T, true>;
|
||||
using base_t::out_;
|
||||
|
||||
check(const output& out) : base_t(out)
|
||||
{
|
||||
check<C> { out_ };
|
||||
out_.compact()("::*");
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
Pointers to member functions
|
||||
*/
|
||||
|
||||
#pragma push_macro("CAPO_CHECK_TYPE_MEM_FUNC__")
|
||||
#undef CAPO_CHECK_TYPE_MEM_FUNC__
|
||||
#define CAPO_CHECK_TYPE_MEM_FUNC__(...) \
|
||||
template <typename T, bool IsBase, typename C, typename... P> \
|
||||
struct check<T(C::*)(P...) __VA_ARGS__, IsBase> \
|
||||
{ \
|
||||
scope_guard<> at_destruct_cv_; \
|
||||
check<T(P...), true> base_; \
|
||||
output& out_ = base_.out_; \
|
||||
\
|
||||
check(const output& out) \
|
||||
: at_destruct_cv_([this]{ out_(#__VA_ARGS__); }) \
|
||||
, base_(out) \
|
||||
{ \
|
||||
check<C> { out_ }; \
|
||||
out_.compact()("::*"); \
|
||||
} \
|
||||
};
|
||||
|
||||
CAPO_CHECK_TYPE_MEM_FUNC__()
|
||||
CAPO_CHECK_TYPE_MEM_FUNC__(const)
|
||||
CAPO_CHECK_TYPE_MEM_FUNC__(volatile)
|
||||
CAPO_CHECK_TYPE_MEM_FUNC__(const volatile)
|
||||
|
||||
#pragma pop_macro("CAPO_CHECK_TYPE_MEM_FUNC__")
|
||||
|
||||
} // namespace detail_type_name
|
||||
|
||||
////////////////////////////////////////////////////////////////
|
||||
/// Get the name of the given type
|
||||
////////////////////////////////////////////////////////////////
|
||||
|
||||
/*
|
||||
type_name<const volatile void *>()
|
||||
-->
|
||||
void const volatile *
|
||||
*/
|
||||
|
||||
template <typename T>
|
||||
inline std::string type_name(void)
|
||||
{
|
||||
std::string str;
|
||||
detail_type_name::check<T> { str };
|
||||
return str;
|
||||
}
|
||||
|
||||
} // namespace capo
|
23
3rdparty/capo/unused.hpp
vendored
Normal file
23
3rdparty/capo/unused.hpp
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
/*
|
||||
The Capo Library
|
||||
Code covered by the MIT License
|
||||
Author: mutouyun (http://orzz.org)
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifdef CAPO_UNUSED_
|
||||
# error "CAPO_UNUSED_ has been defined."
|
||||
#endif
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
# define CAPO_UNUSED_ __pragma(warning(suppress: 4100 4101 4189))
|
||||
#elif defined(__GNUC__)
|
||||
# define CAPO_UNUSED_ __attribute__((__unused__))
|
||||
#else
|
||||
# define CAPO_UNUSED_
|
||||
#endif
|
||||
|
||||
////////////////////////////////////////////////////////////////
|
1
3rdparty/gperftools/libtcmalloc_minimal.so.4
vendored
Normal file
1
3rdparty/gperftools/libtcmalloc_minimal.so.4
vendored
Normal file
@ -0,0 +1 @@
|
||||
libtcmalloc_minimal.so
|
1
3rdparty/gperftools/libtcmalloc_minimal.so.4.5.3
vendored
Normal file
1
3rdparty/gperftools/libtcmalloc_minimal.so.4.5.3
vendored
Normal file
@ -0,0 +1 @@
|
||||
libtcmalloc_minimal.so
|
163
3rdparty/gperftools/tcmalloc.h
vendored
Normal file
163
3rdparty/gperftools/tcmalloc.h
vendored
Normal file
@ -0,0 +1,163 @@
|
||||
// -*- Mode: C; c-basic-offset: 2; indent-tabs-mode: nil -*-
|
||||
/* Copyright (c) 2003, 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: Sanjay Ghemawat <opensource@google.com>
|
||||
* .h file by Craig Silverstein <opensource@google.com>
|
||||
*/
|
||||
|
||||
#ifndef TCMALLOC_TCMALLOC_H_
|
||||
#define TCMALLOC_TCMALLOC_H_
|
||||
|
||||
#include <stddef.h> /* for size_t */
|
||||
#ifdef __cplusplus
|
||||
#include <new> /* for std::nothrow_t, std::align_val_t */
|
||||
#endif
|
||||
|
||||
/* Define the version number so folks can check against it */
|
||||
#define TC_VERSION_MAJOR 2
|
||||
#define TC_VERSION_MINOR 7
|
||||
#define TC_VERSION_PATCH ""
|
||||
#define TC_VERSION_STRING "gperftools 2.7"
|
||||
|
||||
/* For struct mallinfo, if it's defined. */
|
||||
#if 1
|
||||
# include <malloc.h>
|
||||
#endif
|
||||
|
||||
#ifndef PERFTOOLS_NOTHROW
|
||||
|
||||
#if __cplusplus >= 201103L
|
||||
#define PERFTOOLS_NOTHROW noexcept
|
||||
#elif defined(__cplusplus)
|
||||
#define PERFTOOLS_NOTHROW throw()
|
||||
#else
|
||||
# ifdef __GNUC__
|
||||
# define PERFTOOLS_NOTHROW __attribute__((__nothrow__))
|
||||
# else
|
||||
# define PERFTOOLS_NOTHROW
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
#ifndef PERFTOOLS_DLL_DECL
|
||||
# ifdef _WIN32
|
||||
# define PERFTOOLS_DLL_DECL __declspec(dllimport)
|
||||
# else
|
||||
# define PERFTOOLS_DLL_DECL
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
/*
|
||||
* Returns a human-readable version string. If major, minor,
|
||||
* and/or patch are not NULL, they are set to the major version,
|
||||
* minor version, and patch-code (a string, usually "").
|
||||
*/
|
||||
PERFTOOLS_DLL_DECL const char* tc_version(int* major, int* minor,
|
||||
const char** patch) PERFTOOLS_NOTHROW;
|
||||
|
||||
PERFTOOLS_DLL_DECL void* tc_malloc(size_t size) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void* tc_malloc_skip_new_handler(size_t size) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void tc_free(void* ptr) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void tc_free_sized(void *ptr, size_t size) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void* tc_realloc(void* ptr, size_t size) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void* tc_calloc(size_t nmemb, size_t size) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void tc_cfree(void* ptr) PERFTOOLS_NOTHROW;
|
||||
|
||||
PERFTOOLS_DLL_DECL void* tc_memalign(size_t __alignment,
|
||||
size_t __size) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL int tc_posix_memalign(void** ptr,
|
||||
size_t align, size_t size) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void* tc_valloc(size_t __size) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void* tc_pvalloc(size_t __size) PERFTOOLS_NOTHROW;
|
||||
|
||||
PERFTOOLS_DLL_DECL void tc_malloc_stats(void) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL int tc_mallopt(int cmd, int value) PERFTOOLS_NOTHROW;
|
||||
#if 1
|
||||
PERFTOOLS_DLL_DECL struct mallinfo tc_mallinfo(void) PERFTOOLS_NOTHROW;
|
||||
#endif
|
||||
|
||||
/*
|
||||
* This is an alias for MallocExtension::instance()->GetAllocatedSize().
|
||||
* It is equivalent to
|
||||
* OS X: malloc_size()
|
||||
* glibc: malloc_usable_size()
|
||||
* Windows: _msize()
|
||||
*/
|
||||
PERFTOOLS_DLL_DECL size_t tc_malloc_size(void* ptr) PERFTOOLS_NOTHROW;
|
||||
|
||||
#ifdef __cplusplus
|
||||
PERFTOOLS_DLL_DECL int tc_set_new_mode(int flag) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void* tc_new(size_t size);
|
||||
PERFTOOLS_DLL_DECL void* tc_new_nothrow(size_t size,
|
||||
const std::nothrow_t&) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void tc_delete(void* p) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void tc_delete_sized(void* p, size_t size) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void tc_delete_nothrow(void* p,
|
||||
const std::nothrow_t&) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void* tc_newarray(size_t size);
|
||||
PERFTOOLS_DLL_DECL void* tc_newarray_nothrow(size_t size,
|
||||
const std::nothrow_t&) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void tc_deletearray(void* p) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void tc_deletearray_sized(void* p, size_t size) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void tc_deletearray_nothrow(void* p,
|
||||
const std::nothrow_t&) PERFTOOLS_NOTHROW;
|
||||
|
||||
#if 1 && __cplusplus >= 201703L
|
||||
PERFTOOLS_DLL_DECL void* tc_new_aligned(size_t size, std::align_val_t al);
|
||||
PERFTOOLS_DLL_DECL void* tc_new_aligned_nothrow(size_t size, std::align_val_t al,
|
||||
const std::nothrow_t&) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void tc_delete_aligned(void* p, std::align_val_t al) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void tc_delete_sized_aligned(void* p, size_t size, std::align_val_t al) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void tc_delete_aligned_nothrow(void* p, std::align_val_t al,
|
||||
const std::nothrow_t&) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void* tc_newarray_aligned(size_t size, std::align_val_t al);
|
||||
PERFTOOLS_DLL_DECL void* tc_newarray_aligned_nothrow(size_t size, std::align_val_t al,
|
||||
const std::nothrow_t&) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void tc_deletearray_aligned(void* p, std::align_val_t al) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void tc_deletearray_sized_aligned(void* p, size_t size, std::align_val_t al) PERFTOOLS_NOTHROW;
|
||||
PERFTOOLS_DLL_DECL void tc_deletearray_aligned_nothrow(void* p, std::align_val_t al,
|
||||
const std::nothrow_t&) PERFTOOLS_NOTHROW;
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
/* We're only un-defining for public */
|
||||
#if !defined(GPERFTOOLS_CONFIG_H_)
|
||||
|
||||
#undef PERFTOOLS_NOTHROW
|
||||
|
||||
#endif /* GPERFTOOLS_CONFIG_H_ */
|
||||
|
||||
#endif /* #ifndef TCMALLOC_TCMALLOC_H_ */
|
332
3rdparty/gtest/CMakeLists.txt
vendored
Normal file
332
3rdparty/gtest/CMakeLists.txt
vendored
Normal file
@ -0,0 +1,332 @@
|
||||
########################################################################
|
||||
# Note: CMake support is community-based. The maintainers do not use CMake
|
||||
# internally.
|
||||
#
|
||||
# CMake build script for Google Test.
|
||||
#
|
||||
# To run the tests for Google Test itself on Linux, use 'make test' or
|
||||
# ctest. You can select which tests to run using 'ctest -R regex'.
|
||||
# For more options, run 'ctest --help'.
|
||||
|
||||
if (POLICY CMP0077)
|
||||
cmake_policy(SET CMP0077 NEW)
|
||||
endif (POLICY CMP0077)
|
||||
|
||||
# When other libraries are using a shared version of runtime libraries,
|
||||
# Google Test also has to use one.
|
||||
option(
|
||||
gtest_force_shared_crt
|
||||
"Use shared (DLL) run-time lib even when Google Test is built as static lib."
|
||||
OFF)
|
||||
|
||||
option(gtest_build_tests "Build all of gtest's own tests." OFF)
|
||||
|
||||
option(gtest_build_samples "Build gtest's sample programs." OFF)
|
||||
|
||||
option(gtest_disable_pthreads "Disable uses of pthreads in gtest." OFF)
|
||||
|
||||
option(
|
||||
gtest_hide_internal_symbols
|
||||
"Build gtest with internal symbols hidden in shared libraries."
|
||||
OFF)
|
||||
|
||||
# Defines pre_project_set_up_hermetic_build() and set_up_hermetic_build().
|
||||
include(cmake/hermetic_build.cmake OPTIONAL)
|
||||
|
||||
if (COMMAND pre_project_set_up_hermetic_build)
|
||||
pre_project_set_up_hermetic_build()
|
||||
endif()
|
||||
|
||||
########################################################################
|
||||
#
|
||||
# Project-wide settings
|
||||
|
||||
# Name of the project.
|
||||
#
|
||||
# CMake files in this project can refer to the root source directory
|
||||
# as ${gtest_SOURCE_DIR} and to the root binary directory as
|
||||
# ${gtest_BINARY_DIR}.
|
||||
# Language "C" is required for find_package(Threads).
|
||||
|
||||
# Project version:
|
||||
|
||||
if (CMAKE_VERSION VERSION_LESS 3.0)
|
||||
project(gtest CXX C)
|
||||
set(PROJECT_VERSION ${GOOGLETEST_VERSION})
|
||||
else()
|
||||
cmake_policy(SET CMP0048 NEW)
|
||||
project(gtest VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
|
||||
endif()
|
||||
cmake_minimum_required(VERSION 2.6.4)
|
||||
|
||||
if (POLICY CMP0063) # Visibility
|
||||
cmake_policy(SET CMP0063 NEW)
|
||||
endif (POLICY CMP0063)
|
||||
|
||||
if (COMMAND set_up_hermetic_build)
|
||||
set_up_hermetic_build()
|
||||
endif()
|
||||
|
||||
# These commands only run if this is the main project
|
||||
if(CMAKE_PROJECT_NAME STREQUAL "gtest" OR CMAKE_PROJECT_NAME STREQUAL "googletest-distribution")
|
||||
|
||||
# BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to
|
||||
# make it prominent in the GUI.
|
||||
option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF)
|
||||
|
||||
else()
|
||||
|
||||
mark_as_advanced(
|
||||
gtest_force_shared_crt
|
||||
gtest_build_tests
|
||||
gtest_build_samples
|
||||
gtest_disable_pthreads
|
||||
gtest_hide_internal_symbols)
|
||||
|
||||
endif()
|
||||
|
||||
|
||||
if (gtest_hide_internal_symbols)
|
||||
set(CMAKE_CXX_VISIBILITY_PRESET hidden)
|
||||
set(CMAKE_VISIBILITY_INLINES_HIDDEN 1)
|
||||
endif()
|
||||
|
||||
# Define helper functions and macros used by Google Test.
|
||||
include(cmake/internal_utils.cmake)
|
||||
|
||||
config_compiler_and_linker() # Defined in internal_utils.cmake.
|
||||
|
||||
# Create the CMake package file descriptors.
|
||||
if (INSTALL_GTEST)
|
||||
include(CMakePackageConfigHelpers)
|
||||
set(cmake_package_name GTest)
|
||||
set(targets_export_name ${cmake_package_name}Targets CACHE INTERNAL "")
|
||||
set(generated_dir "${CMAKE_CURRENT_BINARY_DIR}/generated" CACHE INTERNAL "")
|
||||
set(cmake_files_install_dir "${CMAKE_INSTALL_LIBDIR}/cmake/${cmake_package_name}")
|
||||
set(version_file "${generated_dir}/${cmake_package_name}ConfigVersion.cmake")
|
||||
write_basic_package_version_file(${version_file} VERSION ${GOOGLETEST_VERSION} COMPATIBILITY AnyNewerVersion)
|
||||
install(EXPORT ${targets_export_name}
|
||||
NAMESPACE ${cmake_package_name}::
|
||||
DESTINATION ${cmake_files_install_dir})
|
||||
set(config_file "${generated_dir}/${cmake_package_name}Config.cmake")
|
||||
configure_package_config_file("${gtest_SOURCE_DIR}/cmake/Config.cmake.in"
|
||||
"${config_file}" INSTALL_DESTINATION ${cmake_files_install_dir})
|
||||
install(FILES ${version_file} ${config_file}
|
||||
DESTINATION ${cmake_files_install_dir})
|
||||
endif()
|
||||
|
||||
# Where Google Test's .h files can be found.
|
||||
set(gtest_build_include_dirs
|
||||
"${gtest_SOURCE_DIR}/include"
|
||||
"${gtest_SOURCE_DIR}")
|
||||
include_directories(${gtest_build_include_dirs})
|
||||
|
||||
########################################################################
|
||||
#
|
||||
# Defines the gtest & gtest_main libraries. User tests should link
|
||||
# with one of them.
|
||||
|
||||
# Google Test libraries. We build them using more strict warnings than what
|
||||
# are used for other targets, to ensure that gtest can be compiled by a user
|
||||
# aggressive about warnings.
|
||||
cxx_library(gtest "${cxx_strict}" src/gtest-all.cc)
|
||||
cxx_library(gtest_main "${cxx_strict}" src/gtest_main.cc)
|
||||
# If the CMake version supports it, attach header directory information
|
||||
# to the targets for when we are part of a parent build (ie being pulled
|
||||
# in via add_subdirectory() rather than being a standalone build).
|
||||
if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11")
|
||||
target_include_directories(gtest SYSTEM INTERFACE
|
||||
"$<BUILD_INTERFACE:${gtest_build_include_dirs}>"
|
||||
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
|
||||
target_include_directories(gtest_main SYSTEM INTERFACE
|
||||
"$<BUILD_INTERFACE:${gtest_build_include_dirs}>"
|
||||
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
|
||||
endif()
|
||||
target_link_libraries(gtest_main PUBLIC gtest)
|
||||
|
||||
########################################################################
|
||||
#
|
||||
# Install rules
|
||||
install_project(gtest gtest_main)
|
||||
|
||||
########################################################################
|
||||
#
|
||||
# Samples on how to link user tests with gtest or gtest_main.
|
||||
#
|
||||
# They are not built by default. To build them, set the
|
||||
# gtest_build_samples option to ON. You can do it by running ccmake
|
||||
# or specifying the -Dgtest_build_samples=ON flag when running cmake.
|
||||
|
||||
if (gtest_build_samples)
|
||||
cxx_executable(sample1_unittest samples gtest_main samples/sample1.cc)
|
||||
cxx_executable(sample2_unittest samples gtest_main samples/sample2.cc)
|
||||
cxx_executable(sample3_unittest samples gtest_main)
|
||||
cxx_executable(sample4_unittest samples gtest_main samples/sample4.cc)
|
||||
cxx_executable(sample5_unittest samples gtest_main samples/sample1.cc)
|
||||
cxx_executable(sample6_unittest samples gtest_main)
|
||||
cxx_executable(sample7_unittest samples gtest_main)
|
||||
cxx_executable(sample8_unittest samples gtest_main)
|
||||
cxx_executable(sample9_unittest samples gtest)
|
||||
cxx_executable(sample10_unittest samples gtest)
|
||||
endif()
|
||||
|
||||
########################################################################
|
||||
#
|
||||
# Google Test's own tests.
|
||||
#
|
||||
# You can skip this section if you aren't interested in testing
|
||||
# Google Test itself.
|
||||
#
|
||||
# The tests are not built by default. To build them, set the
|
||||
# gtest_build_tests option to ON. You can do it by running ccmake
|
||||
# or specifying the -Dgtest_build_tests=ON flag when running cmake.
|
||||
|
||||
if (gtest_build_tests)
|
||||
# This must be set in the root directory for the tests to be run by
|
||||
# 'make test' or ctest.
|
||||
enable_testing()
|
||||
|
||||
if (WIN32)
|
||||
file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>/RunTest.ps1"
|
||||
CONTENT
|
||||
"$project_bin = \"${CMAKE_BINARY_DIR}/bin/$<CONFIG>\"
|
||||
$env:Path = \"$project_bin;$env:Path\"
|
||||
& $args")
|
||||
elseif (MINGW OR CYGWIN)
|
||||
file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/RunTest.ps1"
|
||||
CONTENT
|
||||
"$project_bin = (cygpath --windows ${CMAKE_BINARY_DIR}/bin)
|
||||
$env:Path = \"$project_bin;$env:Path\"
|
||||
& $args")
|
||||
endif()
|
||||
|
||||
############################################################
|
||||
# C++ tests built with standard compiler flags.
|
||||
|
||||
cxx_test(googletest-death-test-test gtest_main)
|
||||
cxx_test(gtest_environment_test gtest)
|
||||
cxx_test(googletest-filepath-test gtest_main)
|
||||
cxx_test(googletest-listener-test gtest_main)
|
||||
cxx_test(gtest_main_unittest gtest_main)
|
||||
cxx_test(googletest-message-test gtest_main)
|
||||
cxx_test(gtest_no_test_unittest gtest)
|
||||
cxx_test(googletest-options-test gtest_main)
|
||||
cxx_test(googletest-param-test-test gtest
|
||||
test/googletest-param-test2-test.cc)
|
||||
cxx_test(googletest-port-test gtest_main)
|
||||
cxx_test(gtest_pred_impl_unittest gtest_main)
|
||||
cxx_test(gtest_premature_exit_test gtest
|
||||
test/gtest_premature_exit_test.cc)
|
||||
cxx_test(googletest-printers-test gtest_main)
|
||||
cxx_test(gtest_prod_test gtest_main
|
||||
test/production.cc)
|
||||
cxx_test(gtest_repeat_test gtest)
|
||||
cxx_test(gtest_sole_header_test gtest_main)
|
||||
cxx_test(gtest_stress_test gtest)
|
||||
cxx_test(googletest-test-part-test gtest_main)
|
||||
cxx_test(gtest_throw_on_failure_ex_test gtest)
|
||||
cxx_test(gtest-typed-test_test gtest_main
|
||||
test/gtest-typed-test2_test.cc)
|
||||
cxx_test(gtest_unittest gtest_main)
|
||||
cxx_test(gtest-unittest-api_test gtest)
|
||||
cxx_test(gtest_skip_in_environment_setup_test gtest_main)
|
||||
cxx_test(gtest_skip_test gtest_main)
|
||||
|
||||
############################################################
|
||||
# C++ tests built with non-standard compiler flags.
|
||||
|
||||
# MSVC 7.1 does not support STL with exceptions disabled.
|
||||
if (NOT MSVC OR MSVC_VERSION GREATER 1310)
|
||||
cxx_library(gtest_no_exception "${cxx_no_exception}"
|
||||
src/gtest-all.cc)
|
||||
cxx_library(gtest_main_no_exception "${cxx_no_exception}"
|
||||
src/gtest-all.cc src/gtest_main.cc)
|
||||
endif()
|
||||
cxx_library(gtest_main_no_rtti "${cxx_no_rtti}"
|
||||
src/gtest-all.cc src/gtest_main.cc)
|
||||
|
||||
cxx_test_with_flags(gtest-death-test_ex_nocatch_test
|
||||
"${cxx_exception} -DGTEST_ENABLE_CATCH_EXCEPTIONS_=0"
|
||||
gtest test/googletest-death-test_ex_test.cc)
|
||||
cxx_test_with_flags(gtest-death-test_ex_catch_test
|
||||
"${cxx_exception} -DGTEST_ENABLE_CATCH_EXCEPTIONS_=1"
|
||||
gtest test/googletest-death-test_ex_test.cc)
|
||||
|
||||
cxx_test_with_flags(gtest_no_rtti_unittest "${cxx_no_rtti}"
|
||||
gtest_main_no_rtti test/gtest_unittest.cc)
|
||||
|
||||
cxx_shared_library(gtest_dll "${cxx_default}"
|
||||
src/gtest-all.cc src/gtest_main.cc)
|
||||
|
||||
cxx_executable_with_flags(gtest_dll_test_ "${cxx_default}"
|
||||
gtest_dll test/gtest_all_test.cc)
|
||||
set_target_properties(gtest_dll_test_
|
||||
PROPERTIES
|
||||
COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1")
|
||||
|
||||
############################################################
|
||||
# Python tests.
|
||||
|
||||
cxx_executable(googletest-break-on-failure-unittest_ test gtest)
|
||||
py_test(googletest-break-on-failure-unittest)
|
||||
|
||||
py_test(gtest_skip_environment_check_output_test)
|
||||
|
||||
# Visual Studio .NET 2003 does not support STL with exceptions disabled.
|
||||
if (NOT MSVC OR MSVC_VERSION GREATER 1310) # 1310 is Visual Studio .NET 2003
|
||||
cxx_executable_with_flags(
|
||||
googletest-catch-exceptions-no-ex-test_
|
||||
"${cxx_no_exception}"
|
||||
gtest_main_no_exception
|
||||
test/googletest-catch-exceptions-test_.cc)
|
||||
endif()
|
||||
|
||||
cxx_executable_with_flags(
|
||||
googletest-catch-exceptions-ex-test_
|
||||
"${cxx_exception}"
|
||||
gtest_main
|
||||
test/googletest-catch-exceptions-test_.cc)
|
||||
py_test(googletest-catch-exceptions-test)
|
||||
|
||||
cxx_executable(googletest-color-test_ test gtest)
|
||||
py_test(googletest-color-test)
|
||||
|
||||
cxx_executable(googletest-env-var-test_ test gtest)
|
||||
py_test(googletest-env-var-test)
|
||||
|
||||
cxx_executable(googletest-filter-unittest_ test gtest)
|
||||
py_test(googletest-filter-unittest)
|
||||
|
||||
cxx_executable(gtest_help_test_ test gtest_main)
|
||||
py_test(gtest_help_test)
|
||||
|
||||
cxx_executable(googletest-list-tests-unittest_ test gtest)
|
||||
py_test(googletest-list-tests-unittest)
|
||||
|
||||
cxx_executable(googletest-output-test_ test gtest)
|
||||
py_test(googletest-output-test --no_stacktrace_support)
|
||||
|
||||
cxx_executable(googletest-shuffle-test_ test gtest)
|
||||
py_test(googletest-shuffle-test)
|
||||
|
||||
# MSVC 7.1 does not support STL with exceptions disabled.
|
||||
if (NOT MSVC OR MSVC_VERSION GREATER 1310)
|
||||
cxx_executable(googletest-throw-on-failure-test_ test gtest_no_exception)
|
||||
set_target_properties(googletest-throw-on-failure-test_
|
||||
PROPERTIES
|
||||
COMPILE_FLAGS "${cxx_no_exception}")
|
||||
py_test(googletest-throw-on-failure-test)
|
||||
endif()
|
||||
|
||||
cxx_executable(googletest-uninitialized-test_ test gtest)
|
||||
py_test(googletest-uninitialized-test)
|
||||
|
||||
cxx_executable(gtest_xml_outfile1_test_ test gtest_main)
|
||||
cxx_executable(gtest_xml_outfile2_test_ test gtest_main)
|
||||
py_test(gtest_xml_outfiles_test)
|
||||
py_test(googletest-json-outfiles-test)
|
||||
|
||||
cxx_executable(gtest_xml_output_unittest_ test gtest)
|
||||
py_test(gtest_xml_output_unittest --no_stacktrace_support)
|
||||
py_test(googletest-json-output-unittest --no_stacktrace_support)
|
||||
endif()
|
37
3rdparty/gtest/CONTRIBUTORS
vendored
Normal file
37
3rdparty/gtest/CONTRIBUTORS
vendored
Normal file
@ -0,0 +1,37 @@
|
||||
# This file contains a list of people who've made non-trivial
|
||||
# contribution to the Google C++ Testing Framework project. People
|
||||
# who commit code to the project are encouraged to add their names
|
||||
# here. Please keep the list sorted by first names.
|
||||
|
||||
Ajay Joshi <jaj@google.com>
|
||||
Balázs Dán <balazs.dan@gmail.com>
|
||||
Bharat Mediratta <bharat@menalto.com>
|
||||
Chandler Carruth <chandlerc@google.com>
|
||||
Chris Prince <cprince@google.com>
|
||||
Chris Taylor <taylorc@google.com>
|
||||
Dan Egnor <egnor@google.com>
|
||||
Eric Roman <eroman@chromium.org>
|
||||
Hady Zalek <hady.zalek@gmail.com>
|
||||
Jeffrey Yasskin <jyasskin@google.com>
|
||||
Jói Sigurðsson <joi@google.com>
|
||||
Keir Mierle <mierle@gmail.com>
|
||||
Keith Ray <keith.ray@gmail.com>
|
||||
Kenton Varda <kenton@google.com>
|
||||
Manuel Klimek <klimek@google.com>
|
||||
Markus Heule <markus.heule@gmail.com>
|
||||
Mika Raento <mikie@iki.fi>
|
||||
Miklós Fazekas <mfazekas@szemafor.com>
|
||||
Pasi Valminen <pasi.valminen@gmail.com>
|
||||
Patrick Hanna <phanna@google.com>
|
||||
Patrick Riley <pfr@google.com>
|
||||
Peter Kaminski <piotrk@google.com>
|
||||
Preston Jackson <preston.a.jackson@gmail.com>
|
||||
Rainer Klaffenboeck <rainer.klaffenboeck@dynatrace.com>
|
||||
Russ Cox <rsc@google.com>
|
||||
Russ Rufer <russ@pentad.com>
|
||||
Sean Mcafee <eefacm@gmail.com>
|
||||
Sigurður Ásgeirsson <siggi@google.com>
|
||||
Tracy Bialik <tracy@pentad.com>
|
||||
Vadim Berman <vadimb@google.com>
|
||||
Vlad Losev <vladl@google.com>
|
||||
Zhanyong Wan <wan@google.com>
|
28
3rdparty/gtest/LICENSE
vendored
Normal file
28
3rdparty/gtest/LICENSE
vendored
Normal file
@ -0,0 +1,28 @@
|
||||
Copyright 2008, 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.
|
244
3rdparty/gtest/README.md
vendored
Normal file
244
3rdparty/gtest/README.md
vendored
Normal file
@ -0,0 +1,244 @@
|
||||
### Generic Build Instructions
|
||||
|
||||
#### Setup
|
||||
|
||||
To build Google Test and your tests that use it, you need to tell your build
|
||||
system where to find its headers and source files. The exact way to do it
|
||||
depends on which build system you use, and is usually straightforward.
|
||||
|
||||
### Build with CMake
|
||||
|
||||
Google Test comes with a CMake build script (
|
||||
[CMakeLists.txt](https://github.com/google/googletest/blob/master/CMakeLists.txt))
|
||||
that can be used on a wide range of platforms ("C" stands for cross-platform.).
|
||||
If you don't have CMake installed already, you can download it for free from
|
||||
<http://www.cmake.org/>.
|
||||
|
||||
CMake works by generating native makefiles or build projects that can be used in
|
||||
the compiler environment of your choice. You can either build Google Test as a
|
||||
standalone project or it can be incorporated into an existing CMake build for
|
||||
another project.
|
||||
|
||||
#### Standalone CMake Project
|
||||
|
||||
When building Google Test as a standalone project, the typical workflow starts
|
||||
with:
|
||||
|
||||
mkdir mybuild # Create a directory to hold the build output.
|
||||
cd mybuild
|
||||
cmake ${GTEST_DIR} # Generate native build scripts.
|
||||
|
||||
If you want to build Google Test's samples, you should replace the last command
|
||||
with
|
||||
|
||||
cmake -Dgtest_build_samples=ON ${GTEST_DIR}
|
||||
|
||||
If you are on a \*nix system, you should now see a Makefile in the current
|
||||
directory. Just type 'make' to build gtest.
|
||||
|
||||
If you use Windows and have Visual Studio installed, a `gtest.sln` file and
|
||||
several `.vcproj` files will be created. You can then build them using Visual
|
||||
Studio.
|
||||
|
||||
On Mac OS X with Xcode installed, a `.xcodeproj` file will be generated.
|
||||
|
||||
#### Incorporating Into An Existing CMake Project
|
||||
|
||||
If you want to use gtest in a project which already uses CMake, then a more
|
||||
robust and flexible approach is to build gtest as part of that project directly.
|
||||
This is done by making the GoogleTest source code available to the main build
|
||||
and adding it using CMake's `add_subdirectory()` command. This has the
|
||||
significant advantage that the same compiler and linker settings are used
|
||||
between gtest and the rest of your project, so issues associated with using
|
||||
incompatible libraries (eg debug/release), etc. are avoided. This is
|
||||
particularly useful on Windows. Making GoogleTest's source code available to the
|
||||
main build can be done a few different ways:
|
||||
|
||||
* Download the GoogleTest source code manually and place it at a known
|
||||
location. This is the least flexible approach and can make it more difficult
|
||||
to use with continuous integration systems, etc.
|
||||
* Embed the GoogleTest source code as a direct copy in the main project's
|
||||
source tree. This is often the simplest approach, but is also the hardest to
|
||||
keep up to date. Some organizations may not permit this method.
|
||||
* Add GoogleTest as a git submodule or equivalent. This may not always be
|
||||
possible or appropriate. Git submodules, for example, have their own set of
|
||||
advantages and drawbacks.
|
||||
* Use CMake to download GoogleTest as part of the build's configure step. This
|
||||
is just a little more complex, but doesn't have the limitations of the other
|
||||
methods.
|
||||
|
||||
The last of the above methods is implemented with a small piece of CMake code in
|
||||
a separate file (e.g. `CMakeLists.txt.in`) which is copied to the build area and
|
||||
then invoked as a sub-build _during the CMake stage_. That directory is then
|
||||
pulled into the main build with `add_subdirectory()`. For example:
|
||||
|
||||
New file `CMakeLists.txt.in`:
|
||||
|
||||
```cmake
|
||||
cmake_minimum_required(VERSION 2.8.2)
|
||||
|
||||
project(googletest-download NONE)
|
||||
|
||||
include(ExternalProject)
|
||||
ExternalProject_Add(googletest
|
||||
GIT_REPOSITORY https://github.com/google/googletest.git
|
||||
GIT_TAG master
|
||||
SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/googletest-src"
|
||||
BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/googletest-build"
|
||||
CONFIGURE_COMMAND ""
|
||||
BUILD_COMMAND ""
|
||||
INSTALL_COMMAND ""
|
||||
TEST_COMMAND ""
|
||||
)
|
||||
```
|
||||
|
||||
Existing build's `CMakeLists.txt`:
|
||||
|
||||
```cmake
|
||||
# Download and unpack googletest at configure time
|
||||
configure_file(CMakeLists.txt.in googletest-download/CMakeLists.txt)
|
||||
execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" .
|
||||
RESULT_VARIABLE result
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download )
|
||||
if(result)
|
||||
message(FATAL_ERROR "CMake step for googletest failed: ${result}")
|
||||
endif()
|
||||
execute_process(COMMAND ${CMAKE_COMMAND} --build .
|
||||
RESULT_VARIABLE result
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download )
|
||||
if(result)
|
||||
message(FATAL_ERROR "Build step for googletest failed: ${result}")
|
||||
endif()
|
||||
|
||||
# Prevent overriding the parent project's compiler/linker
|
||||
# settings on Windows
|
||||
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
|
||||
|
||||
# Add googletest directly to our build. This defines
|
||||
# the gtest and gtest_main targets.
|
||||
add_subdirectory(${CMAKE_CURRENT_BINARY_DIR}/googletest-src
|
||||
${CMAKE_CURRENT_BINARY_DIR}/googletest-build
|
||||
EXCLUDE_FROM_ALL)
|
||||
|
||||
# The gtest/gtest_main targets carry header search path
|
||||
# dependencies automatically when using CMake 2.8.11 or
|
||||
# later. Otherwise we have to add them here ourselves.
|
||||
if (CMAKE_VERSION VERSION_LESS 2.8.11)
|
||||
include_directories("${gtest_SOURCE_DIR}/include")
|
||||
endif()
|
||||
|
||||
# Now simply link against gtest or gtest_main as needed. Eg
|
||||
add_executable(example example.cpp)
|
||||
target_link_libraries(example gtest_main)
|
||||
add_test(NAME example_test COMMAND example)
|
||||
```
|
||||
|
||||
Note that this approach requires CMake 2.8.2 or later due to its use of the
|
||||
`ExternalProject_Add()` command. The above technique is discussed in more detail
|
||||
in [this separate article](http://crascit.com/2015/07/25/cmake-gtest/) which
|
||||
also contains a link to a fully generalized implementation of the technique.
|
||||
|
||||
##### Visual Studio Dynamic vs Static Runtimes
|
||||
|
||||
By default, new Visual Studio projects link the C runtimes dynamically but
|
||||
Google Test links them statically. This will generate an error that looks
|
||||
something like the following: gtest.lib(gtest-all.obj) : error LNK2038: mismatch
|
||||
detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value
|
||||
'MDd_DynamicDebug' in main.obj
|
||||
|
||||
Google Test already has a CMake option for this: `gtest_force_shared_crt`
|
||||
|
||||
Enabling this option will make gtest link the runtimes dynamically too, and
|
||||
match the project in which it is included.
|
||||
|
||||
#### C++ Standard Version
|
||||
|
||||
An environment that supports C++11 is required in order to successfully build
|
||||
Google Test. One way to ensure this is to specify the standard in the top-level
|
||||
project, for example by using the `set(CMAKE_CXX_STANDARD 11)` command. If this
|
||||
is not feasible, for example in a C project using Google Test for validation,
|
||||
then it can be specified by adding it to the options for cmake via the
|
||||
`DCMAKE_CXX_FLAGS` option.
|
||||
|
||||
### Tweaking Google Test
|
||||
|
||||
Google Test can be used in diverse environments. The default configuration may
|
||||
not work (or may not work well) out of the box in some environments. However,
|
||||
you can easily tweak Google Test by defining control macros on the compiler
|
||||
command line. Generally, these macros are named like `GTEST_XYZ` and you define
|
||||
them to either 1 or 0 to enable or disable a certain feature.
|
||||
|
||||
We list the most frequently used macros below. For a complete list, see file
|
||||
[include/gtest/internal/gtest-port.h](https://github.com/google/googletest/blob/master/googletest/include/gtest/internal/gtest-port.h).
|
||||
|
||||
### Multi-threaded Tests
|
||||
|
||||
Google Test is thread-safe where the pthread library is available. After
|
||||
`#include "gtest/gtest.h"`, you can check the
|
||||
`GTEST_IS_THREADSAFE` macro to see whether this is the case (yes if the macro is
|
||||
`#defined` to 1, no if it's undefined.).
|
||||
|
||||
If Google Test doesn't correctly detect whether pthread is available in your
|
||||
environment, you can force it with
|
||||
|
||||
-DGTEST_HAS_PTHREAD=1
|
||||
|
||||
or
|
||||
|
||||
-DGTEST_HAS_PTHREAD=0
|
||||
|
||||
When Google Test uses pthread, you may need to add flags to your compiler and/or
|
||||
linker to select the pthread library, or you'll get link errors. If you use the
|
||||
CMake script or the deprecated Autotools script, this is taken care of for you.
|
||||
If you use your own build script, you'll need to read your compiler and linker's
|
||||
manual to figure out what flags to add.
|
||||
|
||||
### As a Shared Library (DLL)
|
||||
|
||||
Google Test is compact, so most users can build and link it as a static library
|
||||
for the simplicity. You can choose to use Google Test as a shared library (known
|
||||
as a DLL on Windows) if you prefer.
|
||||
|
||||
To compile *gtest* as a shared library, add
|
||||
|
||||
-DGTEST_CREATE_SHARED_LIBRARY=1
|
||||
|
||||
to the compiler flags. You'll also need to tell the linker to produce a shared
|
||||
library instead - consult your linker's manual for how to do it.
|
||||
|
||||
To compile your *tests* that use the gtest shared library, add
|
||||
|
||||
-DGTEST_LINKED_AS_SHARED_LIBRARY=1
|
||||
|
||||
to the compiler flags.
|
||||
|
||||
Note: while the above steps aren't technically necessary today when using some
|
||||
compilers (e.g. GCC), they may become necessary in the future, if we decide to
|
||||
improve the speed of loading the library (see
|
||||
<http://gcc.gnu.org/wiki/Visibility> for details). Therefore you are recommended
|
||||
to always add the above flags when using Google Test as a shared library.
|
||||
Otherwise a future release of Google Test may break your build script.
|
||||
|
||||
### Avoiding Macro Name Clashes
|
||||
|
||||
In C++, macros don't obey namespaces. Therefore two libraries that both define a
|
||||
macro of the same name will clash if you `#include` both definitions. In case a
|
||||
Google Test macro clashes with another library, you can force Google Test to
|
||||
rename its macro to avoid the conflict.
|
||||
|
||||
Specifically, if both Google Test and some other code define macro FOO, you can
|
||||
add
|
||||
|
||||
-DGTEST_DONT_DEFINE_FOO=1
|
||||
|
||||
to the compiler flags to tell Google Test to change the macro's name from `FOO`
|
||||
to `GTEST_FOO`. Currently `FOO` can be `FAIL`, `SUCCEED`, or `TEST`. For
|
||||
example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write
|
||||
|
||||
GTEST_TEST(SomeTest, DoesThis) { ... }
|
||||
|
||||
instead of
|
||||
|
||||
TEST(SomeTest, DoesThis) { ... }
|
||||
|
||||
in order to define a test.
|
9
3rdparty/gtest/cmake/Config.cmake.in
vendored
Normal file
9
3rdparty/gtest/cmake/Config.cmake.in
vendored
Normal file
@ -0,0 +1,9 @@
|
||||
@PACKAGE_INIT@
|
||||
include(CMakeFindDependencyMacro)
|
||||
if (@GTEST_HAS_PTHREAD@)
|
||||
set(THREADS_PREFER_PTHREAD_FLAG @THREADS_PREFER_PTHREAD_FLAG@)
|
||||
find_dependency(Threads)
|
||||
endif()
|
||||
|
||||
include("${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake")
|
||||
check_required_components("@project_name@")
|
10
3rdparty/gtest/cmake/gtest.pc.in
vendored
Normal file
10
3rdparty/gtest/cmake/gtest.pc.in
vendored
Normal file
@ -0,0 +1,10 @@
|
||||
prefix=${pcfiledir}/../..
|
||||
libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@
|
||||
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
|
||||
|
||||
Name: gtest
|
||||
Description: GoogleTest (without main() function)
|
||||
Version: @PROJECT_VERSION@
|
||||
URL: https://github.com/google/googletest
|
||||
Libs: -L${libdir} -lgtest @CMAKE_THREAD_LIBS_INIT@
|
||||
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@
|
11
3rdparty/gtest/cmake/gtest_main.pc.in
vendored
Normal file
11
3rdparty/gtest/cmake/gtest_main.pc.in
vendored
Normal file
@ -0,0 +1,11 @@
|
||||
prefix=${pcfiledir}/../..
|
||||
libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@
|
||||
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
|
||||
|
||||
Name: gtest_main
|
||||
Description: GoogleTest (with main() function)
|
||||
Version: @PROJECT_VERSION@
|
||||
URL: https://github.com/google/googletest
|
||||
Requires: gtest
|
||||
Libs: -L${libdir} -lgtest_main @CMAKE_THREAD_LIBS_INIT@
|
||||
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@
|
358
3rdparty/gtest/cmake/internal_utils.cmake
vendored
Normal file
358
3rdparty/gtest/cmake/internal_utils.cmake
vendored
Normal file
@ -0,0 +1,358 @@
|
||||
# Defines functions and macros useful for building Google Test and
|
||||
# Google Mock.
|
||||
#
|
||||
# Note:
|
||||
#
|
||||
# - This file will be run twice when building Google Mock (once via
|
||||
# Google Test's CMakeLists.txt, and once via Google Mock's).
|
||||
# Therefore it shouldn't have any side effects other than defining
|
||||
# the functions and macros.
|
||||
#
|
||||
# - The functions/macros defined in this file may depend on Google
|
||||
# Test and Google Mock's option() definitions, and thus must be
|
||||
# called *after* the options have been defined.
|
||||
|
||||
if (POLICY CMP0054)
|
||||
cmake_policy(SET CMP0054 NEW)
|
||||
endif (POLICY CMP0054)
|
||||
|
||||
# Tweaks CMake's default compiler/linker settings to suit Google Test's needs.
|
||||
#
|
||||
# This must be a macro(), as inside a function string() can only
|
||||
# update variables in the function scope.
|
||||
macro(fix_default_compiler_settings_)
|
||||
if (MSVC)
|
||||
# For MSVC, CMake sets certain flags to defaults we want to override.
|
||||
# This replacement code is taken from sample in the CMake Wiki at
|
||||
# https://gitlab.kitware.com/cmake/community/wikis/FAQ#dynamic-replace.
|
||||
foreach (flag_var
|
||||
CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE
|
||||
CMAKE_C_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELWITHDEBINFO
|
||||
CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
|
||||
CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
|
||||
if (NOT BUILD_SHARED_LIBS AND NOT gtest_force_shared_crt)
|
||||
# When Google Test is built as a shared library, it should also use
|
||||
# shared runtime libraries. Otherwise, it may end up with multiple
|
||||
# copies of runtime library data in different modules, resulting in
|
||||
# hard-to-find crashes. When it is built as a static library, it is
|
||||
# preferable to use CRT as static libraries, as we don't have to rely
|
||||
# on CRT DLLs being available. CMake always defaults to using shared
|
||||
# CRT libraries, so we override that default here.
|
||||
string(REPLACE "/MD" "-MT" ${flag_var} "${${flag_var}}")
|
||||
endif()
|
||||
|
||||
# We prefer more strict warning checking for building Google Test.
|
||||
# Replaces /W3 with /W4 in defaults.
|
||||
string(REPLACE "/W3" "/W4" ${flag_var} "${${flag_var}}")
|
||||
|
||||
# Prevent D9025 warning for targets that have exception handling
|
||||
# turned off (/EHs-c- flag). Where required, exceptions are explicitly
|
||||
# re-enabled using the cxx_exception_flags variable.
|
||||
string(REPLACE "/EHsc" "" ${flag_var} "${${flag_var}}")
|
||||
endforeach()
|
||||
endif()
|
||||
endmacro()
|
||||
|
||||
# Defines the compiler/linker flags used to build Google Test and
|
||||
# Google Mock. You can tweak these definitions to suit your need. A
|
||||
# variable's value is empty before it's explicitly assigned to.
|
||||
macro(config_compiler_and_linker)
|
||||
# Note: pthreads on MinGW is not supported, even if available
|
||||
# instead, we use windows threading primitives
|
||||
unset(GTEST_HAS_PTHREAD)
|
||||
if (NOT gtest_disable_pthreads AND NOT MINGW)
|
||||
# Defines CMAKE_USE_PTHREADS_INIT and CMAKE_THREAD_LIBS_INIT.
|
||||
find_package(Threads)
|
||||
if (CMAKE_USE_PTHREADS_INIT)
|
||||
set(GTEST_HAS_PTHREAD ON)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
fix_default_compiler_settings_()
|
||||
if (MSVC)
|
||||
# Newlines inside flags variables break CMake's NMake generator.
|
||||
# TODO(vladl@google.com): Add -RTCs and -RTCu to debug builds.
|
||||
set(cxx_base_flags "-GS -W4 -WX -wd4251 -wd4275 -nologo -J -Zi")
|
||||
set(cxx_base_flags "${cxx_base_flags} -D_UNICODE -DUNICODE -DWIN32 -D_WIN32")
|
||||
set(cxx_base_flags "${cxx_base_flags} -DSTRICT -DWIN32_LEAN_AND_MEAN")
|
||||
set(cxx_exception_flags "-EHsc -D_HAS_EXCEPTIONS=1")
|
||||
set(cxx_no_exception_flags "-EHs-c- -D_HAS_EXCEPTIONS=0")
|
||||
set(cxx_no_rtti_flags "-GR-")
|
||||
# Suppress "unreachable code" warning
|
||||
# http://stackoverflow.com/questions/3232669 explains the issue.
|
||||
set(cxx_base_flags "${cxx_base_flags} -wd4702")
|
||||
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
|
||||
set(cxx_base_flags "-Wall -Wshadow -Werror -Wconversion")
|
||||
set(cxx_exception_flags "-fexceptions")
|
||||
set(cxx_no_exception_flags "-fno-exceptions")
|
||||
set(cxx_strict_flags "-W -Wpointer-arith -Wreturn-type -Wcast-qual -Wwrite-strings -Wswitch -Wunused-parameter -Wcast-align -Wchar-subscripts -Winline -Wredundant-decls")
|
||||
set(cxx_no_rtti_flags "-fno-rtti")
|
||||
elseif (CMAKE_COMPILER_IS_GNUCXX)
|
||||
set(cxx_base_flags "-Wall -Wshadow -Werror")
|
||||
if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.0.0)
|
||||
set(cxx_base_flags "${cxx_base_flags} -Wno-error=dangling-else")
|
||||
endif()
|
||||
set(cxx_exception_flags "-fexceptions")
|
||||
set(cxx_no_exception_flags "-fno-exceptions")
|
||||
# Until version 4.3.2, GCC doesn't define a macro to indicate
|
||||
# whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI
|
||||
# explicitly.
|
||||
set(cxx_no_rtti_flags "-fno-rtti -DGTEST_HAS_RTTI=0")
|
||||
set(cxx_strict_flags
|
||||
"-Wextra -Wno-unused-parameter -Wno-missing-field-initializers")
|
||||
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "SunPro")
|
||||
set(cxx_exception_flags "-features=except")
|
||||
# Sun Pro doesn't provide macros to indicate whether exceptions and
|
||||
# RTTI are enabled, so we define GTEST_HAS_* explicitly.
|
||||
set(cxx_no_exception_flags "-features=no%except -DGTEST_HAS_EXCEPTIONS=0")
|
||||
set(cxx_no_rtti_flags "-features=no%rtti -DGTEST_HAS_RTTI=0")
|
||||
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "VisualAge" OR
|
||||
CMAKE_CXX_COMPILER_ID STREQUAL "XL")
|
||||
# CMake 2.8 changes Visual Age's compiler ID to "XL".
|
||||
set(cxx_exception_flags "-qeh")
|
||||
set(cxx_no_exception_flags "-qnoeh")
|
||||
# Until version 9.0, Visual Age doesn't define a macro to indicate
|
||||
# whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI
|
||||
# explicitly.
|
||||
set(cxx_no_rtti_flags "-qnortti -DGTEST_HAS_RTTI=0")
|
||||
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "HP")
|
||||
set(cxx_base_flags "-AA -mt")
|
||||
set(cxx_exception_flags "-DGTEST_HAS_EXCEPTIONS=1")
|
||||
set(cxx_no_exception_flags "+noeh -DGTEST_HAS_EXCEPTIONS=0")
|
||||
# RTTI can not be disabled in HP aCC compiler.
|
||||
set(cxx_no_rtti_flags "")
|
||||
endif()
|
||||
|
||||
# The pthreads library is available and allowed?
|
||||
if (DEFINED GTEST_HAS_PTHREAD)
|
||||
set(GTEST_HAS_PTHREAD_MACRO "-DGTEST_HAS_PTHREAD=1")
|
||||
else()
|
||||
set(GTEST_HAS_PTHREAD_MACRO "-DGTEST_HAS_PTHREAD=0")
|
||||
endif()
|
||||
set(cxx_base_flags "${cxx_base_flags} ${GTEST_HAS_PTHREAD_MACRO}")
|
||||
|
||||
# For building gtest's own tests and samples.
|
||||
set(cxx_exception "${cxx_base_flags} ${cxx_exception_flags}")
|
||||
set(cxx_no_exception
|
||||
"${CMAKE_CXX_FLAGS} ${cxx_base_flags} ${cxx_no_exception_flags}")
|
||||
set(cxx_default "${cxx_exception}")
|
||||
set(cxx_no_rtti "${cxx_default} ${cxx_no_rtti_flags}")
|
||||
|
||||
# For building the gtest libraries.
|
||||
set(cxx_strict "${cxx_default} ${cxx_strict_flags}")
|
||||
endmacro()
|
||||
|
||||
# Defines the gtest & gtest_main libraries. User tests should link
|
||||
# with one of them.
|
||||
function(cxx_library_with_type name type cxx_flags)
|
||||
# type can be either STATIC or SHARED to denote a static or shared library.
|
||||
# ARGN refers to additional arguments after 'cxx_flags'.
|
||||
add_library(${name} ${type} ${ARGN})
|
||||
set_target_properties(${name}
|
||||
PROPERTIES
|
||||
COMPILE_FLAGS "${cxx_flags}")
|
||||
# Generate debug library name with a postfix.
|
||||
set_target_properties(${name}
|
||||
PROPERTIES
|
||||
DEBUG_POSTFIX "d")
|
||||
# Set the output directory for build artifacts
|
||||
set_target_properties(${name}
|
||||
PROPERTIES
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
|
||||
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
|
||||
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
|
||||
PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
# make PDBs match library name
|
||||
get_target_property(pdb_debug_postfix ${name} DEBUG_POSTFIX)
|
||||
set_target_properties(${name}
|
||||
PROPERTIES
|
||||
PDB_NAME "${name}"
|
||||
PDB_NAME_DEBUG "${name}${pdb_debug_postfix}"
|
||||
COMPILE_PDB_NAME "${name}"
|
||||
COMPILE_PDB_NAME_DEBUG "${name}${pdb_debug_postfix}")
|
||||
|
||||
if (BUILD_SHARED_LIBS OR type STREQUAL "SHARED")
|
||||
set_target_properties(${name}
|
||||
PROPERTIES
|
||||
COMPILE_DEFINITIONS "GTEST_CREATE_SHARED_LIBRARY=1")
|
||||
if (NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11")
|
||||
target_compile_definitions(${name} INTERFACE
|
||||
$<INSTALL_INTERFACE:GTEST_LINKED_AS_SHARED_LIBRARY=1>)
|
||||
endif()
|
||||
endif()
|
||||
if (DEFINED GTEST_HAS_PTHREAD)
|
||||
if ("${CMAKE_VERSION}" VERSION_LESS "3.1.0")
|
||||
set(threads_spec ${CMAKE_THREAD_LIBS_INIT})
|
||||
else()
|
||||
set(threads_spec Threads::Threads)
|
||||
endif()
|
||||
target_link_libraries(${name} PUBLIC ${threads_spec})
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
########################################################################
|
||||
#
|
||||
# Helper functions for creating build targets.
|
||||
|
||||
function(cxx_shared_library name cxx_flags)
|
||||
cxx_library_with_type(${name} SHARED "${cxx_flags}" ${ARGN})
|
||||
endfunction()
|
||||
|
||||
function(cxx_library name cxx_flags)
|
||||
cxx_library_with_type(${name} "" "${cxx_flags}" ${ARGN})
|
||||
endfunction()
|
||||
|
||||
# cxx_executable_with_flags(name cxx_flags libs srcs...)
|
||||
#
|
||||
# creates a named C++ executable that depends on the given libraries and
|
||||
# is built from the given source files with the given compiler flags.
|
||||
function(cxx_executable_with_flags name cxx_flags libs)
|
||||
add_executable(${name} ${ARGN})
|
||||
if (MSVC)
|
||||
# BigObj required for tests.
|
||||
set(cxx_flags "${cxx_flags} -bigobj")
|
||||
endif()
|
||||
if (cxx_flags)
|
||||
set_target_properties(${name}
|
||||
PROPERTIES
|
||||
COMPILE_FLAGS "${cxx_flags}")
|
||||
endif()
|
||||
if (BUILD_SHARED_LIBS)
|
||||
set_target_properties(${name}
|
||||
PROPERTIES
|
||||
COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1")
|
||||
endif()
|
||||
# To support mixing linking in static and dynamic libraries, link each
|
||||
# library in with an extra call to target_link_libraries.
|
||||
foreach (lib "${libs}")
|
||||
target_link_libraries(${name} ${lib})
|
||||
endforeach()
|
||||
endfunction()
|
||||
|
||||
# cxx_executable(name dir lib srcs...)
|
||||
#
|
||||
# creates a named target that depends on the given libs and is built
|
||||
# from the given source files. dir/name.cc is implicitly included in
|
||||
# the source file list.
|
||||
function(cxx_executable name dir libs)
|
||||
cxx_executable_with_flags(
|
||||
${name} "${cxx_default}" "${libs}" "${dir}/${name}.cc" ${ARGN})
|
||||
endfunction()
|
||||
|
||||
# Sets PYTHONINTERP_FOUND and PYTHON_EXECUTABLE.
|
||||
find_package(PythonInterp)
|
||||
|
||||
# cxx_test_with_flags(name cxx_flags libs srcs...)
|
||||
#
|
||||
# creates a named C++ test that depends on the given libs and is built
|
||||
# from the given source files with the given compiler flags.
|
||||
function(cxx_test_with_flags name cxx_flags libs)
|
||||
cxx_executable_with_flags(${name} "${cxx_flags}" "${libs}" ${ARGN})
|
||||
if (WIN32 OR MINGW)
|
||||
add_test(NAME ${name}
|
||||
COMMAND "powershell" "-Command" "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>/RunTest.ps1" "$<TARGET_FILE:${name}>")
|
||||
else()
|
||||
add_test(NAME ${name}
|
||||
COMMAND "$<TARGET_FILE:${name}>")
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
# cxx_test(name libs srcs...)
|
||||
#
|
||||
# creates a named test target that depends on the given libs and is
|
||||
# built from the given source files. Unlike cxx_test_with_flags,
|
||||
# test/name.cc is already implicitly included in the source file list.
|
||||
function(cxx_test name libs)
|
||||
cxx_test_with_flags("${name}" "${cxx_default}" "${libs}"
|
||||
"test/${name}.cc" ${ARGN})
|
||||
endfunction()
|
||||
|
||||
# py_test(name)
|
||||
#
|
||||
# creates a Python test with the given name whose main module is in
|
||||
# test/name.py. It does nothing if Python is not installed.
|
||||
function(py_test name)
|
||||
if (PYTHONINTERP_FOUND)
|
||||
if ("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" VERSION_GREATER 3.1)
|
||||
if (CMAKE_CONFIGURATION_TYPES)
|
||||
# Multi-configuration build generators as for Visual Studio save
|
||||
# output in a subdirectory of CMAKE_CURRENT_BINARY_DIR (Debug,
|
||||
# Release etc.), so we have to provide it here.
|
||||
if (WIN32 OR MINGW)
|
||||
add_test(NAME ${name}
|
||||
COMMAND powershell -Command ${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>/RunTest.ps1
|
||||
${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
|
||||
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG> ${ARGN})
|
||||
else()
|
||||
add_test(NAME ${name}
|
||||
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
|
||||
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG> ${ARGN})
|
||||
endif()
|
||||
else (CMAKE_CONFIGURATION_TYPES)
|
||||
# Single-configuration build generators like Makefile generators
|
||||
# don't have subdirs below CMAKE_CURRENT_BINARY_DIR.
|
||||
if (WIN32 OR MINGW)
|
||||
add_test(NAME ${name}
|
||||
COMMAND powershell -Command ${CMAKE_CURRENT_BINARY_DIR}/RunTest.ps1
|
||||
${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
|
||||
--build_dir=${CMAKE_CURRENT_BINARY_DIR} ${ARGN})
|
||||
else()
|
||||
add_test(NAME ${name}
|
||||
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
|
||||
--build_dir=${CMAKE_CURRENT_BINARY_DIR} ${ARGN})
|
||||
endif()
|
||||
endif (CMAKE_CONFIGURATION_TYPES)
|
||||
else()
|
||||
# ${CMAKE_CURRENT_BINARY_DIR} is known at configuration time, so we can
|
||||
# directly bind it from cmake. ${CTEST_CONFIGURATION_TYPE} is known
|
||||
# only at ctest runtime (by calling ctest -c <Configuration>), so
|
||||
# we have to escape $ to delay variable substitution here.
|
||||
if (WIN32 OR MINGW)
|
||||
add_test(NAME ${name}
|
||||
COMMAND powershell -Command ${CMAKE_CURRENT_BINARY_DIR}/RunTest.ps1
|
||||
${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
|
||||
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE} ${ARGN})
|
||||
else()
|
||||
add_test(NAME ${name}
|
||||
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
|
||||
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE} ${ARGN})
|
||||
endif()
|
||||
endif()
|
||||
endif(PYTHONINTERP_FOUND)
|
||||
endfunction()
|
||||
|
||||
# install_project(targets...)
|
||||
#
|
||||
# Installs the specified targets and configures the associated pkgconfig files.
|
||||
function(install_project)
|
||||
if(INSTALL_GTEST)
|
||||
install(DIRECTORY "${PROJECT_SOURCE_DIR}/include/"
|
||||
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
|
||||
# Install the project targets.
|
||||
install(TARGETS ${ARGN}
|
||||
EXPORT ${targets_export_name}
|
||||
RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
|
||||
ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
|
||||
LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}")
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
|
||||
# Install PDBs
|
||||
foreach(t ${ARGN})
|
||||
get_target_property(t_pdb_name ${t} COMPILE_PDB_NAME)
|
||||
get_target_property(t_pdb_name_debug ${t} COMPILE_PDB_NAME_DEBUG)
|
||||
get_target_property(t_pdb_output_directory ${t} PDB_OUTPUT_DIRECTORY)
|
||||
install(FILES
|
||||
"${t_pdb_output_directory}/\${CMAKE_INSTALL_CONFIG_NAME}/$<$<CONFIG:Debug>:${t_pdb_name_debug}>$<$<NOT:$<CONFIG:Debug>>:${t_pdb_name}>.pdb"
|
||||
DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
OPTIONAL)
|
||||
endforeach()
|
||||
endif()
|
||||
# Configure and install pkgconfig files.
|
||||
foreach(t ${ARGN})
|
||||
set(configured_pc "${generated_dir}/${t}.pc")
|
||||
configure_file("${PROJECT_SOURCE_DIR}/cmake/${t}.pc.in"
|
||||
"${configured_pc}" @ONLY)
|
||||
install(FILES "${configured_pc}"
|
||||
DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
|
||||
endforeach()
|
||||
endif()
|
||||
endfunction()
|
21
3rdparty/gtest/cmake/libgtest.la.in
vendored
Normal file
21
3rdparty/gtest/cmake/libgtest.la.in
vendored
Normal file
@ -0,0 +1,21 @@
|
||||
# libgtest.la - a libtool library file
|
||||
# Generated by libtool (GNU libtool) 2.4.6
|
||||
|
||||
# Please DO NOT delete this file!
|
||||
# It is necessary for linking the library.
|
||||
|
||||
# Names of this library.
|
||||
library_names='libgtest.so'
|
||||
|
||||
# Is this an already installed library?
|
||||
installed=yes
|
||||
|
||||
# Should we warn about portability when linking against -modules?
|
||||
shouldnotlink=no
|
||||
|
||||
# Files to dlopen/dlpreopen
|
||||
dlopen=''
|
||||
dlpreopen=''
|
||||
|
||||
# Directory that this library needs to be installed in:
|
||||
libdir='@CMAKE_INSTALL_FULL_LIBDIR@'
|
2567
3rdparty/gtest/docs/advanced.md
vendored
Normal file
2567
3rdparty/gtest/docs/advanced.md
vendored
Normal file
File diff suppressed because it is too large
Load Diff
753
3rdparty/gtest/docs/faq.md
vendored
Normal file
753
3rdparty/gtest/docs/faq.md
vendored
Normal file
@ -0,0 +1,753 @@
|
||||
# Googletest FAQ
|
||||
|
||||
<!-- GOOGLETEST_CM0014 DO NOT DELETE -->
|
||||
|
||||
## Why should test suite names and test names not contain underscore?
|
||||
|
||||
Underscore (`_`) is special, as C++ reserves the following to be used by the
|
||||
compiler and the standard library:
|
||||
|
||||
1. any identifier that starts with an `_` followed by an upper-case letter, and
|
||||
2. any identifier that contains two consecutive underscores (i.e. `__`)
|
||||
*anywhere* in its name.
|
||||
|
||||
User code is *prohibited* from using such identifiers.
|
||||
|
||||
Now let's look at what this means for `TEST` and `TEST_F`.
|
||||
|
||||
Currently `TEST(TestSuiteName, TestName)` generates a class named
|
||||
`TestSuiteName_TestName_Test`. What happens if `TestSuiteName` or `TestName`
|
||||
contains `_`?
|
||||
|
||||
1. If `TestSuiteName` starts with an `_` followed by an upper-case letter (say,
|
||||
`_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus
|
||||
invalid.
|
||||
2. If `TestSuiteName` ends with an `_` (say, `Foo_`), we get
|
||||
`Foo__TestName_Test`, which is invalid.
|
||||
3. If `TestName` starts with an `_` (say, `_Bar`), we get
|
||||
`TestSuiteName__Bar_Test`, which is invalid.
|
||||
4. If `TestName` ends with an `_` (say, `Bar_`), we get
|
||||
`TestSuiteName_Bar__Test`, which is invalid.
|
||||
|
||||
So clearly `TestSuiteName` and `TestName` cannot start or end with `_`
|
||||
(Actually, `TestSuiteName` can start with `_` -- as long as the `_` isn't
|
||||
followed by an upper-case letter. But that's getting complicated. So for
|
||||
simplicity we just say that it cannot start with `_`.).
|
||||
|
||||
It may seem fine for `TestSuiteName` and `TestName` to contain `_` in the
|
||||
middle. However, consider this:
|
||||
|
||||
```c++
|
||||
TEST(Time, Flies_Like_An_Arrow) { ... }
|
||||
TEST(Time_Flies, Like_An_Arrow) { ... }
|
||||
```
|
||||
|
||||
Now, the two `TEST`s will both generate the same class
|
||||
(`Time_Flies_Like_An_Arrow_Test`). That's not good.
|
||||
|
||||
So for simplicity, we just ask the users to avoid `_` in `TestSuiteName` and
|
||||
`TestName`. The rule is more constraining than necessary, but it's simple and
|
||||
easy to remember. It also gives googletest some wiggle room in case its
|
||||
implementation needs to change in the future.
|
||||
|
||||
If you violate the rule, there may not be immediate consequences, but your test
|
||||
may (just may) break with a new compiler (or a new version of the compiler you
|
||||
are using) or with a new version of googletest. Therefore it's best to follow
|
||||
the rule.
|
||||
|
||||
## Why does googletest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`?
|
||||
|
||||
First of all you can use `EXPECT_NE(nullptr, ptr)` and `ASSERT_NE(nullptr,
|
||||
ptr)`. This is the preferred syntax in the style guide because nullptr does not
|
||||
have the type problems that NULL does. Which is why NULL does not work.
|
||||
|
||||
Due to some peculiarity of C++, it requires some non-trivial template meta
|
||||
programming tricks to support using `NULL` as an argument of the `EXPECT_XX()`
|
||||
and `ASSERT_XX()` macros. Therefore we only do it where it's most needed
|
||||
(otherwise we make the implementation of googletest harder to maintain and more
|
||||
error-prone than necessary).
|
||||
|
||||
The `EXPECT_EQ()` macro takes the *expected* value as its first argument and the
|
||||
*actual* value as the second. It's reasonable that someone wants to write
|
||||
`EXPECT_EQ(NULL, some_expression)`, and this indeed was requested several times.
|
||||
Therefore we implemented it.
|
||||
|
||||
The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the assertion
|
||||
fails, you already know that `ptr` must be `NULL`, so it doesn't add any
|
||||
information to print `ptr` in this case. That means `EXPECT_TRUE(ptr != NULL)`
|
||||
works just as well.
|
||||
|
||||
If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll have to
|
||||
support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`, we don't have a
|
||||
convention on the order of the two arguments for `EXPECT_NE`. This means using
|
||||
the template meta programming tricks twice in the implementation, making it even
|
||||
harder to understand and maintain. We believe the benefit doesn't justify the
|
||||
cost.
|
||||
|
||||
Finally, with the growth of the gMock matcher library, we are encouraging people
|
||||
to use the unified `EXPECT_THAT(value, matcher)` syntax more often in tests. One
|
||||
significant advantage of the matcher approach is that matchers can be easily
|
||||
combined to form new matchers, while the `EXPECT_NE`, etc, macros cannot be
|
||||
easily combined. Therefore we want to invest more in the matchers than in the
|
||||
`EXPECT_XX()` macros.
|
||||
|
||||
## I need to test that different implementations of an interface satisfy some common requirements. Should I use typed tests or value-parameterized tests?
|
||||
|
||||
For testing various implementations of the same interface, either typed tests or
|
||||
value-parameterized tests can get it done. It's really up to you the user to
|
||||
decide which is more convenient for you, depending on your particular case. Some
|
||||
rough guidelines:
|
||||
|
||||
* Typed tests can be easier to write if instances of the different
|
||||
implementations can be created the same way, modulo the type. For example,
|
||||
if all these implementations have a public default constructor (such that
|
||||
you can write `new TypeParam`), or if their factory functions have the same
|
||||
form (e.g. `CreateInstance<TypeParam>()`).
|
||||
* Value-parameterized tests can be easier to write if you need different code
|
||||
patterns to create different implementations' instances, e.g. `new Foo` vs
|
||||
`new Bar(5)`. To accommodate for the differences, you can write factory
|
||||
function wrappers and pass these function pointers to the tests as their
|
||||
parameters.
|
||||
* When a typed test fails, the default output includes the name of the type,
|
||||
which can help you quickly identify which implementation is wrong.
|
||||
Value-parameterized tests only show the number of the failed iteration by
|
||||
default. You will need to define a function that returns the iteration name
|
||||
and pass it as the third parameter to INSTANTIATE_TEST_SUITE_P to have more
|
||||
useful output.
|
||||
* When using typed tests, you need to make sure you are testing against the
|
||||
interface type, not the concrete types (in other words, you want to make
|
||||
sure `implicit_cast<MyInterface*>(my_concrete_impl)` works, not just that
|
||||
`my_concrete_impl` works). It's less likely to make mistakes in this area
|
||||
when using value-parameterized tests.
|
||||
|
||||
I hope I didn't confuse you more. :-) If you don't mind, I'd suggest you to give
|
||||
both approaches a try. Practice is a much better way to grasp the subtle
|
||||
differences between the two tools. Once you have some concrete experience, you
|
||||
can much more easily decide which one to use the next time.
|
||||
|
||||
## I got some run-time errors about invalid proto descriptors when using `ProtocolMessageEquals`. Help!
|
||||
|
||||
**Note:** `ProtocolMessageEquals` and `ProtocolMessageEquiv` are *deprecated*
|
||||
now. Please use `EqualsProto`, etc instead.
|
||||
|
||||
`ProtocolMessageEquals` and `ProtocolMessageEquiv` were redefined recently and
|
||||
are now less tolerant of invalid protocol buffer definitions. In particular, if
|
||||
you have a `foo.proto` that doesn't fully qualify the type of a protocol message
|
||||
it references (e.g. `message<Bar>` where it should be `message<blah.Bar>`), you
|
||||
will now get run-time errors like:
|
||||
|
||||
```
|
||||
... descriptor.cc:...] Invalid proto descriptor for file "path/to/foo.proto":
|
||||
... descriptor.cc:...] blah.MyMessage.my_field: ".Bar" is not defined.
|
||||
```
|
||||
|
||||
If you see this, your `.proto` file is broken and needs to be fixed by making
|
||||
the types fully qualified. The new definition of `ProtocolMessageEquals` and
|
||||
`ProtocolMessageEquiv` just happen to reveal your bug.
|
||||
|
||||
## My death test modifies some state, but the change seems lost after the death test finishes. Why?
|
||||
|
||||
Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the
|
||||
expected crash won't kill the test program (i.e. the parent process). As a
|
||||
result, any in-memory side effects they incur are observable in their respective
|
||||
sub-processes, but not in the parent process. You can think of them as running
|
||||
in a parallel universe, more or less.
|
||||
|
||||
In particular, if you use mocking and the death test statement invokes some mock
|
||||
methods, the parent process will think the calls have never occurred. Therefore,
|
||||
you may want to move your `EXPECT_CALL` statements inside the `EXPECT_DEATH`
|
||||
macro.
|
||||
|
||||
## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a googletest bug?
|
||||
|
||||
Actually, the bug is in `htonl()`.
|
||||
|
||||
According to `'man htonl'`, `htonl()` is a *function*, which means it's valid to
|
||||
use `htonl` as a function pointer. However, in opt mode `htonl()` is defined as
|
||||
a *macro*, which breaks this usage.
|
||||
|
||||
Worse, the macro definition of `htonl()` uses a `gcc` extension and is *not*
|
||||
standard C++. That hacky implementation has some ad hoc limitations. In
|
||||
particular, it prevents you from writing `Foo<sizeof(htonl(x))>()`, where `Foo`
|
||||
is a template that has an integral argument.
|
||||
|
||||
The implementation of `EXPECT_EQ(a, b)` uses `sizeof(... a ...)` inside a
|
||||
template argument, and thus doesn't compile in opt mode when `a` contains a call
|
||||
to `htonl()`. It is difficult to make `EXPECT_EQ` bypass the `htonl()` bug, as
|
||||
the solution must work with different compilers on various platforms.
|
||||
|
||||
`htonl()` has some other problems as described in `//util/endian/endian.h`,
|
||||
which defines `ghtonl()` to replace it. `ghtonl()` does the same thing `htonl()`
|
||||
does, only without its problems. We suggest you to use `ghtonl()` instead of
|
||||
`htonl()`, both in your tests and production code.
|
||||
|
||||
`//util/endian/endian.h` also defines `ghtons()`, which solves similar problems
|
||||
in `htons()`.
|
||||
|
||||
Don't forget to add `//util/endian` to the list of dependencies in the `BUILD`
|
||||
file wherever `ghtonl()` and `ghtons()` are used. The library consists of a
|
||||
single header file and will not bloat your binary.
|
||||
|
||||
## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong?
|
||||
|
||||
If your class has a static data member:
|
||||
|
||||
```c++
|
||||
// foo.h
|
||||
class Foo {
|
||||
...
|
||||
static const int kBar = 100;
|
||||
};
|
||||
```
|
||||
|
||||
You also need to define it *outside* of the class body in `foo.cc`:
|
||||
|
||||
```c++
|
||||
const int Foo::kBar; // No initializer here.
|
||||
```
|
||||
|
||||
Otherwise your code is **invalid C++**, and may break in unexpected ways. In
|
||||
particular, using it in googletest comparison assertions (`EXPECT_EQ`, etc) will
|
||||
generate an "undefined reference" linker error. The fact that "it used to work"
|
||||
doesn't mean it's valid. It just means that you were lucky. :-)
|
||||
|
||||
## Can I derive a test fixture from another?
|
||||
|
||||
Yes.
|
||||
|
||||
Each test fixture has a corresponding and same named test suite. This means only
|
||||
one test suite can use a particular fixture. Sometimes, however, multiple test
|
||||
cases may want to use the same or slightly different fixtures. For example, you
|
||||
may want to make sure that all of a GUI library's test suites don't leak
|
||||
important system resources like fonts and brushes.
|
||||
|
||||
In googletest, you share a fixture among test suites by putting the shared logic
|
||||
in a base test fixture, then deriving from that base a separate fixture for each
|
||||
test suite that wants to use this common logic. You then use `TEST_F()` to write
|
||||
tests using each derived fixture.
|
||||
|
||||
Typically, your code looks like this:
|
||||
|
||||
```c++
|
||||
// Defines a base test fixture.
|
||||
class BaseTest : public ::testing::Test {
|
||||
protected:
|
||||
...
|
||||
};
|
||||
|
||||
// Derives a fixture FooTest from BaseTest.
|
||||
class FooTest : public BaseTest {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
BaseTest::SetUp(); // Sets up the base fixture first.
|
||||
... additional set-up work ...
|
||||
}
|
||||
|
||||
void TearDown() override {
|
||||
... clean-up work for FooTest ...
|
||||
BaseTest::TearDown(); // Remember to tear down the base fixture
|
||||
// after cleaning up FooTest!
|
||||
}
|
||||
|
||||
... functions and variables for FooTest ...
|
||||
};
|
||||
|
||||
// Tests that use the fixture FooTest.
|
||||
TEST_F(FooTest, Bar) { ... }
|
||||
TEST_F(FooTest, Baz) { ... }
|
||||
|
||||
... additional fixtures derived from BaseTest ...
|
||||
```
|
||||
|
||||
If necessary, you can continue to derive test fixtures from a derived fixture.
|
||||
googletest has no limit on how deep the hierarchy can be.
|
||||
|
||||
For a complete example using derived test fixtures, see
|
||||
[sample5_unittest.cc](../samples/sample5_unittest.cc).
|
||||
|
||||
## My compiler complains "void value not ignored as it ought to be." What does this mean?
|
||||
|
||||
You're probably using an `ASSERT_*()` in a function that doesn't return `void`.
|
||||
`ASSERT_*()` can only be used in `void` functions, due to exceptions being
|
||||
disabled by our build system. Please see more details
|
||||
[here](advanced.md#assertion-placement).
|
||||
|
||||
## My death test hangs (or seg-faults). How do I fix it?
|
||||
|
||||
In googletest, death tests are run in a child process and the way they work is
|
||||
delicate. To write death tests you really need to understand how they work.
|
||||
Please make sure you have read [this](advanced.md#how-it-works).
|
||||
|
||||
In particular, death tests don't like having multiple threads in the parent
|
||||
process. So the first thing you can try is to eliminate creating threads outside
|
||||
of `EXPECT_DEATH()`. For example, you may want to use mocks or fake objects
|
||||
instead of real ones in your tests.
|
||||
|
||||
Sometimes this is impossible as some library you must use may be creating
|
||||
threads before `main()` is even reached. In this case, you can try to minimize
|
||||
the chance of conflicts by either moving as many activities as possible inside
|
||||
`EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or
|
||||
leaving as few things as possible in it. Also, you can try to set the death test
|
||||
style to `"threadsafe"`, which is safer but slower, and see if it helps.
|
||||
|
||||
If you go with thread-safe death tests, remember that they rerun the test
|
||||
program from the beginning in the child process. Therefore make sure your
|
||||
program can run side-by-side with itself and is deterministic.
|
||||
|
||||
In the end, this boils down to good concurrent programming. You have to make
|
||||
sure that there is no race conditions or dead locks in your program. No silver
|
||||
bullet - sorry!
|
||||
|
||||
## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? {#CtorVsSetUp}
|
||||
|
||||
The first thing to remember is that googletest does **not** reuse the same test
|
||||
fixture object across multiple tests. For each `TEST_F`, googletest will create
|
||||
a **fresh** test fixture object, immediately call `SetUp()`, run the test body,
|
||||
call `TearDown()`, and then delete the test fixture object.
|
||||
|
||||
When you need to write per-test set-up and tear-down logic, you have the choice
|
||||
between using the test fixture constructor/destructor or `SetUp()/TearDown()`.
|
||||
The former is usually preferred, as it has the following benefits:
|
||||
|
||||
* By initializing a member variable in the constructor, we have the option to
|
||||
make it `const`, which helps prevent accidental changes to its value and
|
||||
makes the tests more obviously correct.
|
||||
* In case we need to subclass the test fixture class, the subclass'
|
||||
constructor is guaranteed to call the base class' constructor *first*, and
|
||||
the subclass' destructor is guaranteed to call the base class' destructor
|
||||
*afterward*. With `SetUp()/TearDown()`, a subclass may make the mistake of
|
||||
forgetting to call the base class' `SetUp()/TearDown()` or call them at the
|
||||
wrong time.
|
||||
|
||||
You may still want to use `SetUp()/TearDown()` in the following cases:
|
||||
|
||||
* C++ does not allow virtual function calls in constructors and destructors.
|
||||
You can call a method declared as virtual, but it will not use dynamic
|
||||
dispatch, it will use the definition from the class the constructor of which
|
||||
is currently executing. This is because calling a virtual method before the
|
||||
derived class constructor has a chance to run is very dangerous - the
|
||||
virtual method might operate on uninitialized data. Therefore, if you need
|
||||
to call a method that will be overridden in a derived class, you have to use
|
||||
`SetUp()/TearDown()`.
|
||||
* In the body of a constructor (or destructor), it's not possible to use the
|
||||
`ASSERT_xx` macros. Therefore, if the set-up operation could cause a fatal
|
||||
test failure that should prevent the test from running, it's necessary to
|
||||
use `abort` <!-- GOOGLETEST_CM0015 DO NOT DELETE --> and abort the whole test executable,
|
||||
or to use `SetUp()` instead of a constructor.
|
||||
* If the tear-down operation could throw an exception, you must use
|
||||
`TearDown()` as opposed to the destructor, as throwing in a destructor leads
|
||||
to undefined behavior and usually will kill your program right away. Note
|
||||
that many standard libraries (like STL) may throw when exceptions are
|
||||
enabled in the compiler. Therefore you should prefer `TearDown()` if you
|
||||
want to write portable tests that work with or without exceptions.
|
||||
* The googletest team is considering making the assertion macros throw on
|
||||
platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux
|
||||
client-side), which will eliminate the need for the user to propagate
|
||||
failures from a subroutine to its caller. Therefore, you shouldn't use
|
||||
googletest assertions in a destructor if your code could run on such a
|
||||
platform.
|
||||
|
||||
## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it?
|
||||
|
||||
If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is
|
||||
overloaded or a template, the compiler will have trouble figuring out which
|
||||
overloaded version it should use. `ASSERT_PRED_FORMAT*` and
|
||||
`EXPECT_PRED_FORMAT*` don't have this problem.
|
||||
|
||||
If you see this error, you might want to switch to
|
||||
`(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure
|
||||
message. If, however, that is not an option, you can resolve the problem by
|
||||
explicitly telling the compiler which version to pick.
|
||||
|
||||
For example, suppose you have
|
||||
|
||||
```c++
|
||||
bool IsPositive(int n) {
|
||||
return n > 0;
|
||||
}
|
||||
|
||||
bool IsPositive(double x) {
|
||||
return x > 0;
|
||||
}
|
||||
```
|
||||
|
||||
you will get a compiler error if you write
|
||||
|
||||
```c++
|
||||
EXPECT_PRED1(IsPositive, 5);
|
||||
```
|
||||
|
||||
However, this will work:
|
||||
|
||||
```c++
|
||||
EXPECT_PRED1(static_cast<bool (*)(int)>(IsPositive), 5);
|
||||
```
|
||||
|
||||
(The stuff inside the angled brackets for the `static_cast` operator is the type
|
||||
of the function pointer for the `int`-version of `IsPositive()`.)
|
||||
|
||||
As another example, when you have a template function
|
||||
|
||||
```c++
|
||||
template <typename T>
|
||||
bool IsNegative(T x) {
|
||||
return x < 0;
|
||||
}
|
||||
```
|
||||
|
||||
you can use it in a predicate assertion like this:
|
||||
|
||||
```c++
|
||||
ASSERT_PRED1(IsNegative<int>, -5);
|
||||
```
|
||||
|
||||
Things are more interesting if your template has more than one parameters. The
|
||||
following won't compile:
|
||||
|
||||
```c++
|
||||
ASSERT_PRED2(GreaterThan<int, int>, 5, 0);
|
||||
```
|
||||
|
||||
as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments, which
|
||||
is one more than expected. The workaround is to wrap the predicate function in
|
||||
parentheses:
|
||||
|
||||
```c++
|
||||
ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
|
||||
```
|
||||
|
||||
## My compiler complains about "ignoring return value" when I call RUN_ALL_TESTS(). Why?
|
||||
|
||||
Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is,
|
||||
instead of
|
||||
|
||||
```c++
|
||||
return RUN_ALL_TESTS();
|
||||
```
|
||||
|
||||
they write
|
||||
|
||||
```c++
|
||||
RUN_ALL_TESTS();
|
||||
```
|
||||
|
||||
This is **wrong and dangerous**. The testing services needs to see the return
|
||||
value of `RUN_ALL_TESTS()` in order to determine if a test has passed. If your
|
||||
`main()` function ignores it, your test will be considered successful even if it
|
||||
has a googletest assertion failure. Very bad.
|
||||
|
||||
We have decided to fix this (thanks to Michael Chastain for the idea). Now, your
|
||||
code will no longer be able to ignore `RUN_ALL_TESTS()` when compiled with
|
||||
`gcc`. If you do so, you'll get a compiler error.
|
||||
|
||||
If you see the compiler complaining about you ignoring the return value of
|
||||
`RUN_ALL_TESTS()`, the fix is simple: just make sure its value is used as the
|
||||
return value of `main()`.
|
||||
|
||||
But how could we introduce a change that breaks existing tests? Well, in this
|
||||
case, the code was already broken in the first place, so we didn't break it. :-)
|
||||
|
||||
## My compiler complains that a constructor (or destructor) cannot return a value. What's going on?
|
||||
|
||||
Due to a peculiarity of C++, in order to support the syntax for streaming
|
||||
messages to an `ASSERT_*`, e.g.
|
||||
|
||||
```c++
|
||||
ASSERT_EQ(1, Foo()) << "blah blah" << foo;
|
||||
```
|
||||
|
||||
we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and
|
||||
`ADD_FAILURE*`) in constructors and destructors. The workaround is to move the
|
||||
content of your constructor/destructor to a private void member function, or
|
||||
switch to `EXPECT_*()` if that works. This
|
||||
[section](advanced.md#assertion-placement) in the user's guide explains it.
|
||||
|
||||
## My SetUp() function is not called. Why?
|
||||
|
||||
C++ is case-sensitive. Did you spell it as `Setup()`?
|
||||
|
||||
Similarly, sometimes people spell `SetUpTestSuite()` as `SetupTestSuite()` and
|
||||
wonder why it's never called.
|
||||
|
||||
|
||||
## I have several test suites which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious.
|
||||
|
||||
You don't have to. Instead of
|
||||
|
||||
```c++
|
||||
class FooTest : public BaseTest {};
|
||||
|
||||
TEST_F(FooTest, Abc) { ... }
|
||||
TEST_F(FooTest, Def) { ... }
|
||||
|
||||
class BarTest : public BaseTest {};
|
||||
|
||||
TEST_F(BarTest, Abc) { ... }
|
||||
TEST_F(BarTest, Def) { ... }
|
||||
```
|
||||
|
||||
you can simply `typedef` the test fixtures:
|
||||
|
||||
```c++
|
||||
typedef BaseTest FooTest;
|
||||
|
||||
TEST_F(FooTest, Abc) { ... }
|
||||
TEST_F(FooTest, Def) { ... }
|
||||
|
||||
typedef BaseTest BarTest;
|
||||
|
||||
TEST_F(BarTest, Abc) { ... }
|
||||
TEST_F(BarTest, Def) { ... }
|
||||
```
|
||||
|
||||
## googletest output is buried in a whole bunch of LOG messages. What do I do?
|
||||
|
||||
The googletest output is meant to be a concise and human-friendly report. If
|
||||
your test generates textual output itself, it will mix with the googletest
|
||||
output, making it hard to read. However, there is an easy solution to this
|
||||
problem.
|
||||
|
||||
Since `LOG` messages go to stderr, we decided to let googletest output go to
|
||||
stdout. This way, you can easily separate the two using redirection. For
|
||||
example:
|
||||
|
||||
```shell
|
||||
$ ./my_test > gtest_output.txt
|
||||
```
|
||||
|
||||
## Why should I prefer test fixtures over global variables?
|
||||
|
||||
There are several good reasons:
|
||||
|
||||
1. It's likely your test needs to change the states of its global variables.
|
||||
This makes it difficult to keep side effects from escaping one test and
|
||||
contaminating others, making debugging difficult. By using fixtures, each
|
||||
test has a fresh set of variables that's different (but with the same
|
||||
names). Thus, tests are kept independent of each other.
|
||||
2. Global variables pollute the global namespace.
|
||||
3. Test fixtures can be reused via subclassing, which cannot be done easily
|
||||
with global variables. This is useful if many test suites have something in
|
||||
common.
|
||||
|
||||
## What can the statement argument in ASSERT_DEATH() be?
|
||||
|
||||
`ASSERT_DEATH(*statement*, *regex*)` (or any death assertion macro) can be used
|
||||
wherever `*statement*` is valid. So basically `*statement*` can be any C++
|
||||
statement that makes sense in the current context. In particular, it can
|
||||
reference global and/or local variables, and can be:
|
||||
|
||||
* a simple function call (often the case),
|
||||
* a complex expression, or
|
||||
* a compound statement.
|
||||
|
||||
Some examples are shown here:
|
||||
|
||||
```c++
|
||||
// A death test can be a simple function call.
|
||||
TEST(MyDeathTest, FunctionCall) {
|
||||
ASSERT_DEATH(Xyz(5), "Xyz failed");
|
||||
}
|
||||
|
||||
// Or a complex expression that references variables and functions.
|
||||
TEST(MyDeathTest, ComplexExpression) {
|
||||
const bool c = Condition();
|
||||
ASSERT_DEATH((c ? Func1(0) : object2.Method("test")),
|
||||
"(Func1|Method) failed");
|
||||
}
|
||||
|
||||
// Death assertions can be used any where in a function. In
|
||||
// particular, they can be inside a loop.
|
||||
TEST(MyDeathTest, InsideLoop) {
|
||||
// Verifies that Foo(0), Foo(1), ..., and Foo(4) all die.
|
||||
for (int i = 0; i < 5; i++) {
|
||||
EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors",
|
||||
::testing::Message() << "where i is " << i);
|
||||
}
|
||||
}
|
||||
|
||||
// A death assertion can contain a compound statement.
|
||||
TEST(MyDeathTest, CompoundStatement) {
|
||||
// Verifies that at lease one of Bar(0), Bar(1), ..., and
|
||||
// Bar(4) dies.
|
||||
ASSERT_DEATH({
|
||||
for (int i = 0; i < 5; i++) {
|
||||
Bar(i);
|
||||
}
|
||||
},
|
||||
"Bar has \\d+ errors");
|
||||
}
|
||||
```
|
||||
|
||||
gtest-death-test_test.cc contains more examples if you are interested.
|
||||
|
||||
## I have a fixture class `FooTest`, but `TEST_F(FooTest, Bar)` gives me error ``"no matching function for call to `FooTest::FooTest()'"``. Why?
|
||||
|
||||
Googletest needs to be able to create objects of your test fixture class, so it
|
||||
must have a default constructor. Normally the compiler will define one for you.
|
||||
However, there are cases where you have to define your own:
|
||||
|
||||
* If you explicitly declare a non-default constructor for class `FooTest`
|
||||
(`DISALLOW_EVIL_CONSTRUCTORS()` does this), then you need to define a
|
||||
default constructor, even if it would be empty.
|
||||
* If `FooTest` has a const non-static data member, then you have to define the
|
||||
default constructor *and* initialize the const member in the initializer
|
||||
list of the constructor. (Early versions of `gcc` doesn't force you to
|
||||
initialize the const member. It's a bug that has been fixed in `gcc 4`.)
|
||||
|
||||
## Why does ASSERT_DEATH complain about previous threads that were already joined?
|
||||
|
||||
With the Linux pthread library, there is no turning back once you cross the line
|
||||
from single thread to multiple threads. The first time you create a thread, a
|
||||
manager thread is created in addition, so you get 3, not 2, threads. Later when
|
||||
the thread you create joins the main thread, the thread count decrements by 1,
|
||||
but the manager thread will never be killed, so you still have 2 threads, which
|
||||
means you cannot safely run a death test.
|
||||
|
||||
The new NPTL thread library doesn't suffer from this problem, as it doesn't
|
||||
create a manager thread. However, if you don't control which machine your test
|
||||
runs on, you shouldn't depend on this.
|
||||
|
||||
## Why does googletest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH?
|
||||
|
||||
googletest does not interleave tests from different test suites. That is, it
|
||||
runs all tests in one test suite first, and then runs all tests in the next test
|
||||
suite, and so on. googletest does this because it needs to set up a test suite
|
||||
before the first test in it is run, and tear it down afterwords. Splitting up
|
||||
the test case would require multiple set-up and tear-down processes, which is
|
||||
inefficient and makes the semantics unclean.
|
||||
|
||||
If we were to determine the order of tests based on test name instead of test
|
||||
case name, then we would have a problem with the following situation:
|
||||
|
||||
```c++
|
||||
TEST_F(FooTest, AbcDeathTest) { ... }
|
||||
TEST_F(FooTest, Uvw) { ... }
|
||||
|
||||
TEST_F(BarTest, DefDeathTest) { ... }
|
||||
TEST_F(BarTest, Xyz) { ... }
|
||||
```
|
||||
|
||||
Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't
|
||||
interleave tests from different test suites, we need to run all tests in the
|
||||
`FooTest` case before running any test in the `BarTest` case. This contradicts
|
||||
with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`.
|
||||
|
||||
## But I don't like calling my entire test suite \*DeathTest when it contains both death tests and non-death tests. What do I do?
|
||||
|
||||
You don't have to, but if you like, you may split up the test suite into
|
||||
`FooTest` and `FooDeathTest`, where the names make it clear that they are
|
||||
related:
|
||||
|
||||
```c++
|
||||
class FooTest : public ::testing::Test { ... };
|
||||
|
||||
TEST_F(FooTest, Abc) { ... }
|
||||
TEST_F(FooTest, Def) { ... }
|
||||
|
||||
using FooDeathTest = FooTest;
|
||||
|
||||
TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... }
|
||||
TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... }
|
||||
```
|
||||
|
||||
## googletest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds?
|
||||
|
||||
Printing the LOG messages generated by the statement inside `EXPECT_DEATH()`
|
||||
makes it harder to search for real problems in the parent's log. Therefore,
|
||||
googletest only prints them when the death test has failed.
|
||||
|
||||
If you really need to see such LOG messages, a workaround is to temporarily
|
||||
break the death test (e.g. by changing the regex pattern it is expected to
|
||||
match). Admittedly, this is a hack. We'll consider a more permanent solution
|
||||
after the fork-and-exec-style death tests are implemented.
|
||||
|
||||
## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives?
|
||||
|
||||
If you use a user-defined type `FooType` in an assertion, you must make sure
|
||||
there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function
|
||||
defined such that we can print a value of `FooType`.
|
||||
|
||||
In addition, if `FooType` is declared in a name space, the `<<` operator also
|
||||
needs to be defined in the *same* name space. See https://abseil.io/tips/49 for details.
|
||||
|
||||
## How do I suppress the memory leak messages on Windows?
|
||||
|
||||
Since the statically initialized googletest singleton requires allocations on
|
||||
the heap, the Visual C++ memory leak detector will report memory leaks at the
|
||||
end of the program run. The easiest way to avoid this is to use the
|
||||
`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any
|
||||
statically initialized heap objects. See MSDN for more details and additional
|
||||
heap check/debug routines.
|
||||
|
||||
## How can my code detect if it is running in a test?
|
||||
|
||||
If you write code that sniffs whether it's running in a test and does different
|
||||
things accordingly, you are leaking test-only logic into production code and
|
||||
there is no easy way to ensure that the test-only code paths aren't run by
|
||||
mistake in production. Such cleverness also leads to
|
||||
[Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly
|
||||
advise against the practice, and googletest doesn't provide a way to do it.
|
||||
|
||||
In general, the recommended way to cause the code to behave differently under
|
||||
test is [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection). You can inject
|
||||
different functionality from the test and from the production code. Since your
|
||||
production code doesn't link in the for-test logic at all (the
|
||||
[`testonly`](https://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure
|
||||
that), there is no danger in accidentally running it.
|
||||
|
||||
However, if you *really*, *really*, *really* have no choice, and if you follow
|
||||
the rule of ending your test program names with `_test`, you can use the
|
||||
*horrible* hack of sniffing your executable name (`argv[0]` in `main()`) to know
|
||||
whether the code is under test.
|
||||
|
||||
## How do I temporarily disable a test?
|
||||
|
||||
If you have a broken test that you cannot fix right away, you can add the
|
||||
DISABLED_ prefix to its name. This will exclude it from execution. This is
|
||||
better than commenting out the code or using #if 0, as disabled tests are still
|
||||
compiled (and thus won't rot).
|
||||
|
||||
To include disabled tests in test execution, just invoke the test program with
|
||||
the --gtest_also_run_disabled_tests flag.
|
||||
|
||||
## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces?
|
||||
|
||||
Yes.
|
||||
|
||||
The rule is **all test methods in the same test suite must use the same fixture
|
||||
class.** This means that the following is **allowed** because both tests use the
|
||||
same fixture class (`::testing::Test`).
|
||||
|
||||
```c++
|
||||
namespace foo {
|
||||
TEST(CoolTest, DoSomething) {
|
||||
SUCCEED();
|
||||
}
|
||||
} // namespace foo
|
||||
|
||||
namespace bar {
|
||||
TEST(CoolTest, DoSomething) {
|
||||
SUCCEED();
|
||||
}
|
||||
} // namespace bar
|
||||
```
|
||||
|
||||
However, the following code is **not allowed** and will produce a runtime error
|
||||
from googletest because the test methods are using different test fixture
|
||||
classes with the same test suite name.
|
||||
|
||||
```c++
|
||||
namespace foo {
|
||||
class CoolTest : public ::testing::Test {}; // Fixture foo::CoolTest
|
||||
TEST_F(CoolTest, DoSomething) {
|
||||
SUCCEED();
|
||||
}
|
||||
} // namespace foo
|
||||
|
||||
namespace bar {
|
||||
class CoolTest : public ::testing::Test {}; // Fixture: bar::CoolTest
|
||||
TEST_F(CoolTest, DoSomething) {
|
||||
SUCCEED();
|
||||
}
|
||||
} // namespace bar
|
||||
```
|
141
3rdparty/gtest/docs/pkgconfig.md
vendored
Normal file
141
3rdparty/gtest/docs/pkgconfig.md
vendored
Normal file
@ -0,0 +1,141 @@
|
||||
## Using GoogleTest from various build systems
|
||||
|
||||
GoogleTest comes with pkg-config files that can be used to determine all
|
||||
necessary flags for compiling and linking to GoogleTest (and GoogleMock).
|
||||
Pkg-config is a standardised plain-text format containing
|
||||
|
||||
* the includedir (-I) path
|
||||
* necessary macro (-D) definitions
|
||||
* further required flags (-pthread)
|
||||
* the library (-L) path
|
||||
* the library (-l) to link to
|
||||
|
||||
All current build systems support pkg-config in one way or another. For all
|
||||
examples here we assume you want to compile the sample
|
||||
`samples/sample3_unittest.cc`.
|
||||
|
||||
### CMake
|
||||
|
||||
Using `pkg-config` in CMake is fairly easy:
|
||||
|
||||
```cmake
|
||||
cmake_minimum_required(VERSION 3.0)
|
||||
|
||||
cmake_policy(SET CMP0048 NEW)
|
||||
project(my_gtest_pkgconfig VERSION 0.0.1 LANGUAGES CXX)
|
||||
|
||||
find_package(PkgConfig)
|
||||
pkg_search_module(GTEST REQUIRED gtest_main)
|
||||
|
||||
add_executable(testapp samples/sample3_unittest.cc)
|
||||
target_link_libraries(testapp ${GTEST_LDFLAGS})
|
||||
target_compile_options(testapp PUBLIC ${GTEST_CFLAGS})
|
||||
|
||||
include(CTest)
|
||||
add_test(first_and_only_test testapp)
|
||||
```
|
||||
|
||||
It is generally recommended that you use `target_compile_options` + `_CFLAGS`
|
||||
over `target_include_directories` + `_INCLUDE_DIRS` as the former includes not
|
||||
just -I flags (GoogleTest might require a macro indicating to internal headers
|
||||
that all libraries have been compiled with threading enabled. In addition,
|
||||
GoogleTest might also require `-pthread` in the compiling step, and as such
|
||||
splitting the pkg-config `Cflags` variable into include dirs and macros for
|
||||
`target_compile_definitions()` might still miss this). The same recommendation
|
||||
goes for using `_LDFLAGS` over the more commonplace `_LIBRARIES`, which happens
|
||||
to discard `-L` flags and `-pthread`.
|
||||
|
||||
### Autotools
|
||||
|
||||
Finding GoogleTest in Autoconf and using it from Automake is also fairly easy:
|
||||
|
||||
In your `configure.ac`:
|
||||
|
||||
```
|
||||
AC_PREREQ([2.69])
|
||||
AC_INIT([my_gtest_pkgconfig], [0.0.1])
|
||||
AC_CONFIG_SRCDIR([samples/sample3_unittest.cc])
|
||||
AC_PROG_CXX
|
||||
|
||||
PKG_CHECK_MODULES([GTEST], [gtest_main])
|
||||
|
||||
AM_INIT_AUTOMAKE([foreign subdir-objects])
|
||||
AC_CONFIG_FILES([Makefile])
|
||||
AC_OUTPUT
|
||||
```
|
||||
|
||||
and in your `Makefile.am`:
|
||||
|
||||
```
|
||||
check_PROGRAMS = testapp
|
||||
TESTS = $(check_PROGRAMS)
|
||||
|
||||
testapp_SOURCES = samples/sample3_unittest.cc
|
||||
testapp_CXXFLAGS = $(GTEST_CFLAGS)
|
||||
testapp_LDADD = $(GTEST_LIBS)
|
||||
```
|
||||
|
||||
### Meson
|
||||
|
||||
Meson natively uses pkgconfig to query dependencies:
|
||||
|
||||
```
|
||||
project('my_gtest_pkgconfig', 'cpp', version : '0.0.1')
|
||||
|
||||
gtest_dep = dependency('gtest_main')
|
||||
|
||||
testapp = executable(
|
||||
'testapp',
|
||||
files(['samples/sample3_unittest.cc']),
|
||||
dependencies : gtest_dep,
|
||||
install : false)
|
||||
|
||||
test('first_and_only_test', testapp)
|
||||
```
|
||||
|
||||
### Plain Makefiles
|
||||
|
||||
Since `pkg-config` is a small Unix command-line utility, it can be used in
|
||||
handwritten `Makefile`s too:
|
||||
|
||||
```makefile
|
||||
GTEST_CFLAGS = `pkg-config --cflags gtest_main`
|
||||
GTEST_LIBS = `pkg-config --libs gtest_main`
|
||||
|
||||
.PHONY: tests all
|
||||
|
||||
tests: all
|
||||
./testapp
|
||||
|
||||
all: testapp
|
||||
|
||||
testapp: testapp.o
|
||||
$(CXX) $(CXXFLAGS) $(LDFLAGS) $< -o $@ $(GTEST_LIBS)
|
||||
|
||||
testapp.o: samples/sample3_unittest.cc
|
||||
$(CXX) $(CPPFLAGS) $(CXXFLAGS) $< -c -o $@ $(GTEST_CFLAGS)
|
||||
```
|
||||
|
||||
### Help! pkg-config can't find GoogleTest!
|
||||
|
||||
Let's say you have a `CMakeLists.txt` along the lines of the one in this
|
||||
tutorial and you try to run `cmake`. It is very possible that you get a failure
|
||||
along the lines of:
|
||||
|
||||
```
|
||||
-- Checking for one of the modules 'gtest_main'
|
||||
CMake Error at /usr/share/cmake/Modules/FindPkgConfig.cmake:640 (message):
|
||||
None of the required 'gtest_main' found
|
||||
```
|
||||
|
||||
These failures are common if you installed GoogleTest yourself and have not
|
||||
sourced it from a distro or other package manager. If so, you need to tell
|
||||
pkg-config where it can find the `.pc` files containing the information. Say you
|
||||
installed GoogleTest to `/usr/local`, then it might be that the `.pc` files are
|
||||
installed under `/usr/local/lib64/pkgconfig`. If you set
|
||||
|
||||
```
|
||||
export PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig
|
||||
```
|
||||
|
||||
pkg-config will also try to look in `PKG_CONFIG_PATH` to find `gtest_main.pc`.
|
567
3rdparty/gtest/docs/primer.md
vendored
Normal file
567
3rdparty/gtest/docs/primer.md
vendored
Normal file
@ -0,0 +1,567 @@
|
||||
# Googletest Primer
|
||||
|
||||
## Introduction: Why googletest?
|
||||
|
||||
*googletest* helps you write better C++ tests.
|
||||
|
||||
googletest is a testing framework developed by the Testing Technology team with
|
||||
Google's specific requirements and constraints in mind. Whether you work on
|
||||
Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it
|
||||
supports *any* kind of tests, not just unit tests.
|
||||
|
||||
So what makes a good test, and how does googletest fit in? We believe:
|
||||
|
||||
1. Tests should be *independent* and *repeatable*. It's a pain to debug a test
|
||||
that succeeds or fails as a result of other tests. googletest isolates the
|
||||
tests by running each of them on a different object. When a test fails,
|
||||
googletest allows you to run it in isolation for quick debugging.
|
||||
2. Tests should be well *organized* and reflect the structure of the tested
|
||||
code. googletest groups related tests into test suites that can share data
|
||||
and subroutines. This common pattern is easy to recognize and makes tests
|
||||
easy to maintain. Such consistency is especially helpful when people switch
|
||||
projects and start to work on a new code base.
|
||||
3. Tests should be *portable* and *reusable*. Google has a lot of code that is
|
||||
platform-neutral; its tests should also be platform-neutral. googletest
|
||||
works on different OSes, with different compilers, with or without
|
||||
exceptions, so googletest tests can work with a variety of configurations.
|
||||
4. When tests fail, they should provide as much *information* about the problem
|
||||
as possible. googletest doesn't stop at the first test failure. Instead, it
|
||||
only stops the current test and continues with the next. You can also set up
|
||||
tests that report non-fatal failures after which the current test continues.
|
||||
Thus, you can detect and fix multiple bugs in a single run-edit-compile
|
||||
cycle.
|
||||
5. The testing framework should liberate test writers from housekeeping chores
|
||||
and let them focus on the test *content*. googletest automatically keeps
|
||||
track of all tests defined, and doesn't require the user to enumerate them
|
||||
in order to run them.
|
||||
6. Tests should be *fast*. With googletest, you can reuse shared resources
|
||||
across tests and pay for the set-up/tear-down only once, without making
|
||||
tests depend on each other.
|
||||
|
||||
Since googletest is based on the popular xUnit architecture, you'll feel right
|
||||
at home if you've used JUnit or PyUnit before. If not, it will take you about 10
|
||||
minutes to learn the basics and get started. So let's go!
|
||||
|
||||
## Beware of the nomenclature
|
||||
|
||||
_Note:_ There might be some confusion arising from different definitions of the
|
||||
terms _Test_, _Test Case_ and _Test Suite_, so beware of misunderstanding these.
|
||||
|
||||
Historically, googletest started to use the term _Test Case_ for grouping
|
||||
related tests, whereas current publications, including International Software
|
||||
Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) materials and
|
||||
various textbooks on software quality, use the term
|
||||
_[Test Suite][istqb test suite]_ for this.
|
||||
|
||||
The related term _Test_, as it is used in googletest, corresponds to the term
|
||||
_[Test Case][istqb test case]_ of ISTQB and others.
|
||||
|
||||
The term _Test_ is commonly of broad enough sense, including ISTQB's definition
|
||||
of _Test Case_, so it's not much of a problem here. But the term _Test Case_ as
|
||||
was used in Google Test is of contradictory sense and thus confusing.
|
||||
|
||||
googletest recently started replacing the term _Test Case_ with _Test Suite_.
|
||||
The preferred API is *TestSuite*. The older TestCase API is being slowly
|
||||
deprecated and refactored away.
|
||||
|
||||
So please be aware of the different definitions of the terms:
|
||||
|
||||
<!-- mdformat off(github rendering does not support multiline tables) -->
|
||||
|
||||
Meaning | googletest Term | [ISTQB](http://www.istqb.org/) Term
|
||||
:----------------------------------------------------------------------------------- | :---------------------- | :----------------------------------
|
||||
Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case]
|
||||
|
||||
<!-- mdformat on -->
|
||||
|
||||
[istqb test case]: http://glossary.istqb.org/en/search/test%20case
|
||||
[istqb test suite]: http://glossary.istqb.org/en/search/test%20suite
|
||||
|
||||
## Basic Concepts
|
||||
|
||||
When using googletest, you start by writing *assertions*, which are statements
|
||||
that check whether a condition is true. An assertion's result can be *success*,
|
||||
*nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the
|
||||
current function; otherwise the program continues normally.
|
||||
|
||||
*Tests* use assertions to verify the tested code's behavior. If a test crashes
|
||||
or has a failed assertion, then it *fails*; otherwise it *succeeds*.
|
||||
|
||||
A *test suite* contains one or many tests. You should group your tests into test
|
||||
suites that reflect the structure of the tested code. When multiple tests in a
|
||||
test suite need to share common objects and subroutines, you can put them into a
|
||||
*test fixture* class.
|
||||
|
||||
A *test program* can contain multiple test suites.
|
||||
|
||||
We'll now explain how to write a test program, starting at the individual
|
||||
assertion level and building up to tests and test suites.
|
||||
|
||||
## Assertions
|
||||
|
||||
googletest assertions are macros that resemble function calls. You test a class
|
||||
or function by making assertions about its behavior. When an assertion fails,
|
||||
googletest prints the assertion's source file and line number location, along
|
||||
with a failure message. You may also supply a custom failure message which will
|
||||
be appended to googletest's message.
|
||||
|
||||
The assertions come in pairs that test the same thing but have different effects
|
||||
on the current function. `ASSERT_*` versions generate fatal failures when they
|
||||
fail, and **abort the current function**. `EXPECT_*` versions generate nonfatal
|
||||
failures, which don't abort the current function. Usually `EXPECT_*` are
|
||||
preferred, as they allow more than one failure to be reported in a test.
|
||||
However, you should use `ASSERT_*` if it doesn't make sense to continue when the
|
||||
assertion in question fails.
|
||||
|
||||
Since a failed `ASSERT_*` returns from the current function immediately,
|
||||
possibly skipping clean-up code that comes after it, it may cause a space leak.
|
||||
Depending on the nature of the leak, it may or may not be worth fixing - so keep
|
||||
this in mind if you get a heap checker error in addition to assertion errors.
|
||||
|
||||
To provide a custom failure message, simply stream it into the macro using the
|
||||
`<<` operator or a sequence of such operators. An example:
|
||||
|
||||
```c++
|
||||
ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";
|
||||
|
||||
for (int i = 0; i < x.size(); ++i) {
|
||||
EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;
|
||||
}
|
||||
```
|
||||
|
||||
Anything that can be streamed to an `ostream` can be streamed to an assertion
|
||||
macro--in particular, C strings and `string` objects. If a wide string
|
||||
(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is
|
||||
streamed to an assertion, it will be translated to UTF-8 when printed.
|
||||
|
||||
### Basic Assertions
|
||||
|
||||
These assertions do basic true/false condition testing.
|
||||
|
||||
Fatal assertion | Nonfatal assertion | Verifies
|
||||
-------------------------- | -------------------------- | --------------------
|
||||
`ASSERT_TRUE(condition);` | `EXPECT_TRUE(condition);` | `condition` is true
|
||||
`ASSERT_FALSE(condition);` | `EXPECT_FALSE(condition);` | `condition` is false
|
||||
|
||||
Remember, when they fail, `ASSERT_*` yields a fatal failure and returns from the
|
||||
current function, while `EXPECT_*` yields a nonfatal failure, allowing the
|
||||
function to continue running. In either case, an assertion failure means its
|
||||
containing test fails.
|
||||
|
||||
**Availability**: Linux, Windows, Mac.
|
||||
|
||||
### Binary Comparison
|
||||
|
||||
This section describes assertions that compare two values.
|
||||
|
||||
Fatal assertion | Nonfatal assertion | Verifies
|
||||
------------------------ | ------------------------ | --------------
|
||||
`ASSERT_EQ(val1, val2);` | `EXPECT_EQ(val1, val2);` | `val1 == val2`
|
||||
`ASSERT_NE(val1, val2);` | `EXPECT_NE(val1, val2);` | `val1 != val2`
|
||||
`ASSERT_LT(val1, val2);` | `EXPECT_LT(val1, val2);` | `val1 < val2`
|
||||
`ASSERT_LE(val1, val2);` | `EXPECT_LE(val1, val2);` | `val1 <= val2`
|
||||
`ASSERT_GT(val1, val2);` | `EXPECT_GT(val1, val2);` | `val1 > val2`
|
||||
`ASSERT_GE(val1, val2);` | `EXPECT_GE(val1, val2);` | `val1 >= val2`
|
||||
|
||||
Value arguments must be comparable by the assertion's comparison operator or
|
||||
you'll get a compiler error. We used to require the arguments to support the
|
||||
`<<` operator for streaming to an `ostream`, but this is no longer necessary. If
|
||||
`<<` is supported, it will be called to print the arguments when the assertion
|
||||
fails; otherwise googletest will attempt to print them in the best way it can.
|
||||
For more details and how to customize the printing of the arguments, see the
|
||||
[documentation](../../googlemock/docs/cook_book.md#teaching-gmock-how-to-print-your-values).
|
||||
|
||||
These assertions can work with a user-defined type, but only if you define the
|
||||
corresponding comparison operator (e.g., `==` or `<`). Since this is discouraged
|
||||
by the Google
|
||||
[C++ Style Guide](https://google.github.io/styleguide/cppguide.html#Operator_Overloading),
|
||||
you may need to use `ASSERT_TRUE()` or `EXPECT_TRUE()` to assert the equality of
|
||||
two objects of a user-defined type.
|
||||
|
||||
However, when possible, `ASSERT_EQ(actual, expected)` is preferred to
|
||||
`ASSERT_TRUE(actual == expected)`, since it tells you `actual` and `expected`'s
|
||||
values on failure.
|
||||
|
||||
Arguments are always evaluated exactly once. Therefore, it's OK for the
|
||||
arguments to have side effects. However, as with any ordinary C/C++ function,
|
||||
the arguments' evaluation order is undefined (i.e., the compiler is free to
|
||||
choose any order), and your code should not depend on any particular argument
|
||||
evaluation order.
|
||||
|
||||
`ASSERT_EQ()` does pointer equality on pointers. If used on two C strings, it
|
||||
tests if they are in the same memory location, not if they have the same value.
|
||||
Therefore, if you want to compare C strings (e.g. `const char*`) by value, use
|
||||
`ASSERT_STREQ()`, which will be described later on. In particular, to assert
|
||||
that a C string is `NULL`, use `ASSERT_STREQ(c_string, NULL)`. Consider using
|
||||
`ASSERT_EQ(c_string, nullptr)` if c++11 is supported. To compare two `string`
|
||||
objects, you should use `ASSERT_EQ`.
|
||||
|
||||
When doing pointer comparisons use `*_EQ(ptr, nullptr)` and `*_NE(ptr, nullptr)`
|
||||
instead of `*_EQ(ptr, NULL)` and `*_NE(ptr, NULL)`. This is because `nullptr` is
|
||||
typed, while `NULL` is not. See the [FAQ](faq.md) for more details.
|
||||
|
||||
If you're working with floating point numbers, you may want to use the floating
|
||||
point variations of some of these macros in order to avoid problems caused by
|
||||
rounding. See [Advanced googletest Topics](advanced.md) for details.
|
||||
|
||||
Macros in this section work with both narrow and wide string objects (`string`
|
||||
and `wstring`).
|
||||
|
||||
**Availability**: Linux, Windows, Mac.
|
||||
|
||||
**Historical note**: Before February 2016 `*_EQ` had a convention of calling it
|
||||
as `ASSERT_EQ(expected, actual)`, so lots of existing code uses this order. Now
|
||||
`*_EQ` treats both parameters in the same way.
|
||||
|
||||
### String Comparison
|
||||
|
||||
The assertions in this group compare two **C strings**. If you want to compare
|
||||
two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead.
|
||||
|
||||
<!-- mdformat off(github rendering does not support multiline tables) -->
|
||||
|
||||
| Fatal assertion | Nonfatal assertion | Verifies |
|
||||
| -------------------------- | ------------------------------ | -------------------------------------------------------- |
|
||||
| `ASSERT_STREQ(str1,str2);` | `EXPECT_STREQ(str1,str2);` | the two C strings have the same content |
|
||||
| `ASSERT_STRNE(str1,str2);` | `EXPECT_STRNE(str1,str2);` | the two C strings have different contents |
|
||||
| `ASSERT_STRCASEEQ(str1,str2);` | `EXPECT_STRCASEEQ(str1,str2);` | the two C strings have the same content, ignoring case |
|
||||
| `ASSERT_STRCASENE(str1,str2);` | `EXPECT_STRCASENE(str1,str2);` | the two C strings have different contents, ignoring case |
|
||||
|
||||
<!-- mdformat on-->
|
||||
|
||||
Note that "CASE" in an assertion name means that case is ignored. A `NULL`
|
||||
pointer and an empty string are considered *different*.
|
||||
|
||||
`*STREQ*` and `*STRNE*` also accept wide C strings (`wchar_t*`). If a comparison
|
||||
of two wide strings fails, their values will be printed as UTF-8 narrow strings.
|
||||
|
||||
**Availability**: Linux, Windows, Mac.
|
||||
|
||||
**See also**: For more string comparison tricks (substring, prefix, suffix, and
|
||||
regular expression matching, for example), see [this](advanced.md) in the
|
||||
Advanced googletest Guide.
|
||||
|
||||
## Simple Tests
|
||||
|
||||
To create a test:
|
||||
|
||||
1. Use the `TEST()` macro to define and name a test function. These are
|
||||
ordinary C++ functions that don't return a value.
|
||||
2. In this function, along with any valid C++ statements you want to include,
|
||||
use the various googletest assertions to check values.
|
||||
3. The test's result is determined by the assertions; if any assertion in the
|
||||
test fails (either fatally or non-fatally), or if the test crashes, the
|
||||
entire test fails. Otherwise, it succeeds.
|
||||
|
||||
```c++
|
||||
TEST(TestSuiteName, TestName) {
|
||||
... test body ...
|
||||
}
|
||||
```
|
||||
|
||||
`TEST()` arguments go from general to specific. The *first* argument is the name
|
||||
of the test suite, and the *second* argument is the test's name within the test
|
||||
case. Both names must be valid C++ identifiers, and they should not contain
|
||||
any underscores (`_`). A test's *full name* consists of its containing test suite and
|
||||
its individual name. Tests from different test suites can have the same
|
||||
individual name.
|
||||
|
||||
For example, let's take a simple integer function:
|
||||
|
||||
```c++
|
||||
int Factorial(int n); // Returns the factorial of n
|
||||
```
|
||||
|
||||
A test suite for this function might look like:
|
||||
|
||||
```c++
|
||||
// Tests factorial of 0.
|
||||
TEST(FactorialTest, HandlesZeroInput) {
|
||||
EXPECT_EQ(Factorial(0), 1);
|
||||
}
|
||||
|
||||
// Tests factorial of positive numbers.
|
||||
TEST(FactorialTest, HandlesPositiveInput) {
|
||||
EXPECT_EQ(Factorial(1), 1);
|
||||
EXPECT_EQ(Factorial(2), 2);
|
||||
EXPECT_EQ(Factorial(3), 6);
|
||||
EXPECT_EQ(Factorial(8), 40320);
|
||||
}
|
||||
```
|
||||
|
||||
googletest groups the test results by test suites, so logically related tests
|
||||
should be in the same test suite; in other words, the first argument to their
|
||||
`TEST()` should be the same. In the above example, we have two tests,
|
||||
`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test
|
||||
suite `FactorialTest`.
|
||||
|
||||
When naming your test suites and tests, you should follow the same convention as
|
||||
for
|
||||
[naming functions and classes](https://google.github.io/styleguide/cppguide.html#Function_Names).
|
||||
|
||||
**Availability**: Linux, Windows, Mac.
|
||||
|
||||
## Test Fixtures: Using the Same Data Configuration for Multiple Tests {#same-data-multiple-tests}
|
||||
|
||||
If you find yourself writing two or more tests that operate on similar data, you
|
||||
can use a *test fixture*. This allows you to reuse the same configuration of
|
||||
objects for several different tests.
|
||||
|
||||
To create a fixture:
|
||||
|
||||
1. Derive a class from `::testing::Test` . Start its body with `protected:`, as
|
||||
we'll want to access fixture members from sub-classes.
|
||||
2. Inside the class, declare any objects you plan to use.
|
||||
3. If necessary, write a default constructor or `SetUp()` function to prepare
|
||||
the objects for each test. A common mistake is to spell `SetUp()` as
|
||||
**`Setup()`** with a small `u` - Use `override` in C++11 to make sure you
|
||||
spelled it correctly.
|
||||
4. If necessary, write a destructor or `TearDown()` function to release any
|
||||
resources you allocated in `SetUp()` . To learn when you should use the
|
||||
constructor/destructor and when you should use `SetUp()/TearDown()`, read
|
||||
the [FAQ](faq.md#CtorVsSetUp).
|
||||
5. If needed, define subroutines for your tests to share.
|
||||
|
||||
When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to
|
||||
access objects and subroutines in the test fixture:
|
||||
|
||||
```c++
|
||||
TEST_F(TestFixtureName, TestName) {
|
||||
... test body ...
|
||||
}
|
||||
```
|
||||
|
||||
Like `TEST()`, the first argument is the test suite name, but for `TEST_F()`
|
||||
this must be the name of the test fixture class. You've probably guessed: `_F`
|
||||
is for fixture.
|
||||
|
||||
Unfortunately, the C++ macro system does not allow us to create a single macro
|
||||
that can handle both types of tests. Using the wrong macro causes a compiler
|
||||
error.
|
||||
|
||||
Also, you must first define a test fixture class before using it in a
|
||||
`TEST_F()`, or you'll get the compiler error "`virtual outside class
|
||||
declaration`".
|
||||
|
||||
For each test defined with `TEST_F()`, googletest will create a *fresh* test
|
||||
fixture at runtime, immediately initialize it via `SetUp()`, run the test,
|
||||
clean up by calling `TearDown()`, and then delete the test fixture. Note that
|
||||
different tests in the same test suite have different test fixture objects, and
|
||||
googletest always deletes a test fixture before it creates the next one.
|
||||
googletest does **not** reuse the same test fixture for multiple tests. Any
|
||||
changes one test makes to the fixture do not affect other tests.
|
||||
|
||||
As an example, let's write tests for a FIFO queue class named `Queue`, which has
|
||||
the following interface:
|
||||
|
||||
```c++
|
||||
template <typename E> // E is the element type.
|
||||
class Queue {
|
||||
public:
|
||||
Queue();
|
||||
void Enqueue(const E& element);
|
||||
E* Dequeue(); // Returns NULL if the queue is empty.
|
||||
size_t size() const;
|
||||
...
|
||||
};
|
||||
```
|
||||
|
||||
First, define a fixture class. By convention, you should give it the name
|
||||
`FooTest` where `Foo` is the class being tested.
|
||||
|
||||
```c++
|
||||
class QueueTest : public ::testing::Test {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
q1_.Enqueue(1);
|
||||
q2_.Enqueue(2);
|
||||
q2_.Enqueue(3);
|
||||
}
|
||||
|
||||
// void TearDown() override {}
|
||||
|
||||
Queue<int> q0_;
|
||||
Queue<int> q1_;
|
||||
Queue<int> q2_;
|
||||
};
|
||||
```
|
||||
|
||||
In this case, `TearDown()` is not needed since we don't have to clean up after
|
||||
each test, other than what's already done by the destructor.
|
||||
|
||||
Now we'll write tests using `TEST_F()` and this fixture.
|
||||
|
||||
```c++
|
||||
TEST_F(QueueTest, IsEmptyInitially) {
|
||||
EXPECT_EQ(q0_.size(), 0);
|
||||
}
|
||||
|
||||
TEST_F(QueueTest, DequeueWorks) {
|
||||
int* n = q0_.Dequeue();
|
||||
EXPECT_EQ(n, nullptr);
|
||||
|
||||
n = q1_.Dequeue();
|
||||
ASSERT_NE(n, nullptr);
|
||||
EXPECT_EQ(*n, 1);
|
||||
EXPECT_EQ(q1_.size(), 0);
|
||||
delete n;
|
||||
|
||||
n = q2_.Dequeue();
|
||||
ASSERT_NE(n, nullptr);
|
||||
EXPECT_EQ(*n, 2);
|
||||
EXPECT_EQ(q2_.size(), 1);
|
||||
delete n;
|
||||
}
|
||||
```
|
||||
|
||||
The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is
|
||||
to use `EXPECT_*` when you want the test to continue to reveal more errors after
|
||||
the assertion failure, and use `ASSERT_*` when continuing after failure doesn't
|
||||
make sense. For example, the second assertion in the `Dequeue` test is
|
||||
`ASSERT_NE(nullptr, n)`, as we need to dereference the pointer `n` later, which
|
||||
would lead to a segfault when `n` is `NULL`.
|
||||
|
||||
When these tests run, the following happens:
|
||||
|
||||
1. googletest constructs a `QueueTest` object (let's call it `t1`).
|
||||
2. `t1.SetUp()` initializes `t1`.
|
||||
3. The first test (`IsEmptyInitially`) runs on `t1`.
|
||||
4. `t1.TearDown()` cleans up after the test finishes.
|
||||
5. `t1` is destructed.
|
||||
6. The above steps are repeated on another `QueueTest` object, this time
|
||||
running the `DequeueWorks` test.
|
||||
|
||||
**Availability**: Linux, Windows, Mac.
|
||||
|
||||
## Invoking the Tests
|
||||
|
||||
`TEST()` and `TEST_F()` implicitly register their tests with googletest. So,
|
||||
unlike with many other C++ testing frameworks, you don't have to re-list all
|
||||
your defined tests in order to run them.
|
||||
|
||||
After defining your tests, you can run them with `RUN_ALL_TESTS()`, which
|
||||
returns `0` if all the tests are successful, or `1` otherwise. Note that
|
||||
`RUN_ALL_TESTS()` runs *all tests* in your link unit--they can be from
|
||||
different test suites, or even different source files.
|
||||
|
||||
When invoked, the `RUN_ALL_TESTS()` macro:
|
||||
|
||||
* Saves the state of all googletest flags.
|
||||
|
||||
* Creates a test fixture object for the first test.
|
||||
|
||||
* Initializes it via `SetUp()`.
|
||||
|
||||
* Runs the test on the fixture object.
|
||||
|
||||
* Cleans up the fixture via `TearDown()`.
|
||||
|
||||
* Deletes the fixture.
|
||||
|
||||
* Restores the state of all googletest flags.
|
||||
|
||||
* Repeats the above steps for the next test, until all tests have run.
|
||||
|
||||
If a fatal failure happens the subsequent steps will be skipped.
|
||||
|
||||
> IMPORTANT: You must **not** ignore the return value of `RUN_ALL_TESTS()`, or
|
||||
> you will get a compiler error. The rationale for this design is that the
|
||||
> automated testing service determines whether a test has passed based on its
|
||||
> exit code, not on its stdout/stderr output; thus your `main()` function must
|
||||
> return the value of `RUN_ALL_TESTS()`.
|
||||
>
|
||||
> Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than
|
||||
> once conflicts with some advanced googletest features (e.g., thread-safe
|
||||
> [death tests](advanced.md#death-tests)) and thus is not supported.
|
||||
|
||||
**Availability**: Linux, Windows, Mac.
|
||||
|
||||
## Writing the main() Function
|
||||
|
||||
Write your own main() function, which should return the value of
|
||||
`RUN_ALL_TESTS()`.
|
||||
|
||||
You can start from this boilerplate:
|
||||
|
||||
```c++
|
||||
#include "this/package/foo.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace {
|
||||
|
||||
// The fixture for testing class Foo.
|
||||
class FooTest : public ::testing::Test {
|
||||
protected:
|
||||
// You can remove any or all of the following functions if its body
|
||||
// is empty.
|
||||
|
||||
FooTest() {
|
||||
// You can do set-up work for each test here.
|
||||
}
|
||||
|
||||
~FooTest() override {
|
||||
// You can do clean-up work that doesn't throw exceptions here.
|
||||
}
|
||||
|
||||
// If the constructor and destructor are not enough for setting up
|
||||
// and cleaning up each test, you can define the following methods:
|
||||
|
||||
void SetUp() override {
|
||||
// Code here will be called immediately after the constructor (right
|
||||
// before each test).
|
||||
}
|
||||
|
||||
void TearDown() override {
|
||||
// Code here will be called immediately after each test (right
|
||||
// before the destructor).
|
||||
}
|
||||
|
||||
// Objects declared here can be used by all tests in the test suite for Foo.
|
||||
};
|
||||
|
||||
// Tests that the Foo::Bar() method does Abc.
|
||||
TEST_F(FooTest, MethodBarDoesAbc) {
|
||||
const std::string input_filepath = "this/package/testdata/myinputfile.dat";
|
||||
const std::string output_filepath = "this/package/testdata/myoutputfile.dat";
|
||||
Foo f;
|
||||
EXPECT_EQ(f.Bar(input_filepath, output_filepath), 0);
|
||||
}
|
||||
|
||||
// Tests that Foo does Xyz.
|
||||
TEST_F(FooTest, DoesXyz) {
|
||||
// Exercises the Xyz feature of Foo.
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
```
|
||||
|
||||
The `::testing::InitGoogleTest()` function parses the command line for
|
||||
googletest flags, and removes all recognized flags. This allows the user to
|
||||
control a test program's behavior via various flags, which we'll cover in
|
||||
the [AdvancedGuide](advanced.md). You **must** call this function before calling
|
||||
`RUN_ALL_TESTS()`, or the flags won't be properly initialized.
|
||||
|
||||
On Windows, `InitGoogleTest()` also works with wide strings, so it can be used
|
||||
in programs compiled in `UNICODE` mode as well.
|
||||
|
||||
But maybe you think that writing all those main() functions is too much work? We
|
||||
agree with you completely, and that's why Google Test provides a basic
|
||||
implementation of main(). If it fits your needs, then just link your test with
|
||||
gtest\_main library and you are good to go.
|
||||
|
||||
NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`.
|
||||
|
||||
## Known Limitations
|
||||
|
||||
* Google Test is designed to be thread-safe. The implementation is thread-safe
|
||||
on systems where the `pthreads` library is available. It is currently
|
||||
_unsafe_ to use Google Test assertions from two threads concurrently on
|
||||
other systems (e.g. Windows). In most tests this is not an issue as usually
|
||||
the assertions are done in the main thread. If you want to help, you can
|
||||
volunteer to implement the necessary synchronization primitives in
|
||||
`gtest-port.h` for your platform.
|
190
3rdparty/gtest/docs/pump_manual.md
vendored
Normal file
190
3rdparty/gtest/docs/pump_manual.md
vendored
Normal file
@ -0,0 +1,190 @@
|
||||
<b>P</b>ump is <b>U</b>seful for <b>M</b>eta <b>P</b>rogramming.
|
||||
|
||||
# The Problem
|
||||
|
||||
Template and macro libraries often need to define many classes, functions, or
|
||||
macros that vary only (or almost only) in the number of arguments they take.
|
||||
It's a lot of repetitive, mechanical, and error-prone work.
|
||||
|
||||
Variadic templates and variadic macros can alleviate the problem. However, while
|
||||
both are being considered by the C++ committee, neither is in the standard yet
|
||||
or widely supported by compilers. Thus they are often not a good choice,
|
||||
especially when your code needs to be portable. And their capabilities are still
|
||||
limited.
|
||||
|
||||
As a result, authors of such libraries often have to write scripts to generate
|
||||
their implementation. However, our experience is that it's tedious to write such
|
||||
scripts, which tend to reflect the structure of the generated code poorly and
|
||||
are often hard to read and edit. For example, a small change needed in the
|
||||
generated code may require some non-intuitive, non-trivial changes in the
|
||||
script. This is especially painful when experimenting with the code.
|
||||
|
||||
# Our Solution
|
||||
|
||||
Pump (for Pump is Useful for Meta Programming, Pretty Useful for Meta
|
||||
Programming, or Practical Utility for Meta Programming, whichever you prefer) is
|
||||
a simple meta-programming tool for C++. The idea is that a programmer writes a
|
||||
`foo.pump` file which contains C++ code plus meta code that manipulates the C++
|
||||
code. The meta code can handle iterations over a range, nested iterations, local
|
||||
meta variable definitions, simple arithmetic, and conditional expressions. You
|
||||
can view it as a small Domain-Specific Language. The meta language is designed
|
||||
to be non-intrusive (s.t. it won't confuse Emacs' C++ mode, for example) and
|
||||
concise, making Pump code intuitive and easy to maintain.
|
||||
|
||||
## Highlights
|
||||
|
||||
* The implementation is in a single Python script and thus ultra portable: no
|
||||
build or installation is needed and it works cross platforms.
|
||||
* Pump tries to be smart with respect to
|
||||
[Google's style guide](https://github.com/google/styleguide): it breaks long
|
||||
lines (easy to have when they are generated) at acceptable places to fit
|
||||
within 80 columns and indent the continuation lines correctly.
|
||||
* The format is human-readable and more concise than XML.
|
||||
* The format works relatively well with Emacs' C++ mode.
|
||||
|
||||
## Examples
|
||||
|
||||
The following Pump code (where meta keywords start with `$`, `[[` and `]]` are
|
||||
meta brackets, and `$$` starts a meta comment that ends with the line):
|
||||
|
||||
```
|
||||
$var n = 3 $$ Defines a meta variable n.
|
||||
$range i 0..n $$ Declares the range of meta iterator i (inclusive).
|
||||
$for i [[
|
||||
$$ Meta loop.
|
||||
// Foo$i does blah for $i-ary predicates.
|
||||
$range j 1..i
|
||||
template <size_t N $for j [[, typename A$j]]>
|
||||
class Foo$i {
|
||||
$if i == 0 [[
|
||||
blah a;
|
||||
]] $elif i <= 2 [[
|
||||
blah b;
|
||||
]] $else [[
|
||||
blah c;
|
||||
]]
|
||||
};
|
||||
|
||||
]]
|
||||
```
|
||||
|
||||
will be translated by the Pump compiler to:
|
||||
|
||||
```cpp
|
||||
// Foo0 does blah for 0-ary predicates.
|
||||
template <size_t N>
|
||||
class Foo0 {
|
||||
blah a;
|
||||
};
|
||||
|
||||
// Foo1 does blah for 1-ary predicates.
|
||||
template <size_t N, typename A1>
|
||||
class Foo1 {
|
||||
blah b;
|
||||
};
|
||||
|
||||
// Foo2 does blah for 2-ary predicates.
|
||||
template <size_t N, typename A1, typename A2>
|
||||
class Foo2 {
|
||||
blah b;
|
||||
};
|
||||
|
||||
// Foo3 does blah for 3-ary predicates.
|
||||
template <size_t N, typename A1, typename A2, typename A3>
|
||||
class Foo3 {
|
||||
blah c;
|
||||
};
|
||||
```
|
||||
|
||||
In another example,
|
||||
|
||||
```
|
||||
$range i 1..n
|
||||
Func($for i + [[a$i]]);
|
||||
$$ The text between i and [[ is the separator between iterations.
|
||||
```
|
||||
|
||||
will generate one of the following lines (without the comments), depending on
|
||||
the value of `n`:
|
||||
|
||||
```cpp
|
||||
Func(); // If n is 0.
|
||||
Func(a1); // If n is 1.
|
||||
Func(a1 + a2); // If n is 2.
|
||||
Func(a1 + a2 + a3); // If n is 3.
|
||||
// And so on...
|
||||
```
|
||||
|
||||
## Constructs
|
||||
|
||||
We support the following meta programming constructs:
|
||||
|
||||
| `$var id = exp` | Defines a named constant value. `$id` is |
|
||||
: : valid util the end of the current meta :
|
||||
: : lexical block. :
|
||||
| :------------------------------- | :--------------------------------------- |
|
||||
| `$range id exp..exp` | Sets the range of an iteration variable, |
|
||||
: : which can be reused in multiple loops :
|
||||
: : later. :
|
||||
| `$for id sep [[ code ]]` | Iteration. The range of `id` must have |
|
||||
: : been defined earlier. `$id` is valid in :
|
||||
: : `code`. :
|
||||
| `$($)` | Generates a single `$` character. |
|
||||
| `$id` | Value of the named constant or iteration |
|
||||
: : variable. :
|
||||
| `$(exp)` | Value of the expression. |
|
||||
| `$if exp [[ code ]] else_branch` | Conditional. |
|
||||
| `[[ code ]]` | Meta lexical block. |
|
||||
| `cpp_code` | Raw C++ code. |
|
||||
| `$$ comment` | Meta comment. |
|
||||
|
||||
**Note:** To give the user some freedom in formatting the Pump source code, Pump
|
||||
ignores a new-line character if it's right after `$for foo` or next to `[[` or
|
||||
`]]`. Without this rule you'll often be forced to write very long lines to get
|
||||
the desired output. Therefore sometimes you may need to insert an extra new-line
|
||||
in such places for a new-line to show up in your output.
|
||||
|
||||
## Grammar
|
||||
|
||||
```ebnf
|
||||
code ::= atomic_code*
|
||||
atomic_code ::= $var id = exp
|
||||
| $var id = [[ code ]]
|
||||
| $range id exp..exp
|
||||
| $for id sep [[ code ]]
|
||||
| $($)
|
||||
| $id
|
||||
| $(exp)
|
||||
| $if exp [[ code ]] else_branch
|
||||
| [[ code ]]
|
||||
| cpp_code
|
||||
sep ::= cpp_code | empty_string
|
||||
else_branch ::= $else [[ code ]]
|
||||
| $elif exp [[ code ]] else_branch
|
||||
| empty_string
|
||||
exp ::= simple_expression_in_Python_syntax
|
||||
```
|
||||
|
||||
## Code
|
||||
|
||||
You can find the source code of Pump in [scripts/pump.py](../scripts/pump.py).
|
||||
It is still very unpolished and lacks automated tests, although it has been
|
||||
successfully used many times. If you find a chance to use it in your project,
|
||||
please let us know what you think! We also welcome help on improving Pump.
|
||||
|
||||
## Real Examples
|
||||
|
||||
You can find real-world applications of Pump in
|
||||
[Google Test](https://github.com/google/googletest/tree/master/googletest) and
|
||||
[Google Mock](https://github.com/google/googletest/tree/master/googlemock). The
|
||||
source file `foo.h.pump` generates `foo.h`.
|
||||
|
||||
## Tips
|
||||
|
||||
* If a meta variable is followed by a letter or digit, you can separate them
|
||||
using `[[]]`, which inserts an empty string. For example `Foo$j[[]]Helper`
|
||||
generate `Foo1Helper` when `j` is 1.
|
||||
* To avoid extra-long Pump source lines, you can break a line anywhere you
|
||||
want by inserting `[[]]` followed by a new line. Since any new-line
|
||||
character next to `[[` or `]]` is ignored, the generated code won't contain
|
||||
this new line.
|
22
3rdparty/gtest/docs/samples.md
vendored
Normal file
22
3rdparty/gtest/docs/samples.md
vendored
Normal file
@ -0,0 +1,22 @@
|
||||
# Googletest Samples {#samples}
|
||||
|
||||
If you're like us, you'd like to look at
|
||||
[googletest samples.](https://github.com/google/googletest/tree/master/googletest/samples)
|
||||
The sample directory has a number of well-commented samples showing how to use a
|
||||
variety of googletest features.
|
||||
|
||||
* Sample #1 shows the basic steps of using googletest to test C++ functions.
|
||||
* Sample #2 shows a more complex unit test for a class with multiple member
|
||||
functions.
|
||||
* Sample #3 uses a test fixture.
|
||||
* Sample #4 teaches you how to use googletest and `googletest.h` together to
|
||||
get the best of both libraries.
|
||||
* Sample #5 puts shared testing logic in a base test fixture, and reuses it in
|
||||
derived fixtures.
|
||||
* Sample #6 demonstrates type-parameterized tests.
|
||||
* Sample #7 teaches the basics of value-parameterized tests.
|
||||
* Sample #8 shows using `Combine()` in value-parameterized tests.
|
||||
* Sample #9 shows use of the listener API to modify Google Test's console
|
||||
output and the use of its reflection API to inspect test results.
|
||||
* Sample #10 shows use of the listener API to implement a primitive memory
|
||||
leak checker.
|
343
3rdparty/gtest/include/gtest/gtest-death-test.h
vendored
Normal file
343
3rdparty/gtest/include/gtest/gtest-death-test.h
vendored
Normal file
@ -0,0 +1,343 @@
|
||||
// Copyright 2005, 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.
|
||||
|
||||
//
|
||||
// The Google C++ Testing and Mocking Framework (Google Test)
|
||||
//
|
||||
// This header file defines the public API for death tests. It is
|
||||
// #included by gtest.h so a user doesn't need to include this
|
||||
// directly.
|
||||
// GOOGLETEST_CM0001 DO NOT DELETE
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
|
||||
|
||||
#include "gtest/internal/gtest-death-test-internal.h"
|
||||
|
||||
namespace testing {
|
||||
|
||||
// This flag controls the style of death tests. Valid values are "threadsafe",
|
||||
// meaning that the death test child process will re-execute the test binary
|
||||
// from the start, running only a single death test, or "fast",
|
||||
// meaning that the child process will execute the test logic immediately
|
||||
// after forking.
|
||||
GTEST_DECLARE_string_(death_test_style);
|
||||
|
||||
#if GTEST_HAS_DEATH_TEST
|
||||
|
||||
namespace internal {
|
||||
|
||||
// Returns a Boolean value indicating whether the caller is currently
|
||||
// executing in the context of the death test child process. Tools such as
|
||||
// Valgrind heap checkers may need this to modify their behavior in death
|
||||
// tests. IMPORTANT: This is an internal utility. Using it may break the
|
||||
// implementation of death tests. User code MUST NOT use it.
|
||||
GTEST_API_ bool InDeathTestChild();
|
||||
|
||||
} // namespace internal
|
||||
|
||||
// The following macros are useful for writing death tests.
|
||||
|
||||
// Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is
|
||||
// executed:
|
||||
//
|
||||
// 1. It generates a warning if there is more than one active
|
||||
// thread. This is because it's safe to fork() or clone() only
|
||||
// when there is a single thread.
|
||||
//
|
||||
// 2. The parent process clone()s a sub-process and runs the death
|
||||
// test in it; the sub-process exits with code 0 at the end of the
|
||||
// death test, if it hasn't exited already.
|
||||
//
|
||||
// 3. The parent process waits for the sub-process to terminate.
|
||||
//
|
||||
// 4. The parent process checks the exit code and error message of
|
||||
// the sub-process.
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number");
|
||||
// for (int i = 0; i < 5; i++) {
|
||||
// EXPECT_DEATH(server.ProcessRequest(i),
|
||||
// "Invalid request .* in ProcessRequest()")
|
||||
// << "Failed to die on request " << i;
|
||||
// }
|
||||
//
|
||||
// ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting");
|
||||
//
|
||||
// bool KilledBySIGHUP(int exit_code) {
|
||||
// return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP;
|
||||
// }
|
||||
//
|
||||
// ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!");
|
||||
//
|
||||
// On the regular expressions used in death tests:
|
||||
//
|
||||
// GOOGLETEST_CM0005 DO NOT DELETE
|
||||
// On POSIX-compliant systems (*nix), we use the <regex.h> library,
|
||||
// which uses the POSIX extended regex syntax.
|
||||
//
|
||||
// On other platforms (e.g. Windows or Mac), we only support a simple regex
|
||||
// syntax implemented as part of Google Test. This limited
|
||||
// implementation should be enough most of the time when writing
|
||||
// death tests; though it lacks many features you can find in PCRE
|
||||
// or POSIX extended regex syntax. For example, we don't support
|
||||
// union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and
|
||||
// repetition count ("x{5,7}"), among others.
|
||||
//
|
||||
// Below is the syntax that we do support. We chose it to be a
|
||||
// subset of both PCRE and POSIX extended regex, so it's easy to
|
||||
// learn wherever you come from. In the following: 'A' denotes a
|
||||
// literal character, period (.), or a single \\ escape sequence;
|
||||
// 'x' and 'y' denote regular expressions; 'm' and 'n' are for
|
||||
// natural numbers.
|
||||
//
|
||||
// c matches any literal character c
|
||||
// \\d matches any decimal digit
|
||||
// \\D matches any character that's not a decimal digit
|
||||
// \\f matches \f
|
||||
// \\n matches \n
|
||||
// \\r matches \r
|
||||
// \\s matches any ASCII whitespace, including \n
|
||||
// \\S matches any character that's not a whitespace
|
||||
// \\t matches \t
|
||||
// \\v matches \v
|
||||
// \\w matches any letter, _, or decimal digit
|
||||
// \\W matches any character that \\w doesn't match
|
||||
// \\c matches any literal character c, which must be a punctuation
|
||||
// . matches any single character except \n
|
||||
// A? matches 0 or 1 occurrences of A
|
||||
// A* matches 0 or many occurrences of A
|
||||
// A+ matches 1 or many occurrences of A
|
||||
// ^ matches the beginning of a string (not that of each line)
|
||||
// $ matches the end of a string (not that of each line)
|
||||
// xy matches x followed by y
|
||||
//
|
||||
// If you accidentally use PCRE or POSIX extended regex features
|
||||
// not implemented by us, you will get a run-time failure. In that
|
||||
// case, please try to rewrite your regular expression within the
|
||||
// above syntax.
|
||||
//
|
||||
// This implementation is *not* meant to be as highly tuned or robust
|
||||
// as a compiled regex library, but should perform well enough for a
|
||||
// death test, which already incurs significant overhead by launching
|
||||
// a child process.
|
||||
//
|
||||
// Known caveats:
|
||||
//
|
||||
// A "threadsafe" style death test obtains the path to the test
|
||||
// program from argv[0] and re-executes it in the sub-process. For
|
||||
// simplicity, the current implementation doesn't search the PATH
|
||||
// when launching the sub-process. This means that the user must
|
||||
// invoke the test program via a path that contains at least one
|
||||
// path separator (e.g. path/to/foo_test and
|
||||
// /absolute/path/to/bar_test are fine, but foo_test is not). This
|
||||
// is rarely a problem as people usually don't put the test binary
|
||||
// directory in PATH.
|
||||
//
|
||||
|
||||
// Asserts that a given statement causes the program to exit, with an
|
||||
// integer exit status that satisfies predicate, and emitting error output
|
||||
// that matches regex.
|
||||
# define ASSERT_EXIT(statement, predicate, regex) \
|
||||
GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_)
|
||||
|
||||
// Like ASSERT_EXIT, but continues on to successive tests in the
|
||||
// test suite, if any:
|
||||
# define EXPECT_EXIT(statement, predicate, regex) \
|
||||
GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_)
|
||||
|
||||
// Asserts that a given statement causes the program to exit, either by
|
||||
// explicitly exiting with a nonzero exit code or being killed by a
|
||||
// signal, and emitting error output that matches regex.
|
||||
# define ASSERT_DEATH(statement, regex) \
|
||||
ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
|
||||
|
||||
// Like ASSERT_DEATH, but continues on to successive tests in the
|
||||
// test suite, if any:
|
||||
# define EXPECT_DEATH(statement, regex) \
|
||||
EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
|
||||
|
||||
// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
|
||||
|
||||
// Tests that an exit code describes a normal exit with a given exit code.
|
||||
class GTEST_API_ ExitedWithCode {
|
||||
public:
|
||||
explicit ExitedWithCode(int exit_code);
|
||||
bool operator()(int exit_status) const;
|
||||
private:
|
||||
// No implementation - assignment is unsupported.
|
||||
void operator=(const ExitedWithCode& other);
|
||||
|
||||
const int exit_code_;
|
||||
};
|
||||
|
||||
# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
|
||||
// Tests that an exit code describes an exit due to termination by a
|
||||
// given signal.
|
||||
// GOOGLETEST_CM0006 DO NOT DELETE
|
||||
class GTEST_API_ KilledBySignal {
|
||||
public:
|
||||
explicit KilledBySignal(int signum);
|
||||
bool operator()(int exit_status) const;
|
||||
private:
|
||||
const int signum_;
|
||||
};
|
||||
# endif // !GTEST_OS_WINDOWS
|
||||
|
||||
// EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode.
|
||||
// The death testing framework causes this to have interesting semantics,
|
||||
// since the sideeffects of the call are only visible in opt mode, and not
|
||||
// in debug mode.
|
||||
//
|
||||
// In practice, this can be used to test functions that utilize the
|
||||
// LOG(DFATAL) macro using the following style:
|
||||
//
|
||||
// int DieInDebugOr12(int* sideeffect) {
|
||||
// if (sideeffect) {
|
||||
// *sideeffect = 12;
|
||||
// }
|
||||
// LOG(DFATAL) << "death";
|
||||
// return 12;
|
||||
// }
|
||||
//
|
||||
// TEST(TestSuite, TestDieOr12WorksInDgbAndOpt) {
|
||||
// int sideeffect = 0;
|
||||
// // Only asserts in dbg.
|
||||
// EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death");
|
||||
//
|
||||
// #ifdef NDEBUG
|
||||
// // opt-mode has sideeffect visible.
|
||||
// EXPECT_EQ(12, sideeffect);
|
||||
// #else
|
||||
// // dbg-mode no visible sideeffect.
|
||||
// EXPECT_EQ(0, sideeffect);
|
||||
// #endif
|
||||
// }
|
||||
//
|
||||
// This will assert that DieInDebugReturn12InOpt() crashes in debug
|
||||
// mode, usually due to a DCHECK or LOG(DFATAL), but returns the
|
||||
// appropriate fallback value (12 in this case) in opt mode. If you
|
||||
// need to test that a function has appropriate side-effects in opt
|
||||
// mode, include assertions against the side-effects. A general
|
||||
// pattern for this is:
|
||||
//
|
||||
// EXPECT_DEBUG_DEATH({
|
||||
// // Side-effects here will have an effect after this statement in
|
||||
// // opt mode, but none in debug mode.
|
||||
// EXPECT_EQ(12, DieInDebugOr12(&sideeffect));
|
||||
// }, "death");
|
||||
//
|
||||
# ifdef NDEBUG
|
||||
|
||||
# define EXPECT_DEBUG_DEATH(statement, regex) \
|
||||
GTEST_EXECUTE_STATEMENT_(statement, regex)
|
||||
|
||||
# define ASSERT_DEBUG_DEATH(statement, regex) \
|
||||
GTEST_EXECUTE_STATEMENT_(statement, regex)
|
||||
|
||||
# else
|
||||
|
||||
# define EXPECT_DEBUG_DEATH(statement, regex) \
|
||||
EXPECT_DEATH(statement, regex)
|
||||
|
||||
# define ASSERT_DEBUG_DEATH(statement, regex) \
|
||||
ASSERT_DEATH(statement, regex)
|
||||
|
||||
# endif // NDEBUG for EXPECT_DEBUG_DEATH
|
||||
#endif // GTEST_HAS_DEATH_TEST
|
||||
|
||||
// This macro is used for implementing macros such as
|
||||
// EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where
|
||||
// death tests are not supported. Those macros must compile on such systems
|
||||
// if and only if EXPECT_DEATH and ASSERT_DEATH compile with the same parameters
|
||||
// on systems that support death tests. This allows one to write such a macro on
|
||||
// a system that does not support death tests and be sure that it will compile
|
||||
// on a death-test supporting system. It is exposed publicly so that systems
|
||||
// that have death-tests with stricter requirements than GTEST_HAS_DEATH_TEST
|
||||
// can write their own equivalent of EXPECT_DEATH_IF_SUPPORTED and
|
||||
// ASSERT_DEATH_IF_SUPPORTED.
|
||||
//
|
||||
// Parameters:
|
||||
// statement - A statement that a macro such as EXPECT_DEATH would test
|
||||
// for program termination. This macro has to make sure this
|
||||
// statement is compiled but not executed, to ensure that
|
||||
// EXPECT_DEATH_IF_SUPPORTED compiles with a certain
|
||||
// parameter if and only if EXPECT_DEATH compiles with it.
|
||||
// regex - A regex that a macro such as EXPECT_DEATH would use to test
|
||||
// the output of statement. This parameter has to be
|
||||
// compiled but not evaluated by this macro, to ensure that
|
||||
// this macro only accepts expressions that a macro such as
|
||||
// EXPECT_DEATH would accept.
|
||||
// terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED
|
||||
// and a return statement for ASSERT_DEATH_IF_SUPPORTED.
|
||||
// This ensures that ASSERT_DEATH_IF_SUPPORTED will not
|
||||
// compile inside functions where ASSERT_DEATH doesn't
|
||||
// compile.
|
||||
//
|
||||
// The branch that has an always false condition is used to ensure that
|
||||
// statement and regex are compiled (and thus syntactically correct) but
|
||||
// never executed. The unreachable code macro protects the terminator
|
||||
// statement from generating an 'unreachable code' warning in case
|
||||
// statement unconditionally returns or throws. The Message constructor at
|
||||
// the end allows the syntax of streaming additional messages into the
|
||||
// macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
|
||||
# define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
|
||||
if (::testing::internal::AlwaysTrue()) { \
|
||||
GTEST_LOG_(WARNING) \
|
||||
<< "Death tests are not supported on this platform.\n" \
|
||||
<< "Statement '" #statement "' cannot be verified."; \
|
||||
} else if (::testing::internal::AlwaysFalse()) { \
|
||||
::testing::internal::RE::PartialMatch(".*", (regex)); \
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
|
||||
terminator; \
|
||||
} else \
|
||||
::testing::Message()
|
||||
|
||||
// EXPECT_DEATH_IF_SUPPORTED(statement, regex) and
|
||||
// ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if
|
||||
// death tests are supported; otherwise they just issue a warning. This is
|
||||
// useful when you are combining death test assertions with normal test
|
||||
// assertions in one test.
|
||||
#if GTEST_HAS_DEATH_TEST
|
||||
# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
EXPECT_DEATH(statement, regex)
|
||||
# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
ASSERT_DEATH(statement, regex)
|
||||
#else
|
||||
# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, )
|
||||
# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return)
|
||||
#endif
|
||||
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
|
750
3rdparty/gtest/include/gtest/gtest-matchers.h
vendored
Normal file
750
3rdparty/gtest/include/gtest/gtest-matchers.h
vendored
Normal file
@ -0,0 +1,750 @@
|
||||
// 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.
|
||||
|
||||
// The Google C++ Testing and Mocking Framework (Google Test)
|
||||
//
|
||||
// This file implements just enough of the matcher interface to allow
|
||||
// EXPECT_DEATH and friends to accept a matcher argument.
|
||||
|
||||
// IWYU pragma: private, include "testing/base/public/gunit.h"
|
||||
// IWYU pragma: friend third_party/googletest/googlemock/.*
|
||||
// IWYU pragma: friend third_party/googletest/googletest/.*
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
|
||||
|
||||
#include <memory>
|
||||
#include <ostream>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
|
||||
#include "gtest/gtest-printers.h"
|
||||
#include "gtest/internal/gtest-internal.h"
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
|
||||
// MSVC warning C5046 is new as of VS2017 version 15.8.
|
||||
#if defined(_MSC_VER) && _MSC_VER >= 1915
|
||||
#define GTEST_MAYBE_5046_ 5046
|
||||
#else
|
||||
#define GTEST_MAYBE_5046_
|
||||
#endif
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_PUSH_(
|
||||
4251 GTEST_MAYBE_5046_ /* class A needs to have dll-interface to be used by
|
||||
clients of class B */
|
||||
/* Symbol involving type with internal linkage not defined */)
|
||||
|
||||
namespace testing {
|
||||
|
||||
// To implement a matcher Foo for type T, define:
|
||||
// 1. a class FooMatcherImpl that implements the
|
||||
// MatcherInterface<T> interface, and
|
||||
// 2. a factory function that creates a Matcher<T> object from a
|
||||
// FooMatcherImpl*.
|
||||
//
|
||||
// The two-level delegation design makes it possible to allow a user
|
||||
// to write "v" instead of "Eq(v)" where a Matcher is expected, which
|
||||
// is impossible if we pass matchers by pointers. It also eases
|
||||
// ownership management as Matcher objects can now be copied like
|
||||
// plain values.
|
||||
|
||||
// MatchResultListener is an abstract class. Its << operator can be
|
||||
// used by a matcher to explain why a value matches or doesn't match.
|
||||
//
|
||||
class MatchResultListener {
|
||||
public:
|
||||
// Creates a listener object with the given underlying ostream. The
|
||||
// listener does not own the ostream, and does not dereference it
|
||||
// in the constructor or destructor.
|
||||
explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
|
||||
virtual ~MatchResultListener() = 0; // Makes this class abstract.
|
||||
|
||||
// Streams x to the underlying ostream; does nothing if the ostream
|
||||
// is NULL.
|
||||
template <typename T>
|
||||
MatchResultListener& operator<<(const T& x) {
|
||||
if (stream_ != nullptr) *stream_ << x;
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Returns the underlying ostream.
|
||||
::std::ostream* stream() { return stream_; }
|
||||
|
||||
// Returns true if and only if the listener is interested in an explanation
|
||||
// of the match result. A matcher's MatchAndExplain() method can use
|
||||
// this information to avoid generating the explanation when no one
|
||||
// intends to hear it.
|
||||
bool IsInterested() const { return stream_ != nullptr; }
|
||||
|
||||
private:
|
||||
::std::ostream* const stream_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
|
||||
};
|
||||
|
||||
inline MatchResultListener::~MatchResultListener() {
|
||||
}
|
||||
|
||||
// An instance of a subclass of this knows how to describe itself as a
|
||||
// matcher.
|
||||
class MatcherDescriberInterface {
|
||||
public:
|
||||
virtual ~MatcherDescriberInterface() {}
|
||||
|
||||
// Describes this matcher to an ostream. The function should print
|
||||
// a verb phrase that describes the property a value matching this
|
||||
// matcher should have. The subject of the verb phrase is the value
|
||||
// being matched. For example, the DescribeTo() method of the Gt(7)
|
||||
// matcher prints "is greater than 7".
|
||||
virtual void DescribeTo(::std::ostream* os) const = 0;
|
||||
|
||||
// Describes the negation of this matcher to an ostream. For
|
||||
// example, if the description of this matcher is "is greater than
|
||||
// 7", the negated description could be "is not greater than 7".
|
||||
// You are not required to override this when implementing
|
||||
// MatcherInterface, but it is highly advised so that your matcher
|
||||
// can produce good error messages.
|
||||
virtual void DescribeNegationTo(::std::ostream* os) const {
|
||||
*os << "not (";
|
||||
DescribeTo(os);
|
||||
*os << ")";
|
||||
}
|
||||
};
|
||||
|
||||
// The implementation of a matcher.
|
||||
template <typename T>
|
||||
class MatcherInterface : public MatcherDescriberInterface {
|
||||
public:
|
||||
// Returns true if and only if the matcher matches x; also explains the
|
||||
// match result to 'listener' if necessary (see the next paragraph), in
|
||||
// the form of a non-restrictive relative clause ("which ...",
|
||||
// "whose ...", etc) that describes x. For example, the
|
||||
// MatchAndExplain() method of the Pointee(...) matcher should
|
||||
// generate an explanation like "which points to ...".
|
||||
//
|
||||
// Implementations of MatchAndExplain() should add an explanation of
|
||||
// the match result *if and only if* they can provide additional
|
||||
// information that's not already present (or not obvious) in the
|
||||
// print-out of x and the matcher's description. Whether the match
|
||||
// succeeds is not a factor in deciding whether an explanation is
|
||||
// needed, as sometimes the caller needs to print a failure message
|
||||
// when the match succeeds (e.g. when the matcher is used inside
|
||||
// Not()).
|
||||
//
|
||||
// For example, a "has at least 10 elements" matcher should explain
|
||||
// what the actual element count is, regardless of the match result,
|
||||
// as it is useful information to the reader; on the other hand, an
|
||||
// "is empty" matcher probably only needs to explain what the actual
|
||||
// size is when the match fails, as it's redundant to say that the
|
||||
// size is 0 when the value is already known to be empty.
|
||||
//
|
||||
// You should override this method when defining a new matcher.
|
||||
//
|
||||
// It's the responsibility of the caller (Google Test) to guarantee
|
||||
// that 'listener' is not NULL. This helps to simplify a matcher's
|
||||
// implementation when it doesn't care about the performance, as it
|
||||
// can talk to 'listener' without checking its validity first.
|
||||
// However, in order to implement dummy listeners efficiently,
|
||||
// listener->stream() may be NULL.
|
||||
virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
|
||||
|
||||
// Inherits these methods from MatcherDescriberInterface:
|
||||
// virtual void DescribeTo(::std::ostream* os) const = 0;
|
||||
// virtual void DescribeNegationTo(::std::ostream* os) const;
|
||||
};
|
||||
|
||||
namespace internal {
|
||||
|
||||
// Converts a MatcherInterface<T> to a MatcherInterface<const T&>.
|
||||
template <typename T>
|
||||
class MatcherInterfaceAdapter : public MatcherInterface<const T&> {
|
||||
public:
|
||||
explicit MatcherInterfaceAdapter(const MatcherInterface<T>* impl)
|
||||
: impl_(impl) {}
|
||||
~MatcherInterfaceAdapter() override { delete impl_; }
|
||||
|
||||
void DescribeTo(::std::ostream* os) const override { impl_->DescribeTo(os); }
|
||||
|
||||
void DescribeNegationTo(::std::ostream* os) const override {
|
||||
impl_->DescribeNegationTo(os);
|
||||
}
|
||||
|
||||
bool MatchAndExplain(const T& x,
|
||||
MatchResultListener* listener) const override {
|
||||
return impl_->MatchAndExplain(x, listener);
|
||||
}
|
||||
|
||||
private:
|
||||
const MatcherInterface<T>* const impl_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(MatcherInterfaceAdapter);
|
||||
};
|
||||
|
||||
struct AnyEq {
|
||||
template <typename A, typename B>
|
||||
bool operator()(const A& a, const B& b) const { return a == b; }
|
||||
};
|
||||
struct AnyNe {
|
||||
template <typename A, typename B>
|
||||
bool operator()(const A& a, const B& b) const { return a != b; }
|
||||
};
|
||||
struct AnyLt {
|
||||
template <typename A, typename B>
|
||||
bool operator()(const A& a, const B& b) const { return a < b; }
|
||||
};
|
||||
struct AnyGt {
|
||||
template <typename A, typename B>
|
||||
bool operator()(const A& a, const B& b) const { return a > b; }
|
||||
};
|
||||
struct AnyLe {
|
||||
template <typename A, typename B>
|
||||
bool operator()(const A& a, const B& b) const { return a <= b; }
|
||||
};
|
||||
struct AnyGe {
|
||||
template <typename A, typename B>
|
||||
bool operator()(const A& a, const B& b) const { return a >= b; }
|
||||
};
|
||||
|
||||
// A match result listener that ignores the explanation.
|
||||
class DummyMatchResultListener : public MatchResultListener {
|
||||
public:
|
||||
DummyMatchResultListener() : MatchResultListener(nullptr) {}
|
||||
|
||||
private:
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
|
||||
};
|
||||
|
||||
// A match result listener that forwards the explanation to a given
|
||||
// ostream. The difference between this and MatchResultListener is
|
||||
// that the former is concrete.
|
||||
class StreamMatchResultListener : public MatchResultListener {
|
||||
public:
|
||||
explicit StreamMatchResultListener(::std::ostream* os)
|
||||
: MatchResultListener(os) {}
|
||||
|
||||
private:
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
|
||||
};
|
||||
|
||||
// An internal class for implementing Matcher<T>, which will derive
|
||||
// from it. We put functionalities common to all Matcher<T>
|
||||
// specializations here to avoid code duplication.
|
||||
template <typename T>
|
||||
class MatcherBase {
|
||||
public:
|
||||
// Returns true if and only if the matcher matches x; also explains the
|
||||
// match result to 'listener'.
|
||||
bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
|
||||
return impl_->MatchAndExplain(x, listener);
|
||||
}
|
||||
|
||||
// Returns true if and only if this matcher matches x.
|
||||
bool Matches(const T& x) const {
|
||||
DummyMatchResultListener dummy;
|
||||
return MatchAndExplain(x, &dummy);
|
||||
}
|
||||
|
||||
// Describes this matcher to an ostream.
|
||||
void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
|
||||
|
||||
// Describes the negation of this matcher to an ostream.
|
||||
void DescribeNegationTo(::std::ostream* os) const {
|
||||
impl_->DescribeNegationTo(os);
|
||||
}
|
||||
|
||||
// Explains why x matches, or doesn't match, the matcher.
|
||||
void ExplainMatchResultTo(const T& x, ::std::ostream* os) const {
|
||||
StreamMatchResultListener listener(os);
|
||||
MatchAndExplain(x, &listener);
|
||||
}
|
||||
|
||||
// Returns the describer for this matcher object; retains ownership
|
||||
// of the describer, which is only guaranteed to be alive when
|
||||
// this matcher object is alive.
|
||||
const MatcherDescriberInterface* GetDescriber() const {
|
||||
return impl_.get();
|
||||
}
|
||||
|
||||
protected:
|
||||
MatcherBase() {}
|
||||
|
||||
// Constructs a matcher from its implementation.
|
||||
explicit MatcherBase(const MatcherInterface<const T&>* impl) : impl_(impl) {}
|
||||
|
||||
template <typename U>
|
||||
explicit MatcherBase(
|
||||
const MatcherInterface<U>* impl,
|
||||
typename std::enable_if<!std::is_same<U, const U&>::value>::type* =
|
||||
nullptr)
|
||||
: impl_(new internal::MatcherInterfaceAdapter<U>(impl)) {}
|
||||
|
||||
MatcherBase(const MatcherBase&) = default;
|
||||
MatcherBase& operator=(const MatcherBase&) = default;
|
||||
MatcherBase(MatcherBase&&) = default;
|
||||
MatcherBase& operator=(MatcherBase&&) = default;
|
||||
|
||||
virtual ~MatcherBase() {}
|
||||
|
||||
private:
|
||||
std::shared_ptr<const MatcherInterface<const T&>> impl_;
|
||||
};
|
||||
|
||||
} // namespace internal
|
||||
|
||||
// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
|
||||
// object that can check whether a value of type T matches. The
|
||||
// implementation of Matcher<T> is just a std::shared_ptr to const
|
||||
// MatcherInterface<T>. Don't inherit from Matcher!
|
||||
template <typename T>
|
||||
class Matcher : public internal::MatcherBase<T> {
|
||||
public:
|
||||
// Constructs a null matcher. Needed for storing Matcher objects in STL
|
||||
// containers. A default-constructed matcher is not yet initialized. You
|
||||
// cannot use it until a valid value has been assigned to it.
|
||||
explicit Matcher() {} // NOLINT
|
||||
|
||||
// Constructs a matcher from its implementation.
|
||||
explicit Matcher(const MatcherInterface<const T&>* impl)
|
||||
: internal::MatcherBase<T>(impl) {}
|
||||
|
||||
template <typename U>
|
||||
explicit Matcher(
|
||||
const MatcherInterface<U>* impl,
|
||||
typename std::enable_if<!std::is_same<U, const U&>::value>::type* =
|
||||
nullptr)
|
||||
: internal::MatcherBase<T>(impl) {}
|
||||
|
||||
// Implicit constructor here allows people to write
|
||||
// EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
|
||||
Matcher(T value); // NOLINT
|
||||
};
|
||||
|
||||
// The following two specializations allow the user to write str
|
||||
// instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
|
||||
// matcher is expected.
|
||||
template <>
|
||||
class GTEST_API_ Matcher<const std::string&>
|
||||
: public internal::MatcherBase<const std::string&> {
|
||||
public:
|
||||
Matcher() {}
|
||||
|
||||
explicit Matcher(const MatcherInterface<const std::string&>* impl)
|
||||
: internal::MatcherBase<const std::string&>(impl) {}
|
||||
|
||||
// Allows the user to write str instead of Eq(str) sometimes, where
|
||||
// str is a std::string object.
|
||||
Matcher(const std::string& s); // NOLINT
|
||||
|
||||
// Allows the user to write "foo" instead of Eq("foo") sometimes.
|
||||
Matcher(const char* s); // NOLINT
|
||||
};
|
||||
|
||||
template <>
|
||||
class GTEST_API_ Matcher<std::string>
|
||||
: public internal::MatcherBase<std::string> {
|
||||
public:
|
||||
Matcher() {}
|
||||
|
||||
explicit Matcher(const MatcherInterface<const std::string&>* impl)
|
||||
: internal::MatcherBase<std::string>(impl) {}
|
||||
explicit Matcher(const MatcherInterface<std::string>* impl)
|
||||
: internal::MatcherBase<std::string>(impl) {}
|
||||
|
||||
// Allows the user to write str instead of Eq(str) sometimes, where
|
||||
// str is a string object.
|
||||
Matcher(const std::string& s); // NOLINT
|
||||
|
||||
// Allows the user to write "foo" instead of Eq("foo") sometimes.
|
||||
Matcher(const char* s); // NOLINT
|
||||
};
|
||||
|
||||
#if GTEST_HAS_ABSL
|
||||
// The following two specializations allow the user to write str
|
||||
// instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
|
||||
// matcher is expected.
|
||||
template <>
|
||||
class GTEST_API_ Matcher<const absl::string_view&>
|
||||
: public internal::MatcherBase<const absl::string_view&> {
|
||||
public:
|
||||
Matcher() {}
|
||||
|
||||
explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
|
||||
: internal::MatcherBase<const absl::string_view&>(impl) {}
|
||||
|
||||
// Allows the user to write str instead of Eq(str) sometimes, where
|
||||
// str is a std::string object.
|
||||
Matcher(const std::string& s); // NOLINT
|
||||
|
||||
// Allows the user to write "foo" instead of Eq("foo") sometimes.
|
||||
Matcher(const char* s); // NOLINT
|
||||
|
||||
// Allows the user to pass absl::string_views directly.
|
||||
Matcher(absl::string_view s); // NOLINT
|
||||
};
|
||||
|
||||
template <>
|
||||
class GTEST_API_ Matcher<absl::string_view>
|
||||
: public internal::MatcherBase<absl::string_view> {
|
||||
public:
|
||||
Matcher() {}
|
||||
|
||||
explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
|
||||
: internal::MatcherBase<absl::string_view>(impl) {}
|
||||
explicit Matcher(const MatcherInterface<absl::string_view>* impl)
|
||||
: internal::MatcherBase<absl::string_view>(impl) {}
|
||||
|
||||
// Allows the user to write str instead of Eq(str) sometimes, where
|
||||
// str is a std::string object.
|
||||
Matcher(const std::string& s); // NOLINT
|
||||
|
||||
// Allows the user to write "foo" instead of Eq("foo") sometimes.
|
||||
Matcher(const char* s); // NOLINT
|
||||
|
||||
// Allows the user to pass absl::string_views directly.
|
||||
Matcher(absl::string_view s); // NOLINT
|
||||
};
|
||||
#endif // GTEST_HAS_ABSL
|
||||
|
||||
// Prints a matcher in a human-readable format.
|
||||
template <typename T>
|
||||
std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
|
||||
matcher.DescribeTo(&os);
|
||||
return os;
|
||||
}
|
||||
|
||||
// The PolymorphicMatcher class template makes it easy to implement a
|
||||
// polymorphic matcher (i.e. a matcher that can match values of more
|
||||
// than one type, e.g. Eq(n) and NotNull()).
|
||||
//
|
||||
// To define a polymorphic matcher, a user should provide an Impl
|
||||
// class that has a DescribeTo() method and a DescribeNegationTo()
|
||||
// method, and define a member function (or member function template)
|
||||
//
|
||||
// bool MatchAndExplain(const Value& value,
|
||||
// MatchResultListener* listener) const;
|
||||
//
|
||||
// See the definition of NotNull() for a complete example.
|
||||
template <class Impl>
|
||||
class PolymorphicMatcher {
|
||||
public:
|
||||
explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
|
||||
|
||||
// Returns a mutable reference to the underlying matcher
|
||||
// implementation object.
|
||||
Impl& mutable_impl() { return impl_; }
|
||||
|
||||
// Returns an immutable reference to the underlying matcher
|
||||
// implementation object.
|
||||
const Impl& impl() const { return impl_; }
|
||||
|
||||
template <typename T>
|
||||
operator Matcher<T>() const {
|
||||
return Matcher<T>(new MonomorphicImpl<const T&>(impl_));
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename T>
|
||||
class MonomorphicImpl : public MatcherInterface<T> {
|
||||
public:
|
||||
explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
|
||||
|
||||
virtual void DescribeTo(::std::ostream* os) const { impl_.DescribeTo(os); }
|
||||
|
||||
virtual void DescribeNegationTo(::std::ostream* os) const {
|
||||
impl_.DescribeNegationTo(os);
|
||||
}
|
||||
|
||||
virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
|
||||
return impl_.MatchAndExplain(x, listener);
|
||||
}
|
||||
|
||||
private:
|
||||
const Impl impl_;
|
||||
};
|
||||
|
||||
Impl impl_;
|
||||
};
|
||||
|
||||
// Creates a matcher from its implementation.
|
||||
// DEPRECATED: Especially in the generic code, prefer:
|
||||
// Matcher<T>(new MyMatcherImpl<const T&>(...));
|
||||
//
|
||||
// MakeMatcher may create a Matcher that accepts its argument by value, which
|
||||
// leads to unnecessary copies & lack of support for non-copyable types.
|
||||
template <typename T>
|
||||
inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
|
||||
return Matcher<T>(impl);
|
||||
}
|
||||
|
||||
// Creates a polymorphic matcher from its implementation. This is
|
||||
// easier to use than the PolymorphicMatcher<Impl> constructor as it
|
||||
// doesn't require you to explicitly write the template argument, e.g.
|
||||
//
|
||||
// MakePolymorphicMatcher(foo);
|
||||
// vs
|
||||
// PolymorphicMatcher<TypeOfFoo>(foo);
|
||||
template <class Impl>
|
||||
inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
|
||||
return PolymorphicMatcher<Impl>(impl);
|
||||
}
|
||||
|
||||
namespace internal {
|
||||
// Implements a matcher that compares a given value with a
|
||||
// pre-supplied value using one of the ==, <=, <, etc, operators. The
|
||||
// two values being compared don't have to have the same type.
|
||||
//
|
||||
// The matcher defined here is polymorphic (for example, Eq(5) can be
|
||||
// used to match an int, a short, a double, etc). Therefore we use
|
||||
// a template type conversion operator in the implementation.
|
||||
//
|
||||
// The following template definition assumes that the Rhs parameter is
|
||||
// a "bare" type (i.e. neither 'const T' nor 'T&').
|
||||
template <typename D, typename Rhs, typename Op>
|
||||
class ComparisonBase {
|
||||
public:
|
||||
explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
|
||||
template <typename Lhs>
|
||||
operator Matcher<Lhs>() const {
|
||||
return Matcher<Lhs>(new Impl<const Lhs&>(rhs_));
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename T>
|
||||
static const T& Unwrap(const T& v) { return v; }
|
||||
template <typename T>
|
||||
static const T& Unwrap(std::reference_wrapper<T> v) { return v; }
|
||||
|
||||
template <typename Lhs, typename = Rhs>
|
||||
class Impl : public MatcherInterface<Lhs> {
|
||||
public:
|
||||
explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
|
||||
bool MatchAndExplain(Lhs lhs,
|
||||
MatchResultListener* /* listener */) const override {
|
||||
return Op()(lhs, Unwrap(rhs_));
|
||||
}
|
||||
void DescribeTo(::std::ostream* os) const override {
|
||||
*os << D::Desc() << " ";
|
||||
UniversalPrint(Unwrap(rhs_), os);
|
||||
}
|
||||
void DescribeNegationTo(::std::ostream* os) const override {
|
||||
*os << D::NegatedDesc() << " ";
|
||||
UniversalPrint(Unwrap(rhs_), os);
|
||||
}
|
||||
|
||||
private:
|
||||
Rhs rhs_;
|
||||
};
|
||||
Rhs rhs_;
|
||||
};
|
||||
|
||||
template <typename Rhs>
|
||||
class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
|
||||
public:
|
||||
explicit EqMatcher(const Rhs& rhs)
|
||||
: ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
|
||||
static const char* Desc() { return "is equal to"; }
|
||||
static const char* NegatedDesc() { return "isn't equal to"; }
|
||||
};
|
||||
template <typename Rhs>
|
||||
class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
|
||||
public:
|
||||
explicit NeMatcher(const Rhs& rhs)
|
||||
: ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
|
||||
static const char* Desc() { return "isn't equal to"; }
|
||||
static const char* NegatedDesc() { return "is equal to"; }
|
||||
};
|
||||
template <typename Rhs>
|
||||
class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
|
||||
public:
|
||||
explicit LtMatcher(const Rhs& rhs)
|
||||
: ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
|
||||
static const char* Desc() { return "is <"; }
|
||||
static const char* NegatedDesc() { return "isn't <"; }
|
||||
};
|
||||
template <typename Rhs>
|
||||
class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
|
||||
public:
|
||||
explicit GtMatcher(const Rhs& rhs)
|
||||
: ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
|
||||
static const char* Desc() { return "is >"; }
|
||||
static const char* NegatedDesc() { return "isn't >"; }
|
||||
};
|
||||
template <typename Rhs>
|
||||
class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
|
||||
public:
|
||||
explicit LeMatcher(const Rhs& rhs)
|
||||
: ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
|
||||
static const char* Desc() { return "is <="; }
|
||||
static const char* NegatedDesc() { return "isn't <="; }
|
||||
};
|
||||
template <typename Rhs>
|
||||
class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
|
||||
public:
|
||||
explicit GeMatcher(const Rhs& rhs)
|
||||
: ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
|
||||
static const char* Desc() { return "is >="; }
|
||||
static const char* NegatedDesc() { return "isn't >="; }
|
||||
};
|
||||
|
||||
// Implements polymorphic matchers MatchesRegex(regex) and
|
||||
// ContainsRegex(regex), which can be used as a Matcher<T> as long as
|
||||
// T can be converted to a string.
|
||||
class MatchesRegexMatcher {
|
||||
public:
|
||||
MatchesRegexMatcher(const RE* regex, bool full_match)
|
||||
: regex_(regex), full_match_(full_match) {}
|
||||
|
||||
#if GTEST_HAS_ABSL
|
||||
bool MatchAndExplain(const absl::string_view& s,
|
||||
MatchResultListener* listener) const {
|
||||
return MatchAndExplain(std::string(s), listener);
|
||||
}
|
||||
#endif // GTEST_HAS_ABSL
|
||||
|
||||
// Accepts pointer types, particularly:
|
||||
// const char*
|
||||
// char*
|
||||
// const wchar_t*
|
||||
// wchar_t*
|
||||
template <typename CharType>
|
||||
bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
|
||||
return s != nullptr && MatchAndExplain(std::string(s), listener);
|
||||
}
|
||||
|
||||
// Matches anything that can convert to std::string.
|
||||
//
|
||||
// This is a template, not just a plain function with const std::string&,
|
||||
// because absl::string_view has some interfering non-explicit constructors.
|
||||
template <class MatcheeStringType>
|
||||
bool MatchAndExplain(const MatcheeStringType& s,
|
||||
MatchResultListener* /* listener */) const {
|
||||
const std::string& s2(s);
|
||||
return full_match_ ? RE::FullMatch(s2, *regex_)
|
||||
: RE::PartialMatch(s2, *regex_);
|
||||
}
|
||||
|
||||
void DescribeTo(::std::ostream* os) const {
|
||||
*os << (full_match_ ? "matches" : "contains") << " regular expression ";
|
||||
UniversalPrinter<std::string>::Print(regex_->pattern(), os);
|
||||
}
|
||||
|
||||
void DescribeNegationTo(::std::ostream* os) const {
|
||||
*os << "doesn't " << (full_match_ ? "match" : "contain")
|
||||
<< " regular expression ";
|
||||
UniversalPrinter<std::string>::Print(regex_->pattern(), os);
|
||||
}
|
||||
|
||||
private:
|
||||
const std::shared_ptr<const RE> regex_;
|
||||
const bool full_match_;
|
||||
};
|
||||
} // namespace internal
|
||||
|
||||
// Matches a string that fully matches regular expression 'regex'.
|
||||
// The matcher takes ownership of 'regex'.
|
||||
inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
|
||||
const internal::RE* regex) {
|
||||
return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
|
||||
}
|
||||
inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
|
||||
const std::string& regex) {
|
||||
return MatchesRegex(new internal::RE(regex));
|
||||
}
|
||||
|
||||
// Matches a string that contains regular expression 'regex'.
|
||||
// The matcher takes ownership of 'regex'.
|
||||
inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
|
||||
const internal::RE* regex) {
|
||||
return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
|
||||
}
|
||||
inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
|
||||
const std::string& regex) {
|
||||
return ContainsRegex(new internal::RE(regex));
|
||||
}
|
||||
|
||||
// Creates a polymorphic matcher that matches anything equal to x.
|
||||
// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
|
||||
// wouldn't compile.
|
||||
template <typename T>
|
||||
inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
|
||||
|
||||
// Constructs a Matcher<T> from a 'value' of type T. The constructed
|
||||
// matcher matches any value that's equal to 'value'.
|
||||
template <typename T>
|
||||
Matcher<T>::Matcher(T value) { *this = Eq(value); }
|
||||
|
||||
// Creates a monomorphic matcher that matches anything with type Lhs
|
||||
// and equal to rhs. A user may need to use this instead of Eq(...)
|
||||
// in order to resolve an overloading ambiguity.
|
||||
//
|
||||
// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
|
||||
// or Matcher<T>(x), but more readable than the latter.
|
||||
//
|
||||
// We could define similar monomorphic matchers for other comparison
|
||||
// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
|
||||
// it yet as those are used much less than Eq() in practice. A user
|
||||
// can always write Matcher<T>(Lt(5)) to be explicit about the type,
|
||||
// for example.
|
||||
template <typename Lhs, typename Rhs>
|
||||
inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
|
||||
|
||||
// Creates a polymorphic matcher that matches anything >= x.
|
||||
template <typename Rhs>
|
||||
inline internal::GeMatcher<Rhs> Ge(Rhs x) {
|
||||
return internal::GeMatcher<Rhs>(x);
|
||||
}
|
||||
|
||||
// Creates a polymorphic matcher that matches anything > x.
|
||||
template <typename Rhs>
|
||||
inline internal::GtMatcher<Rhs> Gt(Rhs x) {
|
||||
return internal::GtMatcher<Rhs>(x);
|
||||
}
|
||||
|
||||
// Creates a polymorphic matcher that matches anything <= x.
|
||||
template <typename Rhs>
|
||||
inline internal::LeMatcher<Rhs> Le(Rhs x) {
|
||||
return internal::LeMatcher<Rhs>(x);
|
||||
}
|
||||
|
||||
// Creates a polymorphic matcher that matches anything < x.
|
||||
template <typename Rhs>
|
||||
inline internal::LtMatcher<Rhs> Lt(Rhs x) {
|
||||
return internal::LtMatcher<Rhs>(x);
|
||||
}
|
||||
|
||||
// Creates a polymorphic matcher that matches anything != x.
|
||||
template <typename Rhs>
|
||||
inline internal::NeMatcher<Rhs> Ne(Rhs x) {
|
||||
return internal::NeMatcher<Rhs>(x);
|
||||
}
|
||||
} // namespace testing
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
|
218
3rdparty/gtest/include/gtest/gtest-message.h
vendored
Normal file
218
3rdparty/gtest/include/gtest/gtest-message.h
vendored
Normal file
@ -0,0 +1,218 @@
|
||||
// Copyright 2005, 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.
|
||||
|
||||
//
|
||||
// The Google C++ Testing and Mocking Framework (Google Test)
|
||||
//
|
||||
// This header file defines the Message class.
|
||||
//
|
||||
// IMPORTANT NOTE: Due to limitation of the C++ language, we have to
|
||||
// leave some internal implementation details in this header file.
|
||||
// They are clearly marked by comments like this:
|
||||
//
|
||||
// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
|
||||
//
|
||||
// Such code is NOT meant to be used by a user directly, and is subject
|
||||
// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
|
||||
// program!
|
||||
|
||||
// GOOGLETEST_CM0001 DO NOT DELETE
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
|
||||
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
|
||||
/* class A needs to have dll-interface to be used by clients of class B */)
|
||||
|
||||
// Ensures that there is at least one operator<< in the global namespace.
|
||||
// See Message& operator<<(...) below for why.
|
||||
void operator<<(const testing::internal::Secret&, int);
|
||||
|
||||
namespace testing {
|
||||
|
||||
// The Message class works like an ostream repeater.
|
||||
//
|
||||
// Typical usage:
|
||||
//
|
||||
// 1. You stream a bunch of values to a Message object.
|
||||
// It will remember the text in a stringstream.
|
||||
// 2. Then you stream the Message object to an ostream.
|
||||
// This causes the text in the Message to be streamed
|
||||
// to the ostream.
|
||||
//
|
||||
// For example;
|
||||
//
|
||||
// testing::Message foo;
|
||||
// foo << 1 << " != " << 2;
|
||||
// std::cout << foo;
|
||||
//
|
||||
// will print "1 != 2".
|
||||
//
|
||||
// Message is not intended to be inherited from. In particular, its
|
||||
// destructor is not virtual.
|
||||
//
|
||||
// Note that stringstream behaves differently in gcc and in MSVC. You
|
||||
// can stream a NULL char pointer to it in the former, but not in the
|
||||
// latter (it causes an access violation if you do). The Message
|
||||
// class hides this difference by treating a NULL char pointer as
|
||||
// "(null)".
|
||||
class GTEST_API_ Message {
|
||||
private:
|
||||
// The type of basic IO manipulators (endl, ends, and flush) for
|
||||
// narrow streams.
|
||||
typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&);
|
||||
|
||||
public:
|
||||
// Constructs an empty Message.
|
||||
Message();
|
||||
|
||||
// Copy constructor.
|
||||
Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT
|
||||
*ss_ << msg.GetString();
|
||||
}
|
||||
|
||||
// Constructs a Message from a C-string.
|
||||
explicit Message(const char* str) : ss_(new ::std::stringstream) {
|
||||
*ss_ << str;
|
||||
}
|
||||
|
||||
// Streams a non-pointer value to this object.
|
||||
template <typename T>
|
||||
inline Message& operator <<(const T& val) {
|
||||
// Some libraries overload << for STL containers. These
|
||||
// overloads are defined in the global namespace instead of ::std.
|
||||
//
|
||||
// C++'s symbol lookup rule (i.e. Koenig lookup) says that these
|
||||
// overloads are visible in either the std namespace or the global
|
||||
// namespace, but not other namespaces, including the testing
|
||||
// namespace which Google Test's Message class is in.
|
||||
//
|
||||
// To allow STL containers (and other types that has a << operator
|
||||
// defined in the global namespace) to be used in Google Test
|
||||
// assertions, testing::Message must access the custom << operator
|
||||
// from the global namespace. With this using declaration,
|
||||
// overloads of << defined in the global namespace and those
|
||||
// visible via Koenig lookup are both exposed in this function.
|
||||
using ::operator <<;
|
||||
*ss_ << val;
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Streams a pointer value to this object.
|
||||
//
|
||||
// This function is an overload of the previous one. When you
|
||||
// stream a pointer to a Message, this definition will be used as it
|
||||
// is more specialized. (The C++ Standard, section
|
||||
// [temp.func.order].) If you stream a non-pointer, then the
|
||||
// previous definition will be used.
|
||||
//
|
||||
// The reason for this overload is that streaming a NULL pointer to
|
||||
// ostream is undefined behavior. Depending on the compiler, you
|
||||
// may get "0", "(nil)", "(null)", or an access violation. To
|
||||
// ensure consistent result across compilers, we always treat NULL
|
||||
// as "(null)".
|
||||
template <typename T>
|
||||
inline Message& operator <<(T* const& pointer) { // NOLINT
|
||||
if (pointer == nullptr) {
|
||||
*ss_ << "(null)";
|
||||
} else {
|
||||
*ss_ << pointer;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Since the basic IO manipulators are overloaded for both narrow
|
||||
// and wide streams, we have to provide this specialized definition
|
||||
// of operator <<, even though its body is the same as the
|
||||
// templatized version above. Without this definition, streaming
|
||||
// endl or other basic IO manipulators to Message will confuse the
|
||||
// compiler.
|
||||
Message& operator <<(BasicNarrowIoManip val) {
|
||||
*ss_ << val;
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Instead of 1/0, we want to see true/false for bool values.
|
||||
Message& operator <<(bool b) {
|
||||
return *this << (b ? "true" : "false");
|
||||
}
|
||||
|
||||
// These two overloads allow streaming a wide C string to a Message
|
||||
// using the UTF-8 encoding.
|
||||
Message& operator <<(const wchar_t* wide_c_str);
|
||||
Message& operator <<(wchar_t* wide_c_str);
|
||||
|
||||
#if GTEST_HAS_STD_WSTRING
|
||||
// Converts the given wide string to a narrow string using the UTF-8
|
||||
// encoding, and streams the result to this Message object.
|
||||
Message& operator <<(const ::std::wstring& wstr);
|
||||
#endif // GTEST_HAS_STD_WSTRING
|
||||
|
||||
// Gets the text streamed to this object so far as an std::string.
|
||||
// Each '\0' character in the buffer is replaced with "\\0".
|
||||
//
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
|
||||
std::string GetString() const;
|
||||
|
||||
private:
|
||||
// We'll hold the text streamed to this object here.
|
||||
const std::unique_ptr< ::std::stringstream> ss_;
|
||||
|
||||
// We declare (but don't implement) this to prevent the compiler
|
||||
// from implementing the assignment operator.
|
||||
void operator=(const Message&);
|
||||
};
|
||||
|
||||
// Streams a Message to an ostream.
|
||||
inline std::ostream& operator <<(std::ostream& os, const Message& sb) {
|
||||
return os << sb.GetString();
|
||||
}
|
||||
|
||||
namespace internal {
|
||||
|
||||
// Converts a streamable value to an std::string. A NULL pointer is
|
||||
// converted to "(null)". When the input value is a ::string,
|
||||
// ::std::string, ::wstring, or ::std::wstring object, each NUL
|
||||
// character in it is replaced with "\\0".
|
||||
template <typename T>
|
||||
std::string StreamableToString(const T& streamable) {
|
||||
return (Message() << streamable).GetString();
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
|
503
3rdparty/gtest/include/gtest/gtest-param-test.h
vendored
Normal file
503
3rdparty/gtest/include/gtest/gtest-param-test.h
vendored
Normal file
@ -0,0 +1,503 @@
|
||||
// Copyright 2008, 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.
|
||||
//
|
||||
// Macros and functions for implementing parameterized tests
|
||||
// in Google C++ Testing and Mocking Framework (Google Test)
|
||||
//
|
||||
// This file is generated by a SCRIPT. DO NOT EDIT BY HAND!
|
||||
//
|
||||
// GOOGLETEST_CM0001 DO NOT DELETE
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
|
||||
|
||||
|
||||
// Value-parameterized tests allow you to test your code with different
|
||||
// parameters without writing multiple copies of the same test.
|
||||
//
|
||||
// Here is how you use value-parameterized tests:
|
||||
|
||||
#if 0
|
||||
|
||||
// To write value-parameterized tests, first you should define a fixture
|
||||
// class. It is usually derived from testing::TestWithParam<T> (see below for
|
||||
// another inheritance scheme that's sometimes useful in more complicated
|
||||
// class hierarchies), where the type of your parameter values.
|
||||
// TestWithParam<T> is itself derived from testing::Test. T can be any
|
||||
// copyable type. If it's a raw pointer, you are responsible for managing the
|
||||
// lifespan of the pointed values.
|
||||
|
||||
class FooTest : public ::testing::TestWithParam<const char*> {
|
||||
// You can implement all the usual class fixture members here.
|
||||
};
|
||||
|
||||
// Then, use the TEST_P macro to define as many parameterized tests
|
||||
// for this fixture as you want. The _P suffix is for "parameterized"
|
||||
// or "pattern", whichever you prefer to think.
|
||||
|
||||
TEST_P(FooTest, DoesBlah) {
|
||||
// Inside a test, access the test parameter with the GetParam() method
|
||||
// of the TestWithParam<T> class:
|
||||
EXPECT_TRUE(foo.Blah(GetParam()));
|
||||
...
|
||||
}
|
||||
|
||||
TEST_P(FooTest, HasBlahBlah) {
|
||||
...
|
||||
}
|
||||
|
||||
// Finally, you can use INSTANTIATE_TEST_SUITE_P to instantiate the test
|
||||
// case with any set of parameters you want. Google Test defines a number
|
||||
// of functions for generating test parameters. They return what we call
|
||||
// (surprise!) parameter generators. Here is a summary of them, which
|
||||
// are all in the testing namespace:
|
||||
//
|
||||
//
|
||||
// Range(begin, end [, step]) - Yields values {begin, begin+step,
|
||||
// begin+step+step, ...}. The values do not
|
||||
// include end. step defaults to 1.
|
||||
// Values(v1, v2, ..., vN) - Yields values {v1, v2, ..., vN}.
|
||||
// ValuesIn(container) - Yields values from a C-style array, an STL
|
||||
// ValuesIn(begin,end) container, or an iterator range [begin, end).
|
||||
// Bool() - Yields sequence {false, true}.
|
||||
// Combine(g1, g2, ..., gN) - Yields all combinations (the Cartesian product
|
||||
// for the math savvy) of the values generated
|
||||
// by the N generators.
|
||||
//
|
||||
// For more details, see comments at the definitions of these functions below
|
||||
// in this file.
|
||||
//
|
||||
// The following statement will instantiate tests from the FooTest test suite
|
||||
// each with parameter values "meeny", "miny", and "moe".
|
||||
|
||||
INSTANTIATE_TEST_SUITE_P(InstantiationName,
|
||||
FooTest,
|
||||
Values("meeny", "miny", "moe"));
|
||||
|
||||
// To distinguish different instances of the pattern, (yes, you
|
||||
// can instantiate it more than once) the first argument to the
|
||||
// INSTANTIATE_TEST_SUITE_P macro is a prefix that will be added to the
|
||||
// actual test suite name. Remember to pick unique prefixes for different
|
||||
// instantiations. The tests from the instantiation above will have
|
||||
// these names:
|
||||
//
|
||||
// * InstantiationName/FooTest.DoesBlah/0 for "meeny"
|
||||
// * InstantiationName/FooTest.DoesBlah/1 for "miny"
|
||||
// * InstantiationName/FooTest.DoesBlah/2 for "moe"
|
||||
// * InstantiationName/FooTest.HasBlahBlah/0 for "meeny"
|
||||
// * InstantiationName/FooTest.HasBlahBlah/1 for "miny"
|
||||
// * InstantiationName/FooTest.HasBlahBlah/2 for "moe"
|
||||
//
|
||||
// You can use these names in --gtest_filter.
|
||||
//
|
||||
// This statement will instantiate all tests from FooTest again, each
|
||||
// with parameter values "cat" and "dog":
|
||||
|
||||
const char* pets[] = {"cat", "dog"};
|
||||
INSTANTIATE_TEST_SUITE_P(AnotherInstantiationName, FooTest, ValuesIn(pets));
|
||||
|
||||
// The tests from the instantiation above will have these names:
|
||||
//
|
||||
// * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat"
|
||||
// * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog"
|
||||
// * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat"
|
||||
// * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog"
|
||||
//
|
||||
// Please note that INSTANTIATE_TEST_SUITE_P will instantiate all tests
|
||||
// in the given test suite, whether their definitions come before or
|
||||
// AFTER the INSTANTIATE_TEST_SUITE_P statement.
|
||||
//
|
||||
// Please also note that generator expressions (including parameters to the
|
||||
// generators) are evaluated in InitGoogleTest(), after main() has started.
|
||||
// This allows the user on one hand, to adjust generator parameters in order
|
||||
// to dynamically determine a set of tests to run and on the other hand,
|
||||
// give the user a chance to inspect the generated tests with Google Test
|
||||
// reflection API before RUN_ALL_TESTS() is executed.
|
||||
//
|
||||
// You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc
|
||||
// for more examples.
|
||||
//
|
||||
// In the future, we plan to publish the API for defining new parameter
|
||||
// generators. But for now this interface remains part of the internal
|
||||
// implementation and is subject to change.
|
||||
//
|
||||
//
|
||||
// A parameterized test fixture must be derived from testing::Test and from
|
||||
// testing::WithParamInterface<T>, where T is the type of the parameter
|
||||
// values. Inheriting from TestWithParam<T> satisfies that requirement because
|
||||
// TestWithParam<T> inherits from both Test and WithParamInterface. In more
|
||||
// complicated hierarchies, however, it is occasionally useful to inherit
|
||||
// separately from Test and WithParamInterface. For example:
|
||||
|
||||
class BaseTest : public ::testing::Test {
|
||||
// You can inherit all the usual members for a non-parameterized test
|
||||
// fixture here.
|
||||
};
|
||||
|
||||
class DerivedTest : public BaseTest, public ::testing::WithParamInterface<int> {
|
||||
// The usual test fixture members go here too.
|
||||
};
|
||||
|
||||
TEST_F(BaseTest, HasFoo) {
|
||||
// This is an ordinary non-parameterized test.
|
||||
}
|
||||
|
||||
TEST_P(DerivedTest, DoesBlah) {
|
||||
// GetParam works just the same here as if you inherit from TestWithParam.
|
||||
EXPECT_TRUE(foo.Blah(GetParam()));
|
||||
}
|
||||
|
||||
#endif // 0
|
||||
|
||||
#include <iterator>
|
||||
#include <utility>
|
||||
|
||||
#include "gtest/internal/gtest-internal.h"
|
||||
#include "gtest/internal/gtest-param-util.h"
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
|
||||
namespace testing {
|
||||
|
||||
// Functions producing parameter generators.
|
||||
//
|
||||
// Google Test uses these generators to produce parameters for value-
|
||||
// parameterized tests. When a parameterized test suite is instantiated
|
||||
// with a particular generator, Google Test creates and runs tests
|
||||
// for each element in the sequence produced by the generator.
|
||||
//
|
||||
// In the following sample, tests from test suite FooTest are instantiated
|
||||
// each three times with parameter values 3, 5, and 8:
|
||||
//
|
||||
// class FooTest : public TestWithParam<int> { ... };
|
||||
//
|
||||
// TEST_P(FooTest, TestThis) {
|
||||
// }
|
||||
// TEST_P(FooTest, TestThat) {
|
||||
// }
|
||||
// INSTANTIATE_TEST_SUITE_P(TestSequence, FooTest, Values(3, 5, 8));
|
||||
//
|
||||
|
||||
// Range() returns generators providing sequences of values in a range.
|
||||
//
|
||||
// Synopsis:
|
||||
// Range(start, end)
|
||||
// - returns a generator producing a sequence of values {start, start+1,
|
||||
// start+2, ..., }.
|
||||
// Range(start, end, step)
|
||||
// - returns a generator producing a sequence of values {start, start+step,
|
||||
// start+step+step, ..., }.
|
||||
// Notes:
|
||||
// * The generated sequences never include end. For example, Range(1, 5)
|
||||
// returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2)
|
||||
// returns a generator producing {1, 3, 5, 7}.
|
||||
// * start and end must have the same type. That type may be any integral or
|
||||
// floating-point type or a user defined type satisfying these conditions:
|
||||
// * It must be assignable (have operator=() defined).
|
||||
// * It must have operator+() (operator+(int-compatible type) for
|
||||
// two-operand version).
|
||||
// * It must have operator<() defined.
|
||||
// Elements in the resulting sequences will also have that type.
|
||||
// * Condition start < end must be satisfied in order for resulting sequences
|
||||
// to contain any elements.
|
||||
//
|
||||
template <typename T, typename IncrementT>
|
||||
internal::ParamGenerator<T> Range(T start, T end, IncrementT step) {
|
||||
return internal::ParamGenerator<T>(
|
||||
new internal::RangeGenerator<T, IncrementT>(start, end, step));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
internal::ParamGenerator<T> Range(T start, T end) {
|
||||
return Range(start, end, 1);
|
||||
}
|
||||
|
||||
// ValuesIn() function allows generation of tests with parameters coming from
|
||||
// a container.
|
||||
//
|
||||
// Synopsis:
|
||||
// ValuesIn(const T (&array)[N])
|
||||
// - returns a generator producing sequences with elements from
|
||||
// a C-style array.
|
||||
// ValuesIn(const Container& container)
|
||||
// - returns a generator producing sequences with elements from
|
||||
// an STL-style container.
|
||||
// ValuesIn(Iterator begin, Iterator end)
|
||||
// - returns a generator producing sequences with elements from
|
||||
// a range [begin, end) defined by a pair of STL-style iterators. These
|
||||
// iterators can also be plain C pointers.
|
||||
//
|
||||
// Please note that ValuesIn copies the values from the containers
|
||||
// passed in and keeps them to generate tests in RUN_ALL_TESTS().
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// This instantiates tests from test suite StringTest
|
||||
// each with C-string values of "foo", "bar", and "baz":
|
||||
//
|
||||
// const char* strings[] = {"foo", "bar", "baz"};
|
||||
// INSTANTIATE_TEST_SUITE_P(StringSequence, StringTest, ValuesIn(strings));
|
||||
//
|
||||
// This instantiates tests from test suite StlStringTest
|
||||
// each with STL strings with values "a" and "b":
|
||||
//
|
||||
// ::std::vector< ::std::string> GetParameterStrings() {
|
||||
// ::std::vector< ::std::string> v;
|
||||
// v.push_back("a");
|
||||
// v.push_back("b");
|
||||
// return v;
|
||||
// }
|
||||
//
|
||||
// INSTANTIATE_TEST_SUITE_P(CharSequence,
|
||||
// StlStringTest,
|
||||
// ValuesIn(GetParameterStrings()));
|
||||
//
|
||||
//
|
||||
// This will also instantiate tests from CharTest
|
||||
// each with parameter values 'a' and 'b':
|
||||
//
|
||||
// ::std::list<char> GetParameterChars() {
|
||||
// ::std::list<char> list;
|
||||
// list.push_back('a');
|
||||
// list.push_back('b');
|
||||
// return list;
|
||||
// }
|
||||
// ::std::list<char> l = GetParameterChars();
|
||||
// INSTANTIATE_TEST_SUITE_P(CharSequence2,
|
||||
// CharTest,
|
||||
// ValuesIn(l.begin(), l.end()));
|
||||
//
|
||||
template <typename ForwardIterator>
|
||||
internal::ParamGenerator<
|
||||
typename std::iterator_traits<ForwardIterator>::value_type>
|
||||
ValuesIn(ForwardIterator begin, ForwardIterator end) {
|
||||
typedef typename std::iterator_traits<ForwardIterator>::value_type ParamType;
|
||||
return internal::ParamGenerator<ParamType>(
|
||||
new internal::ValuesInIteratorRangeGenerator<ParamType>(begin, end));
|
||||
}
|
||||
|
||||
template <typename T, size_t N>
|
||||
internal::ParamGenerator<T> ValuesIn(const T (&array)[N]) {
|
||||
return ValuesIn(array, array + N);
|
||||
}
|
||||
|
||||
template <class Container>
|
||||
internal::ParamGenerator<typename Container::value_type> ValuesIn(
|
||||
const Container& container) {
|
||||
return ValuesIn(container.begin(), container.end());
|
||||
}
|
||||
|
||||
// Values() allows generating tests from explicitly specified list of
|
||||
// parameters.
|
||||
//
|
||||
// Synopsis:
|
||||
// Values(T v1, T v2, ..., T vN)
|
||||
// - returns a generator producing sequences with elements v1, v2, ..., vN.
|
||||
//
|
||||
// For example, this instantiates tests from test suite BarTest each
|
||||
// with values "one", "two", and "three":
|
||||
//
|
||||
// INSTANTIATE_TEST_SUITE_P(NumSequence,
|
||||
// BarTest,
|
||||
// Values("one", "two", "three"));
|
||||
//
|
||||
// This instantiates tests from test suite BazTest each with values 1, 2, 3.5.
|
||||
// The exact type of values will depend on the type of parameter in BazTest.
|
||||
//
|
||||
// INSTANTIATE_TEST_SUITE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5));
|
||||
//
|
||||
//
|
||||
template <typename... T>
|
||||
internal::ValueArray<T...> Values(T... v) {
|
||||
return internal::ValueArray<T...>(std::move(v)...);
|
||||
}
|
||||
|
||||
// Bool() allows generating tests with parameters in a set of (false, true).
|
||||
//
|
||||
// Synopsis:
|
||||
// Bool()
|
||||
// - returns a generator producing sequences with elements {false, true}.
|
||||
//
|
||||
// It is useful when testing code that depends on Boolean flags. Combinations
|
||||
// of multiple flags can be tested when several Bool()'s are combined using
|
||||
// Combine() function.
|
||||
//
|
||||
// In the following example all tests in the test suite FlagDependentTest
|
||||
// will be instantiated twice with parameters false and true.
|
||||
//
|
||||
// class FlagDependentTest : public testing::TestWithParam<bool> {
|
||||
// virtual void SetUp() {
|
||||
// external_flag = GetParam();
|
||||
// }
|
||||
// }
|
||||
// INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool());
|
||||
//
|
||||
inline internal::ParamGenerator<bool> Bool() {
|
||||
return Values(false, true);
|
||||
}
|
||||
|
||||
// Combine() allows the user to combine two or more sequences to produce
|
||||
// values of a Cartesian product of those sequences' elements.
|
||||
//
|
||||
// Synopsis:
|
||||
// Combine(gen1, gen2, ..., genN)
|
||||
// - returns a generator producing sequences with elements coming from
|
||||
// the Cartesian product of elements from the sequences generated by
|
||||
// gen1, gen2, ..., genN. The sequence elements will have a type of
|
||||
// std::tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types
|
||||
// of elements from sequences produces by gen1, gen2, ..., genN.
|
||||
//
|
||||
// Combine can have up to 10 arguments.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// This will instantiate tests in test suite AnimalTest each one with
|
||||
// the parameter values tuple("cat", BLACK), tuple("cat", WHITE),
|
||||
// tuple("dog", BLACK), and tuple("dog", WHITE):
|
||||
//
|
||||
// enum Color { BLACK, GRAY, WHITE };
|
||||
// class AnimalTest
|
||||
// : public testing::TestWithParam<std::tuple<const char*, Color> > {...};
|
||||
//
|
||||
// TEST_P(AnimalTest, AnimalLooksNice) {...}
|
||||
//
|
||||
// INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest,
|
||||
// Combine(Values("cat", "dog"),
|
||||
// Values(BLACK, WHITE)));
|
||||
//
|
||||
// This will instantiate tests in FlagDependentTest with all variations of two
|
||||
// Boolean flags:
|
||||
//
|
||||
// class FlagDependentTest
|
||||
// : public testing::TestWithParam<std::tuple<bool, bool> > {
|
||||
// virtual void SetUp() {
|
||||
// // Assigns external_flag_1 and external_flag_2 values from the tuple.
|
||||
// std::tie(external_flag_1, external_flag_2) = GetParam();
|
||||
// }
|
||||
// };
|
||||
//
|
||||
// TEST_P(FlagDependentTest, TestFeature1) {
|
||||
// // Test your code using external_flag_1 and external_flag_2 here.
|
||||
// }
|
||||
// INSTANTIATE_TEST_SUITE_P(TwoBoolSequence, FlagDependentTest,
|
||||
// Combine(Bool(), Bool()));
|
||||
//
|
||||
template <typename... Generator>
|
||||
internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
|
||||
return internal::CartesianProductHolder<Generator...>(g...);
|
||||
}
|
||||
|
||||
#define TEST_P(test_suite_name, test_name) \
|
||||
class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
|
||||
: public test_suite_name { \
|
||||
public: \
|
||||
GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
|
||||
virtual void TestBody(); \
|
||||
\
|
||||
private: \
|
||||
static int AddToRegistry() { \
|
||||
::testing::UnitTest::GetInstance() \
|
||||
->parameterized_test_registry() \
|
||||
.GetTestSuitePatternHolder<test_suite_name>( \
|
||||
#test_suite_name, \
|
||||
::testing::internal::CodeLocation(__FILE__, __LINE__)) \
|
||||
->AddTestPattern( \
|
||||
GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name), \
|
||||
new ::testing::internal::TestMetaFactory<GTEST_TEST_CLASS_NAME_( \
|
||||
test_suite_name, test_name)>()); \
|
||||
return 0; \
|
||||
} \
|
||||
static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
|
||||
test_name)); \
|
||||
}; \
|
||||
int GTEST_TEST_CLASS_NAME_(test_suite_name, \
|
||||
test_name)::gtest_registering_dummy_ = \
|
||||
GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::AddToRegistry(); \
|
||||
void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
|
||||
|
||||
// The last argument to INSTANTIATE_TEST_SUITE_P allows the user to specify
|
||||
// generator and an optional function or functor that generates custom test name
|
||||
// suffixes based on the test parameters. Such a function or functor should
|
||||
// accept one argument of type testing::TestParamInfo<class ParamType>, and
|
||||
// return std::string.
|
||||
//
|
||||
// testing::PrintToStringParamName is a builtin test suffix generator that
|
||||
// returns the value of testing::PrintToString(GetParam()).
|
||||
//
|
||||
// Note: test names must be non-empty, unique, and may only contain ASCII
|
||||
// alphanumeric characters or underscore. Because PrintToString adds quotes
|
||||
// to std::string and C strings, it won't work for these types.
|
||||
|
||||
#define GTEST_EXPAND_(arg) arg
|
||||
#define GTEST_GET_FIRST_(first, ...) first
|
||||
#define GTEST_GET_SECOND_(first, second, ...) second
|
||||
|
||||
#define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \
|
||||
static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \
|
||||
gtest_##prefix##test_suite_name##_EvalGenerator_() { \
|
||||
return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \
|
||||
} \
|
||||
static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \
|
||||
const ::testing::TestParamInfo<test_suite_name::ParamType>& info) { \
|
||||
if (::testing::internal::AlwaysFalse()) { \
|
||||
::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \
|
||||
__VA_ARGS__, \
|
||||
::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
|
||||
DUMMY_PARAM_))); \
|
||||
auto t = std::make_tuple(__VA_ARGS__); \
|
||||
static_assert(std::tuple_size<decltype(t)>::value <= 2, \
|
||||
"Too Many Args!"); \
|
||||
} \
|
||||
return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \
|
||||
__VA_ARGS__, \
|
||||
::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
|
||||
DUMMY_PARAM_))))(info); \
|
||||
} \
|
||||
static int gtest_##prefix##test_suite_name##_dummy_ \
|
||||
GTEST_ATTRIBUTE_UNUSED_ = \
|
||||
::testing::UnitTest::GetInstance() \
|
||||
->parameterized_test_registry() \
|
||||
.GetTestSuitePatternHolder<test_suite_name>( \
|
||||
#test_suite_name, \
|
||||
::testing::internal::CodeLocation(__FILE__, __LINE__)) \
|
||||
->AddTestSuiteInstantiation( \
|
||||
#prefix, >est_##prefix##test_suite_name##_EvalGenerator_, \
|
||||
>est_##prefix##test_suite_name##_EvalGenerateName_, \
|
||||
__FILE__, __LINE__)
|
||||
|
||||
// Legacy API is deprecated but still available
|
||||
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
#define INSTANTIATE_TEST_CASE_P \
|
||||
static_assert(::testing::internal::InstantiateTestCase_P_IsDeprecated(), \
|
||||
""); \
|
||||
INSTANTIATE_TEST_SUITE_P
|
||||
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
|
928
3rdparty/gtest/include/gtest/gtest-printers.h
vendored
Normal file
928
3rdparty/gtest/include/gtest/gtest-printers.h
vendored
Normal file
@ -0,0 +1,928 @@
|
||||
// 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.
|
||||
|
||||
|
||||
// Google Test - The Google C++ Testing and Mocking Framework
|
||||
//
|
||||
// This file implements a universal value printer that can print a
|
||||
// value of any type T:
|
||||
//
|
||||
// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
|
||||
//
|
||||
// A user can teach this function how to print a class type T by
|
||||
// defining either operator<<() or PrintTo() in the namespace that
|
||||
// defines T. More specifically, the FIRST defined function in the
|
||||
// following list will be used (assuming T is defined in namespace
|
||||
// foo):
|
||||
//
|
||||
// 1. foo::PrintTo(const T&, ostream*)
|
||||
// 2. operator<<(ostream&, const T&) defined in either foo or the
|
||||
// global namespace.
|
||||
//
|
||||
// However if T is an STL-style container then it is printed element-wise
|
||||
// unless foo::PrintTo(const T&, ostream*) is defined. Note that
|
||||
// operator<<() is ignored for container types.
|
||||
//
|
||||
// If none of the above is defined, it will print the debug string of
|
||||
// the value if it is a protocol buffer, or print the raw bytes in the
|
||||
// value otherwise.
|
||||
//
|
||||
// To aid debugging: when T is a reference type, the address of the
|
||||
// value is also printed; when T is a (const) char pointer, both the
|
||||
// pointer value and the NUL-terminated string it points to are
|
||||
// printed.
|
||||
//
|
||||
// We also provide some convenient wrappers:
|
||||
//
|
||||
// // Prints a value to a string. For a (const or not) char
|
||||
// // pointer, the NUL-terminated string (but not the pointer) is
|
||||
// // printed.
|
||||
// std::string ::testing::PrintToString(const T& value);
|
||||
//
|
||||
// // Prints a value tersely: for a reference type, the referenced
|
||||
// // value (but not the address) is printed; for a (const or not) char
|
||||
// // pointer, the NUL-terminated string (but not the pointer) is
|
||||
// // printed.
|
||||
// void ::testing::internal::UniversalTersePrint(const T& value, ostream*);
|
||||
//
|
||||
// // Prints value using the type inferred by the compiler. The difference
|
||||
// // from UniversalTersePrint() is that this function prints both the
|
||||
// // pointer and the NUL-terminated string for a (const or not) char pointer.
|
||||
// void ::testing::internal::UniversalPrint(const T& value, ostream*);
|
||||
//
|
||||
// // Prints the fields of a tuple tersely to a string vector, one
|
||||
// // element for each field. Tuple support must be enabled in
|
||||
// // gtest-port.h.
|
||||
// std::vector<string> UniversalTersePrintTupleFieldsToStrings(
|
||||
// const Tuple& value);
|
||||
//
|
||||
// Known limitation:
|
||||
//
|
||||
// The print primitives print the elements of an STL-style container
|
||||
// using the compiler-inferred type of *iter where iter is a
|
||||
// const_iterator of the container. When const_iterator is an input
|
||||
// iterator but not a forward iterator, this inferred type may not
|
||||
// match value_type, and the print output may be incorrect. In
|
||||
// practice, this is rarely a problem as for most containers
|
||||
// const_iterator is a forward iterator. We'll fix this if there's an
|
||||
// actual need for it. Note that this fix cannot rely on value_type
|
||||
// being defined as many user-defined container types don't have
|
||||
// value_type.
|
||||
|
||||
// GOOGLETEST_CM0001 DO NOT DELETE
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
|
||||
|
||||
#include <functional>
|
||||
#include <ostream> // NOLINT
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
#include "gtest/internal/gtest-internal.h"
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
|
||||
#if GTEST_HAS_ABSL
|
||||
#include "absl/strings/string_view.h"
|
||||
#include "absl/types/optional.h"
|
||||
#include "absl/types/variant.h"
|
||||
#endif // GTEST_HAS_ABSL
|
||||
|
||||
namespace testing {
|
||||
|
||||
// Definitions in the 'internal' and 'internal2' name spaces are
|
||||
// subject to change without notice. DO NOT USE THEM IN USER CODE!
|
||||
namespace internal2 {
|
||||
|
||||
// Prints the given number of bytes in the given object to the given
|
||||
// ostream.
|
||||
GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
|
||||
size_t count,
|
||||
::std::ostream* os);
|
||||
|
||||
// For selecting which printer to use when a given type has neither <<
|
||||
// nor PrintTo().
|
||||
enum TypeKind {
|
||||
kProtobuf, // a protobuf type
|
||||
kConvertibleToInteger, // a type implicitly convertible to BiggestInt
|
||||
// (e.g. a named or unnamed enum type)
|
||||
#if GTEST_HAS_ABSL
|
||||
kConvertibleToStringView, // a type implicitly convertible to
|
||||
// absl::string_view
|
||||
#endif
|
||||
kOtherType // anything else
|
||||
};
|
||||
|
||||
// TypeWithoutFormatter<T, kTypeKind>::PrintValue(value, os) is called
|
||||
// by the universal printer to print a value of type T when neither
|
||||
// operator<< nor PrintTo() is defined for T, where kTypeKind is the
|
||||
// "kind" of T as defined by enum TypeKind.
|
||||
template <typename T, TypeKind kTypeKind>
|
||||
class TypeWithoutFormatter {
|
||||
public:
|
||||
// This default version is called when kTypeKind is kOtherType.
|
||||
static void PrintValue(const T& value, ::std::ostream* os) {
|
||||
PrintBytesInObjectTo(
|
||||
static_cast<const unsigned char*>(
|
||||
reinterpret_cast<const void*>(std::addressof(value))),
|
||||
sizeof(value), os);
|
||||
}
|
||||
};
|
||||
|
||||
// We print a protobuf using its ShortDebugString() when the string
|
||||
// doesn't exceed this many characters; otherwise we print it using
|
||||
// DebugString() for better readability.
|
||||
const size_t kProtobufOneLinerMaxLength = 50;
|
||||
|
||||
template <typename T>
|
||||
class TypeWithoutFormatter<T, kProtobuf> {
|
||||
public:
|
||||
static void PrintValue(const T& value, ::std::ostream* os) {
|
||||
std::string pretty_str = value.ShortDebugString();
|
||||
if (pretty_str.length() > kProtobufOneLinerMaxLength) {
|
||||
pretty_str = "\n" + value.DebugString();
|
||||
}
|
||||
*os << ("<" + pretty_str + ">");
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class TypeWithoutFormatter<T, kConvertibleToInteger> {
|
||||
public:
|
||||
// Since T has no << operator or PrintTo() but can be implicitly
|
||||
// converted to BiggestInt, we print it as a BiggestInt.
|
||||
//
|
||||
// Most likely T is an enum type (either named or unnamed), in which
|
||||
// case printing it as an integer is the desired behavior. In case
|
||||
// T is not an enum, printing it as an integer is the best we can do
|
||||
// given that it has no user-defined printer.
|
||||
static void PrintValue(const T& value, ::std::ostream* os) {
|
||||
const internal::BiggestInt kBigInt = value;
|
||||
*os << kBigInt;
|
||||
}
|
||||
};
|
||||
|
||||
#if GTEST_HAS_ABSL
|
||||
template <typename T>
|
||||
class TypeWithoutFormatter<T, kConvertibleToStringView> {
|
||||
public:
|
||||
// Since T has neither operator<< nor PrintTo() but can be implicitly
|
||||
// converted to absl::string_view, we print it as a absl::string_view.
|
||||
//
|
||||
// Note: the implementation is further below, as it depends on
|
||||
// internal::PrintTo symbol which is defined later in the file.
|
||||
static void PrintValue(const T& value, ::std::ostream* os);
|
||||
};
|
||||
#endif
|
||||
|
||||
// Prints the given value to the given ostream. If the value is a
|
||||
// protocol message, its debug string is printed; if it's an enum or
|
||||
// of a type implicitly convertible to BiggestInt, it's printed as an
|
||||
// integer; otherwise the bytes in the value are printed. This is
|
||||
// what UniversalPrinter<T>::Print() does when it knows nothing about
|
||||
// type T and T has neither << operator nor PrintTo().
|
||||
//
|
||||
// A user can override this behavior for a class type Foo by defining
|
||||
// a << operator in the namespace where Foo is defined.
|
||||
//
|
||||
// We put this operator in namespace 'internal2' instead of 'internal'
|
||||
// to simplify the implementation, as much code in 'internal' needs to
|
||||
// use << in STL, which would conflict with our own << were it defined
|
||||
// in 'internal'.
|
||||
//
|
||||
// Note that this operator<< takes a generic std::basic_ostream<Char,
|
||||
// CharTraits> type instead of the more restricted std::ostream. If
|
||||
// we define it to take an std::ostream instead, we'll get an
|
||||
// "ambiguous overloads" compiler error when trying to print a type
|
||||
// Foo that supports streaming to std::basic_ostream<Char,
|
||||
// CharTraits>, as the compiler cannot tell whether
|
||||
// operator<<(std::ostream&, const T&) or
|
||||
// operator<<(std::basic_stream<Char, CharTraits>, const Foo&) is more
|
||||
// specific.
|
||||
template <typename Char, typename CharTraits, typename T>
|
||||
::std::basic_ostream<Char, CharTraits>& operator<<(
|
||||
::std::basic_ostream<Char, CharTraits>& os, const T& x) {
|
||||
TypeWithoutFormatter<T, (internal::IsAProtocolMessage<T>::value
|
||||
? kProtobuf
|
||||
: std::is_convertible<
|
||||
const T&, internal::BiggestInt>::value
|
||||
? kConvertibleToInteger
|
||||
:
|
||||
#if GTEST_HAS_ABSL
|
||||
std::is_convertible<
|
||||
const T&, absl::string_view>::value
|
||||
? kConvertibleToStringView
|
||||
:
|
||||
#endif
|
||||
kOtherType)>::PrintValue(x, &os);
|
||||
return os;
|
||||
}
|
||||
|
||||
} // namespace internal2
|
||||
} // namespace testing
|
||||
|
||||
// This namespace MUST NOT BE NESTED IN ::testing, or the name look-up
|
||||
// magic needed for implementing UniversalPrinter won't work.
|
||||
namespace testing_internal {
|
||||
|
||||
// Used to print a value that is not an STL-style container when the
|
||||
// user doesn't define PrintTo() for it.
|
||||
template <typename T>
|
||||
void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) {
|
||||
// With the following statement, during unqualified name lookup,
|
||||
// testing::internal2::operator<< appears as if it was declared in
|
||||
// the nearest enclosing namespace that contains both
|
||||
// ::testing_internal and ::testing::internal2, i.e. the global
|
||||
// namespace. For more details, refer to the C++ Standard section
|
||||
// 7.3.4-1 [namespace.udir]. This allows us to fall back onto
|
||||
// testing::internal2::operator<< in case T doesn't come with a <<
|
||||
// operator.
|
||||
//
|
||||
// We cannot write 'using ::testing::internal2::operator<<;', which
|
||||
// gcc 3.3 fails to compile due to a compiler bug.
|
||||
using namespace ::testing::internal2; // NOLINT
|
||||
|
||||
// Assuming T is defined in namespace foo, in the next statement,
|
||||
// the compiler will consider all of:
|
||||
//
|
||||
// 1. foo::operator<< (thanks to Koenig look-up),
|
||||
// 2. ::operator<< (as the current namespace is enclosed in ::),
|
||||
// 3. testing::internal2::operator<< (thanks to the using statement above).
|
||||
//
|
||||
// The operator<< whose type matches T best will be picked.
|
||||
//
|
||||
// We deliberately allow #2 to be a candidate, as sometimes it's
|
||||
// impossible to define #1 (e.g. when foo is ::std, defining
|
||||
// anything in it is undefined behavior unless you are a compiler
|
||||
// vendor.).
|
||||
*os << value;
|
||||
}
|
||||
|
||||
} // namespace testing_internal
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
// FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
|
||||
// value of type ToPrint that is an operand of a comparison assertion
|
||||
// (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in
|
||||
// the comparison, and is used to help determine the best way to
|
||||
// format the value. In particular, when the value is a C string
|
||||
// (char pointer) and the other operand is an STL string object, we
|
||||
// want to format the C string as a string, since we know it is
|
||||
// compared by value with the string object. If the value is a char
|
||||
// pointer but the other operand is not an STL string object, we don't
|
||||
// know whether the pointer is supposed to point to a NUL-terminated
|
||||
// string, and thus want to print it as a pointer to be safe.
|
||||
//
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
|
||||
|
||||
// The default case.
|
||||
template <typename ToPrint, typename OtherOperand>
|
||||
class FormatForComparison {
|
||||
public:
|
||||
static ::std::string Format(const ToPrint& value) {
|
||||
return ::testing::PrintToString(value);
|
||||
}
|
||||
};
|
||||
|
||||
// Array.
|
||||
template <typename ToPrint, size_t N, typename OtherOperand>
|
||||
class FormatForComparison<ToPrint[N], OtherOperand> {
|
||||
public:
|
||||
static ::std::string Format(const ToPrint* value) {
|
||||
return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
|
||||
}
|
||||
};
|
||||
|
||||
// By default, print C string as pointers to be safe, as we don't know
|
||||
// whether they actually point to a NUL-terminated string.
|
||||
|
||||
#define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \
|
||||
template <typename OtherOperand> \
|
||||
class FormatForComparison<CharType*, OtherOperand> { \
|
||||
public: \
|
||||
static ::std::string Format(CharType* value) { \
|
||||
return ::testing::PrintToString(static_cast<const void*>(value)); \
|
||||
} \
|
||||
}
|
||||
|
||||
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
|
||||
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
|
||||
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
|
||||
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
|
||||
|
||||
#undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
|
||||
|
||||
// If a C string is compared with an STL string object, we know it's meant
|
||||
// to point to a NUL-terminated string, and thus can print it as a string.
|
||||
|
||||
#define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
|
||||
template <> \
|
||||
class FormatForComparison<CharType*, OtherStringType> { \
|
||||
public: \
|
||||
static ::std::string Format(CharType* value) { \
|
||||
return ::testing::PrintToString(value); \
|
||||
} \
|
||||
}
|
||||
|
||||
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
|
||||
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
|
||||
|
||||
#if GTEST_HAS_STD_WSTRING
|
||||
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
|
||||
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
|
||||
#endif
|
||||
|
||||
#undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_
|
||||
|
||||
// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
|
||||
// operand to be used in a failure message. The type (but not value)
|
||||
// of the other operand may affect the format. This allows us to
|
||||
// print a char* as a raw pointer when it is compared against another
|
||||
// char* or void*, and print it as a C string when it is compared
|
||||
// against an std::string object, for example.
|
||||
//
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
|
||||
template <typename T1, typename T2>
|
||||
std::string FormatForComparisonFailureMessage(
|
||||
const T1& value, const T2& /* other_operand */) {
|
||||
return FormatForComparison<T1, T2>::Format(value);
|
||||
}
|
||||
|
||||
// UniversalPrinter<T>::Print(value, ostream_ptr) prints the given
|
||||
// value to the given ostream. The caller must ensure that
|
||||
// 'ostream_ptr' is not NULL, or the behavior is undefined.
|
||||
//
|
||||
// We define UniversalPrinter as a class template (as opposed to a
|
||||
// function template), as we need to partially specialize it for
|
||||
// reference types, which cannot be done with function templates.
|
||||
template <typename T>
|
||||
class UniversalPrinter;
|
||||
|
||||
template <typename T>
|
||||
void UniversalPrint(const T& value, ::std::ostream* os);
|
||||
|
||||
enum DefaultPrinterType {
|
||||
kPrintContainer,
|
||||
kPrintPointer,
|
||||
kPrintFunctionPointer,
|
||||
kPrintOther,
|
||||
};
|
||||
template <DefaultPrinterType type> struct WrapPrinterType {};
|
||||
|
||||
// Used to print an STL-style container when the user doesn't define
|
||||
// a PrintTo() for it.
|
||||
template <typename C>
|
||||
void DefaultPrintTo(WrapPrinterType<kPrintContainer> /* dummy */,
|
||||
const C& container, ::std::ostream* os) {
|
||||
const size_t kMaxCount = 32; // The maximum number of elements to print.
|
||||
*os << '{';
|
||||
size_t count = 0;
|
||||
for (typename C::const_iterator it = container.begin();
|
||||
it != container.end(); ++it, ++count) {
|
||||
if (count > 0) {
|
||||
*os << ',';
|
||||
if (count == kMaxCount) { // Enough has been printed.
|
||||
*os << " ...";
|
||||
break;
|
||||
}
|
||||
}
|
||||
*os << ' ';
|
||||
// We cannot call PrintTo(*it, os) here as PrintTo() doesn't
|
||||
// handle *it being a native array.
|
||||
internal::UniversalPrint(*it, os);
|
||||
}
|
||||
|
||||
if (count > 0) {
|
||||
*os << ' ';
|
||||
}
|
||||
*os << '}';
|
||||
}
|
||||
|
||||
// Used to print a pointer that is neither a char pointer nor a member
|
||||
// pointer, when the user doesn't define PrintTo() for it. (A member
|
||||
// variable pointer or member function pointer doesn't really point to
|
||||
// a location in the address space. Their representation is
|
||||
// implementation-defined. Therefore they will be printed as raw
|
||||
// bytes.)
|
||||
template <typename T>
|
||||
void DefaultPrintTo(WrapPrinterType<kPrintPointer> /* dummy */,
|
||||
T* p, ::std::ostream* os) {
|
||||
if (p == nullptr) {
|
||||
*os << "NULL";
|
||||
} else {
|
||||
// T is not a function type. We just call << to print p,
|
||||
// relying on ADL to pick up user-defined << for their pointer
|
||||
// types, if any.
|
||||
*os << p;
|
||||
}
|
||||
}
|
||||
template <typename T>
|
||||
void DefaultPrintTo(WrapPrinterType<kPrintFunctionPointer> /* dummy */,
|
||||
T* p, ::std::ostream* os) {
|
||||
if (p == nullptr) {
|
||||
*os << "NULL";
|
||||
} else {
|
||||
// T is a function type, so '*os << p' doesn't do what we want
|
||||
// (it just prints p as bool). We want to print p as a const
|
||||
// void*.
|
||||
*os << reinterpret_cast<const void*>(p);
|
||||
}
|
||||
}
|
||||
|
||||
// Used to print a non-container, non-pointer value when the user
|
||||
// doesn't define PrintTo() for it.
|
||||
template <typename T>
|
||||
void DefaultPrintTo(WrapPrinterType<kPrintOther> /* dummy */,
|
||||
const T& value, ::std::ostream* os) {
|
||||
::testing_internal::DefaultPrintNonContainerTo(value, os);
|
||||
}
|
||||
|
||||
// Prints the given value using the << operator if it has one;
|
||||
// otherwise prints the bytes in it. This is what
|
||||
// UniversalPrinter<T>::Print() does when PrintTo() is not specialized
|
||||
// or overloaded for type T.
|
||||
//
|
||||
// A user can override this behavior for a class type Foo by defining
|
||||
// an overload of PrintTo() in the namespace where Foo is defined. We
|
||||
// give the user this option as sometimes defining a << operator for
|
||||
// Foo is not desirable (e.g. the coding style may prevent doing it,
|
||||
// or there is already a << operator but it doesn't do what the user
|
||||
// wants).
|
||||
template <typename T>
|
||||
void PrintTo(const T& value, ::std::ostream* os) {
|
||||
// DefaultPrintTo() is overloaded. The type of its first argument
|
||||
// determines which version will be picked.
|
||||
//
|
||||
// Note that we check for container types here, prior to we check
|
||||
// for protocol message types in our operator<<. The rationale is:
|
||||
//
|
||||
// For protocol messages, we want to give people a chance to
|
||||
// override Google Mock's format by defining a PrintTo() or
|
||||
// operator<<. For STL containers, other formats can be
|
||||
// incompatible with Google Mock's format for the container
|
||||
// elements; therefore we check for container types here to ensure
|
||||
// that our format is used.
|
||||
//
|
||||
// Note that MSVC and clang-cl do allow an implicit conversion from
|
||||
// pointer-to-function to pointer-to-object, but clang-cl warns on it.
|
||||
// So don't use ImplicitlyConvertible if it can be helped since it will
|
||||
// cause this warning, and use a separate overload of DefaultPrintTo for
|
||||
// function pointers so that the `*os << p` in the object pointer overload
|
||||
// doesn't cause that warning either.
|
||||
DefaultPrintTo(
|
||||
WrapPrinterType <
|
||||
(sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
|
||||
!IsRecursiveContainer<T>::value
|
||||
? kPrintContainer
|
||||
: !std::is_pointer<T>::value
|
||||
? kPrintOther
|
||||
: std::is_function<typename std::remove_pointer<T>::type>::value
|
||||
? kPrintFunctionPointer
|
||||
: kPrintPointer > (),
|
||||
value, os);
|
||||
}
|
||||
|
||||
// The following list of PrintTo() overloads tells
|
||||
// UniversalPrinter<T>::Print() how to print standard types (built-in
|
||||
// types, strings, plain arrays, and pointers).
|
||||
|
||||
// Overloads for various char types.
|
||||
GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);
|
||||
GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);
|
||||
inline void PrintTo(char c, ::std::ostream* os) {
|
||||
// When printing a plain char, we always treat it as unsigned. This
|
||||
// way, the output won't be affected by whether the compiler thinks
|
||||
// char is signed or not.
|
||||
PrintTo(static_cast<unsigned char>(c), os);
|
||||
}
|
||||
|
||||
// Overloads for other simple built-in types.
|
||||
inline void PrintTo(bool x, ::std::ostream* os) {
|
||||
*os << (x ? "true" : "false");
|
||||
}
|
||||
|
||||
// Overload for wchar_t type.
|
||||
// Prints a wchar_t as a symbol if it is printable or as its internal
|
||||
// code otherwise and also as its decimal code (except for L'\0').
|
||||
// The L'\0' char is printed as "L'\\0'". The decimal code is printed
|
||||
// as signed integer when wchar_t is implemented by the compiler
|
||||
// as a signed type and is printed as an unsigned integer when wchar_t
|
||||
// is implemented as an unsigned type.
|
||||
GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
|
||||
|
||||
// Overloads for C strings.
|
||||
GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
|
||||
inline void PrintTo(char* s, ::std::ostream* os) {
|
||||
PrintTo(ImplicitCast_<const char*>(s), os);
|
||||
}
|
||||
|
||||
// signed/unsigned char is often used for representing binary data, so
|
||||
// we print pointers to it as void* to be safe.
|
||||
inline void PrintTo(const signed char* s, ::std::ostream* os) {
|
||||
PrintTo(ImplicitCast_<const void*>(s), os);
|
||||
}
|
||||
inline void PrintTo(signed char* s, ::std::ostream* os) {
|
||||
PrintTo(ImplicitCast_<const void*>(s), os);
|
||||
}
|
||||
inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
|
||||
PrintTo(ImplicitCast_<const void*>(s), os);
|
||||
}
|
||||
inline void PrintTo(unsigned char* s, ::std::ostream* os) {
|
||||
PrintTo(ImplicitCast_<const void*>(s), os);
|
||||
}
|
||||
|
||||
// MSVC can be configured to define wchar_t as a typedef of unsigned
|
||||
// short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
|
||||
// type. When wchar_t is a typedef, defining an overload for const
|
||||
// wchar_t* would cause unsigned short* be printed as a wide string,
|
||||
// possibly causing invalid memory accesses.
|
||||
#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
|
||||
// Overloads for wide C strings
|
||||
GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);
|
||||
inline void PrintTo(wchar_t* s, ::std::ostream* os) {
|
||||
PrintTo(ImplicitCast_<const wchar_t*>(s), os);
|
||||
}
|
||||
#endif
|
||||
|
||||
// Overload for C arrays. Multi-dimensional arrays are printed
|
||||
// properly.
|
||||
|
||||
// Prints the given number of elements in an array, without printing
|
||||
// the curly braces.
|
||||
template <typename T>
|
||||
void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
|
||||
UniversalPrint(a[0], os);
|
||||
for (size_t i = 1; i != count; i++) {
|
||||
*os << ", ";
|
||||
UniversalPrint(a[i], os);
|
||||
}
|
||||
}
|
||||
|
||||
// Overloads for ::std::string.
|
||||
GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os);
|
||||
inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
|
||||
PrintStringTo(s, os);
|
||||
}
|
||||
|
||||
// Overloads for ::std::wstring.
|
||||
#if GTEST_HAS_STD_WSTRING
|
||||
GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
|
||||
inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
|
||||
PrintWideStringTo(s, os);
|
||||
}
|
||||
#endif // GTEST_HAS_STD_WSTRING
|
||||
|
||||
#if GTEST_HAS_ABSL
|
||||
// Overload for absl::string_view.
|
||||
inline void PrintTo(absl::string_view sp, ::std::ostream* os) {
|
||||
PrintTo(::std::string(sp), os);
|
||||
}
|
||||
#endif // GTEST_HAS_ABSL
|
||||
|
||||
inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
|
||||
|
||||
template <typename T>
|
||||
void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {
|
||||
UniversalPrinter<T&>::Print(ref.get(), os);
|
||||
}
|
||||
|
||||
// Helper function for printing a tuple. T must be instantiated with
|
||||
// a tuple type.
|
||||
template <typename T>
|
||||
void PrintTupleTo(const T&, std::integral_constant<size_t, 0>,
|
||||
::std::ostream*) {}
|
||||
|
||||
template <typename T, size_t I>
|
||||
void PrintTupleTo(const T& t, std::integral_constant<size_t, I>,
|
||||
::std::ostream* os) {
|
||||
PrintTupleTo(t, std::integral_constant<size_t, I - 1>(), os);
|
||||
GTEST_INTENTIONAL_CONST_COND_PUSH_()
|
||||
if (I > 1) {
|
||||
GTEST_INTENTIONAL_CONST_COND_POP_()
|
||||
*os << ", ";
|
||||
}
|
||||
UniversalPrinter<typename std::tuple_element<I - 1, T>::type>::Print(
|
||||
std::get<I - 1>(t), os);
|
||||
}
|
||||
|
||||
template <typename... Types>
|
||||
void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
|
||||
*os << "(";
|
||||
PrintTupleTo(t, std::integral_constant<size_t, sizeof...(Types)>(), os);
|
||||
*os << ")";
|
||||
}
|
||||
|
||||
// Overload for std::pair.
|
||||
template <typename T1, typename T2>
|
||||
void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
|
||||
*os << '(';
|
||||
// We cannot use UniversalPrint(value.first, os) here, as T1 may be
|
||||
// a reference type. The same for printing value.second.
|
||||
UniversalPrinter<T1>::Print(value.first, os);
|
||||
*os << ", ";
|
||||
UniversalPrinter<T2>::Print(value.second, os);
|
||||
*os << ')';
|
||||
}
|
||||
|
||||
// Implements printing a non-reference type T by letting the compiler
|
||||
// pick the right overload of PrintTo() for T.
|
||||
template <typename T>
|
||||
class UniversalPrinter {
|
||||
public:
|
||||
// MSVC warns about adding const to a function type, so we want to
|
||||
// disable the warning.
|
||||
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
|
||||
|
||||
// Note: we deliberately don't call this PrintTo(), as that name
|
||||
// conflicts with ::testing::internal::PrintTo in the body of the
|
||||
// function.
|
||||
static void Print(const T& value, ::std::ostream* os) {
|
||||
// By default, ::testing::internal::PrintTo() is used for printing
|
||||
// the value.
|
||||
//
|
||||
// Thanks to Koenig look-up, if T is a class and has its own
|
||||
// PrintTo() function defined in its namespace, that function will
|
||||
// be visible here. Since it is more specific than the generic ones
|
||||
// in ::testing::internal, it will be picked by the compiler in the
|
||||
// following statement - exactly what we want.
|
||||
PrintTo(value, os);
|
||||
}
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_POP_()
|
||||
};
|
||||
|
||||
#if GTEST_HAS_ABSL
|
||||
|
||||
// Printer for absl::optional
|
||||
|
||||
template <typename T>
|
||||
class UniversalPrinter<::absl::optional<T>> {
|
||||
public:
|
||||
static void Print(const ::absl::optional<T>& value, ::std::ostream* os) {
|
||||
*os << '(';
|
||||
if (!value) {
|
||||
*os << "nullopt";
|
||||
} else {
|
||||
UniversalPrint(*value, os);
|
||||
}
|
||||
*os << ')';
|
||||
}
|
||||
};
|
||||
|
||||
// Printer for absl::variant
|
||||
|
||||
template <typename... T>
|
||||
class UniversalPrinter<::absl::variant<T...>> {
|
||||
public:
|
||||
static void Print(const ::absl::variant<T...>& value, ::std::ostream* os) {
|
||||
*os << '(';
|
||||
absl::visit(Visitor{os}, value);
|
||||
*os << ')';
|
||||
}
|
||||
|
||||
private:
|
||||
struct Visitor {
|
||||
template <typename U>
|
||||
void operator()(const U& u) const {
|
||||
*os << "'" << GetTypeName<U>() << "' with value ";
|
||||
UniversalPrint(u, os);
|
||||
}
|
||||
::std::ostream* os;
|
||||
};
|
||||
};
|
||||
|
||||
#endif // GTEST_HAS_ABSL
|
||||
|
||||
// UniversalPrintArray(begin, len, os) prints an array of 'len'
|
||||
// elements, starting at address 'begin'.
|
||||
template <typename T>
|
||||
void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
|
||||
if (len == 0) {
|
||||
*os << "{}";
|
||||
} else {
|
||||
*os << "{ ";
|
||||
const size_t kThreshold = 18;
|
||||
const size_t kChunkSize = 8;
|
||||
// If the array has more than kThreshold elements, we'll have to
|
||||
// omit some details by printing only the first and the last
|
||||
// kChunkSize elements.
|
||||
if (len <= kThreshold) {
|
||||
PrintRawArrayTo(begin, len, os);
|
||||
} else {
|
||||
PrintRawArrayTo(begin, kChunkSize, os);
|
||||
*os << ", ..., ";
|
||||
PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);
|
||||
}
|
||||
*os << " }";
|
||||
}
|
||||
}
|
||||
// This overload prints a (const) char array compactly.
|
||||
GTEST_API_ void UniversalPrintArray(
|
||||
const char* begin, size_t len, ::std::ostream* os);
|
||||
|
||||
// This overload prints a (const) wchar_t array compactly.
|
||||
GTEST_API_ void UniversalPrintArray(
|
||||
const wchar_t* begin, size_t len, ::std::ostream* os);
|
||||
|
||||
// Implements printing an array type T[N].
|
||||
template <typename T, size_t N>
|
||||
class UniversalPrinter<T[N]> {
|
||||
public:
|
||||
// Prints the given array, omitting some elements when there are too
|
||||
// many.
|
||||
static void Print(const T (&a)[N], ::std::ostream* os) {
|
||||
UniversalPrintArray(a, N, os);
|
||||
}
|
||||
};
|
||||
|
||||
// Implements printing a reference type T&.
|
||||
template <typename T>
|
||||
class UniversalPrinter<T&> {
|
||||
public:
|
||||
// MSVC warns about adding const to a function type, so we want to
|
||||
// disable the warning.
|
||||
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
|
||||
|
||||
static void Print(const T& value, ::std::ostream* os) {
|
||||
// Prints the address of the value. We use reinterpret_cast here
|
||||
// as static_cast doesn't compile when T is a function type.
|
||||
*os << "@" << reinterpret_cast<const void*>(&value) << " ";
|
||||
|
||||
// Then prints the value itself.
|
||||
UniversalPrint(value, os);
|
||||
}
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_POP_()
|
||||
};
|
||||
|
||||
// Prints a value tersely: for a reference type, the referenced value
|
||||
// (but not the address) is printed; for a (const) char pointer, the
|
||||
// NUL-terminated string (but not the pointer) is printed.
|
||||
|
||||
template <typename T>
|
||||
class UniversalTersePrinter {
|
||||
public:
|
||||
static void Print(const T& value, ::std::ostream* os) {
|
||||
UniversalPrint(value, os);
|
||||
}
|
||||
};
|
||||
template <typename T>
|
||||
class UniversalTersePrinter<T&> {
|
||||
public:
|
||||
static void Print(const T& value, ::std::ostream* os) {
|
||||
UniversalPrint(value, os);
|
||||
}
|
||||
};
|
||||
template <typename T, size_t N>
|
||||
class UniversalTersePrinter<T[N]> {
|
||||
public:
|
||||
static void Print(const T (&value)[N], ::std::ostream* os) {
|
||||
UniversalPrinter<T[N]>::Print(value, os);
|
||||
}
|
||||
};
|
||||
template <>
|
||||
class UniversalTersePrinter<const char*> {
|
||||
public:
|
||||
static void Print(const char* str, ::std::ostream* os) {
|
||||
if (str == nullptr) {
|
||||
*os << "NULL";
|
||||
} else {
|
||||
UniversalPrint(std::string(str), os);
|
||||
}
|
||||
}
|
||||
};
|
||||
template <>
|
||||
class UniversalTersePrinter<char*> {
|
||||
public:
|
||||
static void Print(char* str, ::std::ostream* os) {
|
||||
UniversalTersePrinter<const char*>::Print(str, os);
|
||||
}
|
||||
};
|
||||
|
||||
#if GTEST_HAS_STD_WSTRING
|
||||
template <>
|
||||
class UniversalTersePrinter<const wchar_t*> {
|
||||
public:
|
||||
static void Print(const wchar_t* str, ::std::ostream* os) {
|
||||
if (str == nullptr) {
|
||||
*os << "NULL";
|
||||
} else {
|
||||
UniversalPrint(::std::wstring(str), os);
|
||||
}
|
||||
}
|
||||
};
|
||||
#endif
|
||||
|
||||
template <>
|
||||
class UniversalTersePrinter<wchar_t*> {
|
||||
public:
|
||||
static void Print(wchar_t* str, ::std::ostream* os) {
|
||||
UniversalTersePrinter<const wchar_t*>::Print(str, os);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
void UniversalTersePrint(const T& value, ::std::ostream* os) {
|
||||
UniversalTersePrinter<T>::Print(value, os);
|
||||
}
|
||||
|
||||
// Prints a value using the type inferred by the compiler. The
|
||||
// difference between this and UniversalTersePrint() is that for a
|
||||
// (const) char pointer, this prints both the pointer and the
|
||||
// NUL-terminated string.
|
||||
template <typename T>
|
||||
void UniversalPrint(const T& value, ::std::ostream* os) {
|
||||
// A workarond for the bug in VC++ 7.1 that prevents us from instantiating
|
||||
// UniversalPrinter with T directly.
|
||||
typedef T T1;
|
||||
UniversalPrinter<T1>::Print(value, os);
|
||||
}
|
||||
|
||||
typedef ::std::vector< ::std::string> Strings;
|
||||
|
||||
// Tersely prints the first N fields of a tuple to a string vector,
|
||||
// one element for each field.
|
||||
template <typename Tuple>
|
||||
void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,
|
||||
Strings*) {}
|
||||
template <typename Tuple, size_t I>
|
||||
void TersePrintPrefixToStrings(const Tuple& t,
|
||||
std::integral_constant<size_t, I>,
|
||||
Strings* strings) {
|
||||
TersePrintPrefixToStrings(t, std::integral_constant<size_t, I - 1>(),
|
||||
strings);
|
||||
::std::stringstream ss;
|
||||
UniversalTersePrint(std::get<I - 1>(t), &ss);
|
||||
strings->push_back(ss.str());
|
||||
}
|
||||
|
||||
// Prints the fields of a tuple tersely to a string vector, one
|
||||
// element for each field. See the comment before
|
||||
// UniversalTersePrint() for how we define "tersely".
|
||||
template <typename Tuple>
|
||||
Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
|
||||
Strings result;
|
||||
TersePrintPrefixToStrings(
|
||||
value, std::integral_constant<size_t, std::tuple_size<Tuple>::value>(),
|
||||
&result);
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
|
||||
#if GTEST_HAS_ABSL
|
||||
namespace internal2 {
|
||||
template <typename T>
|
||||
void TypeWithoutFormatter<T, kConvertibleToStringView>::PrintValue(
|
||||
const T& value, ::std::ostream* os) {
|
||||
internal::PrintTo(absl::string_view(value), os);
|
||||
}
|
||||
} // namespace internal2
|
||||
#endif
|
||||
|
||||
template <typename T>
|
||||
::std::string PrintToString(const T& value) {
|
||||
::std::stringstream ss;
|
||||
internal::UniversalTersePrinter<T>::Print(value, &ss);
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
} // namespace testing
|
||||
|
||||
// Include any custom printer added by the local installation.
|
||||
// We must include this header at the end to make sure it can use the
|
||||
// declarations from this file.
|
||||
#include "gtest/internal/custom/gtest-printers.h"
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
|
238
3rdparty/gtest/include/gtest/gtest-spi.h
vendored
Normal file
238
3rdparty/gtest/include/gtest/gtest-spi.h
vendored
Normal file
@ -0,0 +1,238 @@
|
||||
// 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.
|
||||
|
||||
//
|
||||
// Utilities for testing Google Test itself and code that uses Google Test
|
||||
// (e.g. frameworks built on top of Google Test).
|
||||
|
||||
// GOOGLETEST_CM0004 DO NOT DELETE
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
|
||||
/* class A needs to have dll-interface to be used by clients of class B */)
|
||||
|
||||
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.
|
||||
~ScopedFakeTestPartResultReporter() override;
|
||||
|
||||
// Appends the TestPartResult object to the TestPartResultArray
|
||||
// received in the constructor.
|
||||
//
|
||||
// This method is from the TestPartResultReporterInterface
|
||||
// interface.
|
||||
void ReportTestPartResult(const TestPartResult& result) override;
|
||||
|
||||
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 std::string& substr);
|
||||
~SingleFailureChecker();
|
||||
private:
|
||||
const TestPartResultArray* const results_;
|
||||
const TestPartResult::Type type_;
|
||||
const std::string substr_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
|
||||
};
|
||||
|
||||
} // namespace internal
|
||||
|
||||
} // namespace testing
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
|
||||
|
||||
// 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_
|
184
3rdparty/gtest/include/gtest/gtest-test-part.h
vendored
Normal file
184
3rdparty/gtest/include/gtest/gtest-test-part.h
vendored
Normal file
@ -0,0 +1,184 @@
|
||||
// Copyright 2008, 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.
|
||||
//
|
||||
// GOOGLETEST_CM0001 DO NOT DELETE
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
|
||||
|
||||
#include <iosfwd>
|
||||
#include <vector>
|
||||
#include "gtest/internal/gtest-internal.h"
|
||||
#include "gtest/internal/gtest-string.h"
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
|
||||
/* class A needs to have dll-interface to be used by clients of class B */)
|
||||
|
||||
namespace testing {
|
||||
|
||||
// A copyable object representing the result of a test part (i.e. an
|
||||
// assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()).
|
||||
//
|
||||
// Don't inherit from TestPartResult as its destructor is not virtual.
|
||||
class GTEST_API_ TestPartResult {
|
||||
public:
|
||||
// The possible outcomes of a test part (i.e. an assertion or an
|
||||
// explicit SUCCEED(), FAIL(), or ADD_FAILURE()).
|
||||
enum Type {
|
||||
kSuccess, // Succeeded.
|
||||
kNonFatalFailure, // Failed but the test can continue.
|
||||
kFatalFailure, // Failed and the test should be terminated.
|
||||
kSkip // Skipped.
|
||||
};
|
||||
|
||||
// C'tor. TestPartResult does NOT have a default constructor.
|
||||
// Always use this constructor (with parameters) to create a
|
||||
// TestPartResult object.
|
||||
TestPartResult(Type a_type, const char* a_file_name, int a_line_number,
|
||||
const char* a_message)
|
||||
: type_(a_type),
|
||||
file_name_(a_file_name == nullptr ? "" : a_file_name),
|
||||
line_number_(a_line_number),
|
||||
summary_(ExtractSummary(a_message)),
|
||||
message_(a_message) {}
|
||||
|
||||
// Gets the outcome of the test part.
|
||||
Type type() const { return type_; }
|
||||
|
||||
// Gets the name of the source file where the test part took place, or
|
||||
// NULL if it's unknown.
|
||||
const char* file_name() const {
|
||||
return file_name_.empty() ? nullptr : file_name_.c_str();
|
||||
}
|
||||
|
||||
// Gets the line in the source file where the test part took place,
|
||||
// or -1 if it's unknown.
|
||||
int line_number() const { return line_number_; }
|
||||
|
||||
// Gets the summary of the failure message.
|
||||
const char* summary() const { return summary_.c_str(); }
|
||||
|
||||
// Gets the message associated with the test part.
|
||||
const char* message() const { return message_.c_str(); }
|
||||
|
||||
// Returns true if and only if the test part was skipped.
|
||||
bool skipped() const { return type_ == kSkip; }
|
||||
|
||||
// Returns true if and only if the test part passed.
|
||||
bool passed() const { return type_ == kSuccess; }
|
||||
|
||||
// Returns true if and only if the test part non-fatally failed.
|
||||
bool nonfatally_failed() const { return type_ == kNonFatalFailure; }
|
||||
|
||||
// Returns true if and only if the test part fatally failed.
|
||||
bool fatally_failed() const { return type_ == kFatalFailure; }
|
||||
|
||||
// Returns true if and only if the test part failed.
|
||||
bool failed() const { return fatally_failed() || nonfatally_failed(); }
|
||||
|
||||
private:
|
||||
Type type_;
|
||||
|
||||
// Gets the summary of the failure message by omitting the stack
|
||||
// trace in it.
|
||||
static std::string ExtractSummary(const char* message);
|
||||
|
||||
// The name of the source file where the test part took place, or
|
||||
// "" if the source file is unknown.
|
||||
std::string file_name_;
|
||||
// The line in the source file where the test part took place, or -1
|
||||
// if the line number is unknown.
|
||||
int line_number_;
|
||||
std::string summary_; // The test failure summary.
|
||||
std::string message_; // The test failure message.
|
||||
};
|
||||
|
||||
// Prints a TestPartResult object.
|
||||
std::ostream& operator<<(std::ostream& os, const TestPartResult& result);
|
||||
|
||||
// An array of TestPartResult objects.
|
||||
//
|
||||
// Don't inherit from TestPartResultArray as its destructor is not
|
||||
// virtual.
|
||||
class GTEST_API_ TestPartResultArray {
|
||||
public:
|
||||
TestPartResultArray() {}
|
||||
|
||||
// Appends the given TestPartResult to the array.
|
||||
void Append(const TestPartResult& result);
|
||||
|
||||
// Returns the TestPartResult at the given index (0-based).
|
||||
const TestPartResult& GetTestPartResult(int index) const;
|
||||
|
||||
// Returns the number of TestPartResult objects in the array.
|
||||
int size() const;
|
||||
|
||||
private:
|
||||
std::vector<TestPartResult> array_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray);
|
||||
};
|
||||
|
||||
// This interface knows how to report a test part result.
|
||||
class GTEST_API_ TestPartResultReporterInterface {
|
||||
public:
|
||||
virtual ~TestPartResultReporterInterface() {}
|
||||
|
||||
virtual void ReportTestPartResult(const TestPartResult& result) = 0;
|
||||
};
|
||||
|
||||
namespace internal {
|
||||
|
||||
// This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a
|
||||
// statement generates new fatal failures. To do so it registers itself as the
|
||||
// current test part result reporter. Besides checking if fatal failures were
|
||||
// reported, it only delegates the reporting to the former result reporter.
|
||||
// The original result reporter is restored in the destructor.
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
|
||||
class GTEST_API_ HasNewFatalFailureHelper
|
||||
: public TestPartResultReporterInterface {
|
||||
public:
|
||||
HasNewFatalFailureHelper();
|
||||
~HasNewFatalFailureHelper() override;
|
||||
void ReportTestPartResult(const TestPartResult& result) override;
|
||||
bool has_new_fatal_failure() const { return has_new_fatal_failure_; }
|
||||
private:
|
||||
bool has_new_fatal_failure_;
|
||||
TestPartResultReporterInterface* original_reporter_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper);
|
||||
};
|
||||
|
||||
} // namespace internal
|
||||
|
||||
} // namespace testing
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
|
330
3rdparty/gtest/include/gtest/gtest-typed-test.h
vendored
Normal file
330
3rdparty/gtest/include/gtest/gtest-typed-test.h
vendored
Normal file
@ -0,0 +1,330 @@
|
||||
// Copyright 2008 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.
|
||||
|
||||
|
||||
// GOOGLETEST_CM0001 DO NOT DELETE
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
|
||||
|
||||
// This header implements typed tests and type-parameterized tests.
|
||||
|
||||
// Typed (aka type-driven) tests repeat the same test for types in a
|
||||
// list. You must know which types you want to test with when writing
|
||||
// typed tests. Here's how you do it:
|
||||
|
||||
#if 0
|
||||
|
||||
// First, define a fixture class template. It should be parameterized
|
||||
// by a type. Remember to derive it from testing::Test.
|
||||
template <typename T>
|
||||
class FooTest : public testing::Test {
|
||||
public:
|
||||
...
|
||||
typedef std::list<T> List;
|
||||
static T shared_;
|
||||
T value_;
|
||||
};
|
||||
|
||||
// Next, associate a list of types with the test suite, which will be
|
||||
// repeated for each type in the list. The typedef is necessary for
|
||||
// the macro to parse correctly.
|
||||
typedef testing::Types<char, int, unsigned int> MyTypes;
|
||||
TYPED_TEST_SUITE(FooTest, MyTypes);
|
||||
|
||||
// If the type list contains only one type, you can write that type
|
||||
// directly without Types<...>:
|
||||
// TYPED_TEST_SUITE(FooTest, int);
|
||||
|
||||
// Then, use TYPED_TEST() instead of TEST_F() to define as many typed
|
||||
// tests for this test suite as you want.
|
||||
TYPED_TEST(FooTest, DoesBlah) {
|
||||
// Inside a test, refer to the special name TypeParam to get the type
|
||||
// parameter. Since we are inside a derived class template, C++ requires
|
||||
// us to visit the members of FooTest via 'this'.
|
||||
TypeParam n = this->value_;
|
||||
|
||||
// To visit static members of the fixture, add the TestFixture::
|
||||
// prefix.
|
||||
n += TestFixture::shared_;
|
||||
|
||||
// To refer to typedefs in the fixture, add the "typename
|
||||
// TestFixture::" prefix.
|
||||
typename TestFixture::List values;
|
||||
values.push_back(n);
|
||||
...
|
||||
}
|
||||
|
||||
TYPED_TEST(FooTest, HasPropertyA) { ... }
|
||||
|
||||
// TYPED_TEST_SUITE takes an optional third argument which allows to specify a
|
||||
// class that generates custom test name suffixes based on the type. This should
|
||||
// be a class which has a static template function GetName(int index) returning
|
||||
// a string for each type. The provided integer index equals the index of the
|
||||
// type in the provided type list. In many cases the index can be ignored.
|
||||
//
|
||||
// For example:
|
||||
// class MyTypeNames {
|
||||
// public:
|
||||
// template <typename T>
|
||||
// static std::string GetName(int) {
|
||||
// if (std::is_same<T, char>()) return "char";
|
||||
// if (std::is_same<T, int>()) return "int";
|
||||
// if (std::is_same<T, unsigned int>()) return "unsignedInt";
|
||||
// }
|
||||
// };
|
||||
// TYPED_TEST_SUITE(FooTest, MyTypes, MyTypeNames);
|
||||
|
||||
#endif // 0
|
||||
|
||||
// Type-parameterized tests are abstract test patterns parameterized
|
||||
// by a type. Compared with typed tests, type-parameterized tests
|
||||
// allow you to define the test pattern without knowing what the type
|
||||
// parameters are. The defined pattern can be instantiated with
|
||||
// different types any number of times, in any number of translation
|
||||
// units.
|
||||
//
|
||||
// If you are designing an interface or concept, you can define a
|
||||
// suite of type-parameterized tests to verify properties that any
|
||||
// valid implementation of the interface/concept should have. Then,
|
||||
// each implementation can easily instantiate the test suite to verify
|
||||
// that it conforms to the requirements, without having to write
|
||||
// similar tests repeatedly. Here's an example:
|
||||
|
||||
#if 0
|
||||
|
||||
// First, define a fixture class template. It should be parameterized
|
||||
// by a type. Remember to derive it from testing::Test.
|
||||
template <typename T>
|
||||
class FooTest : public testing::Test {
|
||||
...
|
||||
};
|
||||
|
||||
// Next, declare that you will define a type-parameterized test suite
|
||||
// (the _P suffix is for "parameterized" or "pattern", whichever you
|
||||
// prefer):
|
||||
TYPED_TEST_SUITE_P(FooTest);
|
||||
|
||||
// Then, use TYPED_TEST_P() to define as many type-parameterized tests
|
||||
// for this type-parameterized test suite as you want.
|
||||
TYPED_TEST_P(FooTest, DoesBlah) {
|
||||
// Inside a test, refer to TypeParam to get the type parameter.
|
||||
TypeParam n = 0;
|
||||
...
|
||||
}
|
||||
|
||||
TYPED_TEST_P(FooTest, HasPropertyA) { ... }
|
||||
|
||||
// Now the tricky part: you need to register all test patterns before
|
||||
// you can instantiate them. The first argument of the macro is the
|
||||
// test suite name; the rest are the names of the tests in this test
|
||||
// case.
|
||||
REGISTER_TYPED_TEST_SUITE_P(FooTest,
|
||||
DoesBlah, HasPropertyA);
|
||||
|
||||
// Finally, you are free to instantiate the pattern with the types you
|
||||
// want. If you put the above code in a header file, you can #include
|
||||
// it in multiple C++ source files and instantiate it multiple times.
|
||||
//
|
||||
// To distinguish different instances of the pattern, the first
|
||||
// argument to the INSTANTIATE_* macro is a prefix that will be added
|
||||
// to the actual test suite name. Remember to pick unique prefixes for
|
||||
// different instances.
|
||||
typedef testing::Types<char, int, unsigned int> MyTypes;
|
||||
INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
|
||||
|
||||
// If the type list contains only one type, you can write that type
|
||||
// directly without Types<...>:
|
||||
// INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int);
|
||||
//
|
||||
// Similar to the optional argument of TYPED_TEST_SUITE above,
|
||||
// INSTANTIATE_TEST_SUITE_P takes an optional fourth argument which allows to
|
||||
// generate custom names.
|
||||
// INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes, MyTypeNames);
|
||||
|
||||
#endif // 0
|
||||
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
#include "gtest/internal/gtest-type-util.h"
|
||||
|
||||
// Implements typed tests.
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
//
|
||||
// Expands to the name of the typedef for the type parameters of the
|
||||
// given test suite.
|
||||
#define GTEST_TYPE_PARAMS_(TestSuiteName) gtest_type_params_##TestSuiteName##_
|
||||
|
||||
// Expands to the name of the typedef for the NameGenerator, responsible for
|
||||
// creating the suffixes of the name.
|
||||
#define GTEST_NAME_GENERATOR_(TestSuiteName) \
|
||||
gtest_type_params_##TestSuiteName##_NameGenerator
|
||||
|
||||
#define TYPED_TEST_SUITE(CaseName, Types, ...) \
|
||||
typedef ::testing::internal::TypeList<Types>::type GTEST_TYPE_PARAMS_( \
|
||||
CaseName); \
|
||||
typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \
|
||||
GTEST_NAME_GENERATOR_(CaseName)
|
||||
|
||||
# define TYPED_TEST(CaseName, TestName) \
|
||||
template <typename gtest_TypeParam_> \
|
||||
class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \
|
||||
: public CaseName<gtest_TypeParam_> { \
|
||||
private: \
|
||||
typedef CaseName<gtest_TypeParam_> TestFixture; \
|
||||
typedef gtest_TypeParam_ TypeParam; \
|
||||
virtual void TestBody(); \
|
||||
}; \
|
||||
static bool gtest_##CaseName##_##TestName##_registered_ \
|
||||
GTEST_ATTRIBUTE_UNUSED_ = \
|
||||
::testing::internal::TypeParameterizedTest< \
|
||||
CaseName, \
|
||||
::testing::internal::TemplateSel<GTEST_TEST_CLASS_NAME_(CaseName, \
|
||||
TestName)>, \
|
||||
GTEST_TYPE_PARAMS_( \
|
||||
CaseName)>::Register("", \
|
||||
::testing::internal::CodeLocation( \
|
||||
__FILE__, __LINE__), \
|
||||
#CaseName, #TestName, 0, \
|
||||
::testing::internal::GenerateNames< \
|
||||
GTEST_NAME_GENERATOR_(CaseName), \
|
||||
GTEST_TYPE_PARAMS_(CaseName)>()); \
|
||||
template <typename gtest_TypeParam_> \
|
||||
void GTEST_TEST_CLASS_NAME_(CaseName, \
|
||||
TestName)<gtest_TypeParam_>::TestBody()
|
||||
|
||||
// Legacy API is deprecated but still available
|
||||
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
#define TYPED_TEST_CASE \
|
||||
static_assert(::testing::internal::TypedTestCaseIsDeprecated(), ""); \
|
||||
TYPED_TEST_SUITE
|
||||
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST
|
||||
|
||||
// Implements type-parameterized tests.
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
//
|
||||
// Expands to the namespace name that the type-parameterized tests for
|
||||
// the given type-parameterized test suite are defined in. The exact
|
||||
// name of the namespace is subject to change without notice.
|
||||
#define GTEST_SUITE_NAMESPACE_(TestSuiteName) gtest_suite_##TestSuiteName##_
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
//
|
||||
// Expands to the name of the variable used to remember the names of
|
||||
// the defined tests in the given test suite.
|
||||
#define GTEST_TYPED_TEST_SUITE_P_STATE_(TestSuiteName) \
|
||||
gtest_typed_test_suite_p_state_##TestSuiteName##_
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY.
|
||||
//
|
||||
// Expands to the name of the variable used to remember the names of
|
||||
// the registered tests in the given test suite.
|
||||
#define GTEST_REGISTERED_TEST_NAMES_(TestSuiteName) \
|
||||
gtest_registered_test_names_##TestSuiteName##_
|
||||
|
||||
// The variables defined in the type-parameterized test macros are
|
||||
// static as typically these macros are used in a .h file that can be
|
||||
// #included in multiple translation units linked together.
|
||||
#define TYPED_TEST_SUITE_P(SuiteName) \
|
||||
static ::testing::internal::TypedTestSuitePState \
|
||||
GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName)
|
||||
|
||||
// Legacy API is deprecated but still available
|
||||
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
#define TYPED_TEST_CASE_P \
|
||||
static_assert(::testing::internal::TypedTestCase_P_IsDeprecated(), ""); \
|
||||
TYPED_TEST_SUITE_P
|
||||
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
|
||||
#define TYPED_TEST_P(SuiteName, TestName) \
|
||||
namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
|
||||
template <typename gtest_TypeParam_> \
|
||||
class TestName : public SuiteName<gtest_TypeParam_> { \
|
||||
private: \
|
||||
typedef SuiteName<gtest_TypeParam_> TestFixture; \
|
||||
typedef gtest_TypeParam_ TypeParam; \
|
||||
virtual void TestBody(); \
|
||||
}; \
|
||||
static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \
|
||||
GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \
|
||||
__FILE__, __LINE__, #SuiteName, #TestName); \
|
||||
} \
|
||||
template <typename gtest_TypeParam_> \
|
||||
void GTEST_SUITE_NAMESPACE_( \
|
||||
SuiteName)::TestName<gtest_TypeParam_>::TestBody()
|
||||
|
||||
#define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \
|
||||
namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
|
||||
typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \
|
||||
} \
|
||||
static const char* const GTEST_REGISTERED_TEST_NAMES_( \
|
||||
SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \
|
||||
GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \
|
||||
__FILE__, __LINE__, #__VA_ARGS__)
|
||||
|
||||
// Legacy API is deprecated but still available
|
||||
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
#define REGISTER_TYPED_TEST_CASE_P \
|
||||
static_assert(::testing::internal::RegisterTypedTestCase_P_IsDeprecated(), \
|
||||
""); \
|
||||
REGISTER_TYPED_TEST_SUITE_P
|
||||
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
|
||||
#define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \
|
||||
static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \
|
||||
::testing::internal::TypeParameterizedTestSuite< \
|
||||
SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \
|
||||
::testing::internal::TypeList<Types>::type>:: \
|
||||
Register(#Prefix, \
|
||||
::testing::internal::CodeLocation(__FILE__, __LINE__), \
|
||||
>EST_TYPED_TEST_SUITE_P_STATE_(SuiteName), #SuiteName, \
|
||||
GTEST_REGISTERED_TEST_NAMES_(SuiteName), \
|
||||
::testing::internal::GenerateNames< \
|
||||
::testing::internal::NameGeneratorSelector< \
|
||||
__VA_ARGS__>::type, \
|
||||
::testing::internal::TypeList<Types>::type>())
|
||||
|
||||
// Legacy API is deprecated but still available
|
||||
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
#define INSTANTIATE_TYPED_TEST_CASE_P \
|
||||
static_assert( \
|
||||
::testing::internal::InstantiateTypedTestCase_P_IsDeprecated(), ""); \
|
||||
INSTANTIATE_TYPED_TEST_SUITE_P
|
||||
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
|
2478
3rdparty/gtest/include/gtest/gtest.h
vendored
Normal file
2478
3rdparty/gtest/include/gtest/gtest.h
vendored
Normal file
File diff suppressed because it is too large
Load Diff
359
3rdparty/gtest/include/gtest/gtest_pred_impl.h
vendored
Normal file
359
3rdparty/gtest/include/gtest/gtest_pred_impl.h
vendored
Normal file
@ -0,0 +1,359 @@
|
||||
// Copyright 2006, 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.
|
||||
|
||||
// This file is AUTOMATICALLY GENERATED on 01/02/2019 by command
|
||||
// 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND!
|
||||
//
|
||||
// Implements a family of generic predicate assertion macros.
|
||||
// GOOGLETEST_CM0001 DO NOT DELETE
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace testing {
|
||||
|
||||
// This header implements a family of generic predicate assertion
|
||||
// macros:
|
||||
//
|
||||
// ASSERT_PRED_FORMAT1(pred_format, v1)
|
||||
// ASSERT_PRED_FORMAT2(pred_format, v1, v2)
|
||||
// ...
|
||||
//
|
||||
// where pred_format is a function or functor that takes n (in the
|
||||
// case of ASSERT_PRED_FORMATn) values and their source expression
|
||||
// text, and returns a testing::AssertionResult. See the definition
|
||||
// of ASSERT_EQ in gtest.h for an example.
|
||||
//
|
||||
// If you don't care about formatting, you can use the more
|
||||
// restrictive version:
|
||||
//
|
||||
// ASSERT_PRED1(pred, v1)
|
||||
// ASSERT_PRED2(pred, v1, v2)
|
||||
// ...
|
||||
//
|
||||
// where pred is an n-ary function or functor that returns bool,
|
||||
// and the values v1, v2, ..., must support the << operator for
|
||||
// streaming to std::ostream.
|
||||
//
|
||||
// We also define the EXPECT_* variations.
|
||||
//
|
||||
// For now we only support predicates whose arity is at most 5.
|
||||
// Please email googletestframework@googlegroups.com if you need
|
||||
// support for higher arities.
|
||||
|
||||
// GTEST_ASSERT_ is the basic statement to which all of the assertions
|
||||
// in this file reduce. Don't use this in your code.
|
||||
|
||||
#define GTEST_ASSERT_(expression, on_failure) \
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
|
||||
if (const ::testing::AssertionResult gtest_ar = (expression)) \
|
||||
; \
|
||||
else \
|
||||
on_failure(gtest_ar.failure_message())
|
||||
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1>
|
||||
AssertionResult AssertPred1Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
Pred pred,
|
||||
const T1& v1) {
|
||||
if (pred(v1)) return AssertionSuccess();
|
||||
|
||||
return AssertionFailure()
|
||||
<< pred_text << "(" << e1 << ") evaluates to false, where"
|
||||
<< "\n"
|
||||
<< e1 << " evaluates to " << ::testing::PrintToString(v1);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\
|
||||
GTEST_ASSERT_(pred_format(#v1, v1), \
|
||||
on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED1_(pred, v1, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \
|
||||
#v1, \
|
||||
pred, \
|
||||
v1), on_failure)
|
||||
|
||||
// Unary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT1(pred_format, v1) \
|
||||
GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_)
|
||||
#define EXPECT_PRED1(pred, v1) \
|
||||
GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)
|
||||
#define ASSERT_PRED_FORMAT1(pred_format, v1) \
|
||||
GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_)
|
||||
#define ASSERT_PRED1(pred, v1) \
|
||||
GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)
|
||||
|
||||
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1,
|
||||
typename T2>
|
||||
AssertionResult AssertPred2Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
const char* e2,
|
||||
Pred pred,
|
||||
const T1& v1,
|
||||
const T2& v2) {
|
||||
if (pred(v1, v2)) return AssertionSuccess();
|
||||
|
||||
return AssertionFailure()
|
||||
<< pred_text << "(" << e1 << ", " << e2
|
||||
<< ") evaluates to false, where"
|
||||
<< "\n"
|
||||
<< e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
|
||||
<< e2 << " evaluates to " << ::testing::PrintToString(v2);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\
|
||||
GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \
|
||||
on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED2_(pred, v1, v2, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \
|
||||
#v1, \
|
||||
#v2, \
|
||||
pred, \
|
||||
v1, \
|
||||
v2), on_failure)
|
||||
|
||||
// Binary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \
|
||||
GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_)
|
||||
#define EXPECT_PRED2(pred, v1, v2) \
|
||||
GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_)
|
||||
#define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \
|
||||
GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_)
|
||||
#define ASSERT_PRED2(pred, v1, v2) \
|
||||
GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_)
|
||||
|
||||
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1,
|
||||
typename T2,
|
||||
typename T3>
|
||||
AssertionResult AssertPred3Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
const char* e2,
|
||||
const char* e3,
|
||||
Pred pred,
|
||||
const T1& v1,
|
||||
const T2& v2,
|
||||
const T3& v3) {
|
||||
if (pred(v1, v2, v3)) return AssertionSuccess();
|
||||
|
||||
return AssertionFailure()
|
||||
<< pred_text << "(" << e1 << ", " << e2 << ", " << e3
|
||||
<< ") evaluates to false, where"
|
||||
<< "\n"
|
||||
<< e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
|
||||
<< e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
|
||||
<< e3 << " evaluates to " << ::testing::PrintToString(v3);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\
|
||||
GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \
|
||||
on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \
|
||||
#v1, \
|
||||
#v2, \
|
||||
#v3, \
|
||||
pred, \
|
||||
v1, \
|
||||
v2, \
|
||||
v3), on_failure)
|
||||
|
||||
// Ternary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \
|
||||
GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
|
||||
#define EXPECT_PRED3(pred, v1, v2, v3) \
|
||||
GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_)
|
||||
#define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \
|
||||
GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_)
|
||||
#define ASSERT_PRED3(pred, v1, v2, v3) \
|
||||
GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_)
|
||||
|
||||
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1,
|
||||
typename T2,
|
||||
typename T3,
|
||||
typename T4>
|
||||
AssertionResult AssertPred4Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
const char* e2,
|
||||
const char* e3,
|
||||
const char* e4,
|
||||
Pred pred,
|
||||
const T1& v1,
|
||||
const T2& v2,
|
||||
const T3& v3,
|
||||
const T4& v4) {
|
||||
if (pred(v1, v2, v3, v4)) return AssertionSuccess();
|
||||
|
||||
return AssertionFailure()
|
||||
<< pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
|
||||
<< ") evaluates to false, where"
|
||||
<< "\n"
|
||||
<< e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
|
||||
<< e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
|
||||
<< e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
|
||||
<< e4 << " evaluates to " << ::testing::PrintToString(v4);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\
|
||||
GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \
|
||||
on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \
|
||||
#v1, \
|
||||
#v2, \
|
||||
#v3, \
|
||||
#v4, \
|
||||
pred, \
|
||||
v1, \
|
||||
v2, \
|
||||
v3, \
|
||||
v4), on_failure)
|
||||
|
||||
// 4-ary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
|
||||
GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
|
||||
#define EXPECT_PRED4(pred, v1, v2, v3, v4) \
|
||||
GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)
|
||||
#define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
|
||||
GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
|
||||
#define ASSERT_PRED4(pred, v1, v2, v3, v4) \
|
||||
GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
|
||||
|
||||
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1,
|
||||
typename T2,
|
||||
typename T3,
|
||||
typename T4,
|
||||
typename T5>
|
||||
AssertionResult AssertPred5Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
const char* e2,
|
||||
const char* e3,
|
||||
const char* e4,
|
||||
const char* e5,
|
||||
Pred pred,
|
||||
const T1& v1,
|
||||
const T2& v2,
|
||||
const T3& v3,
|
||||
const T4& v4,
|
||||
const T5& v5) {
|
||||
if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess();
|
||||
|
||||
return AssertionFailure()
|
||||
<< pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
|
||||
<< ", " << e5 << ") evaluates to false, where"
|
||||
<< "\n"
|
||||
<< e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
|
||||
<< e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
|
||||
<< e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
|
||||
<< e4 << " evaluates to " << ::testing::PrintToString(v4) << "\n"
|
||||
<< e5 << " evaluates to " << ::testing::PrintToString(v5);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\
|
||||
GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \
|
||||
on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \
|
||||
#v1, \
|
||||
#v2, \
|
||||
#v3, \
|
||||
#v4, \
|
||||
#v5, \
|
||||
pred, \
|
||||
v1, \
|
||||
v2, \
|
||||
v3, \
|
||||
v4, \
|
||||
v5), on_failure)
|
||||
|
||||
// 5-ary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
|
||||
GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
|
||||
#define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \
|
||||
GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)
|
||||
#define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
|
||||
GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
|
||||
#define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \
|
||||
GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
|
||||
|
||||
|
||||
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
61
3rdparty/gtest/include/gtest/gtest_prod.h
vendored
Normal file
61
3rdparty/gtest/include/gtest/gtest_prod.h
vendored
Normal file
@ -0,0 +1,61 @@
|
||||
// Copyright 2006, 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.
|
||||
|
||||
//
|
||||
// Google C++ Testing and Mocking Framework definitions useful in production code.
|
||||
// GOOGLETEST_CM0003 DO NOT DELETE
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_PROD_H_
|
||||
|
||||
// When you need to test the private or protected members of a class,
|
||||
// use the FRIEND_TEST macro to declare your tests as friends of the
|
||||
// class. For example:
|
||||
//
|
||||
// class MyClass {
|
||||
// private:
|
||||
// void PrivateMethod();
|
||||
// FRIEND_TEST(MyClassTest, PrivateMethodWorks);
|
||||
// };
|
||||
//
|
||||
// class MyClassTest : public testing::Test {
|
||||
// // ...
|
||||
// };
|
||||
//
|
||||
// TEST_F(MyClassTest, PrivateMethodWorks) {
|
||||
// // Can call MyClass::PrivateMethod() here.
|
||||
// }
|
||||
//
|
||||
// Note: The test class must be in the same namespace as the class being tested.
|
||||
// For example, putting MyClassTest in an anonymous namespace will not work.
|
||||
|
||||
#define FRIEND_TEST(test_case_name, test_name)\
|
||||
friend class test_case_name##_##test_name##_Test
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_PROD_H_
|
56
3rdparty/gtest/include/gtest/internal/custom/README.md
vendored
Normal file
56
3rdparty/gtest/include/gtest/internal/custom/README.md
vendored
Normal file
@ -0,0 +1,56 @@
|
||||
# Customization Points
|
||||
|
||||
The custom directory is an injection point for custom user configurations.
|
||||
|
||||
## Header `gtest.h`
|
||||
|
||||
### The following macros can be defined:
|
||||
|
||||
* `GTEST_OS_STACK_TRACE_GETTER_` - The name of an implementation of
|
||||
`OsStackTraceGetterInterface`.
|
||||
* `GTEST_CUSTOM_TEMPDIR_FUNCTION_` - An override for `testing::TempDir()`. See
|
||||
`testing::TempDir` for semantics and signature.
|
||||
|
||||
## Header `gtest-port.h`
|
||||
|
||||
The following macros can be defined:
|
||||
|
||||
### Flag related macros:
|
||||
|
||||
* `GTEST_FLAG(flag_name)`
|
||||
* `GTEST_USE_OWN_FLAGFILE_FLAG_` - Define to 0 when the system provides its
|
||||
own flagfile flag parsing.
|
||||
* `GTEST_DECLARE_bool_(name)`
|
||||
* `GTEST_DECLARE_int32_(name)`
|
||||
* `GTEST_DECLARE_string_(name)`
|
||||
* `GTEST_DEFINE_bool_(name, default_val, doc)`
|
||||
* `GTEST_DEFINE_int32_(name, default_val, doc)`
|
||||
* `GTEST_DEFINE_string_(name, default_val, doc)`
|
||||
|
||||
### Logging:
|
||||
|
||||
* `GTEST_LOG_(severity)`
|
||||
* `GTEST_CHECK_(condition)`
|
||||
* Functions `LogToStderr()` and `FlushInfoLog()` have to be provided too.
|
||||
|
||||
### Threading:
|
||||
|
||||
* `GTEST_HAS_NOTIFICATION_` - Enabled if Notification is already provided.
|
||||
* `GTEST_HAS_MUTEX_AND_THREAD_LOCAL_` - Enabled if `Mutex` and `ThreadLocal`
|
||||
are already provided. Must also provide `GTEST_DECLARE_STATIC_MUTEX_(mutex)`
|
||||
and `GTEST_DEFINE_STATIC_MUTEX_(mutex)`
|
||||
* `GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)`
|
||||
* `GTEST_LOCK_EXCLUDED_(locks)`
|
||||
|
||||
### Underlying library support features
|
||||
|
||||
* `GTEST_HAS_CXXABI_H_`
|
||||
|
||||
### Exporting API symbols:
|
||||
|
||||
* `GTEST_API_` - Specifier for exported symbols.
|
||||
|
||||
## Header `gtest-printers.h`
|
||||
|
||||
* See documentation at `gtest/gtest-printers.h` for details on how to define a
|
||||
custom printer.
|
37
3rdparty/gtest/include/gtest/internal/custom/gtest-port.h
vendored
Normal file
37
3rdparty/gtest/include/gtest/internal/custom/gtest-port.h
vendored
Normal file
@ -0,0 +1,37 @@
|
||||
// Copyright 2015, 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.
|
||||
//
|
||||
// Injection point for custom user configurations. See README for details
|
||||
//
|
||||
// ** Custom implementation starts here **
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
|
42
3rdparty/gtest/include/gtest/internal/custom/gtest-printers.h
vendored
Normal file
42
3rdparty/gtest/include/gtest/internal/custom/gtest-printers.h
vendored
Normal file
@ -0,0 +1,42 @@
|
||||
// Copyright 2015, 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.
|
||||
//
|
||||
// This file provides an injection point for custom printers in a local
|
||||
// installation of gTest.
|
||||
// It will be included from gtest-printers.h and the overrides in this file
|
||||
// will be visible to everyone.
|
||||
//
|
||||
// Injection point for custom user configurations. See README for details
|
||||
//
|
||||
// ** Custom implementation starts here **
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
|
37
3rdparty/gtest/include/gtest/internal/custom/gtest.h
vendored
Normal file
37
3rdparty/gtest/include/gtest/internal/custom/gtest.h
vendored
Normal file
@ -0,0 +1,37 @@
|
||||
// Copyright 2015, 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.
|
||||
//
|
||||
// Injection point for custom user configurations. See README for details
|
||||
//
|
||||
// ** Custom implementation starts here **
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
|
304
3rdparty/gtest/include/gtest/internal/gtest-death-test-internal.h
vendored
Normal file
304
3rdparty/gtest/include/gtest/internal/gtest-death-test-internal.h
vendored
Normal file
@ -0,0 +1,304 @@
|
||||
// Copyright 2005, 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.
|
||||
//
|
||||
// The Google C++ Testing and Mocking Framework (Google Test)
|
||||
//
|
||||
// This header file defines internal utilities needed for implementing
|
||||
// death tests. They are subject to change without notice.
|
||||
// GOOGLETEST_CM0001 DO NOT DELETE
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
|
||||
|
||||
#include "gtest/gtest-matchers.h"
|
||||
#include "gtest/internal/gtest-internal.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <memory>
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
GTEST_DECLARE_string_(internal_run_death_test);
|
||||
|
||||
// Names of the flags (needed for parsing Google Test flags).
|
||||
const char kDeathTestStyleFlag[] = "death_test_style";
|
||||
const char kDeathTestUseFork[] = "death_test_use_fork";
|
||||
const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
|
||||
|
||||
#if GTEST_HAS_DEATH_TEST
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
|
||||
/* class A needs to have dll-interface to be used by clients of class B */)
|
||||
|
||||
// DeathTest is a class that hides much of the complexity of the
|
||||
// GTEST_DEATH_TEST_ macro. It is abstract; its static Create method
|
||||
// returns a concrete class that depends on the prevailing death test
|
||||
// style, as defined by the --gtest_death_test_style and/or
|
||||
// --gtest_internal_run_death_test flags.
|
||||
|
||||
// In describing the results of death tests, these terms are used with
|
||||
// the corresponding definitions:
|
||||
//
|
||||
// exit status: The integer exit information in the format specified
|
||||
// by wait(2)
|
||||
// exit code: The integer code passed to exit(3), _exit(2), or
|
||||
// returned from main()
|
||||
class GTEST_API_ DeathTest {
|
||||
public:
|
||||
// Create returns false if there was an error determining the
|
||||
// appropriate action to take for the current death test; for example,
|
||||
// if the gtest_death_test_style flag is set to an invalid value.
|
||||
// The LastMessage method will return a more detailed message in that
|
||||
// case. Otherwise, the DeathTest pointer pointed to by the "test"
|
||||
// argument is set. If the death test should be skipped, the pointer
|
||||
// is set to NULL; otherwise, it is set to the address of a new concrete
|
||||
// DeathTest object that controls the execution of the current test.
|
||||
static bool Create(const char* statement, Matcher<const std::string&> matcher,
|
||||
const char* file, int line, DeathTest** test);
|
||||
DeathTest();
|
||||
virtual ~DeathTest() { }
|
||||
|
||||
// A helper class that aborts a death test when it's deleted.
|
||||
class ReturnSentinel {
|
||||
public:
|
||||
explicit ReturnSentinel(DeathTest* test) : test_(test) { }
|
||||
~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
|
||||
private:
|
||||
DeathTest* const test_;
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel);
|
||||
} GTEST_ATTRIBUTE_UNUSED_;
|
||||
|
||||
// An enumeration of possible roles that may be taken when a death
|
||||
// test is encountered. EXECUTE means that the death test logic should
|
||||
// be executed immediately. OVERSEE means that the program should prepare
|
||||
// the appropriate environment for a child process to execute the death
|
||||
// test, then wait for it to complete.
|
||||
enum TestRole { OVERSEE_TEST, EXECUTE_TEST };
|
||||
|
||||
// An enumeration of the three reasons that a test might be aborted.
|
||||
enum AbortReason {
|
||||
TEST_ENCOUNTERED_RETURN_STATEMENT,
|
||||
TEST_THREW_EXCEPTION,
|
||||
TEST_DID_NOT_DIE
|
||||
};
|
||||
|
||||
// Assumes one of the above roles.
|
||||
virtual TestRole AssumeRole() = 0;
|
||||
|
||||
// Waits for the death test to finish and returns its status.
|
||||
virtual int Wait() = 0;
|
||||
|
||||
// Returns true if the death test passed; that is, the test process
|
||||
// exited during the test, its exit status matches a user-supplied
|
||||
// predicate, and its stderr output matches a user-supplied regular
|
||||
// expression.
|
||||
// The user-supplied predicate may be a macro expression rather
|
||||
// than a function pointer or functor, or else Wait and Passed could
|
||||
// be combined.
|
||||
virtual bool Passed(bool exit_status_ok) = 0;
|
||||
|
||||
// Signals that the death test did not die as expected.
|
||||
virtual void Abort(AbortReason reason) = 0;
|
||||
|
||||
// Returns a human-readable outcome message regarding the outcome of
|
||||
// the last death test.
|
||||
static const char* LastMessage();
|
||||
|
||||
static void set_last_death_test_message(const std::string& message);
|
||||
|
||||
private:
|
||||
// A string containing a description of the outcome of the last death test.
|
||||
static std::string last_death_test_message_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
|
||||
};
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
|
||||
|
||||
// Factory interface for death tests. May be mocked out for testing.
|
||||
class DeathTestFactory {
|
||||
public:
|
||||
virtual ~DeathTestFactory() { }
|
||||
virtual bool Create(const char* statement,
|
||||
Matcher<const std::string&> matcher, const char* file,
|
||||
int line, DeathTest** test) = 0;
|
||||
};
|
||||
|
||||
// A concrete DeathTestFactory implementation for normal use.
|
||||
class DefaultDeathTestFactory : public DeathTestFactory {
|
||||
public:
|
||||
bool Create(const char* statement, Matcher<const std::string&> matcher,
|
||||
const char* file, int line, DeathTest** test) override;
|
||||
};
|
||||
|
||||
// Returns true if exit_status describes a process that was terminated
|
||||
// by a signal, or exited normally with a nonzero exit code.
|
||||
GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
|
||||
|
||||
// A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads
|
||||
// and interpreted as a regex (rather than an Eq matcher) for legacy
|
||||
// compatibility.
|
||||
inline Matcher<const ::std::string&> MakeDeathTestMatcher(
|
||||
::testing::internal::RE regex) {
|
||||
return ContainsRegex(regex.pattern());
|
||||
}
|
||||
inline Matcher<const ::std::string&> MakeDeathTestMatcher(const char* regex) {
|
||||
return ContainsRegex(regex);
|
||||
}
|
||||
inline Matcher<const ::std::string&> MakeDeathTestMatcher(
|
||||
const ::std::string& regex) {
|
||||
return ContainsRegex(regex);
|
||||
}
|
||||
|
||||
// If a Matcher<const ::std::string&> is passed to EXPECT_DEATH (etc.), it's
|
||||
// used directly.
|
||||
inline Matcher<const ::std::string&> MakeDeathTestMatcher(
|
||||
Matcher<const ::std::string&> matcher) {
|
||||
return matcher;
|
||||
}
|
||||
|
||||
// Traps C++ exceptions escaping statement and reports them as test
|
||||
// failures. Note that trapping SEH exceptions is not implemented here.
|
||||
# if GTEST_HAS_EXCEPTIONS
|
||||
# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
|
||||
try { \
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
|
||||
} catch (const ::std::exception& gtest_exception) { \
|
||||
fprintf(\
|
||||
stderr, \
|
||||
"\n%s: Caught std::exception-derived exception escaping the " \
|
||||
"death test statement. Exception message: %s\n", \
|
||||
::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \
|
||||
gtest_exception.what()); \
|
||||
fflush(stderr); \
|
||||
death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
|
||||
} catch (...) { \
|
||||
death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
|
||||
}
|
||||
|
||||
# else
|
||||
# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
|
||||
|
||||
# endif
|
||||
|
||||
// This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
|
||||
// ASSERT_EXIT*, and EXPECT_EXIT*.
|
||||
#define GTEST_DEATH_TEST_(statement, predicate, regex_or_matcher, fail) \
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
|
||||
if (::testing::internal::AlwaysTrue()) { \
|
||||
::testing::internal::DeathTest* gtest_dt; \
|
||||
if (!::testing::internal::DeathTest::Create( \
|
||||
#statement, \
|
||||
::testing::internal::MakeDeathTestMatcher(regex_or_matcher), \
|
||||
__FILE__, __LINE__, >est_dt)) { \
|
||||
goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
|
||||
} \
|
||||
if (gtest_dt != nullptr) { \
|
||||
std::unique_ptr< ::testing::internal::DeathTest> gtest_dt_ptr(gtest_dt); \
|
||||
switch (gtest_dt->AssumeRole()) { \
|
||||
case ::testing::internal::DeathTest::OVERSEE_TEST: \
|
||||
if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \
|
||||
goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
|
||||
} \
|
||||
break; \
|
||||
case ::testing::internal::DeathTest::EXECUTE_TEST: { \
|
||||
::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \
|
||||
gtest_dt); \
|
||||
GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \
|
||||
gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
|
||||
break; \
|
||||
} \
|
||||
default: \
|
||||
break; \
|
||||
} \
|
||||
} \
|
||||
} else \
|
||||
GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__) \
|
||||
: fail(::testing::internal::DeathTest::LastMessage())
|
||||
// The symbol "fail" here expands to something into which a message
|
||||
// can be streamed.
|
||||
|
||||
// This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in
|
||||
// NDEBUG mode. In this case we need the statements to be executed and the macro
|
||||
// must accept a streamed message even though the message is never printed.
|
||||
// The regex object is not evaluated, but it is used to prevent "unused"
|
||||
// warnings and to avoid an expression that doesn't compile in debug mode.
|
||||
#define GTEST_EXECUTE_STATEMENT_(statement, regex_or_matcher) \
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
|
||||
if (::testing::internal::AlwaysTrue()) { \
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
|
||||
} else if (!::testing::internal::AlwaysTrue()) { \
|
||||
::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \
|
||||
} else \
|
||||
::testing::Message()
|
||||
|
||||
// A class representing the parsed contents of the
|
||||
// --gtest_internal_run_death_test flag, as it existed when
|
||||
// RUN_ALL_TESTS was called.
|
||||
class InternalRunDeathTestFlag {
|
||||
public:
|
||||
InternalRunDeathTestFlag(const std::string& a_file,
|
||||
int a_line,
|
||||
int an_index,
|
||||
int a_write_fd)
|
||||
: file_(a_file), line_(a_line), index_(an_index),
|
||||
write_fd_(a_write_fd) {}
|
||||
|
||||
~InternalRunDeathTestFlag() {
|
||||
if (write_fd_ >= 0)
|
||||
posix::Close(write_fd_);
|
||||
}
|
||||
|
||||
const std::string& file() const { return file_; }
|
||||
int line() const { return line_; }
|
||||
int index() const { return index_; }
|
||||
int write_fd() const { return write_fd_; }
|
||||
|
||||
private:
|
||||
std::string file_;
|
||||
int line_;
|
||||
int index_;
|
||||
int write_fd_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag);
|
||||
};
|
||||
|
||||
// Returns a newly created InternalRunDeathTestFlag object with fields
|
||||
// initialized from the GTEST_FLAG(internal_run_death_test) flag if
|
||||
// the flag is specified; otherwise returns NULL.
|
||||
InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
|
||||
|
||||
#endif // GTEST_HAS_DEATH_TEST
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
|
211
3rdparty/gtest/include/gtest/internal/gtest-filepath.h
vendored
Normal file
211
3rdparty/gtest/include/gtest/internal/gtest-filepath.h
vendored
Normal file
@ -0,0 +1,211 @@
|
||||
// Copyright 2008, 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.
|
||||
//
|
||||
// Google Test filepath utilities
|
||||
//
|
||||
// This header file declares classes and functions used internally by
|
||||
// Google Test. They are subject to change without notice.
|
||||
//
|
||||
// This file is #included in gtest/internal/gtest-internal.h.
|
||||
// Do not include this header file separately!
|
||||
|
||||
// GOOGLETEST_CM0001 DO NOT DELETE
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
|
||||
|
||||
#include "gtest/internal/gtest-string.h"
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
|
||||
/* class A needs to have dll-interface to be used by clients of class B */)
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
// FilePath - a class for file and directory pathname manipulation which
|
||||
// handles platform-specific conventions (like the pathname separator).
|
||||
// Used for helper functions for naming files in a directory for xml output.
|
||||
// Except for Set methods, all methods are const or static, which provides an
|
||||
// "immutable value object" -- useful for peace of mind.
|
||||
// A FilePath with a value ending in a path separator ("like/this/") represents
|
||||
// a directory, otherwise it is assumed to represent a file. In either case,
|
||||
// it may or may not represent an actual file or directory in the file system.
|
||||
// Names are NOT checked for syntax correctness -- no checking for illegal
|
||||
// characters, malformed paths, etc.
|
||||
|
||||
class GTEST_API_ FilePath {
|
||||
public:
|
||||
FilePath() : pathname_("") { }
|
||||
FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { }
|
||||
|
||||
explicit FilePath(const std::string& pathname) : pathname_(pathname) {
|
||||
Normalize();
|
||||
}
|
||||
|
||||
FilePath& operator=(const FilePath& rhs) {
|
||||
Set(rhs);
|
||||
return *this;
|
||||
}
|
||||
|
||||
void Set(const FilePath& rhs) {
|
||||
pathname_ = rhs.pathname_;
|
||||
}
|
||||
|
||||
const std::string& string() const { return pathname_; }
|
||||
const char* c_str() const { return pathname_.c_str(); }
|
||||
|
||||
// Returns the current working directory, or "" if unsuccessful.
|
||||
static FilePath GetCurrentDir();
|
||||
|
||||
// Given directory = "dir", base_name = "test", number = 0,
|
||||
// extension = "xml", returns "dir/test.xml". If number is greater
|
||||
// than zero (e.g., 12), returns "dir/test_12.xml".
|
||||
// On Windows platform, uses \ as the separator rather than /.
|
||||
static FilePath MakeFileName(const FilePath& directory,
|
||||
const FilePath& base_name,
|
||||
int number,
|
||||
const char* extension);
|
||||
|
||||
// Given directory = "dir", relative_path = "test.xml",
|
||||
// returns "dir/test.xml".
|
||||
// On Windows, uses \ as the separator rather than /.
|
||||
static FilePath ConcatPaths(const FilePath& directory,
|
||||
const FilePath& relative_path);
|
||||
|
||||
// Returns a pathname for a file that does not currently exist. The pathname
|
||||
// will be directory/base_name.extension or
|
||||
// directory/base_name_<number>.extension if directory/base_name.extension
|
||||
// already exists. The number will be incremented until a pathname is found
|
||||
// that does not already exist.
|
||||
// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
|
||||
// There could be a race condition if two or more processes are calling this
|
||||
// function at the same time -- they could both pick the same filename.
|
||||
static FilePath GenerateUniqueFileName(const FilePath& directory,
|
||||
const FilePath& base_name,
|
||||
const char* extension);
|
||||
|
||||
// Returns true if and only if the path is "".
|
||||
bool IsEmpty() const { return pathname_.empty(); }
|
||||
|
||||
// If input name has a trailing separator character, removes it and returns
|
||||
// the name, otherwise return the name string unmodified.
|
||||
// On Windows platform, uses \ as the separator, other platforms use /.
|
||||
FilePath RemoveTrailingPathSeparator() const;
|
||||
|
||||
// Returns a copy of the FilePath with the directory part removed.
|
||||
// Example: FilePath("path/to/file").RemoveDirectoryName() returns
|
||||
// FilePath("file"). If there is no directory part ("just_a_file"), it returns
|
||||
// the FilePath unmodified. If there is no file part ("just_a_dir/") it
|
||||
// returns an empty FilePath ("").
|
||||
// On Windows platform, '\' is the path separator, otherwise it is '/'.
|
||||
FilePath RemoveDirectoryName() const;
|
||||
|
||||
// RemoveFileName returns the directory path with the filename removed.
|
||||
// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
|
||||
// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
|
||||
// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
|
||||
// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
|
||||
// On Windows platform, '\' is the path separator, otherwise it is '/'.
|
||||
FilePath RemoveFileName() const;
|
||||
|
||||
// Returns a copy of the FilePath with the case-insensitive extension removed.
|
||||
// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
|
||||
// FilePath("dir/file"). If a case-insensitive extension is not
|
||||
// found, returns a copy of the original FilePath.
|
||||
FilePath RemoveExtension(const char* extension) const;
|
||||
|
||||
// Creates directories so that path exists. Returns true if successful or if
|
||||
// the directories already exist; returns false if unable to create
|
||||
// directories for any reason. Will also return false if the FilePath does
|
||||
// not represent a directory (that is, it doesn't end with a path separator).
|
||||
bool CreateDirectoriesRecursively() const;
|
||||
|
||||
// Create the directory so that path exists. Returns true if successful or
|
||||
// if the directory already exists; returns false if unable to create the
|
||||
// directory for any reason, including if the parent directory does not
|
||||
// exist. Not named "CreateDirectory" because that's a macro on Windows.
|
||||
bool CreateFolder() const;
|
||||
|
||||
// Returns true if FilePath describes something in the file-system,
|
||||
// either a file, directory, or whatever, and that something exists.
|
||||
bool FileOrDirectoryExists() const;
|
||||
|
||||
// Returns true if pathname describes a directory in the file-system
|
||||
// that exists.
|
||||
bool DirectoryExists() const;
|
||||
|
||||
// Returns true if FilePath ends with a path separator, which indicates that
|
||||
// it is intended to represent a directory. Returns false otherwise.
|
||||
// This does NOT check that a directory (or file) actually exists.
|
||||
bool IsDirectory() const;
|
||||
|
||||
// Returns true if pathname describes a root directory. (Windows has one
|
||||
// root directory per disk drive.)
|
||||
bool IsRootDirectory() const;
|
||||
|
||||
// Returns true if pathname describes an absolute path.
|
||||
bool IsAbsolutePath() const;
|
||||
|
||||
private:
|
||||
// Replaces multiple consecutive separators with a single separator.
|
||||
// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
|
||||
// redundancies that might be in a pathname involving "." or "..".
|
||||
//
|
||||
// A pathname with multiple consecutive separators may occur either through
|
||||
// user error or as a result of some scripts or APIs that generate a pathname
|
||||
// with a trailing separator. On other platforms the same API or script
|
||||
// may NOT generate a pathname with a trailing "/". Then elsewhere that
|
||||
// pathname may have another "/" and pathname components added to it,
|
||||
// without checking for the separator already being there.
|
||||
// The script language and operating system may allow paths like "foo//bar"
|
||||
// but some of the functions in FilePath will not handle that correctly. In
|
||||
// particular, RemoveTrailingPathSeparator() only removes one separator, and
|
||||
// it is called in CreateDirectoriesRecursively() assuming that it will change
|
||||
// a pathname from directory syntax (trailing separator) to filename syntax.
|
||||
//
|
||||
// On Windows this method also replaces the alternate path separator '/' with
|
||||
// the primary path separator '\\', so that for example "bar\\/\\foo" becomes
|
||||
// "bar\\foo".
|
||||
|
||||
void Normalize();
|
||||
|
||||
// Returns a pointer to the last occurence of a valid path separator in
|
||||
// the FilePath. On Windows, for example, both '/' and '\' are valid path
|
||||
// separators. Returns NULL if no path separator was found.
|
||||
const char* FindLastPathSeparator() const;
|
||||
|
||||
std::string pathname_;
|
||||
}; // class FilePath
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
|
1380
3rdparty/gtest/include/gtest/internal/gtest-internal.h
vendored
Normal file
1380
3rdparty/gtest/include/gtest/internal/gtest-internal.h
vendored
Normal file
File diff suppressed because it is too large
Load Diff
883
3rdparty/gtest/include/gtest/internal/gtest-param-util.h
vendored
Normal file
883
3rdparty/gtest/include/gtest/internal/gtest-param-util.h
vendored
Normal file
@ -0,0 +1,883 @@
|
||||
// Copyright 2008 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.
|
||||
|
||||
|
||||
// Type and function utilities for implementing parameterized tests.
|
||||
|
||||
// GOOGLETEST_CM0001 DO NOT DELETE
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
|
||||
|
||||
#include <ctype.h>
|
||||
|
||||
#include <cassert>
|
||||
#include <iterator>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <tuple>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "gtest/internal/gtest-internal.h"
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
#include "gtest/gtest-printers.h"
|
||||
|
||||
namespace testing {
|
||||
// Input to a parameterized test name generator, describing a test parameter.
|
||||
// Consists of the parameter value and the integer parameter index.
|
||||
template <class ParamType>
|
||||
struct TestParamInfo {
|
||||
TestParamInfo(const ParamType& a_param, size_t an_index) :
|
||||
param(a_param),
|
||||
index(an_index) {}
|
||||
ParamType param;
|
||||
size_t index;
|
||||
};
|
||||
|
||||
// A builtin parameterized test name generator which returns the result of
|
||||
// testing::PrintToString.
|
||||
struct PrintToStringParamName {
|
||||
template <class ParamType>
|
||||
std::string operator()(const TestParamInfo<ParamType>& info) const {
|
||||
return PrintToString(info.param);
|
||||
}
|
||||
};
|
||||
|
||||
namespace internal {
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
// Utility Functions
|
||||
|
||||
// Outputs a message explaining invalid registration of different
|
||||
// fixture class for the same test suite. This may happen when
|
||||
// TEST_P macro is used to define two tests with the same name
|
||||
// but in different namespaces.
|
||||
GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name,
|
||||
CodeLocation code_location);
|
||||
|
||||
template <typename> class ParamGeneratorInterface;
|
||||
template <typename> class ParamGenerator;
|
||||
|
||||
// Interface for iterating over elements provided by an implementation
|
||||
// of ParamGeneratorInterface<T>.
|
||||
template <typename T>
|
||||
class ParamIteratorInterface {
|
||||
public:
|
||||
virtual ~ParamIteratorInterface() {}
|
||||
// A pointer to the base generator instance.
|
||||
// Used only for the purposes of iterator comparison
|
||||
// to make sure that two iterators belong to the same generator.
|
||||
virtual const ParamGeneratorInterface<T>* BaseGenerator() const = 0;
|
||||
// Advances iterator to point to the next element
|
||||
// provided by the generator. The caller is responsible
|
||||
// for not calling Advance() on an iterator equal to
|
||||
// BaseGenerator()->End().
|
||||
virtual void Advance() = 0;
|
||||
// Clones the iterator object. Used for implementing copy semantics
|
||||
// of ParamIterator<T>.
|
||||
virtual ParamIteratorInterface* Clone() const = 0;
|
||||
// Dereferences the current iterator and provides (read-only) access
|
||||
// to the pointed value. It is the caller's responsibility not to call
|
||||
// Current() on an iterator equal to BaseGenerator()->End().
|
||||
// Used for implementing ParamGenerator<T>::operator*().
|
||||
virtual const T* Current() const = 0;
|
||||
// Determines whether the given iterator and other point to the same
|
||||
// element in the sequence generated by the generator.
|
||||
// Used for implementing ParamGenerator<T>::operator==().
|
||||
virtual bool Equals(const ParamIteratorInterface& other) const = 0;
|
||||
};
|
||||
|
||||
// Class iterating over elements provided by an implementation of
|
||||
// ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T>
|
||||
// and implements the const forward iterator concept.
|
||||
template <typename T>
|
||||
class ParamIterator {
|
||||
public:
|
||||
typedef T value_type;
|
||||
typedef const T& reference;
|
||||
typedef ptrdiff_t difference_type;
|
||||
|
||||
// ParamIterator assumes ownership of the impl_ pointer.
|
||||
ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {}
|
||||
ParamIterator& operator=(const ParamIterator& other) {
|
||||
if (this != &other)
|
||||
impl_.reset(other.impl_->Clone());
|
||||
return *this;
|
||||
}
|
||||
|
||||
const T& operator*() const { return *impl_->Current(); }
|
||||
const T* operator->() const { return impl_->Current(); }
|
||||
// Prefix version of operator++.
|
||||
ParamIterator& operator++() {
|
||||
impl_->Advance();
|
||||
return *this;
|
||||
}
|
||||
// Postfix version of operator++.
|
||||
ParamIterator operator++(int /*unused*/) {
|
||||
ParamIteratorInterface<T>* clone = impl_->Clone();
|
||||
impl_->Advance();
|
||||
return ParamIterator(clone);
|
||||
}
|
||||
bool operator==(const ParamIterator& other) const {
|
||||
return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_);
|
||||
}
|
||||
bool operator!=(const ParamIterator& other) const {
|
||||
return !(*this == other);
|
||||
}
|
||||
|
||||
private:
|
||||
friend class ParamGenerator<T>;
|
||||
explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {}
|
||||
std::unique_ptr<ParamIteratorInterface<T> > impl_;
|
||||
};
|
||||
|
||||
// ParamGeneratorInterface<T> is the binary interface to access generators
|
||||
// defined in other translation units.
|
||||
template <typename T>
|
||||
class ParamGeneratorInterface {
|
||||
public:
|
||||
typedef T ParamType;
|
||||
|
||||
virtual ~ParamGeneratorInterface() {}
|
||||
|
||||
// Generator interface definition
|
||||
virtual ParamIteratorInterface<T>* Begin() const = 0;
|
||||
virtual ParamIteratorInterface<T>* End() const = 0;
|
||||
};
|
||||
|
||||
// Wraps ParamGeneratorInterface<T> and provides general generator syntax
|
||||
// compatible with the STL Container concept.
|
||||
// This class implements copy initialization semantics and the contained
|
||||
// ParamGeneratorInterface<T> instance is shared among all copies
|
||||
// of the original object. This is possible because that instance is immutable.
|
||||
template<typename T>
|
||||
class ParamGenerator {
|
||||
public:
|
||||
typedef ParamIterator<T> iterator;
|
||||
|
||||
explicit ParamGenerator(ParamGeneratorInterface<T>* impl) : impl_(impl) {}
|
||||
ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {}
|
||||
|
||||
ParamGenerator& operator=(const ParamGenerator& other) {
|
||||
impl_ = other.impl_;
|
||||
return *this;
|
||||
}
|
||||
|
||||
iterator begin() const { return iterator(impl_->Begin()); }
|
||||
iterator end() const { return iterator(impl_->End()); }
|
||||
|
||||
private:
|
||||
std::shared_ptr<const ParamGeneratorInterface<T> > impl_;
|
||||
};
|
||||
|
||||
// Generates values from a range of two comparable values. Can be used to
|
||||
// generate sequences of user-defined types that implement operator+() and
|
||||
// operator<().
|
||||
// This class is used in the Range() function.
|
||||
template <typename T, typename IncrementT>
|
||||
class RangeGenerator : public ParamGeneratorInterface<T> {
|
||||
public:
|
||||
RangeGenerator(T begin, T end, IncrementT step)
|
||||
: begin_(begin), end_(end),
|
||||
step_(step), end_index_(CalculateEndIndex(begin, end, step)) {}
|
||||
~RangeGenerator() override {}
|
||||
|
||||
ParamIteratorInterface<T>* Begin() const override {
|
||||
return new Iterator(this, begin_, 0, step_);
|
||||
}
|
||||
ParamIteratorInterface<T>* End() const override {
|
||||
return new Iterator(this, end_, end_index_, step_);
|
||||
}
|
||||
|
||||
private:
|
||||
class Iterator : public ParamIteratorInterface<T> {
|
||||
public:
|
||||
Iterator(const ParamGeneratorInterface<T>* base, T value, int index,
|
||||
IncrementT step)
|
||||
: base_(base), value_(value), index_(index), step_(step) {}
|
||||
~Iterator() override {}
|
||||
|
||||
const ParamGeneratorInterface<T>* BaseGenerator() const override {
|
||||
return base_;
|
||||
}
|
||||
void Advance() override {
|
||||
value_ = static_cast<T>(value_ + step_);
|
||||
index_++;
|
||||
}
|
||||
ParamIteratorInterface<T>* Clone() const override {
|
||||
return new Iterator(*this);
|
||||
}
|
||||
const T* Current() const override { return &value_; }
|
||||
bool Equals(const ParamIteratorInterface<T>& other) const override {
|
||||
// Having the same base generator guarantees that the other
|
||||
// iterator is of the same type and we can downcast.
|
||||
GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
|
||||
<< "The program attempted to compare iterators "
|
||||
<< "from different generators." << std::endl;
|
||||
const int other_index =
|
||||
CheckedDowncastToActualType<const Iterator>(&other)->index_;
|
||||
return index_ == other_index;
|
||||
}
|
||||
|
||||
private:
|
||||
Iterator(const Iterator& other)
|
||||
: ParamIteratorInterface<T>(),
|
||||
base_(other.base_), value_(other.value_), index_(other.index_),
|
||||
step_(other.step_) {}
|
||||
|
||||
// No implementation - assignment is unsupported.
|
||||
void operator=(const Iterator& other);
|
||||
|
||||
const ParamGeneratorInterface<T>* const base_;
|
||||
T value_;
|
||||
int index_;
|
||||
const IncrementT step_;
|
||||
}; // class RangeGenerator::Iterator
|
||||
|
||||
static int CalculateEndIndex(const T& begin,
|
||||
const T& end,
|
||||
const IncrementT& step) {
|
||||
int end_index = 0;
|
||||
for (T i = begin; i < end; i = static_cast<T>(i + step))
|
||||
end_index++;
|
||||
return end_index;
|
||||
}
|
||||
|
||||
// No implementation - assignment is unsupported.
|
||||
void operator=(const RangeGenerator& other);
|
||||
|
||||
const T begin_;
|
||||
const T end_;
|
||||
const IncrementT step_;
|
||||
// The index for the end() iterator. All the elements in the generated
|
||||
// sequence are indexed (0-based) to aid iterator comparison.
|
||||
const int end_index_;
|
||||
}; // class RangeGenerator
|
||||
|
||||
|
||||
// Generates values from a pair of STL-style iterators. Used in the
|
||||
// ValuesIn() function. The elements are copied from the source range
|
||||
// since the source can be located on the stack, and the generator
|
||||
// is likely to persist beyond that stack frame.
|
||||
template <typename T>
|
||||
class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
|
||||
public:
|
||||
template <typename ForwardIterator>
|
||||
ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)
|
||||
: container_(begin, end) {}
|
||||
~ValuesInIteratorRangeGenerator() override {}
|
||||
|
||||
ParamIteratorInterface<T>* Begin() const override {
|
||||
return new Iterator(this, container_.begin());
|
||||
}
|
||||
ParamIteratorInterface<T>* End() const override {
|
||||
return new Iterator(this, container_.end());
|
||||
}
|
||||
|
||||
private:
|
||||
typedef typename ::std::vector<T> ContainerType;
|
||||
|
||||
class Iterator : public ParamIteratorInterface<T> {
|
||||
public:
|
||||
Iterator(const ParamGeneratorInterface<T>* base,
|
||||
typename ContainerType::const_iterator iterator)
|
||||
: base_(base), iterator_(iterator) {}
|
||||
~Iterator() override {}
|
||||
|
||||
const ParamGeneratorInterface<T>* BaseGenerator() const override {
|
||||
return base_;
|
||||
}
|
||||
void Advance() override {
|
||||
++iterator_;
|
||||
value_.reset();
|
||||
}
|
||||
ParamIteratorInterface<T>* Clone() const override {
|
||||
return new Iterator(*this);
|
||||
}
|
||||
// We need to use cached value referenced by iterator_ because *iterator_
|
||||
// can return a temporary object (and of type other then T), so just
|
||||
// having "return &*iterator_;" doesn't work.
|
||||
// value_ is updated here and not in Advance() because Advance()
|
||||
// can advance iterator_ beyond the end of the range, and we cannot
|
||||
// detect that fact. The client code, on the other hand, is
|
||||
// responsible for not calling Current() on an out-of-range iterator.
|
||||
const T* Current() const override {
|
||||
if (value_.get() == nullptr) value_.reset(new T(*iterator_));
|
||||
return value_.get();
|
||||
}
|
||||
bool Equals(const ParamIteratorInterface<T>& other) const override {
|
||||
// Having the same base generator guarantees that the other
|
||||
// iterator is of the same type and we can downcast.
|
||||
GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
|
||||
<< "The program attempted to compare iterators "
|
||||
<< "from different generators." << std::endl;
|
||||
return iterator_ ==
|
||||
CheckedDowncastToActualType<const Iterator>(&other)->iterator_;
|
||||
}
|
||||
|
||||
private:
|
||||
Iterator(const Iterator& other)
|
||||
// The explicit constructor call suppresses a false warning
|
||||
// emitted by gcc when supplied with the -Wextra option.
|
||||
: ParamIteratorInterface<T>(),
|
||||
base_(other.base_),
|
||||
iterator_(other.iterator_) {}
|
||||
|
||||
const ParamGeneratorInterface<T>* const base_;
|
||||
typename ContainerType::const_iterator iterator_;
|
||||
// A cached value of *iterator_. We keep it here to allow access by
|
||||
// pointer in the wrapping iterator's operator->().
|
||||
// value_ needs to be mutable to be accessed in Current().
|
||||
// Use of std::unique_ptr helps manage cached value's lifetime,
|
||||
// which is bound by the lifespan of the iterator itself.
|
||||
mutable std::unique_ptr<const T> value_;
|
||||
}; // class ValuesInIteratorRangeGenerator::Iterator
|
||||
|
||||
// No implementation - assignment is unsupported.
|
||||
void operator=(const ValuesInIteratorRangeGenerator& other);
|
||||
|
||||
const ContainerType container_;
|
||||
}; // class ValuesInIteratorRangeGenerator
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
//
|
||||
// Default parameterized test name generator, returns a string containing the
|
||||
// integer test parameter index.
|
||||
template <class ParamType>
|
||||
std::string DefaultParamName(const TestParamInfo<ParamType>& info) {
|
||||
Message name_stream;
|
||||
name_stream << info.index;
|
||||
return name_stream.GetString();
|
||||
}
|
||||
|
||||
template <typename T = int>
|
||||
void TestNotEmpty() {
|
||||
static_assert(sizeof(T) == 0, "Empty arguments are not allowed.");
|
||||
}
|
||||
template <typename T = int>
|
||||
void TestNotEmpty(const T&) {}
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
//
|
||||
// Stores a parameter value and later creates tests parameterized with that
|
||||
// value.
|
||||
template <class TestClass>
|
||||
class ParameterizedTestFactory : public TestFactoryBase {
|
||||
public:
|
||||
typedef typename TestClass::ParamType ParamType;
|
||||
explicit ParameterizedTestFactory(ParamType parameter) :
|
||||
parameter_(parameter) {}
|
||||
Test* CreateTest() override {
|
||||
TestClass::SetParam(¶meter_);
|
||||
return new TestClass();
|
||||
}
|
||||
|
||||
private:
|
||||
const ParamType parameter_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory);
|
||||
};
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
//
|
||||
// TestMetaFactoryBase is a base class for meta-factories that create
|
||||
// test factories for passing into MakeAndRegisterTestInfo function.
|
||||
template <class ParamType>
|
||||
class TestMetaFactoryBase {
|
||||
public:
|
||||
virtual ~TestMetaFactoryBase() {}
|
||||
|
||||
virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0;
|
||||
};
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
//
|
||||
// TestMetaFactory creates test factories for passing into
|
||||
// MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives
|
||||
// ownership of test factory pointer, same factory object cannot be passed
|
||||
// into that method twice. But ParameterizedTestSuiteInfo is going to call
|
||||
// it for each Test/Parameter value combination. Thus it needs meta factory
|
||||
// creator class.
|
||||
template <class TestSuite>
|
||||
class TestMetaFactory
|
||||
: public TestMetaFactoryBase<typename TestSuite::ParamType> {
|
||||
public:
|
||||
using ParamType = typename TestSuite::ParamType;
|
||||
|
||||
TestMetaFactory() {}
|
||||
|
||||
TestFactoryBase* CreateTestFactory(ParamType parameter) override {
|
||||
return new ParameterizedTestFactory<TestSuite>(parameter);
|
||||
}
|
||||
|
||||
private:
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory);
|
||||
};
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
//
|
||||
// ParameterizedTestSuiteInfoBase is a generic interface
|
||||
// to ParameterizedTestSuiteInfo classes. ParameterizedTestSuiteInfoBase
|
||||
// accumulates test information provided by TEST_P macro invocations
|
||||
// and generators provided by INSTANTIATE_TEST_SUITE_P macro invocations
|
||||
// and uses that information to register all resulting test instances
|
||||
// in RegisterTests method. The ParameterizeTestSuiteRegistry class holds
|
||||
// a collection of pointers to the ParameterizedTestSuiteInfo objects
|
||||
// and calls RegisterTests() on each of them when asked.
|
||||
class ParameterizedTestSuiteInfoBase {
|
||||
public:
|
||||
virtual ~ParameterizedTestSuiteInfoBase() {}
|
||||
|
||||
// Base part of test suite name for display purposes.
|
||||
virtual const std::string& GetTestSuiteName() const = 0;
|
||||
// Test case id to verify identity.
|
||||
virtual TypeId GetTestSuiteTypeId() const = 0;
|
||||
// UnitTest class invokes this method to register tests in this
|
||||
// test suite right before running them in RUN_ALL_TESTS macro.
|
||||
// This method should not be called more than once on any single
|
||||
// instance of a ParameterizedTestSuiteInfoBase derived class.
|
||||
virtual void RegisterTests() = 0;
|
||||
|
||||
protected:
|
||||
ParameterizedTestSuiteInfoBase() {}
|
||||
|
||||
private:
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase);
|
||||
};
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
//
|
||||
// ParameterizedTestSuiteInfo accumulates tests obtained from TEST_P
|
||||
// macro invocations for a particular test suite and generators
|
||||
// obtained from INSTANTIATE_TEST_SUITE_P macro invocations for that
|
||||
// test suite. It registers tests with all values generated by all
|
||||
// generators when asked.
|
||||
template <class TestSuite>
|
||||
class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
|
||||
public:
|
||||
// ParamType and GeneratorCreationFunc are private types but are required
|
||||
// for declarations of public methods AddTestPattern() and
|
||||
// AddTestSuiteInstantiation().
|
||||
using ParamType = typename TestSuite::ParamType;
|
||||
// A function that returns an instance of appropriate generator type.
|
||||
typedef ParamGenerator<ParamType>(GeneratorCreationFunc)();
|
||||
using ParamNameGeneratorFunc = std::string(const TestParamInfo<ParamType>&);
|
||||
|
||||
explicit ParameterizedTestSuiteInfo(const char* name,
|
||||
CodeLocation code_location)
|
||||
: test_suite_name_(name), code_location_(code_location) {}
|
||||
|
||||
// Test case base name for display purposes.
|
||||
const std::string& GetTestSuiteName() const override {
|
||||
return test_suite_name_;
|
||||
}
|
||||
// Test case id to verify identity.
|
||||
TypeId GetTestSuiteTypeId() const override { return GetTypeId<TestSuite>(); }
|
||||
// TEST_P macro uses AddTestPattern() to record information
|
||||
// about a single test in a LocalTestInfo structure.
|
||||
// test_suite_name is the base name of the test suite (without invocation
|
||||
// prefix). test_base_name is the name of an individual test without
|
||||
// parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
|
||||
// test suite base name and DoBar is test base name.
|
||||
void AddTestPattern(const char* test_suite_name, const char* test_base_name,
|
||||
TestMetaFactoryBase<ParamType>* meta_factory) {
|
||||
tests_.push_back(std::shared_ptr<TestInfo>(
|
||||
new TestInfo(test_suite_name, test_base_name, meta_factory)));
|
||||
}
|
||||
// INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information
|
||||
// about a generator.
|
||||
int AddTestSuiteInstantiation(const std::string& instantiation_name,
|
||||
GeneratorCreationFunc* func,
|
||||
ParamNameGeneratorFunc* name_func,
|
||||
const char* file, int line) {
|
||||
instantiations_.push_back(
|
||||
InstantiationInfo(instantiation_name, func, name_func, file, line));
|
||||
return 0; // Return value used only to run this method in namespace scope.
|
||||
}
|
||||
// UnitTest class invokes this method to register tests in this test suite
|
||||
// test suites right before running tests in RUN_ALL_TESTS macro.
|
||||
// This method should not be called more than once on any single
|
||||
// instance of a ParameterizedTestSuiteInfoBase derived class.
|
||||
// UnitTest has a guard to prevent from calling this method more than once.
|
||||
void RegisterTests() override {
|
||||
for (typename TestInfoContainer::iterator test_it = tests_.begin();
|
||||
test_it != tests_.end(); ++test_it) {
|
||||
std::shared_ptr<TestInfo> test_info = *test_it;
|
||||
for (typename InstantiationContainer::iterator gen_it =
|
||||
instantiations_.begin(); gen_it != instantiations_.end();
|
||||
++gen_it) {
|
||||
const std::string& instantiation_name = gen_it->name;
|
||||
ParamGenerator<ParamType> generator((*gen_it->generator)());
|
||||
ParamNameGeneratorFunc* name_func = gen_it->name_func;
|
||||
const char* file = gen_it->file;
|
||||
int line = gen_it->line;
|
||||
|
||||
std::string test_suite_name;
|
||||
if ( !instantiation_name.empty() )
|
||||
test_suite_name = instantiation_name + "/";
|
||||
test_suite_name += test_info->test_suite_base_name;
|
||||
|
||||
size_t i = 0;
|
||||
std::set<std::string> test_param_names;
|
||||
for (typename ParamGenerator<ParamType>::iterator param_it =
|
||||
generator.begin();
|
||||
param_it != generator.end(); ++param_it, ++i) {
|
||||
Message test_name_stream;
|
||||
|
||||
std::string param_name = name_func(
|
||||
TestParamInfo<ParamType>(*param_it, i));
|
||||
|
||||
GTEST_CHECK_(IsValidParamName(param_name))
|
||||
<< "Parameterized test name '" << param_name
|
||||
<< "' is invalid, in " << file
|
||||
<< " line " << line << std::endl;
|
||||
|
||||
GTEST_CHECK_(test_param_names.count(param_name) == 0)
|
||||
<< "Duplicate parameterized test name '" << param_name
|
||||
<< "', in " << file << " line " << line << std::endl;
|
||||
|
||||
test_param_names.insert(param_name);
|
||||
|
||||
if (!test_info->test_base_name.empty()) {
|
||||
test_name_stream << test_info->test_base_name << "/";
|
||||
}
|
||||
test_name_stream << param_name;
|
||||
MakeAndRegisterTestInfo(
|
||||
test_suite_name.c_str(), test_name_stream.GetString().c_str(),
|
||||
nullptr, // No type parameter.
|
||||
PrintToString(*param_it).c_str(), code_location_,
|
||||
GetTestSuiteTypeId(),
|
||||
SuiteApiResolver<TestSuite>::GetSetUpCaseOrSuite(file, line),
|
||||
SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line),
|
||||
test_info->test_meta_factory->CreateTestFactory(*param_it));
|
||||
} // for param_it
|
||||
} // for gen_it
|
||||
} // for test_it
|
||||
} // RegisterTests
|
||||
|
||||
private:
|
||||
// LocalTestInfo structure keeps information about a single test registered
|
||||
// with TEST_P macro.
|
||||
struct TestInfo {
|
||||
TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name,
|
||||
TestMetaFactoryBase<ParamType>* a_test_meta_factory)
|
||||
: test_suite_base_name(a_test_suite_base_name),
|
||||
test_base_name(a_test_base_name),
|
||||
test_meta_factory(a_test_meta_factory) {}
|
||||
|
||||
const std::string test_suite_base_name;
|
||||
const std::string test_base_name;
|
||||
const std::unique_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
|
||||
};
|
||||
using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo> >;
|
||||
// Records data received from INSTANTIATE_TEST_SUITE_P macros:
|
||||
// <Instantiation name, Sequence generator creation function,
|
||||
// Name generator function, Source file, Source line>
|
||||
struct InstantiationInfo {
|
||||
InstantiationInfo(const std::string &name_in,
|
||||
GeneratorCreationFunc* generator_in,
|
||||
ParamNameGeneratorFunc* name_func_in,
|
||||
const char* file_in,
|
||||
int line_in)
|
||||
: name(name_in),
|
||||
generator(generator_in),
|
||||
name_func(name_func_in),
|
||||
file(file_in),
|
||||
line(line_in) {}
|
||||
|
||||
std::string name;
|
||||
GeneratorCreationFunc* generator;
|
||||
ParamNameGeneratorFunc* name_func;
|
||||
const char* file;
|
||||
int line;
|
||||
};
|
||||
typedef ::std::vector<InstantiationInfo> InstantiationContainer;
|
||||
|
||||
static bool IsValidParamName(const std::string& name) {
|
||||
// Check for empty string
|
||||
if (name.empty())
|
||||
return false;
|
||||
|
||||
// Check for invalid characters
|
||||
for (std::string::size_type index = 0; index < name.size(); ++index) {
|
||||
if (!isalnum(name[index]) && name[index] != '_')
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
const std::string test_suite_name_;
|
||||
CodeLocation code_location_;
|
||||
TestInfoContainer tests_;
|
||||
InstantiationContainer instantiations_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfo);
|
||||
}; // class ParameterizedTestSuiteInfo
|
||||
|
||||
// Legacy API is deprecated but still available
|
||||
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
template <class TestCase>
|
||||
using ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo<TestCase>;
|
||||
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
//
|
||||
// ParameterizedTestSuiteRegistry contains a map of
|
||||
// ParameterizedTestSuiteInfoBase classes accessed by test suite names. TEST_P
|
||||
// and INSTANTIATE_TEST_SUITE_P macros use it to locate their corresponding
|
||||
// ParameterizedTestSuiteInfo descriptors.
|
||||
class ParameterizedTestSuiteRegistry {
|
||||
public:
|
||||
ParameterizedTestSuiteRegistry() {}
|
||||
~ParameterizedTestSuiteRegistry() {
|
||||
for (auto& test_suite_info : test_suite_infos_) {
|
||||
delete test_suite_info;
|
||||
}
|
||||
}
|
||||
|
||||
// Looks up or creates and returns a structure containing information about
|
||||
// tests and instantiations of a particular test suite.
|
||||
template <class TestSuite>
|
||||
ParameterizedTestSuiteInfo<TestSuite>* GetTestSuitePatternHolder(
|
||||
const char* test_suite_name, CodeLocation code_location) {
|
||||
ParameterizedTestSuiteInfo<TestSuite>* typed_test_info = nullptr;
|
||||
for (auto& test_suite_info : test_suite_infos_) {
|
||||
if (test_suite_info->GetTestSuiteName() == test_suite_name) {
|
||||
if (test_suite_info->GetTestSuiteTypeId() != GetTypeId<TestSuite>()) {
|
||||
// Complain about incorrect usage of Google Test facilities
|
||||
// and terminate the program since we cannot guaranty correct
|
||||
// test suite setup and tear-down in this case.
|
||||
ReportInvalidTestSuiteType(test_suite_name, code_location);
|
||||
posix::Abort();
|
||||
} else {
|
||||
// At this point we are sure that the object we found is of the same
|
||||
// type we are looking for, so we downcast it to that type
|
||||
// without further checks.
|
||||
typed_test_info = CheckedDowncastToActualType<
|
||||
ParameterizedTestSuiteInfo<TestSuite> >(test_suite_info);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (typed_test_info == nullptr) {
|
||||
typed_test_info = new ParameterizedTestSuiteInfo<TestSuite>(
|
||||
test_suite_name, code_location);
|
||||
test_suite_infos_.push_back(typed_test_info);
|
||||
}
|
||||
return typed_test_info;
|
||||
}
|
||||
void RegisterTests() {
|
||||
for (auto& test_suite_info : test_suite_infos_) {
|
||||
test_suite_info->RegisterTests();
|
||||
}
|
||||
}
|
||||
// Legacy API is deprecated but still available
|
||||
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
template <class TestCase>
|
||||
ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder(
|
||||
const char* test_case_name, CodeLocation code_location) {
|
||||
return GetTestSuitePatternHolder<TestCase>(test_case_name, code_location);
|
||||
}
|
||||
|
||||
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
|
||||
private:
|
||||
using TestSuiteInfoContainer = ::std::vector<ParameterizedTestSuiteInfoBase*>;
|
||||
|
||||
TestSuiteInfoContainer test_suite_infos_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteRegistry);
|
||||
};
|
||||
|
||||
} // namespace internal
|
||||
|
||||
// Forward declarations of ValuesIn(), which is implemented in
|
||||
// include/gtest/gtest-param-test.h.
|
||||
template <class Container>
|
||||
internal::ParamGenerator<typename Container::value_type> ValuesIn(
|
||||
const Container& container);
|
||||
|
||||
namespace internal {
|
||||
// Used in the Values() function to provide polymorphic capabilities.
|
||||
|
||||
template <typename... Ts>
|
||||
class ValueArray {
|
||||
public:
|
||||
ValueArray(Ts... v) : v_{std::move(v)...} {}
|
||||
|
||||
template <typename T>
|
||||
operator ParamGenerator<T>() const { // NOLINT
|
||||
return ValuesIn(MakeVector<T>(MakeIndexSequence<sizeof...(Ts)>()));
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename T, size_t... I>
|
||||
std::vector<T> MakeVector(IndexSequence<I...>) const {
|
||||
return std::vector<T>{static_cast<T>(v_.template Get<I>())...};
|
||||
}
|
||||
|
||||
FlatTuple<Ts...> v_;
|
||||
};
|
||||
|
||||
template <typename... T>
|
||||
class CartesianProductGenerator
|
||||
: public ParamGeneratorInterface<::std::tuple<T...>> {
|
||||
public:
|
||||
typedef ::std::tuple<T...> ParamType;
|
||||
|
||||
CartesianProductGenerator(const std::tuple<ParamGenerator<T>...>& g)
|
||||
: generators_(g) {}
|
||||
~CartesianProductGenerator() override {}
|
||||
|
||||
ParamIteratorInterface<ParamType>* Begin() const override {
|
||||
return new Iterator(this, generators_, false);
|
||||
}
|
||||
ParamIteratorInterface<ParamType>* End() const override {
|
||||
return new Iterator(this, generators_, true);
|
||||
}
|
||||
|
||||
private:
|
||||
template <class I>
|
||||
class IteratorImpl;
|
||||
template <size_t... I>
|
||||
class IteratorImpl<IndexSequence<I...>>
|
||||
: public ParamIteratorInterface<ParamType> {
|
||||
public:
|
||||
IteratorImpl(const ParamGeneratorInterface<ParamType>* base,
|
||||
const std::tuple<ParamGenerator<T>...>& generators, bool is_end)
|
||||
: base_(base),
|
||||
begin_(std::get<I>(generators).begin()...),
|
||||
end_(std::get<I>(generators).end()...),
|
||||
current_(is_end ? end_ : begin_) {
|
||||
ComputeCurrentValue();
|
||||
}
|
||||
~IteratorImpl() override {}
|
||||
|
||||
const ParamGeneratorInterface<ParamType>* BaseGenerator() const override {
|
||||
return base_;
|
||||
}
|
||||
// Advance should not be called on beyond-of-range iterators
|
||||
// so no component iterators must be beyond end of range, either.
|
||||
void Advance() override {
|
||||
assert(!AtEnd());
|
||||
// Advance the last iterator.
|
||||
++std::get<sizeof...(T) - 1>(current_);
|
||||
// if that reaches end, propagate that up.
|
||||
AdvanceIfEnd<sizeof...(T) - 1>();
|
||||
ComputeCurrentValue();
|
||||
}
|
||||
ParamIteratorInterface<ParamType>* Clone() const override {
|
||||
return new IteratorImpl(*this);
|
||||
}
|
||||
|
||||
const ParamType* Current() const override { return current_value_.get(); }
|
||||
|
||||
bool Equals(const ParamIteratorInterface<ParamType>& other) const override {
|
||||
// Having the same base generator guarantees that the other
|
||||
// iterator is of the same type and we can downcast.
|
||||
GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
|
||||
<< "The program attempted to compare iterators "
|
||||
<< "from different generators." << std::endl;
|
||||
const IteratorImpl* typed_other =
|
||||
CheckedDowncastToActualType<const IteratorImpl>(&other);
|
||||
|
||||
// We must report iterators equal if they both point beyond their
|
||||
// respective ranges. That can happen in a variety of fashions,
|
||||
// so we have to consult AtEnd().
|
||||
if (AtEnd() && typed_other->AtEnd()) return true;
|
||||
|
||||
bool same = true;
|
||||
bool dummy[] = {
|
||||
(same = same && std::get<I>(current_) ==
|
||||
std::get<I>(typed_other->current_))...};
|
||||
(void)dummy;
|
||||
return same;
|
||||
}
|
||||
|
||||
private:
|
||||
template <size_t ThisI>
|
||||
void AdvanceIfEnd() {
|
||||
if (std::get<ThisI>(current_) != std::get<ThisI>(end_)) return;
|
||||
|
||||
bool last = ThisI == 0;
|
||||
if (last) {
|
||||
// We are done. Nothing else to propagate.
|
||||
return;
|
||||
}
|
||||
|
||||
constexpr size_t NextI = ThisI - (ThisI != 0);
|
||||
std::get<ThisI>(current_) = std::get<ThisI>(begin_);
|
||||
++std::get<NextI>(current_);
|
||||
AdvanceIfEnd<NextI>();
|
||||
}
|
||||
|
||||
void ComputeCurrentValue() {
|
||||
if (!AtEnd())
|
||||
current_value_ = std::make_shared<ParamType>(*std::get<I>(current_)...);
|
||||
}
|
||||
bool AtEnd() const {
|
||||
bool at_end = false;
|
||||
bool dummy[] = {
|
||||
(at_end = at_end || std::get<I>(current_) == std::get<I>(end_))...};
|
||||
(void)dummy;
|
||||
return at_end;
|
||||
}
|
||||
|
||||
const ParamGeneratorInterface<ParamType>* const base_;
|
||||
std::tuple<typename ParamGenerator<T>::iterator...> begin_;
|
||||
std::tuple<typename ParamGenerator<T>::iterator...> end_;
|
||||
std::tuple<typename ParamGenerator<T>::iterator...> current_;
|
||||
std::shared_ptr<ParamType> current_value_;
|
||||
};
|
||||
|
||||
using Iterator = IteratorImpl<typename MakeIndexSequence<sizeof...(T)>::type>;
|
||||
|
||||
std::tuple<ParamGenerator<T>...> generators_;
|
||||
};
|
||||
|
||||
template <class... Gen>
|
||||
class CartesianProductHolder {
|
||||
public:
|
||||
CartesianProductHolder(const Gen&... g) : generators_(g...) {}
|
||||
template <typename... T>
|
||||
operator ParamGenerator<::std::tuple<T...>>() const {
|
||||
return ParamGenerator<::std::tuple<T...>>(
|
||||
new CartesianProductGenerator<T...>(generators_));
|
||||
}
|
||||
|
||||
private:
|
||||
std::tuple<Gen...> generators_;
|
||||
};
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
|
107
3rdparty/gtest/include/gtest/internal/gtest-port-arch.h
vendored
Normal file
107
3rdparty/gtest/include/gtest/internal/gtest-port-arch.h
vendored
Normal file
@ -0,0 +1,107 @@
|
||||
// Copyright 2015, 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.
|
||||
//
|
||||
// The Google C++ Testing and Mocking Framework (Google Test)
|
||||
//
|
||||
// This header file defines the GTEST_OS_* macro.
|
||||
// It is separate from gtest-port.h so that custom/gtest-port.h can include it.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
|
||||
|
||||
// Determines the platform on which Google Test is compiled.
|
||||
#ifdef __CYGWIN__
|
||||
# define GTEST_OS_CYGWIN 1
|
||||
# elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__)
|
||||
# define GTEST_OS_WINDOWS_MINGW 1
|
||||
# define GTEST_OS_WINDOWS 1
|
||||
#elif defined _WIN32
|
||||
# define GTEST_OS_WINDOWS 1
|
||||
# ifdef _WIN32_WCE
|
||||
# define GTEST_OS_WINDOWS_MOBILE 1
|
||||
# elif defined(WINAPI_FAMILY)
|
||||
# include <winapifamily.h>
|
||||
# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
|
||||
# define GTEST_OS_WINDOWS_DESKTOP 1
|
||||
# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
|
||||
# define GTEST_OS_WINDOWS_PHONE 1
|
||||
# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
|
||||
# define GTEST_OS_WINDOWS_RT 1
|
||||
# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE)
|
||||
# define GTEST_OS_WINDOWS_PHONE 1
|
||||
# define GTEST_OS_WINDOWS_TV_TITLE 1
|
||||
# else
|
||||
// WINAPI_FAMILY defined but no known partition matched.
|
||||
// Default to desktop.
|
||||
# define GTEST_OS_WINDOWS_DESKTOP 1
|
||||
# endif
|
||||
# else
|
||||
# define GTEST_OS_WINDOWS_DESKTOP 1
|
||||
# endif // _WIN32_WCE
|
||||
#elif defined __OS2__
|
||||
# define GTEST_OS_OS2 1
|
||||
#elif defined __APPLE__
|
||||
# define GTEST_OS_MAC 1
|
||||
# if TARGET_OS_IPHONE
|
||||
# define GTEST_OS_IOS 1
|
||||
# endif
|
||||
#elif defined __DragonFly__
|
||||
# define GTEST_OS_DRAGONFLY 1
|
||||
#elif defined __FreeBSD__
|
||||
# define GTEST_OS_FREEBSD 1
|
||||
#elif defined __Fuchsia__
|
||||
# define GTEST_OS_FUCHSIA 1
|
||||
#elif defined(__GLIBC__) && defined(__FreeBSD_kernel__)
|
||||
# define GTEST_OS_GNU_KFREEBSD 1
|
||||
#elif defined __linux__
|
||||
# define GTEST_OS_LINUX 1
|
||||
# if defined __ANDROID__
|
||||
# define GTEST_OS_LINUX_ANDROID 1
|
||||
# endif
|
||||
#elif defined __MVS__
|
||||
# define GTEST_OS_ZOS 1
|
||||
#elif defined(__sun) && defined(__SVR4)
|
||||
# define GTEST_OS_SOLARIS 1
|
||||
#elif defined(_AIX)
|
||||
# define GTEST_OS_AIX 1
|
||||
#elif defined(__hpux)
|
||||
# define GTEST_OS_HPUX 1
|
||||
#elif defined __native_client__
|
||||
# define GTEST_OS_NACL 1
|
||||
#elif defined __NetBSD__
|
||||
# define GTEST_OS_NETBSD 1
|
||||
#elif defined __OpenBSD__
|
||||
# define GTEST_OS_OPENBSD 1
|
||||
#elif defined __QNX__
|
||||
# define GTEST_OS_QNX 1
|
||||
#elif defined(__HAIKU__)
|
||||
#define GTEST_OS_HAIKU 1
|
||||
#endif // __CYGWIN__
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
|
2231
3rdparty/gtest/include/gtest/internal/gtest-port.h
vendored
Normal file
2231
3rdparty/gtest/include/gtest/internal/gtest-port.h
vendored
Normal file
File diff suppressed because it is too large
Load Diff
171
3rdparty/gtest/include/gtest/internal/gtest-string.h
vendored
Normal file
171
3rdparty/gtest/include/gtest/internal/gtest-string.h
vendored
Normal file
@ -0,0 +1,171 @@
|
||||
// Copyright 2005, 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.
|
||||
//
|
||||
// The Google C++ Testing and Mocking Framework (Google Test)
|
||||
//
|
||||
// This header file declares the String class and functions used internally by
|
||||
// Google Test. They are subject to change without notice. They should not used
|
||||
// by code external to Google Test.
|
||||
//
|
||||
// This header file is #included by gtest-internal.h.
|
||||
// It should not be #included by other files.
|
||||
|
||||
// GOOGLETEST_CM0001 DO NOT DELETE
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
|
||||
|
||||
#ifdef __BORLANDC__
|
||||
// string.h is not guaranteed to provide strcpy on C++ Builder.
|
||||
# include <mem.h>
|
||||
#endif
|
||||
|
||||
#include <string.h>
|
||||
#include <string>
|
||||
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
// String - an abstract class holding static string utilities.
|
||||
class GTEST_API_ String {
|
||||
public:
|
||||
// Static utility methods
|
||||
|
||||
// Clones a 0-terminated C string, allocating memory using new. The
|
||||
// caller is responsible for deleting the return value using
|
||||
// delete[]. Returns the cloned string, or NULL if the input is
|
||||
// NULL.
|
||||
//
|
||||
// This is different from strdup() in string.h, which allocates
|
||||
// memory using malloc().
|
||||
static const char* CloneCString(const char* c_str);
|
||||
|
||||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
// Windows CE does not have the 'ANSI' versions of Win32 APIs. To be
|
||||
// able to pass strings to Win32 APIs on CE we need to convert them
|
||||
// to 'Unicode', UTF-16.
|
||||
|
||||
// Creates a UTF-16 wide string from the given ANSI string, allocating
|
||||
// memory using new. The caller is responsible for deleting the return
|
||||
// value using delete[]. Returns the wide string, or NULL if the
|
||||
// input is NULL.
|
||||
//
|
||||
// The wide string is created using the ANSI codepage (CP_ACP) to
|
||||
// match the behaviour of the ANSI versions of Win32 calls and the
|
||||
// C runtime.
|
||||
static LPCWSTR AnsiToUtf16(const char* c_str);
|
||||
|
||||
// Creates an ANSI string from the given wide string, allocating
|
||||
// memory using new. The caller is responsible for deleting the return
|
||||
// value using delete[]. Returns the ANSI string, or NULL if the
|
||||
// input is NULL.
|
||||
//
|
||||
// The returned string is created using the ANSI codepage (CP_ACP) to
|
||||
// match the behaviour of the ANSI versions of Win32 calls and the
|
||||
// C runtime.
|
||||
static const char* Utf16ToAnsi(LPCWSTR utf16_str);
|
||||
#endif
|
||||
|
||||
// Compares two C strings. Returns true if and only if they have the same
|
||||
// content.
|
||||
//
|
||||
// Unlike strcmp(), this function can handle NULL argument(s). A
|
||||
// NULL C string is considered different to any non-NULL C string,
|
||||
// including the empty string.
|
||||
static bool CStringEquals(const char* lhs, const char* rhs);
|
||||
|
||||
// Converts a wide C string to a String using the UTF-8 encoding.
|
||||
// NULL will be converted to "(null)". If an error occurred during
|
||||
// the conversion, "(failed to convert from wide string)" is
|
||||
// returned.
|
||||
static std::string ShowWideCString(const wchar_t* wide_c_str);
|
||||
|
||||
// Compares two wide C strings. Returns true if and only if they have the
|
||||
// same content.
|
||||
//
|
||||
// Unlike wcscmp(), this function can handle NULL argument(s). A
|
||||
// NULL C string is considered different to any non-NULL C string,
|
||||
// including the empty string.
|
||||
static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs);
|
||||
|
||||
// Compares two C strings, ignoring case. Returns true if and only if
|
||||
// they have the same content.
|
||||
//
|
||||
// Unlike strcasecmp(), this function can handle NULL argument(s).
|
||||
// A NULL C string is considered different to any non-NULL C string,
|
||||
// including the empty string.
|
||||
static bool CaseInsensitiveCStringEquals(const char* lhs,
|
||||
const char* rhs);
|
||||
|
||||
// Compares two wide C strings, ignoring case. Returns true if and only if
|
||||
// they have the same content.
|
||||
//
|
||||
// Unlike wcscasecmp(), this function can handle NULL argument(s).
|
||||
// A NULL C string is considered different to any non-NULL wide C string,
|
||||
// including the empty string.
|
||||
// NB: The implementations on different platforms slightly differ.
|
||||
// On windows, this method uses _wcsicmp which compares according to LC_CTYPE
|
||||
// environment variable. On GNU platform this method uses wcscasecmp
|
||||
// which compares according to LC_CTYPE category of the current locale.
|
||||
// On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
|
||||
// current locale.
|
||||
static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
|
||||
const wchar_t* rhs);
|
||||
|
||||
// Returns true if and only if the given string ends with the given suffix,
|
||||
// ignoring case. Any string is considered to end with an empty suffix.
|
||||
static bool EndsWithCaseInsensitive(
|
||||
const std::string& str, const std::string& suffix);
|
||||
|
||||
// Formats an int value as "%02d".
|
||||
static std::string FormatIntWidth2(int value); // "%02d" for width == 2
|
||||
|
||||
// Formats an int value as "%X".
|
||||
static std::string FormatHexInt(int value);
|
||||
|
||||
// Formats an int value as "%X".
|
||||
static std::string FormatHexUInt32(UInt32 value);
|
||||
|
||||
// Formats a byte as "%02X".
|
||||
static std::string FormatByte(unsigned char value);
|
||||
|
||||
private:
|
||||
String(); // Not meant to be instantiated.
|
||||
}; // class String
|
||||
|
||||
// Gets the content of the stringstream's buffer as an std::string. Each '\0'
|
||||
// character in the buffer is replaced with "\\0".
|
||||
GTEST_API_ std::string StringStreamToString(::std::stringstream* stream);
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
|
3335
3rdparty/gtest/include/gtest/internal/gtest-type-util.h
vendored
Normal file
3335
3rdparty/gtest/include/gtest/internal/gtest-type-util.h
vendored
Normal file
File diff suppressed because it is too large
Load Diff
302
3rdparty/gtest/include/gtest/internal/gtest-type-util.h.pump
vendored
Normal file
302
3rdparty/gtest/include/gtest/internal/gtest-type-util.h.pump
vendored
Normal file
@ -0,0 +1,302 @@
|
||||
$$ -*- mode: c++; -*-
|
||||
$var n = 50 $$ Maximum length of type lists we want to support.
|
||||
// Copyright 2008 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.
|
||||
|
||||
|
||||
// Type utilities needed for implementing typed and type-parameterized
|
||||
// tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND!
|
||||
//
|
||||
// Currently we support at most $n types in a list, and at most $n
|
||||
// type-parameterized tests in one type-parameterized test suite.
|
||||
// Please contact googletestframework@googlegroups.com if you need
|
||||
// more.
|
||||
|
||||
// GOOGLETEST_CM0001 DO NOT DELETE
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
|
||||
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
|
||||
// #ifdef __GNUC__ is too general here. It is possible to use gcc without using
|
||||
// libstdc++ (which is where cxxabi.h comes from).
|
||||
# if GTEST_HAS_CXXABI_H_
|
||||
# include <cxxabi.h>
|
||||
# elif defined(__HP_aCC)
|
||||
# include <acxx_demangle.h>
|
||||
# endif // GTEST_HASH_CXXABI_H_
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
// Canonicalizes a given name with respect to the Standard C++ Library.
|
||||
// This handles removing the inline namespace within `std` that is
|
||||
// used by various standard libraries (e.g., `std::__1`). Names outside
|
||||
// of namespace std are returned unmodified.
|
||||
inline std::string CanonicalizeForStdLibVersioning(std::string s) {
|
||||
static const char prefix[] = "std::__";
|
||||
if (s.compare(0, strlen(prefix), prefix) == 0) {
|
||||
std::string::size_type end = s.find("::", strlen(prefix));
|
||||
if (end != s.npos) {
|
||||
// Erase everything between the initial `std` and the second `::`.
|
||||
s.erase(strlen("std"), end - strlen("std"));
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
// GetTypeName<T>() returns a human-readable name of type T.
|
||||
// NB: This function is also used in Google Mock, so don't move it inside of
|
||||
// the typed-test-only section below.
|
||||
template <typename T>
|
||||
std::string GetTypeName() {
|
||||
# if GTEST_HAS_RTTI
|
||||
|
||||
const char* const name = typeid(T).name();
|
||||
# if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC)
|
||||
int status = 0;
|
||||
// gcc's implementation of typeid(T).name() mangles the type name,
|
||||
// so we have to demangle it.
|
||||
# if GTEST_HAS_CXXABI_H_
|
||||
using abi::__cxa_demangle;
|
||||
# endif // GTEST_HAS_CXXABI_H_
|
||||
char* const readable_name = __cxa_demangle(name, nullptr, nullptr, &status);
|
||||
const std::string name_str(status == 0 ? readable_name : name);
|
||||
free(readable_name);
|
||||
return CanonicalizeForStdLibVersioning(name_str);
|
||||
# else
|
||||
return name;
|
||||
# endif // GTEST_HAS_CXXABI_H_ || __HP_aCC
|
||||
|
||||
# else
|
||||
|
||||
return "<type>";
|
||||
|
||||
# endif // GTEST_HAS_RTTI
|
||||
}
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
// A unique type used as the default value for the arguments of class
|
||||
// template Types. This allows us to simulate variadic templates
|
||||
// (e.g. Types<int>, Type<int, double>, and etc), which C++ doesn't
|
||||
// support directly.
|
||||
struct None {};
|
||||
|
||||
// The following family of struct and struct templates are used to
|
||||
// represent type lists. In particular, TypesN<T1, T2, ..., TN>
|
||||
// represents a type list with N types (T1, T2, ..., and TN) in it.
|
||||
// Except for Types0, every struct in the family has two member types:
|
||||
// Head for the first type in the list, and Tail for the rest of the
|
||||
// list.
|
||||
|
||||
// The empty type list.
|
||||
struct Types0 {};
|
||||
|
||||
// Type lists of length 1, 2, 3, and so on.
|
||||
|
||||
template <typename T1>
|
||||
struct Types1 {
|
||||
typedef T1 Head;
|
||||
typedef Types0 Tail;
|
||||
};
|
||||
|
||||
$range i 2..n
|
||||
|
||||
$for i [[
|
||||
$range j 1..i
|
||||
$range k 2..i
|
||||
template <$for j, [[typename T$j]]>
|
||||
struct Types$i {
|
||||
typedef T1 Head;
|
||||
typedef Types$(i-1)<$for k, [[T$k]]> Tail;
|
||||
};
|
||||
|
||||
|
||||
]]
|
||||
|
||||
} // namespace internal
|
||||
|
||||
// We don't want to require the users to write TypesN<...> directly,
|
||||
// as that would require them to count the length. Types<...> is much
|
||||
// easier to write, but generates horrible messages when there is a
|
||||
// compiler error, as gcc insists on printing out each template
|
||||
// argument, even if it has the default value (this means Types<int>
|
||||
// will appear as Types<int, None, None, ..., None> in the compiler
|
||||
// errors).
|
||||
//
|
||||
// Our solution is to combine the best part of the two approaches: a
|
||||
// user would write Types<T1, ..., TN>, and Google Test will translate
|
||||
// that to TypesN<T1, ..., TN> internally to make error messages
|
||||
// readable. The translation is done by the 'type' member of the
|
||||
// Types template.
|
||||
|
||||
$range i 1..n
|
||||
template <$for i, [[typename T$i = internal::None]]>
|
||||
struct Types {
|
||||
typedef internal::Types$n<$for i, [[T$i]]> type;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct Types<$for i, [[internal::None]]> {
|
||||
typedef internal::Types0 type;
|
||||
};
|
||||
|
||||
$range i 1..n-1
|
||||
$for i [[
|
||||
$range j 1..i
|
||||
$range k i+1..n
|
||||
template <$for j, [[typename T$j]]>
|
||||
struct Types<$for j, [[T$j]]$for k[[, internal::None]]> {
|
||||
typedef internal::Types$i<$for j, [[T$j]]> type;
|
||||
};
|
||||
|
||||
]]
|
||||
|
||||
namespace internal {
|
||||
|
||||
# define GTEST_TEMPLATE_ template <typename T> class
|
||||
|
||||
// The template "selector" struct TemplateSel<Tmpl> is used to
|
||||
// represent Tmpl, which must be a class template with one type
|
||||
// parameter, as a type. TemplateSel<Tmpl>::Bind<T>::type is defined
|
||||
// as the type Tmpl<T>. This allows us to actually instantiate the
|
||||
// template "selected" by TemplateSel<Tmpl>.
|
||||
//
|
||||
// This trick is necessary for simulating typedef for class templates,
|
||||
// which C++ doesn't support directly.
|
||||
template <GTEST_TEMPLATE_ Tmpl>
|
||||
struct TemplateSel {
|
||||
template <typename T>
|
||||
struct Bind {
|
||||
typedef Tmpl<T> type;
|
||||
};
|
||||
};
|
||||
|
||||
# define GTEST_BIND_(TmplSel, T) \
|
||||
TmplSel::template Bind<T>::type
|
||||
|
||||
// A unique struct template used as the default value for the
|
||||
// arguments of class template Templates. This allows us to simulate
|
||||
// variadic templates (e.g. Templates<int>, Templates<int, double>,
|
||||
// and etc), which C++ doesn't support directly.
|
||||
template <typename T>
|
||||
struct NoneT {};
|
||||
|
||||
// The following family of struct and struct templates are used to
|
||||
// represent template lists. In particular, TemplatesN<T1, T2, ...,
|
||||
// TN> represents a list of N templates (T1, T2, ..., and TN). Except
|
||||
// for Templates0, every struct in the family has two member types:
|
||||
// Head for the selector of the first template in the list, and Tail
|
||||
// for the rest of the list.
|
||||
|
||||
// The empty template list.
|
||||
struct Templates0 {};
|
||||
|
||||
// Template lists of length 1, 2, 3, and so on.
|
||||
|
||||
template <GTEST_TEMPLATE_ T1>
|
||||
struct Templates1 {
|
||||
typedef TemplateSel<T1> Head;
|
||||
typedef Templates0 Tail;
|
||||
};
|
||||
|
||||
$range i 2..n
|
||||
|
||||
$for i [[
|
||||
$range j 1..i
|
||||
$range k 2..i
|
||||
template <$for j, [[GTEST_TEMPLATE_ T$j]]>
|
||||
struct Templates$i {
|
||||
typedef TemplateSel<T1> Head;
|
||||
typedef Templates$(i-1)<$for k, [[T$k]]> Tail;
|
||||
};
|
||||
|
||||
|
||||
]]
|
||||
|
||||
// We don't want to require the users to write TemplatesN<...> directly,
|
||||
// as that would require them to count the length. Templates<...> is much
|
||||
// easier to write, but generates horrible messages when there is a
|
||||
// compiler error, as gcc insists on printing out each template
|
||||
// argument, even if it has the default value (this means Templates<list>
|
||||
// will appear as Templates<list, NoneT, NoneT, ..., NoneT> in the compiler
|
||||
// errors).
|
||||
//
|
||||
// Our solution is to combine the best part of the two approaches: a
|
||||
// user would write Templates<T1, ..., TN>, and Google Test will translate
|
||||
// that to TemplatesN<T1, ..., TN> internally to make error messages
|
||||
// readable. The translation is done by the 'type' member of the
|
||||
// Templates template.
|
||||
|
||||
$range i 1..n
|
||||
template <$for i, [[GTEST_TEMPLATE_ T$i = NoneT]]>
|
||||
struct Templates {
|
||||
typedef Templates$n<$for i, [[T$i]]> type;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct Templates<$for i, [[NoneT]]> {
|
||||
typedef Templates0 type;
|
||||
};
|
||||
|
||||
$range i 1..n-1
|
||||
$for i [[
|
||||
$range j 1..i
|
||||
$range k i+1..n
|
||||
template <$for j, [[GTEST_TEMPLATE_ T$j]]>
|
||||
struct Templates<$for j, [[T$j]]$for k[[, NoneT]]> {
|
||||
typedef Templates$i<$for j, [[T$j]]> type;
|
||||
};
|
||||
|
||||
]]
|
||||
|
||||
// The TypeList template makes it possible to use either a single type
|
||||
// or a Types<...> list in TYPED_TEST_SUITE() and
|
||||
// INSTANTIATE_TYPED_TEST_SUITE_P().
|
||||
|
||||
template <typename T>
|
||||
struct TypeList {
|
||||
typedef Types1<T> type;
|
||||
};
|
||||
|
||||
|
||||
$range i 1..n
|
||||
template <$for i, [[typename T$i]]>
|
||||
struct TypeList<Types<$for i, [[T$i]]> > {
|
||||
typedef typename Types<$for i, [[T$i]]>::type type;
|
||||
};
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
|
126
3rdparty/gtest/samples/prime_tables.h
vendored
Normal file
126
3rdparty/gtest/samples/prime_tables.h
vendored
Normal file
@ -0,0 +1,126 @@
|
||||
// Copyright 2008 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.
|
||||
|
||||
|
||||
|
||||
// This provides interface PrimeTable that determines whether a number is a
|
||||
// prime and determines a next prime number. This interface is used
|
||||
// in Google Test samples demonstrating use of parameterized tests.
|
||||
|
||||
#ifndef GTEST_SAMPLES_PRIME_TABLES_H_
|
||||
#define GTEST_SAMPLES_PRIME_TABLES_H_
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
// The prime table interface.
|
||||
class PrimeTable {
|
||||
public:
|
||||
virtual ~PrimeTable() {}
|
||||
|
||||
// Returns true if and only if n is a prime number.
|
||||
virtual bool IsPrime(int n) const = 0;
|
||||
|
||||
// Returns the smallest prime number greater than p; or returns -1
|
||||
// if the next prime is beyond the capacity of the table.
|
||||
virtual int GetNextPrime(int p) const = 0;
|
||||
};
|
||||
|
||||
// Implementation #1 calculates the primes on-the-fly.
|
||||
class OnTheFlyPrimeTable : public PrimeTable {
|
||||
public:
|
||||
bool IsPrime(int n) const override {
|
||||
if (n <= 1) return false;
|
||||
|
||||
for (int i = 2; i*i <= n; i++) {
|
||||
// n is divisible by an integer other than 1 and itself.
|
||||
if ((n % i) == 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
int GetNextPrime(int p) const override {
|
||||
for (int n = p + 1; n > 0; n++) {
|
||||
if (IsPrime(n)) return n;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
};
|
||||
|
||||
// Implementation #2 pre-calculates the primes and stores the result
|
||||
// in an array.
|
||||
class PreCalculatedPrimeTable : public PrimeTable {
|
||||
public:
|
||||
// 'max' specifies the maximum number the prime table holds.
|
||||
explicit PreCalculatedPrimeTable(int max)
|
||||
: is_prime_size_(max + 1), is_prime_(new bool[max + 1]) {
|
||||
CalculatePrimesUpTo(max);
|
||||
}
|
||||
~PreCalculatedPrimeTable() override { delete[] is_prime_; }
|
||||
|
||||
bool IsPrime(int n) const override {
|
||||
return 0 <= n && n < is_prime_size_ && is_prime_[n];
|
||||
}
|
||||
|
||||
int GetNextPrime(int p) const override {
|
||||
for (int n = p + 1; n < is_prime_size_; n++) {
|
||||
if (is_prime_[n]) return n;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
private:
|
||||
void CalculatePrimesUpTo(int max) {
|
||||
::std::fill(is_prime_, is_prime_ + is_prime_size_, true);
|
||||
is_prime_[0] = is_prime_[1] = false;
|
||||
|
||||
// Checks every candidate for prime number (we know that 2 is the only even
|
||||
// prime).
|
||||
for (int i = 2; i*i <= max; i += i%2+1) {
|
||||
if (!is_prime_[i]) continue;
|
||||
|
||||
// Marks all multiples of i (except i itself) as non-prime.
|
||||
// We are starting here from i-th multiplier, because all smaller
|
||||
// complex numbers were already marked.
|
||||
for (int j = i*i; j <= max; j += i) {
|
||||
is_prime_[j] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const int is_prime_size_;
|
||||
bool* const is_prime_;
|
||||
|
||||
// Disables compiler warning "assignment operator could not be generated."
|
||||
void operator=(const PreCalculatedPrimeTable& rhs);
|
||||
};
|
||||
|
||||
#endif // GTEST_SAMPLES_PRIME_TABLES_H_
|
66
3rdparty/gtest/samples/sample1.cc
vendored
Normal file
66
3rdparty/gtest/samples/sample1.cc
vendored
Normal file
@ -0,0 +1,66 @@
|
||||
// Copyright 2005, 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.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
|
||||
#include "sample1.h"
|
||||
|
||||
// Returns n! (the factorial of n). For negative n, n! is defined to be 1.
|
||||
int Factorial(int n) {
|
||||
int result = 1;
|
||||
for (int i = 1; i <= n; i++) {
|
||||
result *= i;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Returns true if and only if n is a prime number.
|
||||
bool IsPrime(int n) {
|
||||
// Trivial case 1: small numbers
|
||||
if (n <= 1) return false;
|
||||
|
||||
// Trivial case 2: even numbers
|
||||
if (n % 2 == 0) return n == 2;
|
||||
|
||||
// Now, we have that n is odd and n >= 3.
|
||||
|
||||
// Try to divide n by every odd number i, starting from 3
|
||||
for (int i = 3; ; i += 2) {
|
||||
// We only have to try i up to the square root of n
|
||||
if (i > n/i) break;
|
||||
|
||||
// Now, we have i <= n/i < n.
|
||||
// If n is divisible by i, n is not prime.
|
||||
if (n % i == 0) return false;
|
||||
}
|
||||
|
||||
// n has no integer factor in the range (1, n), and thus is prime.
|
||||
return true;
|
||||
}
|
41
3rdparty/gtest/samples/sample1.h
vendored
Normal file
41
3rdparty/gtest/samples/sample1.h
vendored
Normal file
@ -0,0 +1,41 @@
|
||||
// Copyright 2005, 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.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
|
||||
#ifndef GTEST_SAMPLES_SAMPLE1_H_
|
||||
#define GTEST_SAMPLES_SAMPLE1_H_
|
||||
|
||||
// Returns n! (the factorial of n). For negative n, n! is defined to be 1.
|
||||
int Factorial(int n);
|
||||
|
||||
// Returns true if and only if n is a prime number.
|
||||
bool IsPrime(int n);
|
||||
|
||||
#endif // GTEST_SAMPLES_SAMPLE1_H_
|
139
3rdparty/gtest/samples/sample10_unittest.cc
vendored
Normal file
139
3rdparty/gtest/samples/sample10_unittest.cc
vendored
Normal file
@ -0,0 +1,139 @@
|
||||
// Copyright 2009 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.
|
||||
|
||||
|
||||
// This sample shows how to use Google Test listener API to implement
|
||||
// a primitive leak checker.
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
using ::testing::EmptyTestEventListener;
|
||||
using ::testing::InitGoogleTest;
|
||||
using ::testing::Test;
|
||||
using ::testing::TestEventListeners;
|
||||
using ::testing::TestInfo;
|
||||
using ::testing::TestPartResult;
|
||||
using ::testing::UnitTest;
|
||||
|
||||
namespace {
|
||||
// We will track memory used by this class.
|
||||
class Water {
|
||||
public:
|
||||
// Normal Water declarations go here.
|
||||
|
||||
// operator new and operator delete help us control water allocation.
|
||||
void* operator new(size_t allocation_size) {
|
||||
allocated_++;
|
||||
return malloc(allocation_size);
|
||||
}
|
||||
|
||||
void operator delete(void* block, size_t /* allocation_size */) {
|
||||
allocated_--;
|
||||
free(block);
|
||||
}
|
||||
|
||||
static int allocated() { return allocated_; }
|
||||
|
||||
private:
|
||||
static int allocated_;
|
||||
};
|
||||
|
||||
int Water::allocated_ = 0;
|
||||
|
||||
// This event listener monitors how many Water objects are created and
|
||||
// destroyed by each test, and reports a failure if a test leaks some Water
|
||||
// objects. It does this by comparing the number of live Water objects at
|
||||
// the beginning of a test and at the end of a test.
|
||||
class LeakChecker : public EmptyTestEventListener {
|
||||
private:
|
||||
// Called before a test starts.
|
||||
void OnTestStart(const TestInfo& /* test_info */) override {
|
||||
initially_allocated_ = Water::allocated();
|
||||
}
|
||||
|
||||
// Called after a test ends.
|
||||
void OnTestEnd(const TestInfo& /* test_info */) override {
|
||||
int difference = Water::allocated() - initially_allocated_;
|
||||
|
||||
// You can generate a failure in any event handler except
|
||||
// OnTestPartResult. Just use an appropriate Google Test assertion to do
|
||||
// it.
|
||||
EXPECT_LE(difference, 0) << "Leaked " << difference << " unit(s) of Water!";
|
||||
}
|
||||
|
||||
int initially_allocated_;
|
||||
};
|
||||
|
||||
TEST(ListenersTest, DoesNotLeak) {
|
||||
Water* water = new Water;
|
||||
delete water;
|
||||
}
|
||||
|
||||
// This should fail when the --check_for_leaks command line flag is
|
||||
// specified.
|
||||
TEST(ListenersTest, LeaksWater) {
|
||||
Water* water = new Water;
|
||||
EXPECT_TRUE(water != nullptr);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
InitGoogleTest(&argc, argv);
|
||||
|
||||
bool check_for_leaks = false;
|
||||
if (argc > 1 && strcmp(argv[1], "--check_for_leaks") == 0 )
|
||||
check_for_leaks = true;
|
||||
else
|
||||
printf("%s\n", "Run this program with --check_for_leaks to enable "
|
||||
"custom leak checking in the tests.");
|
||||
|
||||
// If we are given the --check_for_leaks command line flag, installs the
|
||||
// leak checker.
|
||||
if (check_for_leaks) {
|
||||
TestEventListeners& listeners = UnitTest::GetInstance()->listeners();
|
||||
|
||||
// Adds the leak checker to the end of the test event listener list,
|
||||
// after the default text output printer and the default XML report
|
||||
// generator.
|
||||
//
|
||||
// The order is important - it ensures that failures generated in the
|
||||
// leak checker's OnTestEnd() method are processed by the text and XML
|
||||
// printers *before* their OnTestEnd() methods are called, such that
|
||||
// they are attributed to the right test. Remember that a listener
|
||||
// receives an OnXyzStart event *after* listeners preceding it in the
|
||||
// list received that event, and receives an OnXyzEnd event *before*
|
||||
// listeners preceding it.
|
||||
//
|
||||
// We don't need to worry about deleting the new listener later, as
|
||||
// Google Test will do it.
|
||||
listeners.Append(new LeakChecker);
|
||||
}
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
151
3rdparty/gtest/samples/sample1_unittest.cc
vendored
Normal file
151
3rdparty/gtest/samples/sample1_unittest.cc
vendored
Normal file
@ -0,0 +1,151 @@
|
||||
// Copyright 2005, 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.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
|
||||
// This sample shows how to write a simple unit test for a function,
|
||||
// using Google C++ testing framework.
|
||||
//
|
||||
// Writing a unit test using Google C++ testing framework is easy as 1-2-3:
|
||||
|
||||
|
||||
// Step 1. Include necessary header files such that the stuff your
|
||||
// test logic needs is declared.
|
||||
//
|
||||
// Don't forget gtest.h, which declares the testing framework.
|
||||
|
||||
#include <limits.h>
|
||||
#include "sample1.h"
|
||||
#include "gtest/gtest.h"
|
||||
namespace {
|
||||
|
||||
// Step 2. Use the TEST macro to define your tests.
|
||||
//
|
||||
// TEST has two parameters: the test case name and the test name.
|
||||
// After using the macro, you should define your test logic between a
|
||||
// pair of braces. You can use a bunch of macros to indicate the
|
||||
// success or failure of a test. EXPECT_TRUE and EXPECT_EQ are
|
||||
// examples of such macros. For a complete list, see gtest.h.
|
||||
//
|
||||
// <TechnicalDetails>
|
||||
//
|
||||
// In Google Test, tests are grouped into test cases. This is how we
|
||||
// keep test code organized. You should put logically related tests
|
||||
// into the same test case.
|
||||
//
|
||||
// The test case name and the test name should both be valid C++
|
||||
// identifiers. And you should not use underscore (_) in the names.
|
||||
//
|
||||
// Google Test guarantees that each test you define is run exactly
|
||||
// once, but it makes no guarantee on the order the tests are
|
||||
// executed. Therefore, you should write your tests in such a way
|
||||
// that their results don't depend on their order.
|
||||
//
|
||||
// </TechnicalDetails>
|
||||
|
||||
|
||||
// Tests Factorial().
|
||||
|
||||
// Tests factorial of negative numbers.
|
||||
TEST(FactorialTest, Negative) {
|
||||
// This test is named "Negative", and belongs to the "FactorialTest"
|
||||
// test case.
|
||||
EXPECT_EQ(1, Factorial(-5));
|
||||
EXPECT_EQ(1, Factorial(-1));
|
||||
EXPECT_GT(Factorial(-10), 0);
|
||||
|
||||
// <TechnicalDetails>
|
||||
//
|
||||
// EXPECT_EQ(expected, actual) is the same as
|
||||
//
|
||||
// EXPECT_TRUE((expected) == (actual))
|
||||
//
|
||||
// except that it will print both the expected value and the actual
|
||||
// value when the assertion fails. This is very helpful for
|
||||
// debugging. Therefore in this case EXPECT_EQ is preferred.
|
||||
//
|
||||
// On the other hand, EXPECT_TRUE accepts any Boolean expression,
|
||||
// and is thus more general.
|
||||
//
|
||||
// </TechnicalDetails>
|
||||
}
|
||||
|
||||
// Tests factorial of 0.
|
||||
TEST(FactorialTest, Zero) {
|
||||
EXPECT_EQ(1, Factorial(0));
|
||||
}
|
||||
|
||||
// Tests factorial of positive numbers.
|
||||
TEST(FactorialTest, Positive) {
|
||||
EXPECT_EQ(1, Factorial(1));
|
||||
EXPECT_EQ(2, Factorial(2));
|
||||
EXPECT_EQ(6, Factorial(3));
|
||||
EXPECT_EQ(40320, Factorial(8));
|
||||
}
|
||||
|
||||
|
||||
// Tests IsPrime()
|
||||
|
||||
// Tests negative input.
|
||||
TEST(IsPrimeTest, Negative) {
|
||||
// This test belongs to the IsPrimeTest test case.
|
||||
|
||||
EXPECT_FALSE(IsPrime(-1));
|
||||
EXPECT_FALSE(IsPrime(-2));
|
||||
EXPECT_FALSE(IsPrime(INT_MIN));
|
||||
}
|
||||
|
||||
// Tests some trivial cases.
|
||||
TEST(IsPrimeTest, Trivial) {
|
||||
EXPECT_FALSE(IsPrime(0));
|
||||
EXPECT_FALSE(IsPrime(1));
|
||||
EXPECT_TRUE(IsPrime(2));
|
||||
EXPECT_TRUE(IsPrime(3));
|
||||
}
|
||||
|
||||
// Tests positive input.
|
||||
TEST(IsPrimeTest, Positive) {
|
||||
EXPECT_FALSE(IsPrime(4));
|
||||
EXPECT_TRUE(IsPrime(5));
|
||||
EXPECT_FALSE(IsPrime(6));
|
||||
EXPECT_TRUE(IsPrime(23));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// Step 3. Call RUN_ALL_TESTS() in main().
|
||||
//
|
||||
// We do this by linking in src/gtest_main.cc file, which consists of
|
||||
// a main() function which calls RUN_ALL_TESTS() for us.
|
||||
//
|
||||
// This runs all the tests you've defined, prints the result, and
|
||||
// returns 0 if successful, or 1 otherwise.
|
||||
//
|
||||
// Did you notice that we didn't register the tests? The
|
||||
// RUN_ALL_TESTS() macro magically knows about all the tests we
|
||||
// defined. Isn't this convenient?
|
54
3rdparty/gtest/samples/sample2.cc
vendored
Normal file
54
3rdparty/gtest/samples/sample2.cc
vendored
Normal file
@ -0,0 +1,54 @@
|
||||
// Copyright 2005, 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.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
|
||||
#include "sample2.h"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
// Clones a 0-terminated C string, allocating memory using new.
|
||||
const char* MyString::CloneCString(const char* a_c_string) {
|
||||
if (a_c_string == nullptr) return nullptr;
|
||||
|
||||
const size_t len = strlen(a_c_string);
|
||||
char* const clone = new char[ len + 1 ];
|
||||
memcpy(clone, a_c_string, len + 1);
|
||||
|
||||
return clone;
|
||||
}
|
||||
|
||||
// Sets the 0-terminated C string this MyString object
|
||||
// represents.
|
||||
void MyString::Set(const char* a_c_string) {
|
||||
// Makes sure this works when c_string == c_string_
|
||||
const char* const temp = MyString::CloneCString(a_c_string);
|
||||
delete[] c_string_;
|
||||
c_string_ = temp;
|
||||
}
|
81
3rdparty/gtest/samples/sample2.h
vendored
Normal file
81
3rdparty/gtest/samples/sample2.h
vendored
Normal file
@ -0,0 +1,81 @@
|
||||
// Copyright 2005, 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.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
|
||||
#ifndef GTEST_SAMPLES_SAMPLE2_H_
|
||||
#define GTEST_SAMPLES_SAMPLE2_H_
|
||||
|
||||
#include <string.h>
|
||||
|
||||
|
||||
// A simple string class.
|
||||
class MyString {
|
||||
private:
|
||||
const char* c_string_;
|
||||
const MyString& operator=(const MyString& rhs);
|
||||
|
||||
public:
|
||||
// Clones a 0-terminated C string, allocating memory using new.
|
||||
static const char* CloneCString(const char* a_c_string);
|
||||
|
||||
////////////////////////////////////////////////////////////
|
||||
//
|
||||
// C'tors
|
||||
|
||||
// The default c'tor constructs a NULL string.
|
||||
MyString() : c_string_(nullptr) {}
|
||||
|
||||
// Constructs a MyString by cloning a 0-terminated C string.
|
||||
explicit MyString(const char* a_c_string) : c_string_(nullptr) {
|
||||
Set(a_c_string);
|
||||
}
|
||||
|
||||
// Copy c'tor
|
||||
MyString(const MyString& string) : c_string_(nullptr) {
|
||||
Set(string.c_string_);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////
|
||||
//
|
||||
// D'tor. MyString is intended to be a final class, so the d'tor
|
||||
// doesn't need to be virtual.
|
||||
~MyString() { delete[] c_string_; }
|
||||
|
||||
// Gets the 0-terminated C string this MyString object represents.
|
||||
const char* c_string() const { return c_string_; }
|
||||
|
||||
size_t Length() const { return c_string_ == nullptr ? 0 : strlen(c_string_); }
|
||||
|
||||
// Sets the 0-terminated C string this MyString object represents.
|
||||
void Set(const char* c_string);
|
||||
};
|
||||
|
||||
|
||||
#endif // GTEST_SAMPLES_SAMPLE2_H_
|
107
3rdparty/gtest/samples/sample2_unittest.cc
vendored
Normal file
107
3rdparty/gtest/samples/sample2_unittest.cc
vendored
Normal file
@ -0,0 +1,107 @@
|
||||
// Copyright 2005, 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.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
|
||||
// This sample shows how to write a more complex unit test for a class
|
||||
// that has multiple member functions.
|
||||
//
|
||||
// Usually, it's a good idea to have one test for each method in your
|
||||
// class. You don't have to do that exactly, but it helps to keep
|
||||
// your tests organized. You may also throw in additional tests as
|
||||
// needed.
|
||||
|
||||
#include "sample2.h"
|
||||
#include "gtest/gtest.h"
|
||||
namespace {
|
||||
// In this example, we test the MyString class (a simple string).
|
||||
|
||||
// Tests the default c'tor.
|
||||
TEST(MyString, DefaultConstructor) {
|
||||
const MyString s;
|
||||
|
||||
// Asserts that s.c_string() returns NULL.
|
||||
//
|
||||
// <TechnicalDetails>
|
||||
//
|
||||
// If we write NULL instead of
|
||||
//
|
||||
// static_cast<const char *>(NULL)
|
||||
//
|
||||
// in this assertion, it will generate a warning on gcc 3.4. The
|
||||
// reason is that EXPECT_EQ needs to know the types of its
|
||||
// arguments in order to print them when it fails. Since NULL is
|
||||
// #defined as 0, the compiler will use the formatter function for
|
||||
// int to print it. However, gcc thinks that NULL should be used as
|
||||
// a pointer, not an int, and therefore complains.
|
||||
//
|
||||
// The root of the problem is C++'s lack of distinction between the
|
||||
// integer number 0 and the null pointer constant. Unfortunately,
|
||||
// we have to live with this fact.
|
||||
//
|
||||
// </TechnicalDetails>
|
||||
EXPECT_STREQ(nullptr, s.c_string());
|
||||
|
||||
EXPECT_EQ(0u, s.Length());
|
||||
}
|
||||
|
||||
const char kHelloString[] = "Hello, world!";
|
||||
|
||||
// Tests the c'tor that accepts a C string.
|
||||
TEST(MyString, ConstructorFromCString) {
|
||||
const MyString s(kHelloString);
|
||||
EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));
|
||||
EXPECT_EQ(sizeof(kHelloString)/sizeof(kHelloString[0]) - 1,
|
||||
s.Length());
|
||||
}
|
||||
|
||||
// Tests the copy c'tor.
|
||||
TEST(MyString, CopyConstructor) {
|
||||
const MyString s1(kHelloString);
|
||||
const MyString s2 = s1;
|
||||
EXPECT_EQ(0, strcmp(s2.c_string(), kHelloString));
|
||||
}
|
||||
|
||||
// Tests the Set method.
|
||||
TEST(MyString, Set) {
|
||||
MyString s;
|
||||
|
||||
s.Set(kHelloString);
|
||||
EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));
|
||||
|
||||
// Set should work when the input pointer is the same as the one
|
||||
// already in the MyString object.
|
||||
s.Set(s.c_string());
|
||||
EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));
|
||||
|
||||
// Can we set the MyString to NULL?
|
||||
s.Set(nullptr);
|
||||
EXPECT_STREQ(nullptr, s.c_string());
|
||||
}
|
||||
} // namespace
|
172
3rdparty/gtest/samples/sample3-inl.h
vendored
Normal file
172
3rdparty/gtest/samples/sample3-inl.h
vendored
Normal file
@ -0,0 +1,172 @@
|
||||
// Copyright 2005, 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.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
|
||||
#ifndef GTEST_SAMPLES_SAMPLE3_INL_H_
|
||||
#define GTEST_SAMPLES_SAMPLE3_INL_H_
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
|
||||
// Queue is a simple queue implemented as a singled-linked list.
|
||||
//
|
||||
// The element type must support copy constructor.
|
||||
template <typename E> // E is the element type
|
||||
class Queue;
|
||||
|
||||
// QueueNode is a node in a Queue, which consists of an element of
|
||||
// type E and a pointer to the next node.
|
||||
template <typename E> // E is the element type
|
||||
class QueueNode {
|
||||
friend class Queue<E>;
|
||||
|
||||
public:
|
||||
// Gets the element in this node.
|
||||
const E& element() const { return element_; }
|
||||
|
||||
// Gets the next node in the queue.
|
||||
QueueNode* next() { return next_; }
|
||||
const QueueNode* next() const { return next_; }
|
||||
|
||||
private:
|
||||
// Creates a node with a given element value. The next pointer is
|
||||
// set to NULL.
|
||||
explicit QueueNode(const E& an_element)
|
||||
: element_(an_element), next_(nullptr) {}
|
||||
|
||||
// We disable the default assignment operator and copy c'tor.
|
||||
const QueueNode& operator = (const QueueNode&);
|
||||
QueueNode(const QueueNode&);
|
||||
|
||||
E element_;
|
||||
QueueNode* next_;
|
||||
};
|
||||
|
||||
template <typename E> // E is the element type.
|
||||
class Queue {
|
||||
public:
|
||||
// Creates an empty queue.
|
||||
Queue() : head_(nullptr), last_(nullptr), size_(0) {}
|
||||
|
||||
// D'tor. Clears the queue.
|
||||
~Queue() { Clear(); }
|
||||
|
||||
// Clears the queue.
|
||||
void Clear() {
|
||||
if (size_ > 0) {
|
||||
// 1. Deletes every node.
|
||||
QueueNode<E>* node = head_;
|
||||
QueueNode<E>* next = node->next();
|
||||
for (; ;) {
|
||||
delete node;
|
||||
node = next;
|
||||
if (node == nullptr) break;
|
||||
next = node->next();
|
||||
}
|
||||
|
||||
// 2. Resets the member variables.
|
||||
head_ = last_ = nullptr;
|
||||
size_ = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Gets the number of elements.
|
||||
size_t Size() const { return size_; }
|
||||
|
||||
// Gets the first element of the queue, or NULL if the queue is empty.
|
||||
QueueNode<E>* Head() { return head_; }
|
||||
const QueueNode<E>* Head() const { return head_; }
|
||||
|
||||
// Gets the last element of the queue, or NULL if the queue is empty.
|
||||
QueueNode<E>* Last() { return last_; }
|
||||
const QueueNode<E>* Last() const { return last_; }
|
||||
|
||||
// Adds an element to the end of the queue. A copy of the element is
|
||||
// created using the copy constructor, and then stored in the queue.
|
||||
// Changes made to the element in the queue doesn't affect the source
|
||||
// object, and vice versa.
|
||||
void Enqueue(const E& element) {
|
||||
QueueNode<E>* new_node = new QueueNode<E>(element);
|
||||
|
||||
if (size_ == 0) {
|
||||
head_ = last_ = new_node;
|
||||
size_ = 1;
|
||||
} else {
|
||||
last_->next_ = new_node;
|
||||
last_ = new_node;
|
||||
size_++;
|
||||
}
|
||||
}
|
||||
|
||||
// Removes the head of the queue and returns it. Returns NULL if
|
||||
// the queue is empty.
|
||||
E* Dequeue() {
|
||||
if (size_ == 0) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const QueueNode<E>* const old_head = head_;
|
||||
head_ = head_->next_;
|
||||
size_--;
|
||||
if (size_ == 0) {
|
||||
last_ = nullptr;
|
||||
}
|
||||
|
||||
E* element = new E(old_head->element());
|
||||
delete old_head;
|
||||
|
||||
return element;
|
||||
}
|
||||
|
||||
// Applies a function/functor on each element of the queue, and
|
||||
// returns the result in a new queue. The original queue is not
|
||||
// affected.
|
||||
template <typename F>
|
||||
Queue* Map(F function) const {
|
||||
Queue* new_queue = new Queue();
|
||||
for (const QueueNode<E>* node = head_; node != nullptr;
|
||||
node = node->next_) {
|
||||
new_queue->Enqueue(function(node->element()));
|
||||
}
|
||||
|
||||
return new_queue;
|
||||
}
|
||||
|
||||
private:
|
||||
QueueNode<E>* head_; // The first node of the queue.
|
||||
QueueNode<E>* last_; // The last node of the queue.
|
||||
size_t size_; // The number of elements in the queue.
|
||||
|
||||
// We disallow copying a queue.
|
||||
Queue(const Queue&);
|
||||
const Queue& operator = (const Queue&);
|
||||
};
|
||||
|
||||
#endif // GTEST_SAMPLES_SAMPLE3_INL_H_
|
149
3rdparty/gtest/samples/sample3_unittest.cc
vendored
Normal file
149
3rdparty/gtest/samples/sample3_unittest.cc
vendored
Normal file
@ -0,0 +1,149 @@
|
||||
// Copyright 2005, 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.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
|
||||
// In this example, we use a more advanced feature of Google Test called
|
||||
// test fixture.
|
||||
//
|
||||
// A test fixture is a place to hold objects and functions shared by
|
||||
// all tests in a test case. Using a test fixture avoids duplicating
|
||||
// the test code necessary to initialize and cleanup those common
|
||||
// objects for each test. It is also useful for defining sub-routines
|
||||
// that your tests need to invoke a lot.
|
||||
//
|
||||
// <TechnicalDetails>
|
||||
//
|
||||
// The tests share the test fixture in the sense of code sharing, not
|
||||
// data sharing. Each test is given its own fresh copy of the
|
||||
// fixture. You cannot expect the data modified by one test to be
|
||||
// passed on to another test, which is a bad idea.
|
||||
//
|
||||
// The reason for this design is that tests should be independent and
|
||||
// repeatable. In particular, a test should not fail as the result of
|
||||
// another test's failure. If one test depends on info produced by
|
||||
// another test, then the two tests should really be one big test.
|
||||
//
|
||||
// The macros for indicating the success/failure of a test
|
||||
// (EXPECT_TRUE, FAIL, etc) need to know what the current test is
|
||||
// (when Google Test prints the test result, it tells you which test
|
||||
// each failure belongs to). Technically, these macros invoke a
|
||||
// member function of the Test class. Therefore, you cannot use them
|
||||
// in a global function. That's why you should put test sub-routines
|
||||
// in a test fixture.
|
||||
//
|
||||
// </TechnicalDetails>
|
||||
|
||||
#include "sample3-inl.h"
|
||||
#include "gtest/gtest.h"
|
||||
namespace {
|
||||
// To use a test fixture, derive a class from testing::Test.
|
||||
class QueueTestSmpl3 : public testing::Test {
|
||||
protected: // You should make the members protected s.t. they can be
|
||||
// accessed from sub-classes.
|
||||
|
||||
// virtual void SetUp() will be called before each test is run. You
|
||||
// should define it if you need to initialize the variables.
|
||||
// Otherwise, this can be skipped.
|
||||
void SetUp() override {
|
||||
q1_.Enqueue(1);
|
||||
q2_.Enqueue(2);
|
||||
q2_.Enqueue(3);
|
||||
}
|
||||
|
||||
// virtual void TearDown() will be called after each test is run.
|
||||
// You should define it if there is cleanup work to do. Otherwise,
|
||||
// you don't have to provide it.
|
||||
//
|
||||
// virtual void TearDown() {
|
||||
// }
|
||||
|
||||
// A helper function that some test uses.
|
||||
static int Double(int n) {
|
||||
return 2*n;
|
||||
}
|
||||
|
||||
// A helper function for testing Queue::Map().
|
||||
void MapTester(const Queue<int> * q) {
|
||||
// Creates a new queue, where each element is twice as big as the
|
||||
// corresponding one in q.
|
||||
const Queue<int> * const new_q = q->Map(Double);
|
||||
|
||||
// Verifies that the new queue has the same size as q.
|
||||
ASSERT_EQ(q->Size(), new_q->Size());
|
||||
|
||||
// Verifies the relationship between the elements of the two queues.
|
||||
for (const QueueNode<int>*n1 = q->Head(), *n2 = new_q->Head();
|
||||
n1 != nullptr; n1 = n1->next(), n2 = n2->next()) {
|
||||
EXPECT_EQ(2 * n1->element(), n2->element());
|
||||
}
|
||||
|
||||
delete new_q;
|
||||
}
|
||||
|
||||
// Declares the variables your tests want to use.
|
||||
Queue<int> q0_;
|
||||
Queue<int> q1_;
|
||||
Queue<int> q2_;
|
||||
};
|
||||
|
||||
// When you have a test fixture, you define a test using TEST_F
|
||||
// instead of TEST.
|
||||
|
||||
// Tests the default c'tor.
|
||||
TEST_F(QueueTestSmpl3, DefaultConstructor) {
|
||||
// You can access data in the test fixture here.
|
||||
EXPECT_EQ(0u, q0_.Size());
|
||||
}
|
||||
|
||||
// Tests Dequeue().
|
||||
TEST_F(QueueTestSmpl3, Dequeue) {
|
||||
int * n = q0_.Dequeue();
|
||||
EXPECT_TRUE(n == nullptr);
|
||||
|
||||
n = q1_.Dequeue();
|
||||
ASSERT_TRUE(n != nullptr);
|
||||
EXPECT_EQ(1, *n);
|
||||
EXPECT_EQ(0u, q1_.Size());
|
||||
delete n;
|
||||
|
||||
n = q2_.Dequeue();
|
||||
ASSERT_TRUE(n != nullptr);
|
||||
EXPECT_EQ(2, *n);
|
||||
EXPECT_EQ(1u, q2_.Size());
|
||||
delete n;
|
||||
}
|
||||
|
||||
// Tests the Queue::Map() function.
|
||||
TEST_F(QueueTestSmpl3, Map) {
|
||||
MapTester(&q0_);
|
||||
MapTester(&q1_);
|
||||
MapTester(&q2_);
|
||||
}
|
||||
} // namespace
|
54
3rdparty/gtest/samples/sample4.cc
vendored
Normal file
54
3rdparty/gtest/samples/sample4.cc
vendored
Normal file
@ -0,0 +1,54 @@
|
||||
// Copyright 2005, 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.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
#include "sample4.h"
|
||||
|
||||
// Returns the current counter value, and increments it.
|
||||
int Counter::Increment() {
|
||||
return counter_++;
|
||||
}
|
||||
|
||||
// Returns the current counter value, and decrements it.
|
||||
// counter can not be less than 0, return 0 in this case
|
||||
int Counter::Decrement() {
|
||||
if (counter_ == 0) {
|
||||
return counter_;
|
||||
} else {
|
||||
return counter_--;
|
||||
}
|
||||
}
|
||||
|
||||
// Prints the current counter value to STDOUT.
|
||||
void Counter::Print() const {
|
||||
printf("%d", counter_);
|
||||
}
|
53
3rdparty/gtest/samples/sample4.h
vendored
Normal file
53
3rdparty/gtest/samples/sample4.h
vendored
Normal file
@ -0,0 +1,53 @@
|
||||
// Copyright 2005, 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.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
#ifndef GTEST_SAMPLES_SAMPLE4_H_
|
||||
#define GTEST_SAMPLES_SAMPLE4_H_
|
||||
|
||||
// A simple monotonic counter.
|
||||
class Counter {
|
||||
private:
|
||||
int counter_;
|
||||
|
||||
public:
|
||||
// Creates a counter that starts at 0.
|
||||
Counter() : counter_(0) {}
|
||||
|
||||
// Returns the current counter value, and increments it.
|
||||
int Increment();
|
||||
|
||||
// Returns the current counter value, and decrements it.
|
||||
int Decrement();
|
||||
|
||||
// Prints the current counter value to STDOUT.
|
||||
void Print() const;
|
||||
};
|
||||
|
||||
#endif // GTEST_SAMPLES_SAMPLE4_H_
|
53
3rdparty/gtest/samples/sample4_unittest.cc
vendored
Normal file
53
3rdparty/gtest/samples/sample4_unittest.cc
vendored
Normal file
@ -0,0 +1,53 @@
|
||||
// Copyright 2005, 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.
|
||||
|
||||
|
||||
#include "sample4.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace {
|
||||
// Tests the Increment() method.
|
||||
|
||||
TEST(Counter, Increment) {
|
||||
Counter c;
|
||||
|
||||
// Test that counter 0 returns 0
|
||||
EXPECT_EQ(0, c.Decrement());
|
||||
|
||||
// EXPECT_EQ() evaluates its arguments exactly once, so they
|
||||
// can have side effects.
|
||||
|
||||
EXPECT_EQ(0, c.Increment());
|
||||
EXPECT_EQ(1, c.Increment());
|
||||
EXPECT_EQ(2, c.Increment());
|
||||
|
||||
EXPECT_EQ(3, c.Decrement());
|
||||
}
|
||||
|
||||
} // namespace
|
196
3rdparty/gtest/samples/sample5_unittest.cc
vendored
Normal file
196
3rdparty/gtest/samples/sample5_unittest.cc
vendored
Normal file
@ -0,0 +1,196 @@
|
||||
// Copyright 2005, 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.
|
||||
|
||||
|
||||
// This sample teaches how to reuse a test fixture in multiple test
|
||||
// cases by deriving sub-fixtures from it.
|
||||
//
|
||||
// When you define a test fixture, you specify the name of the test
|
||||
// case that will use this fixture. Therefore, a test fixture can
|
||||
// be used by only one test case.
|
||||
//
|
||||
// Sometimes, more than one test cases may want to use the same or
|
||||
// slightly different test fixtures. For example, you may want to
|
||||
// make sure that all tests for a GUI library don't leak important
|
||||
// system resources like fonts and brushes. In Google Test, you do
|
||||
// this by putting the shared logic in a super (as in "super class")
|
||||
// test fixture, and then have each test case use a fixture derived
|
||||
// from this super fixture.
|
||||
|
||||
#include <limits.h>
|
||||
#include <time.h>
|
||||
#include "gtest/gtest.h"
|
||||
#include "sample1.h"
|
||||
#include "sample3-inl.h"
|
||||
namespace {
|
||||
// In this sample, we want to ensure that every test finishes within
|
||||
// ~5 seconds. If a test takes longer to run, we consider it a
|
||||
// failure.
|
||||
//
|
||||
// We put the code for timing a test in a test fixture called
|
||||
// "QuickTest". QuickTest is intended to be the super fixture that
|
||||
// other fixtures derive from, therefore there is no test case with
|
||||
// the name "QuickTest". This is OK.
|
||||
//
|
||||
// Later, we will derive multiple test fixtures from QuickTest.
|
||||
class QuickTest : public testing::Test {
|
||||
protected:
|
||||
// Remember that SetUp() is run immediately before a test starts.
|
||||
// This is a good place to record the start time.
|
||||
void SetUp() override { start_time_ = time(nullptr); }
|
||||
|
||||
// TearDown() is invoked immediately after a test finishes. Here we
|
||||
// check if the test was too slow.
|
||||
void TearDown() override {
|
||||
// Gets the time when the test finishes
|
||||
const time_t end_time = time(nullptr);
|
||||
|
||||
// Asserts that the test took no more than ~5 seconds. Did you
|
||||
// know that you can use assertions in SetUp() and TearDown() as
|
||||
// well?
|
||||
EXPECT_TRUE(end_time - start_time_ <= 5) << "The test took too long.";
|
||||
}
|
||||
|
||||
// The UTC time (in seconds) when the test starts
|
||||
time_t start_time_;
|
||||
};
|
||||
|
||||
|
||||
// We derive a fixture named IntegerFunctionTest from the QuickTest
|
||||
// fixture. All tests using this fixture will be automatically
|
||||
// required to be quick.
|
||||
class IntegerFunctionTest : public QuickTest {
|
||||
// We don't need any more logic than already in the QuickTest fixture.
|
||||
// Therefore the body is empty.
|
||||
};
|
||||
|
||||
|
||||
// Now we can write tests in the IntegerFunctionTest test case.
|
||||
|
||||
// Tests Factorial()
|
||||
TEST_F(IntegerFunctionTest, Factorial) {
|
||||
// Tests factorial of negative numbers.
|
||||
EXPECT_EQ(1, Factorial(-5));
|
||||
EXPECT_EQ(1, Factorial(-1));
|
||||
EXPECT_GT(Factorial(-10), 0);
|
||||
|
||||
// Tests factorial of 0.
|
||||
EXPECT_EQ(1, Factorial(0));
|
||||
|
||||
// Tests factorial of positive numbers.
|
||||
EXPECT_EQ(1, Factorial(1));
|
||||
EXPECT_EQ(2, Factorial(2));
|
||||
EXPECT_EQ(6, Factorial(3));
|
||||
EXPECT_EQ(40320, Factorial(8));
|
||||
}
|
||||
|
||||
|
||||
// Tests IsPrime()
|
||||
TEST_F(IntegerFunctionTest, IsPrime) {
|
||||
// Tests negative input.
|
||||
EXPECT_FALSE(IsPrime(-1));
|
||||
EXPECT_FALSE(IsPrime(-2));
|
||||
EXPECT_FALSE(IsPrime(INT_MIN));
|
||||
|
||||
// Tests some trivial cases.
|
||||
EXPECT_FALSE(IsPrime(0));
|
||||
EXPECT_FALSE(IsPrime(1));
|
||||
EXPECT_TRUE(IsPrime(2));
|
||||
EXPECT_TRUE(IsPrime(3));
|
||||
|
||||
// Tests positive input.
|
||||
EXPECT_FALSE(IsPrime(4));
|
||||
EXPECT_TRUE(IsPrime(5));
|
||||
EXPECT_FALSE(IsPrime(6));
|
||||
EXPECT_TRUE(IsPrime(23));
|
||||
}
|
||||
|
||||
|
||||
// The next test case (named "QueueTest") also needs to be quick, so
|
||||
// we derive another fixture from QuickTest.
|
||||
//
|
||||
// The QueueTest test fixture has some logic and shared objects in
|
||||
// addition to what's in QuickTest already. We define the additional
|
||||
// stuff inside the body of the test fixture, as usual.
|
||||
class QueueTest : public QuickTest {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
// First, we need to set up the super fixture (QuickTest).
|
||||
QuickTest::SetUp();
|
||||
|
||||
// Second, some additional setup for this fixture.
|
||||
q1_.Enqueue(1);
|
||||
q2_.Enqueue(2);
|
||||
q2_.Enqueue(3);
|
||||
}
|
||||
|
||||
// By default, TearDown() inherits the behavior of
|
||||
// QuickTest::TearDown(). As we have no additional cleaning work
|
||||
// for QueueTest, we omit it here.
|
||||
//
|
||||
// virtual void TearDown() {
|
||||
// QuickTest::TearDown();
|
||||
// }
|
||||
|
||||
Queue<int> q0_;
|
||||
Queue<int> q1_;
|
||||
Queue<int> q2_;
|
||||
};
|
||||
|
||||
|
||||
// Now, let's write tests using the QueueTest fixture.
|
||||
|
||||
// Tests the default constructor.
|
||||
TEST_F(QueueTest, DefaultConstructor) {
|
||||
EXPECT_EQ(0u, q0_.Size());
|
||||
}
|
||||
|
||||
// Tests Dequeue().
|
||||
TEST_F(QueueTest, Dequeue) {
|
||||
int* n = q0_.Dequeue();
|
||||
EXPECT_TRUE(n == nullptr);
|
||||
|
||||
n = q1_.Dequeue();
|
||||
EXPECT_TRUE(n != nullptr);
|
||||
EXPECT_EQ(1, *n);
|
||||
EXPECT_EQ(0u, q1_.Size());
|
||||
delete n;
|
||||
|
||||
n = q2_.Dequeue();
|
||||
EXPECT_TRUE(n != nullptr);
|
||||
EXPECT_EQ(2, *n);
|
||||
EXPECT_EQ(1u, q2_.Size());
|
||||
delete n;
|
||||
}
|
||||
} // namespace
|
||||
// If necessary, you can derive further test fixtures from a derived
|
||||
// fixture itself. For example, you can derive another fixture from
|
||||
// QueueTest. Google Test imposes no limit on how deep the hierarchy
|
||||
// can be. In practice, however, you probably don't want it to be too
|
||||
// deep as to be confusing.
|
224
3rdparty/gtest/samples/sample6_unittest.cc
vendored
Normal file
224
3rdparty/gtest/samples/sample6_unittest.cc
vendored
Normal file
@ -0,0 +1,224 @@
|
||||
// Copyright 2008 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.
|
||||
|
||||
|
||||
// This sample shows how to test common properties of multiple
|
||||
// implementations of the same interface (aka interface tests).
|
||||
|
||||
// The interface and its implementations are in this header.
|
||||
#include "prime_tables.h"
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
namespace {
|
||||
// First, we define some factory functions for creating instances of
|
||||
// the implementations. You may be able to skip this step if all your
|
||||
// implementations can be constructed the same way.
|
||||
|
||||
template <class T>
|
||||
PrimeTable* CreatePrimeTable();
|
||||
|
||||
template <>
|
||||
PrimeTable* CreatePrimeTable<OnTheFlyPrimeTable>() {
|
||||
return new OnTheFlyPrimeTable;
|
||||
}
|
||||
|
||||
template <>
|
||||
PrimeTable* CreatePrimeTable<PreCalculatedPrimeTable>() {
|
||||
return new PreCalculatedPrimeTable(10000);
|
||||
}
|
||||
|
||||
// Then we define a test fixture class template.
|
||||
template <class T>
|
||||
class PrimeTableTest : public testing::Test {
|
||||
protected:
|
||||
// The ctor calls the factory function to create a prime table
|
||||
// implemented by T.
|
||||
PrimeTableTest() : table_(CreatePrimeTable<T>()) {}
|
||||
|
||||
~PrimeTableTest() override { delete table_; }
|
||||
|
||||
// Note that we test an implementation via the base interface
|
||||
// instead of the actual implementation class. This is important
|
||||
// for keeping the tests close to the real world scenario, where the
|
||||
// implementation is invoked via the base interface. It avoids
|
||||
// got-yas where the implementation class has a method that shadows
|
||||
// a method with the same name (but slightly different argument
|
||||
// types) in the base interface, for example.
|
||||
PrimeTable* const table_;
|
||||
};
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST
|
||||
|
||||
using testing::Types;
|
||||
|
||||
// Google Test offers two ways for reusing tests for different types.
|
||||
// The first is called "typed tests". You should use it if you
|
||||
// already know *all* the types you are gonna exercise when you write
|
||||
// the tests.
|
||||
|
||||
// To write a typed test case, first use
|
||||
//
|
||||
// TYPED_TEST_SUITE(TestCaseName, TypeList);
|
||||
//
|
||||
// to declare it and specify the type parameters. As with TEST_F,
|
||||
// TestCaseName must match the test fixture name.
|
||||
|
||||
// The list of types we want to test.
|
||||
typedef Types<OnTheFlyPrimeTable, PreCalculatedPrimeTable> Implementations;
|
||||
|
||||
TYPED_TEST_SUITE(PrimeTableTest, Implementations);
|
||||
|
||||
// Then use TYPED_TEST(TestCaseName, TestName) to define a typed test,
|
||||
// similar to TEST_F.
|
||||
TYPED_TEST(PrimeTableTest, ReturnsFalseForNonPrimes) {
|
||||
// Inside the test body, you can refer to the type parameter by
|
||||
// TypeParam, and refer to the fixture class by TestFixture. We
|
||||
// don't need them in this example.
|
||||
|
||||
// Since we are in the template world, C++ requires explicitly
|
||||
// writing 'this->' when referring to members of the fixture class.
|
||||
// This is something you have to learn to live with.
|
||||
EXPECT_FALSE(this->table_->IsPrime(-5));
|
||||
EXPECT_FALSE(this->table_->IsPrime(0));
|
||||
EXPECT_FALSE(this->table_->IsPrime(1));
|
||||
EXPECT_FALSE(this->table_->IsPrime(4));
|
||||
EXPECT_FALSE(this->table_->IsPrime(6));
|
||||
EXPECT_FALSE(this->table_->IsPrime(100));
|
||||
}
|
||||
|
||||
TYPED_TEST(PrimeTableTest, ReturnsTrueForPrimes) {
|
||||
EXPECT_TRUE(this->table_->IsPrime(2));
|
||||
EXPECT_TRUE(this->table_->IsPrime(3));
|
||||
EXPECT_TRUE(this->table_->IsPrime(5));
|
||||
EXPECT_TRUE(this->table_->IsPrime(7));
|
||||
EXPECT_TRUE(this->table_->IsPrime(11));
|
||||
EXPECT_TRUE(this->table_->IsPrime(131));
|
||||
}
|
||||
|
||||
TYPED_TEST(PrimeTableTest, CanGetNextPrime) {
|
||||
EXPECT_EQ(2, this->table_->GetNextPrime(0));
|
||||
EXPECT_EQ(3, this->table_->GetNextPrime(2));
|
||||
EXPECT_EQ(5, this->table_->GetNextPrime(3));
|
||||
EXPECT_EQ(7, this->table_->GetNextPrime(5));
|
||||
EXPECT_EQ(11, this->table_->GetNextPrime(7));
|
||||
EXPECT_EQ(131, this->table_->GetNextPrime(128));
|
||||
}
|
||||
|
||||
// That's it! Google Test will repeat each TYPED_TEST for each type
|
||||
// in the type list specified in TYPED_TEST_SUITE. Sit back and be
|
||||
// happy that you don't have to define them multiple times.
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
using testing::Types;
|
||||
|
||||
// Sometimes, however, you don't yet know all the types that you want
|
||||
// to test when you write the tests. For example, if you are the
|
||||
// author of an interface and expect other people to implement it, you
|
||||
// might want to write a set of tests to make sure each implementation
|
||||
// conforms to some basic requirements, but you don't know what
|
||||
// implementations will be written in the future.
|
||||
//
|
||||
// How can you write the tests without committing to the type
|
||||
// parameters? That's what "type-parameterized tests" can do for you.
|
||||
// It is a bit more involved than typed tests, but in return you get a
|
||||
// test pattern that can be reused in many contexts, which is a big
|
||||
// win. Here's how you do it:
|
||||
|
||||
// First, define a test fixture class template. Here we just reuse
|
||||
// the PrimeTableTest fixture defined earlier:
|
||||
|
||||
template <class T>
|
||||
class PrimeTableTest2 : public PrimeTableTest<T> {
|
||||
};
|
||||
|
||||
// Then, declare the test case. The argument is the name of the test
|
||||
// fixture, and also the name of the test case (as usual). The _P
|
||||
// suffix is for "parameterized" or "pattern".
|
||||
TYPED_TEST_SUITE_P(PrimeTableTest2);
|
||||
|
||||
// Next, use TYPED_TEST_P(TestCaseName, TestName) to define a test,
|
||||
// similar to what you do with TEST_F.
|
||||
TYPED_TEST_P(PrimeTableTest2, ReturnsFalseForNonPrimes) {
|
||||
EXPECT_FALSE(this->table_->IsPrime(-5));
|
||||
EXPECT_FALSE(this->table_->IsPrime(0));
|
||||
EXPECT_FALSE(this->table_->IsPrime(1));
|
||||
EXPECT_FALSE(this->table_->IsPrime(4));
|
||||
EXPECT_FALSE(this->table_->IsPrime(6));
|
||||
EXPECT_FALSE(this->table_->IsPrime(100));
|
||||
}
|
||||
|
||||
TYPED_TEST_P(PrimeTableTest2, ReturnsTrueForPrimes) {
|
||||
EXPECT_TRUE(this->table_->IsPrime(2));
|
||||
EXPECT_TRUE(this->table_->IsPrime(3));
|
||||
EXPECT_TRUE(this->table_->IsPrime(5));
|
||||
EXPECT_TRUE(this->table_->IsPrime(7));
|
||||
EXPECT_TRUE(this->table_->IsPrime(11));
|
||||
EXPECT_TRUE(this->table_->IsPrime(131));
|
||||
}
|
||||
|
||||
TYPED_TEST_P(PrimeTableTest2, CanGetNextPrime) {
|
||||
EXPECT_EQ(2, this->table_->GetNextPrime(0));
|
||||
EXPECT_EQ(3, this->table_->GetNextPrime(2));
|
||||
EXPECT_EQ(5, this->table_->GetNextPrime(3));
|
||||
EXPECT_EQ(7, this->table_->GetNextPrime(5));
|
||||
EXPECT_EQ(11, this->table_->GetNextPrime(7));
|
||||
EXPECT_EQ(131, this->table_->GetNextPrime(128));
|
||||
}
|
||||
|
||||
// Type-parameterized tests involve one extra step: you have to
|
||||
// enumerate the tests you defined:
|
||||
REGISTER_TYPED_TEST_SUITE_P(
|
||||
PrimeTableTest2, // The first argument is the test case name.
|
||||
// The rest of the arguments are the test names.
|
||||
ReturnsFalseForNonPrimes, ReturnsTrueForPrimes, CanGetNextPrime);
|
||||
|
||||
// At this point the test pattern is done. However, you don't have
|
||||
// any real test yet as you haven't said which types you want to run
|
||||
// the tests with.
|
||||
|
||||
// To turn the abstract test pattern into real tests, you instantiate
|
||||
// it with a list of types. Usually the test pattern will be defined
|
||||
// in a .h file, and anyone can #include and instantiate it. You can
|
||||
// even instantiate it more than once in the same program. To tell
|
||||
// different instances apart, you give each of them a name, which will
|
||||
// become part of the test case name and can be used in test filters.
|
||||
|
||||
// The list of types we want to test. Note that it doesn't have to be
|
||||
// defined at the time we write the TYPED_TEST_P()s.
|
||||
typedef Types<OnTheFlyPrimeTable, PreCalculatedPrimeTable>
|
||||
PrimeTableImplementations;
|
||||
INSTANTIATE_TYPED_TEST_SUITE_P(OnTheFlyAndPreCalculated, // Instance name
|
||||
PrimeTableTest2, // Test case name
|
||||
PrimeTableImplementations); // Type list
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST_P
|
||||
} // namespace
|
117
3rdparty/gtest/samples/sample7_unittest.cc
vendored
Normal file
117
3rdparty/gtest/samples/sample7_unittest.cc
vendored
Normal file
@ -0,0 +1,117 @@
|
||||
// Copyright 2008 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.
|
||||
|
||||
|
||||
// This sample shows how to test common properties of multiple
|
||||
// implementations of an interface (aka interface tests) using
|
||||
// value-parameterized tests. Each test in the test case has
|
||||
// a parameter that is an interface pointer to an implementation
|
||||
// tested.
|
||||
|
||||
// The interface and its implementations are in this header.
|
||||
#include "prime_tables.h"
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
namespace {
|
||||
|
||||
using ::testing::TestWithParam;
|
||||
using ::testing::Values;
|
||||
|
||||
// As a general rule, to prevent a test from affecting the tests that come
|
||||
// after it, you should create and destroy the tested objects for each test
|
||||
// instead of reusing them. In this sample we will define a simple factory
|
||||
// function for PrimeTable objects. We will instantiate objects in test's
|
||||
// SetUp() method and delete them in TearDown() method.
|
||||
typedef PrimeTable* CreatePrimeTableFunc();
|
||||
|
||||
PrimeTable* CreateOnTheFlyPrimeTable() {
|
||||
return new OnTheFlyPrimeTable();
|
||||
}
|
||||
|
||||
template <size_t max_precalculated>
|
||||
PrimeTable* CreatePreCalculatedPrimeTable() {
|
||||
return new PreCalculatedPrimeTable(max_precalculated);
|
||||
}
|
||||
|
||||
// Inside the test body, fixture constructor, SetUp(), and TearDown() you
|
||||
// can refer to the test parameter by GetParam(). In this case, the test
|
||||
// parameter is a factory function which we call in fixture's SetUp() to
|
||||
// create and store an instance of PrimeTable.
|
||||
class PrimeTableTestSmpl7 : public TestWithParam<CreatePrimeTableFunc*> {
|
||||
public:
|
||||
~PrimeTableTestSmpl7() override { delete table_; }
|
||||
void SetUp() override { table_ = (*GetParam())(); }
|
||||
void TearDown() override {
|
||||
delete table_;
|
||||
table_ = nullptr;
|
||||
}
|
||||
|
||||
protected:
|
||||
PrimeTable* table_;
|
||||
};
|
||||
|
||||
TEST_P(PrimeTableTestSmpl7, ReturnsFalseForNonPrimes) {
|
||||
EXPECT_FALSE(table_->IsPrime(-5));
|
||||
EXPECT_FALSE(table_->IsPrime(0));
|
||||
EXPECT_FALSE(table_->IsPrime(1));
|
||||
EXPECT_FALSE(table_->IsPrime(4));
|
||||
EXPECT_FALSE(table_->IsPrime(6));
|
||||
EXPECT_FALSE(table_->IsPrime(100));
|
||||
}
|
||||
|
||||
TEST_P(PrimeTableTestSmpl7, ReturnsTrueForPrimes) {
|
||||
EXPECT_TRUE(table_->IsPrime(2));
|
||||
EXPECT_TRUE(table_->IsPrime(3));
|
||||
EXPECT_TRUE(table_->IsPrime(5));
|
||||
EXPECT_TRUE(table_->IsPrime(7));
|
||||
EXPECT_TRUE(table_->IsPrime(11));
|
||||
EXPECT_TRUE(table_->IsPrime(131));
|
||||
}
|
||||
|
||||
TEST_P(PrimeTableTestSmpl7, CanGetNextPrime) {
|
||||
EXPECT_EQ(2, table_->GetNextPrime(0));
|
||||
EXPECT_EQ(3, table_->GetNextPrime(2));
|
||||
EXPECT_EQ(5, table_->GetNextPrime(3));
|
||||
EXPECT_EQ(7, table_->GetNextPrime(5));
|
||||
EXPECT_EQ(11, table_->GetNextPrime(7));
|
||||
EXPECT_EQ(131, table_->GetNextPrime(128));
|
||||
}
|
||||
|
||||
// In order to run value-parameterized tests, you need to instantiate them,
|
||||
// or bind them to a list of values which will be used as test parameters.
|
||||
// You can instantiate them in a different translation module, or even
|
||||
// instantiate them several times.
|
||||
//
|
||||
// Here, we instantiate our tests with a list of two PrimeTable object
|
||||
// factory functions:
|
||||
INSTANTIATE_TEST_SUITE_P(OnTheFlyAndPreCalculated, PrimeTableTestSmpl7,
|
||||
Values(&CreateOnTheFlyPrimeTable,
|
||||
&CreatePreCalculatedPrimeTable<1000>));
|
||||
|
||||
} // namespace
|
154
3rdparty/gtest/samples/sample8_unittest.cc
vendored
Normal file
154
3rdparty/gtest/samples/sample8_unittest.cc
vendored
Normal file
@ -0,0 +1,154 @@
|
||||
// Copyright 2008 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.
|
||||
|
||||
|
||||
// This sample shows how to test code relying on some global flag variables.
|
||||
// Combine() helps with generating all possible combinations of such flags,
|
||||
// and each test is given one combination as a parameter.
|
||||
|
||||
// Use class definitions to test from this header.
|
||||
#include "prime_tables.h"
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
namespace {
|
||||
|
||||
// Suppose we want to introduce a new, improved implementation of PrimeTable
|
||||
// which combines speed of PrecalcPrimeTable and versatility of
|
||||
// OnTheFlyPrimeTable (see prime_tables.h). Inside it instantiates both
|
||||
// PrecalcPrimeTable and OnTheFlyPrimeTable and uses the one that is more
|
||||
// appropriate under the circumstances. But in low memory conditions, it can be
|
||||
// told to instantiate without PrecalcPrimeTable instance at all and use only
|
||||
// OnTheFlyPrimeTable.
|
||||
class HybridPrimeTable : public PrimeTable {
|
||||
public:
|
||||
HybridPrimeTable(bool force_on_the_fly, int max_precalculated)
|
||||
: on_the_fly_impl_(new OnTheFlyPrimeTable),
|
||||
precalc_impl_(force_on_the_fly
|
||||
? nullptr
|
||||
: new PreCalculatedPrimeTable(max_precalculated)),
|
||||
max_precalculated_(max_precalculated) {}
|
||||
~HybridPrimeTable() override {
|
||||
delete on_the_fly_impl_;
|
||||
delete precalc_impl_;
|
||||
}
|
||||
|
||||
bool IsPrime(int n) const override {
|
||||
if (precalc_impl_ != nullptr && n < max_precalculated_)
|
||||
return precalc_impl_->IsPrime(n);
|
||||
else
|
||||
return on_the_fly_impl_->IsPrime(n);
|
||||
}
|
||||
|
||||
int GetNextPrime(int p) const override {
|
||||
int next_prime = -1;
|
||||
if (precalc_impl_ != nullptr && p < max_precalculated_)
|
||||
next_prime = precalc_impl_->GetNextPrime(p);
|
||||
|
||||
return next_prime != -1 ? next_prime : on_the_fly_impl_->GetNextPrime(p);
|
||||
}
|
||||
|
||||
private:
|
||||
OnTheFlyPrimeTable* on_the_fly_impl_;
|
||||
PreCalculatedPrimeTable* precalc_impl_;
|
||||
int max_precalculated_;
|
||||
};
|
||||
|
||||
using ::testing::TestWithParam;
|
||||
using ::testing::Bool;
|
||||
using ::testing::Values;
|
||||
using ::testing::Combine;
|
||||
|
||||
// To test all code paths for HybridPrimeTable we must test it with numbers
|
||||
// both within and outside PreCalculatedPrimeTable's capacity and also with
|
||||
// PreCalculatedPrimeTable disabled. We do this by defining fixture which will
|
||||
// accept different combinations of parameters for instantiating a
|
||||
// HybridPrimeTable instance.
|
||||
class PrimeTableTest : public TestWithParam< ::std::tuple<bool, int> > {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
bool force_on_the_fly;
|
||||
int max_precalculated;
|
||||
std::tie(force_on_the_fly, max_precalculated) = GetParam();
|
||||
table_ = new HybridPrimeTable(force_on_the_fly, max_precalculated);
|
||||
}
|
||||
void TearDown() override {
|
||||
delete table_;
|
||||
table_ = nullptr;
|
||||
}
|
||||
HybridPrimeTable* table_;
|
||||
};
|
||||
|
||||
TEST_P(PrimeTableTest, ReturnsFalseForNonPrimes) {
|
||||
// Inside the test body, you can refer to the test parameter by GetParam().
|
||||
// In this case, the test parameter is a PrimeTable interface pointer which
|
||||
// we can use directly.
|
||||
// Please note that you can also save it in the fixture's SetUp() method
|
||||
// or constructor and use saved copy in the tests.
|
||||
|
||||
EXPECT_FALSE(table_->IsPrime(-5));
|
||||
EXPECT_FALSE(table_->IsPrime(0));
|
||||
EXPECT_FALSE(table_->IsPrime(1));
|
||||
EXPECT_FALSE(table_->IsPrime(4));
|
||||
EXPECT_FALSE(table_->IsPrime(6));
|
||||
EXPECT_FALSE(table_->IsPrime(100));
|
||||
}
|
||||
|
||||
TEST_P(PrimeTableTest, ReturnsTrueForPrimes) {
|
||||
EXPECT_TRUE(table_->IsPrime(2));
|
||||
EXPECT_TRUE(table_->IsPrime(3));
|
||||
EXPECT_TRUE(table_->IsPrime(5));
|
||||
EXPECT_TRUE(table_->IsPrime(7));
|
||||
EXPECT_TRUE(table_->IsPrime(11));
|
||||
EXPECT_TRUE(table_->IsPrime(131));
|
||||
}
|
||||
|
||||
TEST_P(PrimeTableTest, CanGetNextPrime) {
|
||||
EXPECT_EQ(2, table_->GetNextPrime(0));
|
||||
EXPECT_EQ(3, table_->GetNextPrime(2));
|
||||
EXPECT_EQ(5, table_->GetNextPrime(3));
|
||||
EXPECT_EQ(7, table_->GetNextPrime(5));
|
||||
EXPECT_EQ(11, table_->GetNextPrime(7));
|
||||
EXPECT_EQ(131, table_->GetNextPrime(128));
|
||||
}
|
||||
|
||||
// In order to run value-parameterized tests, you need to instantiate them,
|
||||
// or bind them to a list of values which will be used as test parameters.
|
||||
// You can instantiate them in a different translation module, or even
|
||||
// instantiate them several times.
|
||||
//
|
||||
// Here, we instantiate our tests with a list of parameters. We must combine
|
||||
// all variations of the boolean flag suppressing PrecalcPrimeTable and some
|
||||
// meaningful values for tests. We choose a small value (1), and a value that
|
||||
// will put some of the tested numbers beyond the capability of the
|
||||
// PrecalcPrimeTable instance and some inside it (10). Combine will produce all
|
||||
// possible combinations.
|
||||
INSTANTIATE_TEST_SUITE_P(MeaningfulTestParameters, PrimeTableTest,
|
||||
Combine(Bool(), Values(1, 10)));
|
||||
|
||||
} // namespace
|
156
3rdparty/gtest/samples/sample9_unittest.cc
vendored
Normal file
156
3rdparty/gtest/samples/sample9_unittest.cc
vendored
Normal file
@ -0,0 +1,156 @@
|
||||
// Copyright 2009 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.
|
||||
|
||||
|
||||
// This sample shows how to use Google Test listener API to implement
|
||||
// an alternative console output and how to use the UnitTest reflection API
|
||||
// to enumerate test cases and tests and to inspect their results.
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
using ::testing::EmptyTestEventListener;
|
||||
using ::testing::InitGoogleTest;
|
||||
using ::testing::Test;
|
||||
using ::testing::TestCase;
|
||||
using ::testing::TestEventListeners;
|
||||
using ::testing::TestInfo;
|
||||
using ::testing::TestPartResult;
|
||||
using ::testing::UnitTest;
|
||||
namespace {
|
||||
// Provides alternative output mode which produces minimal amount of
|
||||
// information about tests.
|
||||
class TersePrinter : public EmptyTestEventListener {
|
||||
private:
|
||||
// Called before any test activity starts.
|
||||
void OnTestProgramStart(const UnitTest& /* unit_test */) override {}
|
||||
|
||||
// Called after all test activities have ended.
|
||||
void OnTestProgramEnd(const UnitTest& unit_test) override {
|
||||
fprintf(stdout, "TEST %s\n", unit_test.Passed() ? "PASSED" : "FAILED");
|
||||
fflush(stdout);
|
||||
}
|
||||
|
||||
// Called before a test starts.
|
||||
void OnTestStart(const TestInfo& test_info) override {
|
||||
fprintf(stdout,
|
||||
"*** Test %s.%s starting.\n",
|
||||
test_info.test_case_name(),
|
||||
test_info.name());
|
||||
fflush(stdout);
|
||||
}
|
||||
|
||||
// Called after a failed assertion or a SUCCEED() invocation.
|
||||
void OnTestPartResult(const TestPartResult& test_part_result) override {
|
||||
fprintf(stdout,
|
||||
"%s in %s:%d\n%s\n",
|
||||
test_part_result.failed() ? "*** Failure" : "Success",
|
||||
test_part_result.file_name(),
|
||||
test_part_result.line_number(),
|
||||
test_part_result.summary());
|
||||
fflush(stdout);
|
||||
}
|
||||
|
||||
// Called after a test ends.
|
||||
void OnTestEnd(const TestInfo& test_info) override {
|
||||
fprintf(stdout,
|
||||
"*** Test %s.%s ending.\n",
|
||||
test_info.test_case_name(),
|
||||
test_info.name());
|
||||
fflush(stdout);
|
||||
}
|
||||
}; // class TersePrinter
|
||||
|
||||
TEST(CustomOutputTest, PrintsMessage) {
|
||||
printf("Printing something from the test body...\n");
|
||||
}
|
||||
|
||||
TEST(CustomOutputTest, Succeeds) {
|
||||
SUCCEED() << "SUCCEED() has been invoked from here";
|
||||
}
|
||||
|
||||
TEST(CustomOutputTest, Fails) {
|
||||
EXPECT_EQ(1, 2)
|
||||
<< "This test fails in order to demonstrate alternative failure messages";
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
InitGoogleTest(&argc, argv);
|
||||
|
||||
bool terse_output = false;
|
||||
if (argc > 1 && strcmp(argv[1], "--terse_output") == 0 )
|
||||
terse_output = true;
|
||||
else
|
||||
printf("%s\n", "Run this program with --terse_output to change the way "
|
||||
"it prints its output.");
|
||||
|
||||
UnitTest& unit_test = *UnitTest::GetInstance();
|
||||
|
||||
// If we are given the --terse_output command line flag, suppresses the
|
||||
// standard output and attaches own result printer.
|
||||
if (terse_output) {
|
||||
TestEventListeners& listeners = unit_test.listeners();
|
||||
|
||||
// Removes the default console output listener from the list so it will
|
||||
// not receive events from Google Test and won't print any output. Since
|
||||
// this operation transfers ownership of the listener to the caller we
|
||||
// have to delete it as well.
|
||||
delete listeners.Release(listeners.default_result_printer());
|
||||
|
||||
// Adds the custom output listener to the list. It will now receive
|
||||
// events from Google Test and print the alternative output. We don't
|
||||
// have to worry about deleting it since Google Test assumes ownership
|
||||
// over it after adding it to the list.
|
||||
listeners.Append(new TersePrinter);
|
||||
}
|
||||
int ret_val = RUN_ALL_TESTS();
|
||||
|
||||
// This is an example of using the UnitTest reflection API to inspect test
|
||||
// results. Here we discount failures from the tests we expected to fail.
|
||||
int unexpectedly_failed_tests = 0;
|
||||
for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
|
||||
const testing::TestSuite& test_suite = *unit_test.GetTestSuite(i);
|
||||
for (int j = 0; j < test_suite.total_test_count(); ++j) {
|
||||
const TestInfo& test_info = *test_suite.GetTestInfo(j);
|
||||
// Counts failed tests that were not meant to fail (those without
|
||||
// 'Fails' in the name).
|
||||
if (test_info.result()->Failed() &&
|
||||
strcmp(test_info.name(), "Fails") != 0) {
|
||||
unexpectedly_failed_tests++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Test that were meant to fail should not affect the test program outcome.
|
||||
if (unexpectedly_failed_tests == 0)
|
||||
ret_val = 0;
|
||||
|
||||
return ret_val;
|
||||
}
|
83
3rdparty/gtest/scripts/common.py
vendored
Normal file
83
3rdparty/gtest/scripts/common.py
vendored
Normal file
@ -0,0 +1,83 @@
|
||||
# Copyright 2013 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.
|
||||
|
||||
"""Shared utilities for writing scripts for Google Test/Mock."""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
|
||||
# Matches the line from 'svn info .' output that describes what SVN
|
||||
# path the current local directory corresponds to. For example, in
|
||||
# a googletest SVN workspace's trunk/test directory, the output will be:
|
||||
#
|
||||
# URL: https://googletest.googlecode.com/svn/trunk/test
|
||||
_SVN_INFO_URL_RE = re.compile(r'^URL: https://(\w+)\.googlecode\.com/svn(.*)')
|
||||
|
||||
|
||||
def GetCommandOutput(command):
|
||||
"""Runs the shell command and returns its stdout as a list of lines."""
|
||||
|
||||
f = os.popen(command, 'r')
|
||||
lines = [line.strip() for line in f.readlines()]
|
||||
f.close()
|
||||
return lines
|
||||
|
||||
|
||||
def GetSvnInfo():
|
||||
"""Returns the project name and the current SVN workspace's root path."""
|
||||
|
||||
for line in GetCommandOutput('svn info .'):
|
||||
m = _SVN_INFO_URL_RE.match(line)
|
||||
if m:
|
||||
project = m.group(1) # googletest or googlemock
|
||||
rel_path = m.group(2)
|
||||
root = os.path.realpath(rel_path.count('/') * '../')
|
||||
return project, root
|
||||
|
||||
return None, None
|
||||
|
||||
|
||||
def GetSvnTrunk():
|
||||
"""Returns the current SVN workspace's trunk root path."""
|
||||
|
||||
_, root = GetSvnInfo()
|
||||
return root + '/trunk' if root else None
|
||||
|
||||
|
||||
def IsInGTestSvn():
|
||||
project, _ = GetSvnInfo()
|
||||
return project == 'googletest'
|
||||
|
||||
|
||||
def IsInGMockSvn():
|
||||
project, _ = GetSvnInfo()
|
||||
return project == 'googlemock'
|
253
3rdparty/gtest/scripts/fuse_gtest_files.py
vendored
Normal file
253
3rdparty/gtest/scripts/fuse_gtest_files.py
vendored
Normal file
@ -0,0 +1,253 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2009, 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.
|
||||
|
||||
"""fuse_gtest_files.py v0.2.0
|
||||
Fuses Google Test source code into a .h file and a .cc file.
|
||||
|
||||
SYNOPSIS
|
||||
fuse_gtest_files.py [GTEST_ROOT_DIR] OUTPUT_DIR
|
||||
|
||||
Scans GTEST_ROOT_DIR for Google Test source code, and generates
|
||||
two files: OUTPUT_DIR/gtest/gtest.h and OUTPUT_DIR/gtest/gtest-all.cc.
|
||||
Then you can build your tests by adding OUTPUT_DIR to the include
|
||||
search path and linking with OUTPUT_DIR/gtest/gtest-all.cc. These
|
||||
two files contain everything you need to use Google Test. Hence
|
||||
you can "install" Google Test by copying them to wherever you want.
|
||||
|
||||
GTEST_ROOT_DIR can be omitted and defaults to the parent
|
||||
directory of the directory holding this script.
|
||||
|
||||
EXAMPLES
|
||||
./fuse_gtest_files.py fused_gtest
|
||||
./fuse_gtest_files.py path/to/unpacked/gtest fused_gtest
|
||||
|
||||
This tool is experimental. In particular, it assumes that there is no
|
||||
conditional inclusion of Google Test headers. Please report any
|
||||
problems to googletestframework@googlegroups.com. You can read
|
||||
https://github.com/google/googletest/blob/master/googletest/docs/advanced.md for
|
||||
more information.
|
||||
"""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import re
|
||||
try:
|
||||
from sets import Set as set # For Python 2.3 compatibility
|
||||
except ImportError:
|
||||
pass
|
||||
import sys
|
||||
|
||||
# We assume that this file is in the scripts/ directory in the Google
|
||||
# Test root directory.
|
||||
DEFAULT_GTEST_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
|
||||
|
||||
# Regex for matching '#include "gtest/..."'.
|
||||
INCLUDE_GTEST_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(gtest/.+)"')
|
||||
|
||||
# Regex for matching '#include "src/..."'.
|
||||
INCLUDE_SRC_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(src/.+)"')
|
||||
|
||||
# Where to find the source seed files.
|
||||
GTEST_H_SEED = 'include/gtest/gtest.h'
|
||||
GTEST_SPI_H_SEED = 'include/gtest/gtest-spi.h'
|
||||
GTEST_ALL_CC_SEED = 'src/gtest-all.cc'
|
||||
|
||||
# Where to put the generated files.
|
||||
GTEST_H_OUTPUT = 'gtest/gtest.h'
|
||||
GTEST_ALL_CC_OUTPUT = 'gtest/gtest-all.cc'
|
||||
|
||||
|
||||
def VerifyFileExists(directory, relative_path):
|
||||
"""Verifies that the given file exists; aborts on failure.
|
||||
|
||||
relative_path is the file path relative to the given directory.
|
||||
"""
|
||||
|
||||
if not os.path.isfile(os.path.join(directory, relative_path)):
|
||||
print('ERROR: Cannot find %s in directory %s.' % (relative_path,
|
||||
directory))
|
||||
print('Please either specify a valid project root directory '
|
||||
'or omit it on the command line.')
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def ValidateGTestRootDir(gtest_root):
|
||||
"""Makes sure gtest_root points to a valid gtest root directory.
|
||||
|
||||
The function aborts the program on failure.
|
||||
"""
|
||||
|
||||
VerifyFileExists(gtest_root, GTEST_H_SEED)
|
||||
VerifyFileExists(gtest_root, GTEST_ALL_CC_SEED)
|
||||
|
||||
|
||||
def VerifyOutputFile(output_dir, relative_path):
|
||||
"""Verifies that the given output file path is valid.
|
||||
|
||||
relative_path is relative to the output_dir directory.
|
||||
"""
|
||||
|
||||
# Makes sure the output file either doesn't exist or can be overwritten.
|
||||
output_file = os.path.join(output_dir, relative_path)
|
||||
if os.path.exists(output_file):
|
||||
# TODO(wan@google.com): The following user-interaction doesn't
|
||||
# work with automated processes. We should provide a way for the
|
||||
# Makefile to force overwriting the files.
|
||||
print('%s already exists in directory %s - overwrite it? (y/N) ' %
|
||||
(relative_path, output_dir))
|
||||
answer = sys.stdin.readline().strip()
|
||||
if answer not in ['y', 'Y']:
|
||||
print('ABORTED.')
|
||||
sys.exit(1)
|
||||
|
||||
# Makes sure the directory holding the output file exists; creates
|
||||
# it and all its ancestors if necessary.
|
||||
parent_directory = os.path.dirname(output_file)
|
||||
if not os.path.isdir(parent_directory):
|
||||
os.makedirs(parent_directory)
|
||||
|
||||
|
||||
def ValidateOutputDir(output_dir):
|
||||
"""Makes sure output_dir points to a valid output directory.
|
||||
|
||||
The function aborts the program on failure.
|
||||
"""
|
||||
|
||||
VerifyOutputFile(output_dir, GTEST_H_OUTPUT)
|
||||
VerifyOutputFile(output_dir, GTEST_ALL_CC_OUTPUT)
|
||||
|
||||
|
||||
def FuseGTestH(gtest_root, output_dir):
|
||||
"""Scans folder gtest_root to generate gtest/gtest.h in output_dir."""
|
||||
|
||||
output_file = open(os.path.join(output_dir, GTEST_H_OUTPUT), 'w')
|
||||
processed_files = set() # Holds all gtest headers we've processed.
|
||||
|
||||
def ProcessFile(gtest_header_path):
|
||||
"""Processes the given gtest header file."""
|
||||
|
||||
# We don't process the same header twice.
|
||||
if gtest_header_path in processed_files:
|
||||
return
|
||||
|
||||
processed_files.add(gtest_header_path)
|
||||
|
||||
# Reads each line in the given gtest header.
|
||||
for line in open(os.path.join(gtest_root, gtest_header_path), 'r'):
|
||||
m = INCLUDE_GTEST_FILE_REGEX.match(line)
|
||||
if m:
|
||||
# It's '#include "gtest/..."' - let's process it recursively.
|
||||
ProcessFile('include/' + m.group(1))
|
||||
else:
|
||||
# Otherwise we copy the line unchanged to the output file.
|
||||
output_file.write(line)
|
||||
|
||||
ProcessFile(GTEST_H_SEED)
|
||||
output_file.close()
|
||||
|
||||
|
||||
def FuseGTestAllCcToFile(gtest_root, output_file):
|
||||
"""Scans folder gtest_root to generate gtest/gtest-all.cc in output_file."""
|
||||
|
||||
processed_files = set()
|
||||
|
||||
def ProcessFile(gtest_source_file):
|
||||
"""Processes the given gtest source file."""
|
||||
|
||||
# We don't process the same #included file twice.
|
||||
if gtest_source_file in processed_files:
|
||||
return
|
||||
|
||||
processed_files.add(gtest_source_file)
|
||||
|
||||
# Reads each line in the given gtest source file.
|
||||
for line in open(os.path.join(gtest_root, gtest_source_file), 'r'):
|
||||
m = INCLUDE_GTEST_FILE_REGEX.match(line)
|
||||
if m:
|
||||
if 'include/' + m.group(1) == GTEST_SPI_H_SEED:
|
||||
# It's '#include "gtest/gtest-spi.h"'. This file is not
|
||||
# #included by "gtest/gtest.h", so we need to process it.
|
||||
ProcessFile(GTEST_SPI_H_SEED)
|
||||
else:
|
||||
# It's '#include "gtest/foo.h"' where foo is not gtest-spi.
|
||||
# We treat it as '#include "gtest/gtest.h"', as all other
|
||||
# gtest headers are being fused into gtest.h and cannot be
|
||||
# #included directly.
|
||||
|
||||
# There is no need to #include "gtest/gtest.h" more than once.
|
||||
if not GTEST_H_SEED in processed_files:
|
||||
processed_files.add(GTEST_H_SEED)
|
||||
output_file.write('#include "%s"\n' % (GTEST_H_OUTPUT,))
|
||||
else:
|
||||
m = INCLUDE_SRC_FILE_REGEX.match(line)
|
||||
if m:
|
||||
# It's '#include "src/foo"' - let's process it recursively.
|
||||
ProcessFile(m.group(1))
|
||||
else:
|
||||
output_file.write(line)
|
||||
|
||||
ProcessFile(GTEST_ALL_CC_SEED)
|
||||
|
||||
|
||||
def FuseGTestAllCc(gtest_root, output_dir):
|
||||
"""Scans folder gtest_root to generate gtest/gtest-all.cc in output_dir."""
|
||||
|
||||
output_file = open(os.path.join(output_dir, GTEST_ALL_CC_OUTPUT), 'w')
|
||||
FuseGTestAllCcToFile(gtest_root, output_file)
|
||||
output_file.close()
|
||||
|
||||
|
||||
def FuseGTest(gtest_root, output_dir):
|
||||
"""Fuses gtest.h and gtest-all.cc."""
|
||||
|
||||
ValidateGTestRootDir(gtest_root)
|
||||
ValidateOutputDir(output_dir)
|
||||
|
||||
FuseGTestH(gtest_root, output_dir)
|
||||
FuseGTestAllCc(gtest_root, output_dir)
|
||||
|
||||
|
||||
def main():
|
||||
argc = len(sys.argv)
|
||||
if argc == 2:
|
||||
# fuse_gtest_files.py OUTPUT_DIR
|
||||
FuseGTest(DEFAULT_GTEST_ROOT_DIR, sys.argv[1])
|
||||
elif argc == 3:
|
||||
# fuse_gtest_files.py GTEST_ROOT_DIR OUTPUT_DIR
|
||||
FuseGTest(sys.argv[1], sys.argv[2])
|
||||
else:
|
||||
print(__doc__)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
730
3rdparty/gtest/scripts/gen_gtest_pred_impl.py
vendored
Normal file
730
3rdparty/gtest/scripts/gen_gtest_pred_impl.py
vendored
Normal file
@ -0,0 +1,730 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2006, 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.
|
||||
|
||||
"""gen_gtest_pred_impl.py v0.1
|
||||
|
||||
Generates the implementation of Google Test predicate assertions and
|
||||
accompanying tests.
|
||||
|
||||
Usage:
|
||||
|
||||
gen_gtest_pred_impl.py MAX_ARITY
|
||||
|
||||
where MAX_ARITY is a positive integer.
|
||||
|
||||
The command generates the implementation of up-to MAX_ARITY-ary
|
||||
predicate assertions, and writes it to file gtest_pred_impl.h in the
|
||||
directory where the script is. It also generates the accompanying
|
||||
unit test in file gtest_pred_impl_unittest.cc.
|
||||
"""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
# Where this script is.
|
||||
SCRIPT_DIR = os.path.dirname(sys.argv[0])
|
||||
|
||||
# Where to store the generated header.
|
||||
HEADER = os.path.join(SCRIPT_DIR, '../include/gtest/gtest_pred_impl.h')
|
||||
|
||||
# Where to store the generated unit test.
|
||||
UNIT_TEST = os.path.join(SCRIPT_DIR, '../test/gtest_pred_impl_unittest.cc')
|
||||
|
||||
|
||||
def HeaderPreamble(n):
|
||||
"""Returns the preamble for the header file.
|
||||
|
||||
Args:
|
||||
n: the maximum arity of the predicate macros to be generated.
|
||||
"""
|
||||
|
||||
# A map that defines the values used in the preamble template.
|
||||
DEFS = {
|
||||
'today' : time.strftime('%m/%d/%Y'),
|
||||
'year' : time.strftime('%Y'),
|
||||
'command' : '%s %s' % (os.path.basename(sys.argv[0]), n),
|
||||
'n' : n
|
||||
}
|
||||
|
||||
return (
|
||||
"""// Copyright 2006, 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.
|
||||
|
||||
// This file is AUTOMATICALLY GENERATED on %(today)s by command
|
||||
// '%(command)s'. DO NOT EDIT BY HAND!
|
||||
//
|
||||
// Implements a family of generic predicate assertion macros.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace testing {
|
||||
|
||||
// This header implements a family of generic predicate assertion
|
||||
// macros:
|
||||
//
|
||||
// ASSERT_PRED_FORMAT1(pred_format, v1)
|
||||
// ASSERT_PRED_FORMAT2(pred_format, v1, v2)
|
||||
// ...
|
||||
//
|
||||
// where pred_format is a function or functor that takes n (in the
|
||||
// case of ASSERT_PRED_FORMATn) values and their source expression
|
||||
// text, and returns a testing::AssertionResult. See the definition
|
||||
// of ASSERT_EQ in gtest.h for an example.
|
||||
//
|
||||
// If you don't care about formatting, you can use the more
|
||||
// restrictive version:
|
||||
//
|
||||
// ASSERT_PRED1(pred, v1)
|
||||
// ASSERT_PRED2(pred, v1, v2)
|
||||
// ...
|
||||
//
|
||||
// where pred is an n-ary function or functor that returns bool,
|
||||
// and the values v1, v2, ..., must support the << operator for
|
||||
// streaming to std::ostream.
|
||||
//
|
||||
// We also define the EXPECT_* variations.
|
||||
//
|
||||
// For now we only support predicates whose arity is at most %(n)s.
|
||||
// Please email googletestframework@googlegroups.com if you need
|
||||
// support for higher arities.
|
||||
|
||||
// GTEST_ASSERT_ is the basic statement to which all of the assertions
|
||||
// in this file reduce. Don't use this in your code.
|
||||
|
||||
#define GTEST_ASSERT_(expression, on_failure) \\
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \\
|
||||
if (const ::testing::AssertionResult gtest_ar = (expression)) \\
|
||||
; \\
|
||||
else \\
|
||||
on_failure(gtest_ar.failure_message())
|
||||
""" % DEFS)
|
||||
|
||||
|
||||
def Arity(n):
|
||||
"""Returns the English name of the given arity."""
|
||||
|
||||
if n < 0:
|
||||
return None
|
||||
elif n <= 3:
|
||||
return ['nullary', 'unary', 'binary', 'ternary'][n]
|
||||
else:
|
||||
return '%s-ary' % n
|
||||
|
||||
|
||||
def Title(word):
|
||||
"""Returns the given word in title case. The difference between
|
||||
this and string's title() method is that Title('4-ary') is '4-ary'
|
||||
while '4-ary'.title() is '4-Ary'."""
|
||||
|
||||
return word[0].upper() + word[1:]
|
||||
|
||||
|
||||
def OneTo(n):
|
||||
"""Returns the list [1, 2, 3, ..., n]."""
|
||||
|
||||
return range(1, n + 1)
|
||||
|
||||
|
||||
def Iter(n, format, sep=''):
|
||||
"""Given a positive integer n, a format string that contains 0 or
|
||||
more '%s' format specs, and optionally a separator string, returns
|
||||
the join of n strings, each formatted with the format string on an
|
||||
iterator ranged from 1 to n.
|
||||
|
||||
Example:
|
||||
|
||||
Iter(3, 'v%s', sep=', ') returns 'v1, v2, v3'.
|
||||
"""
|
||||
|
||||
# How many '%s' specs are in format?
|
||||
spec_count = len(format.split('%s')) - 1
|
||||
return sep.join([format % (spec_count * (i,)) for i in OneTo(n)])
|
||||
|
||||
|
||||
def ImplementationForArity(n):
|
||||
"""Returns the implementation of n-ary predicate assertions."""
|
||||
|
||||
# A map the defines the values used in the implementation template.
|
||||
DEFS = {
|
||||
'n' : str(n),
|
||||
'vs' : Iter(n, 'v%s', sep=', '),
|
||||
'vts' : Iter(n, '#v%s', sep=', '),
|
||||
'arity' : Arity(n),
|
||||
'Arity' : Title(Arity(n))
|
||||
}
|
||||
|
||||
impl = """
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED%(n)s. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred""" % DEFS
|
||||
|
||||
impl += Iter(n, """,
|
||||
typename T%s""")
|
||||
|
||||
impl += """>
|
||||
AssertionResult AssertPred%(n)sHelper(const char* pred_text""" % DEFS
|
||||
|
||||
impl += Iter(n, """,
|
||||
const char* e%s""")
|
||||
|
||||
impl += """,
|
||||
Pred pred"""
|
||||
|
||||
impl += Iter(n, """,
|
||||
const T%s& v%s""")
|
||||
|
||||
impl += """) {
|
||||
if (pred(%(vs)s)) return AssertionSuccess();
|
||||
|
||||
""" % DEFS
|
||||
|
||||
impl += ' return AssertionFailure() << pred_text << "("'
|
||||
|
||||
impl += Iter(n, """
|
||||
<< e%s""", sep=' << ", "')
|
||||
|
||||
impl += ' << ") evaluates to false, where"'
|
||||
|
||||
impl += Iter(n, """
|
||||
<< "\\n" << e%s << " evaluates to " << v%s""")
|
||||
|
||||
impl += """;
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT%(n)s.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, on_failure)\\
|
||||
GTEST_ASSERT_(pred_format(%(vts)s, %(vs)s), \\
|
||||
on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED%(n)s. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED%(n)s_(pred, %(vs)s, on_failure)\\
|
||||
GTEST_ASSERT_(::testing::AssertPred%(n)sHelper(#pred""" % DEFS
|
||||
|
||||
impl += Iter(n, """, \\
|
||||
#v%s""")
|
||||
|
||||
impl += """, \\
|
||||
pred"""
|
||||
|
||||
impl += Iter(n, """, \\
|
||||
v%s""")
|
||||
|
||||
impl += """), on_failure)
|
||||
|
||||
// %(Arity)s predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\
|
||||
GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_NONFATAL_FAILURE_)
|
||||
#define EXPECT_PRED%(n)s(pred, %(vs)s) \\
|
||||
GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_NONFATAL_FAILURE_)
|
||||
#define ASSERT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\
|
||||
GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_FATAL_FAILURE_)
|
||||
#define ASSERT_PRED%(n)s(pred, %(vs)s) \\
|
||||
GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_FATAL_FAILURE_)
|
||||
|
||||
""" % DEFS
|
||||
|
||||
return impl
|
||||
|
||||
|
||||
def HeaderPostamble():
|
||||
"""Returns the postamble for the header file."""
|
||||
|
||||
return """
|
||||
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
||||
"""
|
||||
|
||||
|
||||
def GenerateFile(path, content):
|
||||
"""Given a file path and a content string
|
||||
overwrites it with the given content.
|
||||
"""
|
||||
print 'Updating file %s . . .' % path
|
||||
f = file(path, 'w+')
|
||||
print >>f, content,
|
||||
f.close()
|
||||
|
||||
print 'File %s has been updated.' % path
|
||||
|
||||
|
||||
def GenerateHeader(n):
|
||||
"""Given the maximum arity n, updates the header file that implements
|
||||
the predicate assertions.
|
||||
"""
|
||||
GenerateFile(HEADER,
|
||||
HeaderPreamble(n)
|
||||
+ ''.join([ImplementationForArity(i) for i in OneTo(n)])
|
||||
+ HeaderPostamble())
|
||||
|
||||
|
||||
def UnitTestPreamble():
|
||||
"""Returns the preamble for the unit test file."""
|
||||
|
||||
# A map that defines the values used in the preamble template.
|
||||
DEFS = {
|
||||
'today' : time.strftime('%m/%d/%Y'),
|
||||
'year' : time.strftime('%Y'),
|
||||
'command' : '%s %s' % (os.path.basename(sys.argv[0]), sys.argv[1]),
|
||||
}
|
||||
|
||||
return (
|
||||
"""// Copyright 2006, 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.
|
||||
|
||||
// This file is AUTOMATICALLY GENERATED on %(today)s by command
|
||||
// '%(command)s'. DO NOT EDIT BY HAND!
|
||||
|
||||
// Regression test for gtest_pred_impl.h
|
||||
//
|
||||
// This file is generated by a script and quite long. If you intend to
|
||||
// learn how Google Test works by reading its unit tests, read
|
||||
// gtest_unittest.cc instead.
|
||||
//
|
||||
// This is intended as a regression test for the Google Test predicate
|
||||
// assertions. We compile it as part of the gtest_unittest target
|
||||
// only to keep the implementation tidy and compact, as it is quite
|
||||
// involved to set up the stage for testing Google Test using Google
|
||||
// Test itself.
|
||||
//
|
||||
// Currently, gtest_unittest takes ~11 seconds to run in the testing
|
||||
// daemon. In the future, if it grows too large and needs much more
|
||||
// time to finish, we should consider separating this file into a
|
||||
// stand-alone regression test.
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
#include "gtest/gtest-spi.h"
|
||||
|
||||
// A user-defined data type.
|
||||
struct Bool {
|
||||
explicit Bool(int val) : value(val != 0) {}
|
||||
|
||||
bool operator>(int n) const { return value > Bool(n).value; }
|
||||
|
||||
Bool operator+(const Bool& rhs) const { return Bool(value + rhs.value); }
|
||||
|
||||
bool operator==(const Bool& rhs) const { return value == rhs.value; }
|
||||
|
||||
bool value;
|
||||
};
|
||||
|
||||
// Enables Bool to be used in assertions.
|
||||
std::ostream& operator<<(std::ostream& os, const Bool& x) {
|
||||
return os << (x.value ? "true" : "false");
|
||||
}
|
||||
|
||||
""" % DEFS)
|
||||
|
||||
|
||||
def TestsForArity(n):
|
||||
"""Returns the tests for n-ary predicate assertions."""
|
||||
|
||||
# A map that defines the values used in the template for the tests.
|
||||
DEFS = {
|
||||
'n' : n,
|
||||
'es' : Iter(n, 'e%s', sep=', '),
|
||||
'vs' : Iter(n, 'v%s', sep=', '),
|
||||
'vts' : Iter(n, '#v%s', sep=', '),
|
||||
'tvs' : Iter(n, 'T%s v%s', sep=', '),
|
||||
'int_vs' : Iter(n, 'int v%s', sep=', '),
|
||||
'Bool_vs' : Iter(n, 'Bool v%s', sep=', '),
|
||||
'types' : Iter(n, 'typename T%s', sep=', '),
|
||||
'v_sum' : Iter(n, 'v%s', sep=' + '),
|
||||
'arity' : Arity(n),
|
||||
'Arity' : Title(Arity(n)),
|
||||
}
|
||||
|
||||
tests = (
|
||||
"""// Sample functions/functors for testing %(arity)s predicate assertions.
|
||||
|
||||
// A %(arity)s predicate function.
|
||||
template <%(types)s>
|
||||
bool PredFunction%(n)s(%(tvs)s) {
|
||||
return %(v_sum)s > 0;
|
||||
}
|
||||
|
||||
// The following two functions are needed to circumvent a bug in
|
||||
// gcc 2.95.3, which sometimes has problem with the above template
|
||||
// function.
|
||||
bool PredFunction%(n)sInt(%(int_vs)s) {
|
||||
return %(v_sum)s > 0;
|
||||
}
|
||||
bool PredFunction%(n)sBool(%(Bool_vs)s) {
|
||||
return %(v_sum)s > 0;
|
||||
}
|
||||
""" % DEFS)
|
||||
|
||||
tests += """
|
||||
// A %(arity)s predicate functor.
|
||||
struct PredFunctor%(n)s {
|
||||
template <%(types)s>
|
||||
bool operator()(""" % DEFS
|
||||
|
||||
tests += Iter(n, 'const T%s& v%s', sep=""",
|
||||
""")
|
||||
|
||||
tests += """) {
|
||||
return %(v_sum)s > 0;
|
||||
}
|
||||
};
|
||||
""" % DEFS
|
||||
|
||||
tests += """
|
||||
// A %(arity)s predicate-formatter function.
|
||||
template <%(types)s>
|
||||
testing::AssertionResult PredFormatFunction%(n)s(""" % DEFS
|
||||
|
||||
tests += Iter(n, 'const char* e%s', sep=""",
|
||||
""")
|
||||
|
||||
tests += Iter(n, """,
|
||||
const T%s& v%s""")
|
||||
|
||||
tests += """) {
|
||||
if (PredFunction%(n)s(%(vs)s))
|
||||
return testing::AssertionSuccess();
|
||||
|
||||
return testing::AssertionFailure()
|
||||
<< """ % DEFS
|
||||
|
||||
tests += Iter(n, 'e%s', sep=' << " + " << ')
|
||||
|
||||
tests += """
|
||||
<< " is expected to be positive, but evaluates to "
|
||||
<< %(v_sum)s << ".";
|
||||
}
|
||||
""" % DEFS
|
||||
|
||||
tests += """
|
||||
// A %(arity)s predicate-formatter functor.
|
||||
struct PredFormatFunctor%(n)s {
|
||||
template <%(types)s>
|
||||
testing::AssertionResult operator()(""" % DEFS
|
||||
|
||||
tests += Iter(n, 'const char* e%s', sep=""",
|
||||
""")
|
||||
|
||||
tests += Iter(n, """,
|
||||
const T%s& v%s""")
|
||||
|
||||
tests += """) const {
|
||||
return PredFormatFunction%(n)s(%(es)s, %(vs)s);
|
||||
}
|
||||
};
|
||||
""" % DEFS
|
||||
|
||||
tests += """
|
||||
// Tests for {EXPECT|ASSERT}_PRED_FORMAT%(n)s.
|
||||
|
||||
class Predicate%(n)sTest : public testing::Test {
|
||||
protected:
|
||||
virtual void SetUp() {
|
||||
expected_to_finish_ = true;
|
||||
finished_ = false;""" % DEFS
|
||||
|
||||
tests += """
|
||||
""" + Iter(n, 'n%s_ = ') + """0;
|
||||
}
|
||||
"""
|
||||
|
||||
tests += """
|
||||
virtual void TearDown() {
|
||||
// Verifies that each of the predicate's arguments was evaluated
|
||||
// exactly once."""
|
||||
|
||||
tests += ''.join(["""
|
||||
EXPECT_EQ(1, n%s_) <<
|
||||
"The predicate assertion didn't evaluate argument %s "
|
||||
"exactly once.";""" % (i, i + 1) for i in OneTo(n)])
|
||||
|
||||
tests += """
|
||||
|
||||
// Verifies that the control flow in the test function is expected.
|
||||
if (expected_to_finish_ && !finished_) {
|
||||
FAIL() << "The predicate assertion unexpactedly aborted the test.";
|
||||
} else if (!expected_to_finish_ && finished_) {
|
||||
FAIL() << "The failed predicate assertion didn't abort the test "
|
||||
"as expected.";
|
||||
}
|
||||
}
|
||||
|
||||
// true iff the test function is expected to run to finish.
|
||||
static bool expected_to_finish_;
|
||||
|
||||
// true iff the test function did run to finish.
|
||||
static bool finished_;
|
||||
""" % DEFS
|
||||
|
||||
tests += Iter(n, """
|
||||
static int n%s_;""")
|
||||
|
||||
tests += """
|
||||
};
|
||||
|
||||
bool Predicate%(n)sTest::expected_to_finish_;
|
||||
bool Predicate%(n)sTest::finished_;
|
||||
""" % DEFS
|
||||
|
||||
tests += Iter(n, """int Predicate%%(n)sTest::n%s_;
|
||||
""") % DEFS
|
||||
|
||||
tests += """
|
||||
typedef Predicate%(n)sTest EXPECT_PRED_FORMAT%(n)sTest;
|
||||
typedef Predicate%(n)sTest ASSERT_PRED_FORMAT%(n)sTest;
|
||||
typedef Predicate%(n)sTest EXPECT_PRED%(n)sTest;
|
||||
typedef Predicate%(n)sTest ASSERT_PRED%(n)sTest;
|
||||
""" % DEFS
|
||||
|
||||
def GenTest(use_format, use_assert, expect_failure,
|
||||
use_functor, use_user_type):
|
||||
"""Returns the test for a predicate assertion macro.
|
||||
|
||||
Args:
|
||||
use_format: true iff the assertion is a *_PRED_FORMAT*.
|
||||
use_assert: true iff the assertion is a ASSERT_*.
|
||||
expect_failure: true iff the assertion is expected to fail.
|
||||
use_functor: true iff the first argument of the assertion is
|
||||
a functor (as opposed to a function)
|
||||
use_user_type: true iff the predicate functor/function takes
|
||||
argument(s) of a user-defined type.
|
||||
|
||||
Example:
|
||||
|
||||
GenTest(1, 0, 0, 1, 0) returns a test that tests the behavior
|
||||
of a successful EXPECT_PRED_FORMATn() that takes a functor
|
||||
whose arguments have built-in types."""
|
||||
|
||||
if use_assert:
|
||||
assrt = 'ASSERT' # 'assert' is reserved, so we cannot use
|
||||
# that identifier here.
|
||||
else:
|
||||
assrt = 'EXPECT'
|
||||
|
||||
assertion = assrt + '_PRED'
|
||||
|
||||
if use_format:
|
||||
pred_format = 'PredFormat'
|
||||
assertion += '_FORMAT'
|
||||
else:
|
||||
pred_format = 'Pred'
|
||||
|
||||
assertion += '%(n)s' % DEFS
|
||||
|
||||
if use_functor:
|
||||
pred_format_type = 'functor'
|
||||
pred_format += 'Functor%(n)s()'
|
||||
else:
|
||||
pred_format_type = 'function'
|
||||
pred_format += 'Function%(n)s'
|
||||
if not use_format:
|
||||
if use_user_type:
|
||||
pred_format += 'Bool'
|
||||
else:
|
||||
pred_format += 'Int'
|
||||
|
||||
test_name = pred_format_type.title()
|
||||
|
||||
if use_user_type:
|
||||
arg_type = 'user-defined type (Bool)'
|
||||
test_name += 'OnUserType'
|
||||
if expect_failure:
|
||||
arg = 'Bool(n%s_++)'
|
||||
else:
|
||||
arg = 'Bool(++n%s_)'
|
||||
else:
|
||||
arg_type = 'built-in type (int)'
|
||||
test_name += 'OnBuiltInType'
|
||||
if expect_failure:
|
||||
arg = 'n%s_++'
|
||||
else:
|
||||
arg = '++n%s_'
|
||||
|
||||
if expect_failure:
|
||||
successful_or_failed = 'failed'
|
||||
expected_or_not = 'expected.'
|
||||
test_name += 'Failure'
|
||||
else:
|
||||
successful_or_failed = 'successful'
|
||||
expected_or_not = 'UNEXPECTED!'
|
||||
test_name += 'Success'
|
||||
|
||||
# A map that defines the values used in the test template.
|
||||
defs = DEFS.copy()
|
||||
defs.update({
|
||||
'assert' : assrt,
|
||||
'assertion' : assertion,
|
||||
'test_name' : test_name,
|
||||
'pf_type' : pred_format_type,
|
||||
'pf' : pred_format,
|
||||
'arg_type' : arg_type,
|
||||
'arg' : arg,
|
||||
'successful' : successful_or_failed,
|
||||
'expected' : expected_or_not,
|
||||
})
|
||||
|
||||
test = """
|
||||
// Tests a %(successful)s %(assertion)s where the
|
||||
// predicate-formatter is a %(pf_type)s on a %(arg_type)s.
|
||||
TEST_F(%(assertion)sTest, %(test_name)s) {""" % defs
|
||||
|
||||
indent = (len(assertion) + 3)*' '
|
||||
extra_indent = ''
|
||||
|
||||
if expect_failure:
|
||||
extra_indent = ' '
|
||||
if use_assert:
|
||||
test += """
|
||||
expected_to_finish_ = false;
|
||||
EXPECT_FATAL_FAILURE({ // NOLINT"""
|
||||
else:
|
||||
test += """
|
||||
EXPECT_NONFATAL_FAILURE({ // NOLINT"""
|
||||
|
||||
test += '\n' + extra_indent + """ %(assertion)s(%(pf)s""" % defs
|
||||
|
||||
test = test % defs
|
||||
test += Iter(n, ',\n' + indent + extra_indent + '%(arg)s' % defs)
|
||||
test += ');\n' + extra_indent + ' finished_ = true;\n'
|
||||
|
||||
if expect_failure:
|
||||
test += ' }, "");\n'
|
||||
|
||||
test += '}\n'
|
||||
return test
|
||||
|
||||
# Generates tests for all 2**6 = 64 combinations.
|
||||
tests += ''.join([GenTest(use_format, use_assert, expect_failure,
|
||||
use_functor, use_user_type)
|
||||
for use_format in [0, 1]
|
||||
for use_assert in [0, 1]
|
||||
for expect_failure in [0, 1]
|
||||
for use_functor in [0, 1]
|
||||
for use_user_type in [0, 1]
|
||||
])
|
||||
|
||||
return tests
|
||||
|
||||
|
||||
def UnitTestPostamble():
|
||||
"""Returns the postamble for the tests."""
|
||||
|
||||
return ''
|
||||
|
||||
|
||||
def GenerateUnitTest(n):
|
||||
"""Returns the tests for up-to n-ary predicate assertions."""
|
||||
|
||||
GenerateFile(UNIT_TEST,
|
||||
UnitTestPreamble()
|
||||
+ ''.join([TestsForArity(i) for i in OneTo(n)])
|
||||
+ UnitTestPostamble())
|
||||
|
||||
|
||||
def _Main():
|
||||
"""The entry point of the script. Generates the header file and its
|
||||
unit test."""
|
||||
|
||||
if len(sys.argv) != 2:
|
||||
print __doc__
|
||||
print 'Author: ' + __author__
|
||||
sys.exit(1)
|
||||
|
||||
n = int(sys.argv[1])
|
||||
GenerateHeader(n)
|
||||
GenerateUnitTest(n)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
_Main()
|
274
3rdparty/gtest/scripts/gtest-config.in
vendored
Normal file
274
3rdparty/gtest/scripts/gtest-config.in
vendored
Normal file
@ -0,0 +1,274 @@
|
||||
#!/bin/sh
|
||||
|
||||
# These variables are automatically filled in by the configure script.
|
||||
name="@PACKAGE_TARNAME@"
|
||||
version="@PACKAGE_VERSION@"
|
||||
|
||||
show_usage()
|
||||
{
|
||||
echo "Usage: gtest-config [OPTIONS...]"
|
||||
}
|
||||
|
||||
show_help()
|
||||
{
|
||||
show_usage
|
||||
cat <<\EOF
|
||||
|
||||
The `gtest-config' script provides access to the necessary compile and linking
|
||||
flags to connect with Google C++ Testing Framework, both in a build prior to
|
||||
installation, and on the system proper after installation. The installation
|
||||
overrides may be issued in combination with any other queries, but will only
|
||||
affect installation queries if called on a built but not installed gtest. The
|
||||
installation queries may not be issued with any other types of queries, and
|
||||
only one installation query may be made at a time. The version queries and
|
||||
compiler flag queries may be combined as desired but not mixed. Different
|
||||
version queries are always combined with logical "and" semantics, and only the
|
||||
last of any particular query is used while all previous ones ignored. All
|
||||
versions must be specified as a sequence of numbers separated by periods.
|
||||
Compiler flag queries output the union of the sets of flags when combined.
|
||||
|
||||
Examples:
|
||||
gtest-config --min-version=1.0 || echo "Insufficient Google Test version."
|
||||
|
||||
g++ $(gtest-config --cppflags --cxxflags) -o foo.o -c foo.cpp
|
||||
g++ $(gtest-config --ldflags --libs) -o foo foo.o
|
||||
|
||||
# When using a built but not installed Google Test:
|
||||
g++ $(../../my_gtest_build/scripts/gtest-config ...) ...
|
||||
|
||||
# When using an installed Google Test, but with installation overrides:
|
||||
export GTEST_PREFIX="/opt"
|
||||
g++ $(gtest-config --libdir="/opt/lib64" ...) ...
|
||||
|
||||
Help:
|
||||
--usage brief usage information
|
||||
--help display this help message
|
||||
|
||||
Installation Overrides:
|
||||
--prefix=<dir> overrides the installation prefix
|
||||
--exec-prefix=<dir> overrides the executable installation prefix
|
||||
--libdir=<dir> overrides the library installation prefix
|
||||
--includedir=<dir> overrides the header file installation prefix
|
||||
|
||||
Installation Queries:
|
||||
--prefix installation prefix
|
||||
--exec-prefix executable installation prefix
|
||||
--libdir library installation directory
|
||||
--includedir header file installation directory
|
||||
--version the version of the Google Test installation
|
||||
|
||||
Version Queries:
|
||||
--min-version=VERSION return 0 if the version is at least VERSION
|
||||
--exact-version=VERSION return 0 if the version is exactly VERSION
|
||||
--max-version=VERSION return 0 if the version is at most VERSION
|
||||
|
||||
Compilation Flag Queries:
|
||||
--cppflags compile flags specific to the C-like preprocessors
|
||||
--cxxflags compile flags appropriate for C++ programs
|
||||
--ldflags linker flags
|
||||
--libs libraries for linking
|
||||
|
||||
EOF
|
||||
}
|
||||
|
||||
# This function bounds our version with a min and a max. It uses some clever
|
||||
# POSIX-compliant variable expansion to portably do all the work in the shell
|
||||
# and avoid any dependency on a particular "sed" or "awk" implementation.
|
||||
# Notable is that it will only ever compare the first 3 components of versions.
|
||||
# Further components will be cleanly stripped off. All versions must be
|
||||
# unadorned, so "v1.0" will *not* work. The minimum version must be in $1, and
|
||||
# the max in $2. TODO(chandlerc@google.com): If this ever breaks, we should
|
||||
# investigate expanding this via autom4te from AS_VERSION_COMPARE rather than
|
||||
# continuing to maintain our own shell version.
|
||||
check_versions()
|
||||
{
|
||||
major_version=${version%%.*}
|
||||
minor_version="0"
|
||||
point_version="0"
|
||||
if test "${version#*.}" != "${version}"; then
|
||||
minor_version=${version#*.}
|
||||
minor_version=${minor_version%%.*}
|
||||
fi
|
||||
if test "${version#*.*.}" != "${version}"; then
|
||||
point_version=${version#*.*.}
|
||||
point_version=${point_version%%.*}
|
||||
fi
|
||||
|
||||
min_version="$1"
|
||||
min_major_version=${min_version%%.*}
|
||||
min_minor_version="0"
|
||||
min_point_version="0"
|
||||
if test "${min_version#*.}" != "${min_version}"; then
|
||||
min_minor_version=${min_version#*.}
|
||||
min_minor_version=${min_minor_version%%.*}
|
||||
fi
|
||||
if test "${min_version#*.*.}" != "${min_version}"; then
|
||||
min_point_version=${min_version#*.*.}
|
||||
min_point_version=${min_point_version%%.*}
|
||||
fi
|
||||
|
||||
max_version="$2"
|
||||
max_major_version=${max_version%%.*}
|
||||
max_minor_version="0"
|
||||
max_point_version="0"
|
||||
if test "${max_version#*.}" != "${max_version}"; then
|
||||
max_minor_version=${max_version#*.}
|
||||
max_minor_version=${max_minor_version%%.*}
|
||||
fi
|
||||
if test "${max_version#*.*.}" != "${max_version}"; then
|
||||
max_point_version=${max_version#*.*.}
|
||||
max_point_version=${max_point_version%%.*}
|
||||
fi
|
||||
|
||||
test $(($major_version)) -lt $(($min_major_version)) && exit 1
|
||||
if test $(($major_version)) -eq $(($min_major_version)); then
|
||||
test $(($minor_version)) -lt $(($min_minor_version)) && exit 1
|
||||
if test $(($minor_version)) -eq $(($min_minor_version)); then
|
||||
test $(($point_version)) -lt $(($min_point_version)) && exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
test $(($major_version)) -gt $(($max_major_version)) && exit 1
|
||||
if test $(($major_version)) -eq $(($max_major_version)); then
|
||||
test $(($minor_version)) -gt $(($max_minor_version)) && exit 1
|
||||
if test $(($minor_version)) -eq $(($max_minor_version)); then
|
||||
test $(($point_version)) -gt $(($max_point_version)) && exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Show the usage line when no arguments are specified.
|
||||
if test $# -eq 0; then
|
||||
show_usage
|
||||
exit 1
|
||||
fi
|
||||
|
||||
while test $# -gt 0; do
|
||||
case $1 in
|
||||
--usage) show_usage; exit 0;;
|
||||
--help) show_help; exit 0;;
|
||||
|
||||
# Installation overrides
|
||||
--prefix=*) GTEST_PREFIX=${1#--prefix=};;
|
||||
--exec-prefix=*) GTEST_EXEC_PREFIX=${1#--exec-prefix=};;
|
||||
--libdir=*) GTEST_LIBDIR=${1#--libdir=};;
|
||||
--includedir=*) GTEST_INCLUDEDIR=${1#--includedir=};;
|
||||
|
||||
# Installation queries
|
||||
--prefix|--exec-prefix|--libdir|--includedir|--version)
|
||||
if test -n "${do_query}"; then
|
||||
show_usage
|
||||
exit 1
|
||||
fi
|
||||
do_query=${1#--}
|
||||
;;
|
||||
|
||||
# Version checking
|
||||
--min-version=*)
|
||||
do_check_versions=yes
|
||||
min_version=${1#--min-version=}
|
||||
;;
|
||||
--max-version=*)
|
||||
do_check_versions=yes
|
||||
max_version=${1#--max-version=}
|
||||
;;
|
||||
--exact-version=*)
|
||||
do_check_versions=yes
|
||||
exact_version=${1#--exact-version=}
|
||||
;;
|
||||
|
||||
# Compiler flag output
|
||||
--cppflags) echo_cppflags=yes;;
|
||||
--cxxflags) echo_cxxflags=yes;;
|
||||
--ldflags) echo_ldflags=yes;;
|
||||
--libs) echo_libs=yes;;
|
||||
|
||||
# Everything else is an error
|
||||
*) show_usage; exit 1;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
# These have defaults filled in by the configure script but can also be
|
||||
# overridden by environment variables or command line parameters.
|
||||
prefix="${GTEST_PREFIX:-@prefix@}"
|
||||
exec_prefix="${GTEST_EXEC_PREFIX:-@exec_prefix@}"
|
||||
libdir="${GTEST_LIBDIR:-@libdir@}"
|
||||
includedir="${GTEST_INCLUDEDIR:-@includedir@}"
|
||||
|
||||
# We try and detect if our binary is not located at its installed location. If
|
||||
# it's not, we provide variables pointing to the source and build tree rather
|
||||
# than to the install tree. This allows building against a just-built gtest
|
||||
# rather than an installed gtest.
|
||||
bindir="@bindir@"
|
||||
this_relative_bindir=`dirname $0`
|
||||
this_bindir=`cd ${this_relative_bindir}; pwd -P`
|
||||
if test "${this_bindir}" = "${this_bindir%${bindir}}"; then
|
||||
# The path to the script doesn't end in the bindir sequence from Autoconf,
|
||||
# assume that we are in a build tree.
|
||||
build_dir=`dirname ${this_bindir}`
|
||||
src_dir=`cd ${this_bindir}; cd @top_srcdir@; pwd -P`
|
||||
|
||||
# TODO(chandlerc@google.com): This is a dangerous dependency on libtool, we
|
||||
# should work to remove it, and/or remove libtool altogether, replacing it
|
||||
# with direct references to the library and a link path.
|
||||
gtest_libs="${build_dir}/lib/libgtest.la @PTHREAD_CFLAGS@ @PTHREAD_LIBS@"
|
||||
gtest_ldflags=""
|
||||
|
||||
# We provide hooks to include from either the source or build dir, where the
|
||||
# build dir is always preferred. This will potentially allow us to write
|
||||
# build rules for generated headers and have them automatically be preferred
|
||||
# over provided versions.
|
||||
gtest_cppflags="-I${build_dir}/include -I${src_dir}/include"
|
||||
gtest_cxxflags="@PTHREAD_CFLAGS@"
|
||||
else
|
||||
# We're using an installed gtest, although it may be staged under some
|
||||
# prefix. Assume (as our own libraries do) that we can resolve the prefix,
|
||||
# and are present in the dynamic link paths.
|
||||
gtest_ldflags="-L${libdir}"
|
||||
gtest_libs="-l${name} @PTHREAD_CFLAGS@ @PTHREAD_LIBS@"
|
||||
gtest_cppflags="-I${includedir}"
|
||||
gtest_cxxflags="@PTHREAD_CFLAGS@"
|
||||
fi
|
||||
|
||||
# Do an installation query if requested.
|
||||
if test -n "$do_query"; then
|
||||
case $do_query in
|
||||
prefix) echo $prefix; exit 0;;
|
||||
exec-prefix) echo $exec_prefix; exit 0;;
|
||||
libdir) echo $libdir; exit 0;;
|
||||
includedir) echo $includedir; exit 0;;
|
||||
version) echo $version; exit 0;;
|
||||
*) show_usage; exit 1;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# Do a version check if requested.
|
||||
if test "$do_check_versions" = "yes"; then
|
||||
# Make sure we didn't receive a bad combination of parameters.
|
||||
test "$echo_cppflags" = "yes" && show_usage && exit 1
|
||||
test "$echo_cxxflags" = "yes" && show_usage && exit 1
|
||||
test "$echo_ldflags" = "yes" && show_usage && exit 1
|
||||
test "$echo_libs" = "yes" && show_usage && exit 1
|
||||
|
||||
if test "$exact_version" != ""; then
|
||||
check_versions $exact_version $exact_version
|
||||
# unreachable
|
||||
else
|
||||
check_versions ${min_version:-0.0.0} ${max_version:-9999.9999.9999}
|
||||
# unreachable
|
||||
fi
|
||||
fi
|
||||
|
||||
# Do the output in the correct order so that these can be used in-line of
|
||||
# a compiler invocation.
|
||||
output=""
|
||||
test "$echo_cppflags" = "yes" && output="$output $gtest_cppflags"
|
||||
test "$echo_cxxflags" = "yes" && output="$output $gtest_cxxflags"
|
||||
test "$echo_ldflags" = "yes" && output="$output $gtest_ldflags"
|
||||
test "$echo_libs" = "yes" && output="$output $gtest_libs"
|
||||
echo $output
|
||||
|
||||
exit 0
|
855
3rdparty/gtest/scripts/pump.py
vendored
Normal file
855
3rdparty/gtest/scripts/pump.py
vendored
Normal file
@ -0,0 +1,855 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2008, 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.
|
||||
|
||||
"""pump v0.2.0 - Pretty Useful for Meta Programming.
|
||||
|
||||
A tool for preprocessor meta programming. Useful for generating
|
||||
repetitive boilerplate code. Especially useful for writing C++
|
||||
classes, functions, macros, and templates that need to work with
|
||||
various number of arguments.
|
||||
|
||||
USAGE:
|
||||
pump.py SOURCE_FILE
|
||||
|
||||
EXAMPLES:
|
||||
pump.py foo.cc.pump
|
||||
Converts foo.cc.pump to foo.cc.
|
||||
|
||||
GRAMMAR:
|
||||
CODE ::= ATOMIC_CODE*
|
||||
ATOMIC_CODE ::= $var ID = EXPRESSION
|
||||
| $var ID = [[ CODE ]]
|
||||
| $range ID EXPRESSION..EXPRESSION
|
||||
| $for ID SEPARATOR [[ CODE ]]
|
||||
| $($)
|
||||
| $ID
|
||||
| $(EXPRESSION)
|
||||
| $if EXPRESSION [[ CODE ]] ELSE_BRANCH
|
||||
| [[ CODE ]]
|
||||
| RAW_CODE
|
||||
SEPARATOR ::= RAW_CODE | EMPTY
|
||||
ELSE_BRANCH ::= $else [[ CODE ]]
|
||||
| $elif EXPRESSION [[ CODE ]] ELSE_BRANCH
|
||||
| EMPTY
|
||||
EXPRESSION has Python syntax.
|
||||
"""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
|
||||
TOKEN_TABLE = [
|
||||
(re.compile(r'\$var\s+'), '$var'),
|
||||
(re.compile(r'\$elif\s+'), '$elif'),
|
||||
(re.compile(r'\$else\s+'), '$else'),
|
||||
(re.compile(r'\$for\s+'), '$for'),
|
||||
(re.compile(r'\$if\s+'), '$if'),
|
||||
(re.compile(r'\$range\s+'), '$range'),
|
||||
(re.compile(r'\$[_A-Za-z]\w*'), '$id'),
|
||||
(re.compile(r'\$\(\$\)'), '$($)'),
|
||||
(re.compile(r'\$'), '$'),
|
||||
(re.compile(r'\[\[\n?'), '[['),
|
||||
(re.compile(r'\]\]\n?'), ']]'),
|
||||
]
|
||||
|
||||
|
||||
class Cursor:
|
||||
"""Represents a position (line and column) in a text file."""
|
||||
|
||||
def __init__(self, line=-1, column=-1):
|
||||
self.line = line
|
||||
self.column = column
|
||||
|
||||
def __eq__(self, rhs):
|
||||
return self.line == rhs.line and self.column == rhs.column
|
||||
|
||||
def __ne__(self, rhs):
|
||||
return not self == rhs
|
||||
|
||||
def __lt__(self, rhs):
|
||||
return self.line < rhs.line or (
|
||||
self.line == rhs.line and self.column < rhs.column)
|
||||
|
||||
def __le__(self, rhs):
|
||||
return self < rhs or self == rhs
|
||||
|
||||
def __gt__(self, rhs):
|
||||
return rhs < self
|
||||
|
||||
def __ge__(self, rhs):
|
||||
return rhs <= self
|
||||
|
||||
def __str__(self):
|
||||
if self == Eof():
|
||||
return 'EOF'
|
||||
else:
|
||||
return '%s(%s)' % (self.line + 1, self.column)
|
||||
|
||||
def __add__(self, offset):
|
||||
return Cursor(self.line, self.column + offset)
|
||||
|
||||
def __sub__(self, offset):
|
||||
return Cursor(self.line, self.column - offset)
|
||||
|
||||
def Clone(self):
|
||||
"""Returns a copy of self."""
|
||||
|
||||
return Cursor(self.line, self.column)
|
||||
|
||||
|
||||
# Special cursor to indicate the end-of-file.
|
||||
def Eof():
|
||||
"""Returns the special cursor to denote the end-of-file."""
|
||||
return Cursor(-1, -1)
|
||||
|
||||
|
||||
class Token:
|
||||
"""Represents a token in a Pump source file."""
|
||||
|
||||
def __init__(self, start=None, end=None, value=None, token_type=None):
|
||||
if start is None:
|
||||
self.start = Eof()
|
||||
else:
|
||||
self.start = start
|
||||
if end is None:
|
||||
self.end = Eof()
|
||||
else:
|
||||
self.end = end
|
||||
self.value = value
|
||||
self.token_type = token_type
|
||||
|
||||
def __str__(self):
|
||||
return 'Token @%s: \'%s\' type=%s' % (
|
||||
self.start, self.value, self.token_type)
|
||||
|
||||
def Clone(self):
|
||||
"""Returns a copy of self."""
|
||||
|
||||
return Token(self.start.Clone(), self.end.Clone(), self.value,
|
||||
self.token_type)
|
||||
|
||||
|
||||
def StartsWith(lines, pos, string):
|
||||
"""Returns True iff the given position in lines starts with 'string'."""
|
||||
|
||||
return lines[pos.line][pos.column:].startswith(string)
|
||||
|
||||
|
||||
def FindFirstInLine(line, token_table):
|
||||
best_match_start = -1
|
||||
for (regex, token_type) in token_table:
|
||||
m = regex.search(line)
|
||||
if m:
|
||||
# We found regex in lines
|
||||
if best_match_start < 0 or m.start() < best_match_start:
|
||||
best_match_start = m.start()
|
||||
best_match_length = m.end() - m.start()
|
||||
best_match_token_type = token_type
|
||||
|
||||
if best_match_start < 0:
|
||||
return None
|
||||
|
||||
return (best_match_start, best_match_length, best_match_token_type)
|
||||
|
||||
|
||||
def FindFirst(lines, token_table, cursor):
|
||||
"""Finds the first occurrence of any string in strings in lines."""
|
||||
|
||||
start = cursor.Clone()
|
||||
cur_line_number = cursor.line
|
||||
for line in lines[start.line:]:
|
||||
if cur_line_number == start.line:
|
||||
line = line[start.column:]
|
||||
m = FindFirstInLine(line, token_table)
|
||||
if m:
|
||||
# We found a regex in line.
|
||||
(start_column, length, token_type) = m
|
||||
if cur_line_number == start.line:
|
||||
start_column += start.column
|
||||
found_start = Cursor(cur_line_number, start_column)
|
||||
found_end = found_start + length
|
||||
return MakeToken(lines, found_start, found_end, token_type)
|
||||
cur_line_number += 1
|
||||
# We failed to find str in lines
|
||||
return None
|
||||
|
||||
|
||||
def SubString(lines, start, end):
|
||||
"""Returns a substring in lines."""
|
||||
|
||||
if end == Eof():
|
||||
end = Cursor(len(lines) - 1, len(lines[-1]))
|
||||
|
||||
if start >= end:
|
||||
return ''
|
||||
|
||||
if start.line == end.line:
|
||||
return lines[start.line][start.column:end.column]
|
||||
|
||||
result_lines = ([lines[start.line][start.column:]] +
|
||||
lines[start.line + 1:end.line] +
|
||||
[lines[end.line][:end.column]])
|
||||
return ''.join(result_lines)
|
||||
|
||||
|
||||
def StripMetaComments(str):
|
||||
"""Strip meta comments from each line in the given string."""
|
||||
|
||||
# First, completely remove lines containing nothing but a meta
|
||||
# comment, including the trailing \n.
|
||||
str = re.sub(r'^\s*\$\$.*\n', '', str)
|
||||
|
||||
# Then, remove meta comments from contentful lines.
|
||||
return re.sub(r'\s*\$\$.*', '', str)
|
||||
|
||||
|
||||
def MakeToken(lines, start, end, token_type):
|
||||
"""Creates a new instance of Token."""
|
||||
|
||||
return Token(start, end, SubString(lines, start, end), token_type)
|
||||
|
||||
|
||||
def ParseToken(lines, pos, regex, token_type):
|
||||
line = lines[pos.line][pos.column:]
|
||||
m = regex.search(line)
|
||||
if m and not m.start():
|
||||
return MakeToken(lines, pos, pos + m.end(), token_type)
|
||||
else:
|
||||
print 'ERROR: %s expected at %s.' % (token_type, pos)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
ID_REGEX = re.compile(r'[_A-Za-z]\w*')
|
||||
EQ_REGEX = re.compile(r'=')
|
||||
REST_OF_LINE_REGEX = re.compile(r'.*?(?=$|\$\$)')
|
||||
OPTIONAL_WHITE_SPACES_REGEX = re.compile(r'\s*')
|
||||
WHITE_SPACE_REGEX = re.compile(r'\s')
|
||||
DOT_DOT_REGEX = re.compile(r'\.\.')
|
||||
|
||||
|
||||
def Skip(lines, pos, regex):
|
||||
line = lines[pos.line][pos.column:]
|
||||
m = re.search(regex, line)
|
||||
if m and not m.start():
|
||||
return pos + m.end()
|
||||
else:
|
||||
return pos
|
||||
|
||||
|
||||
def SkipUntil(lines, pos, regex, token_type):
|
||||
line = lines[pos.line][pos.column:]
|
||||
m = re.search(regex, line)
|
||||
if m:
|
||||
return pos + m.start()
|
||||
else:
|
||||
print ('ERROR: %s expected on line %s after column %s.' %
|
||||
(token_type, pos.line + 1, pos.column))
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def ParseExpTokenInParens(lines, pos):
|
||||
def ParseInParens(pos):
|
||||
pos = Skip(lines, pos, OPTIONAL_WHITE_SPACES_REGEX)
|
||||
pos = Skip(lines, pos, r'\(')
|
||||
pos = Parse(pos)
|
||||
pos = Skip(lines, pos, r'\)')
|
||||
return pos
|
||||
|
||||
def Parse(pos):
|
||||
pos = SkipUntil(lines, pos, r'\(|\)', ')')
|
||||
if SubString(lines, pos, pos + 1) == '(':
|
||||
pos = Parse(pos + 1)
|
||||
pos = Skip(lines, pos, r'\)')
|
||||
return Parse(pos)
|
||||
else:
|
||||
return pos
|
||||
|
||||
start = pos.Clone()
|
||||
pos = ParseInParens(pos)
|
||||
return MakeToken(lines, start, pos, 'exp')
|
||||
|
||||
|
||||
def RStripNewLineFromToken(token):
|
||||
if token.value.endswith('\n'):
|
||||
return Token(token.start, token.end, token.value[:-1], token.token_type)
|
||||
else:
|
||||
return token
|
||||
|
||||
|
||||
def TokenizeLines(lines, pos):
|
||||
while True:
|
||||
found = FindFirst(lines, TOKEN_TABLE, pos)
|
||||
if not found:
|
||||
yield MakeToken(lines, pos, Eof(), 'code')
|
||||
return
|
||||
|
||||
if found.start == pos:
|
||||
prev_token = None
|
||||
prev_token_rstripped = None
|
||||
else:
|
||||
prev_token = MakeToken(lines, pos, found.start, 'code')
|
||||
prev_token_rstripped = RStripNewLineFromToken(prev_token)
|
||||
|
||||
if found.token_type == '$var':
|
||||
if prev_token_rstripped:
|
||||
yield prev_token_rstripped
|
||||
yield found
|
||||
id_token = ParseToken(lines, found.end, ID_REGEX, 'id')
|
||||
yield id_token
|
||||
pos = Skip(lines, id_token.end, OPTIONAL_WHITE_SPACES_REGEX)
|
||||
|
||||
eq_token = ParseToken(lines, pos, EQ_REGEX, '=')
|
||||
yield eq_token
|
||||
pos = Skip(lines, eq_token.end, r'\s*')
|
||||
|
||||
if SubString(lines, pos, pos + 2) != '[[':
|
||||
exp_token = ParseToken(lines, pos, REST_OF_LINE_REGEX, 'exp')
|
||||
yield exp_token
|
||||
pos = Cursor(exp_token.end.line + 1, 0)
|
||||
elif found.token_type == '$for':
|
||||
if prev_token_rstripped:
|
||||
yield prev_token_rstripped
|
||||
yield found
|
||||
id_token = ParseToken(lines, found.end, ID_REGEX, 'id')
|
||||
yield id_token
|
||||
pos = Skip(lines, id_token.end, WHITE_SPACE_REGEX)
|
||||
elif found.token_type == '$range':
|
||||
if prev_token_rstripped:
|
||||
yield prev_token_rstripped
|
||||
yield found
|
||||
id_token = ParseToken(lines, found.end, ID_REGEX, 'id')
|
||||
yield id_token
|
||||
pos = Skip(lines, id_token.end, OPTIONAL_WHITE_SPACES_REGEX)
|
||||
|
||||
dots_pos = SkipUntil(lines, pos, DOT_DOT_REGEX, '..')
|
||||
yield MakeToken(lines, pos, dots_pos, 'exp')
|
||||
yield MakeToken(lines, dots_pos, dots_pos + 2, '..')
|
||||
pos = dots_pos + 2
|
||||
new_pos = Cursor(pos.line + 1, 0)
|
||||
yield MakeToken(lines, pos, new_pos, 'exp')
|
||||
pos = new_pos
|
||||
elif found.token_type == '$':
|
||||
if prev_token:
|
||||
yield prev_token
|
||||
yield found
|
||||
exp_token = ParseExpTokenInParens(lines, found.end)
|
||||
yield exp_token
|
||||
pos = exp_token.end
|
||||
elif (found.token_type == ']]' or found.token_type == '$if' or
|
||||
found.token_type == '$elif' or found.token_type == '$else'):
|
||||
if prev_token_rstripped:
|
||||
yield prev_token_rstripped
|
||||
yield found
|
||||
pos = found.end
|
||||
else:
|
||||
if prev_token:
|
||||
yield prev_token
|
||||
yield found
|
||||
pos = found.end
|
||||
|
||||
|
||||
def Tokenize(s):
|
||||
"""A generator that yields the tokens in the given string."""
|
||||
if s != '':
|
||||
lines = s.splitlines(True)
|
||||
for token in TokenizeLines(lines, Cursor(0, 0)):
|
||||
yield token
|
||||
|
||||
|
||||
class CodeNode:
|
||||
def __init__(self, atomic_code_list=None):
|
||||
self.atomic_code = atomic_code_list
|
||||
|
||||
|
||||
class VarNode:
|
||||
def __init__(self, identifier=None, atomic_code=None):
|
||||
self.identifier = identifier
|
||||
self.atomic_code = atomic_code
|
||||
|
||||
|
||||
class RangeNode:
|
||||
def __init__(self, identifier=None, exp1=None, exp2=None):
|
||||
self.identifier = identifier
|
||||
self.exp1 = exp1
|
||||
self.exp2 = exp2
|
||||
|
||||
|
||||
class ForNode:
|
||||
def __init__(self, identifier=None, sep=None, code=None):
|
||||
self.identifier = identifier
|
||||
self.sep = sep
|
||||
self.code = code
|
||||
|
||||
|
||||
class ElseNode:
|
||||
def __init__(self, else_branch=None):
|
||||
self.else_branch = else_branch
|
||||
|
||||
|
||||
class IfNode:
|
||||
def __init__(self, exp=None, then_branch=None, else_branch=None):
|
||||
self.exp = exp
|
||||
self.then_branch = then_branch
|
||||
self.else_branch = else_branch
|
||||
|
||||
|
||||
class RawCodeNode:
|
||||
def __init__(self, token=None):
|
||||
self.raw_code = token
|
||||
|
||||
|
||||
class LiteralDollarNode:
|
||||
def __init__(self, token):
|
||||
self.token = token
|
||||
|
||||
|
||||
class ExpNode:
|
||||
def __init__(self, token, python_exp):
|
||||
self.token = token
|
||||
self.python_exp = python_exp
|
||||
|
||||
|
||||
def PopFront(a_list):
|
||||
head = a_list[0]
|
||||
a_list[:1] = []
|
||||
return head
|
||||
|
||||
|
||||
def PushFront(a_list, elem):
|
||||
a_list[:0] = [elem]
|
||||
|
||||
|
||||
def PopToken(a_list, token_type=None):
|
||||
token = PopFront(a_list)
|
||||
if token_type is not None and token.token_type != token_type:
|
||||
print 'ERROR: %s expected at %s' % (token_type, token.start)
|
||||
print 'ERROR: %s found instead' % (token,)
|
||||
sys.exit(1)
|
||||
|
||||
return token
|
||||
|
||||
|
||||
def PeekToken(a_list):
|
||||
if not a_list:
|
||||
return None
|
||||
|
||||
return a_list[0]
|
||||
|
||||
|
||||
def ParseExpNode(token):
|
||||
python_exp = re.sub(r'([_A-Za-z]\w*)', r'self.GetValue("\1")', token.value)
|
||||
return ExpNode(token, python_exp)
|
||||
|
||||
|
||||
def ParseElseNode(tokens):
|
||||
def Pop(token_type=None):
|
||||
return PopToken(tokens, token_type)
|
||||
|
||||
next = PeekToken(tokens)
|
||||
if not next:
|
||||
return None
|
||||
if next.token_type == '$else':
|
||||
Pop('$else')
|
||||
Pop('[[')
|
||||
code_node = ParseCodeNode(tokens)
|
||||
Pop(']]')
|
||||
return code_node
|
||||
elif next.token_type == '$elif':
|
||||
Pop('$elif')
|
||||
exp = Pop('code')
|
||||
Pop('[[')
|
||||
code_node = ParseCodeNode(tokens)
|
||||
Pop(']]')
|
||||
inner_else_node = ParseElseNode(tokens)
|
||||
return CodeNode([IfNode(ParseExpNode(exp), code_node, inner_else_node)])
|
||||
elif not next.value.strip():
|
||||
Pop('code')
|
||||
return ParseElseNode(tokens)
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
def ParseAtomicCodeNode(tokens):
|
||||
def Pop(token_type=None):
|
||||
return PopToken(tokens, token_type)
|
||||
|
||||
head = PopFront(tokens)
|
||||
t = head.token_type
|
||||
if t == 'code':
|
||||
return RawCodeNode(head)
|
||||
elif t == '$var':
|
||||
id_token = Pop('id')
|
||||
Pop('=')
|
||||
next = PeekToken(tokens)
|
||||
if next.token_type == 'exp':
|
||||
exp_token = Pop()
|
||||
return VarNode(id_token, ParseExpNode(exp_token))
|
||||
Pop('[[')
|
||||
code_node = ParseCodeNode(tokens)
|
||||
Pop(']]')
|
||||
return VarNode(id_token, code_node)
|
||||
elif t == '$for':
|
||||
id_token = Pop('id')
|
||||
next_token = PeekToken(tokens)
|
||||
if next_token.token_type == 'code':
|
||||
sep_token = next_token
|
||||
Pop('code')
|
||||
else:
|
||||
sep_token = None
|
||||
Pop('[[')
|
||||
code_node = ParseCodeNode(tokens)
|
||||
Pop(']]')
|
||||
return ForNode(id_token, sep_token, code_node)
|
||||
elif t == '$if':
|
||||
exp_token = Pop('code')
|
||||
Pop('[[')
|
||||
code_node = ParseCodeNode(tokens)
|
||||
Pop(']]')
|
||||
else_node = ParseElseNode(tokens)
|
||||
return IfNode(ParseExpNode(exp_token), code_node, else_node)
|
||||
elif t == '$range':
|
||||
id_token = Pop('id')
|
||||
exp1_token = Pop('exp')
|
||||
Pop('..')
|
||||
exp2_token = Pop('exp')
|
||||
return RangeNode(id_token, ParseExpNode(exp1_token),
|
||||
ParseExpNode(exp2_token))
|
||||
elif t == '$id':
|
||||
return ParseExpNode(Token(head.start + 1, head.end, head.value[1:], 'id'))
|
||||
elif t == '$($)':
|
||||
return LiteralDollarNode(head)
|
||||
elif t == '$':
|
||||
exp_token = Pop('exp')
|
||||
return ParseExpNode(exp_token)
|
||||
elif t == '[[':
|
||||
code_node = ParseCodeNode(tokens)
|
||||
Pop(']]')
|
||||
return code_node
|
||||
else:
|
||||
PushFront(tokens, head)
|
||||
return None
|
||||
|
||||
|
||||
def ParseCodeNode(tokens):
|
||||
atomic_code_list = []
|
||||
while True:
|
||||
if not tokens:
|
||||
break
|
||||
atomic_code_node = ParseAtomicCodeNode(tokens)
|
||||
if atomic_code_node:
|
||||
atomic_code_list.append(atomic_code_node)
|
||||
else:
|
||||
break
|
||||
return CodeNode(atomic_code_list)
|
||||
|
||||
|
||||
def ParseToAST(pump_src_text):
|
||||
"""Convert the given Pump source text into an AST."""
|
||||
tokens = list(Tokenize(pump_src_text))
|
||||
code_node = ParseCodeNode(tokens)
|
||||
return code_node
|
||||
|
||||
|
||||
class Env:
|
||||
def __init__(self):
|
||||
self.variables = []
|
||||
self.ranges = []
|
||||
|
||||
def Clone(self):
|
||||
clone = Env()
|
||||
clone.variables = self.variables[:]
|
||||
clone.ranges = self.ranges[:]
|
||||
return clone
|
||||
|
||||
def PushVariable(self, var, value):
|
||||
# If value looks like an int, store it as an int.
|
||||
try:
|
||||
int_value = int(value)
|
||||
if ('%s' % int_value) == value:
|
||||
value = int_value
|
||||
except Exception:
|
||||
pass
|
||||
self.variables[:0] = [(var, value)]
|
||||
|
||||
def PopVariable(self):
|
||||
self.variables[:1] = []
|
||||
|
||||
def PushRange(self, var, lower, upper):
|
||||
self.ranges[:0] = [(var, lower, upper)]
|
||||
|
||||
def PopRange(self):
|
||||
self.ranges[:1] = []
|
||||
|
||||
def GetValue(self, identifier):
|
||||
for (var, value) in self.variables:
|
||||
if identifier == var:
|
||||
return value
|
||||
|
||||
print 'ERROR: meta variable %s is undefined.' % (identifier,)
|
||||
sys.exit(1)
|
||||
|
||||
def EvalExp(self, exp):
|
||||
try:
|
||||
result = eval(exp.python_exp)
|
||||
except Exception, e:
|
||||
print 'ERROR: caught exception %s: %s' % (e.__class__.__name__, e)
|
||||
print ('ERROR: failed to evaluate meta expression %s at %s' %
|
||||
(exp.python_exp, exp.token.start))
|
||||
sys.exit(1)
|
||||
return result
|
||||
|
||||
def GetRange(self, identifier):
|
||||
for (var, lower, upper) in self.ranges:
|
||||
if identifier == var:
|
||||
return (lower, upper)
|
||||
|
||||
print 'ERROR: range %s is undefined.' % (identifier,)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
class Output:
|
||||
def __init__(self):
|
||||
self.string = ''
|
||||
|
||||
def GetLastLine(self):
|
||||
index = self.string.rfind('\n')
|
||||
if index < 0:
|
||||
return ''
|
||||
|
||||
return self.string[index + 1:]
|
||||
|
||||
def Append(self, s):
|
||||
self.string += s
|
||||
|
||||
|
||||
def RunAtomicCode(env, node, output):
|
||||
if isinstance(node, VarNode):
|
||||
identifier = node.identifier.value.strip()
|
||||
result = Output()
|
||||
RunAtomicCode(env.Clone(), node.atomic_code, result)
|
||||
value = result.string
|
||||
env.PushVariable(identifier, value)
|
||||
elif isinstance(node, RangeNode):
|
||||
identifier = node.identifier.value.strip()
|
||||
lower = int(env.EvalExp(node.exp1))
|
||||
upper = int(env.EvalExp(node.exp2))
|
||||
env.PushRange(identifier, lower, upper)
|
||||
elif isinstance(node, ForNode):
|
||||
identifier = node.identifier.value.strip()
|
||||
if node.sep is None:
|
||||
sep = ''
|
||||
else:
|
||||
sep = node.sep.value
|
||||
(lower, upper) = env.GetRange(identifier)
|
||||
for i in range(lower, upper + 1):
|
||||
new_env = env.Clone()
|
||||
new_env.PushVariable(identifier, i)
|
||||
RunCode(new_env, node.code, output)
|
||||
if i != upper:
|
||||
output.Append(sep)
|
||||
elif isinstance(node, RawCodeNode):
|
||||
output.Append(node.raw_code.value)
|
||||
elif isinstance(node, IfNode):
|
||||
cond = env.EvalExp(node.exp)
|
||||
if cond:
|
||||
RunCode(env.Clone(), node.then_branch, output)
|
||||
elif node.else_branch is not None:
|
||||
RunCode(env.Clone(), node.else_branch, output)
|
||||
elif isinstance(node, ExpNode):
|
||||
value = env.EvalExp(node)
|
||||
output.Append('%s' % (value,))
|
||||
elif isinstance(node, LiteralDollarNode):
|
||||
output.Append('$')
|
||||
elif isinstance(node, CodeNode):
|
||||
RunCode(env.Clone(), node, output)
|
||||
else:
|
||||
print 'BAD'
|
||||
print node
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def RunCode(env, code_node, output):
|
||||
for atomic_code in code_node.atomic_code:
|
||||
RunAtomicCode(env, atomic_code, output)
|
||||
|
||||
|
||||
def IsSingleLineComment(cur_line):
|
||||
return '//' in cur_line
|
||||
|
||||
|
||||
def IsInPreprocessorDirective(prev_lines, cur_line):
|
||||
if cur_line.lstrip().startswith('#'):
|
||||
return True
|
||||
return prev_lines and prev_lines[-1].endswith('\\')
|
||||
|
||||
|
||||
def WrapComment(line, output):
|
||||
loc = line.find('//')
|
||||
before_comment = line[:loc].rstrip()
|
||||
if before_comment == '':
|
||||
indent = loc
|
||||
else:
|
||||
output.append(before_comment)
|
||||
indent = len(before_comment) - len(before_comment.lstrip())
|
||||
prefix = indent*' ' + '// '
|
||||
max_len = 80 - len(prefix)
|
||||
comment = line[loc + 2:].strip()
|
||||
segs = [seg for seg in re.split(r'(\w+\W*)', comment) if seg != '']
|
||||
cur_line = ''
|
||||
for seg in segs:
|
||||
if len((cur_line + seg).rstrip()) < max_len:
|
||||
cur_line += seg
|
||||
else:
|
||||
if cur_line.strip() != '':
|
||||
output.append(prefix + cur_line.rstrip())
|
||||
cur_line = seg.lstrip()
|
||||
if cur_line.strip() != '':
|
||||
output.append(prefix + cur_line.strip())
|
||||
|
||||
|
||||
def WrapCode(line, line_concat, output):
|
||||
indent = len(line) - len(line.lstrip())
|
||||
prefix = indent*' ' # Prefix of the current line
|
||||
max_len = 80 - indent - len(line_concat) # Maximum length of the current line
|
||||
new_prefix = prefix + 4*' ' # Prefix of a continuation line
|
||||
new_max_len = max_len - 4 # Maximum length of a continuation line
|
||||
# Prefers to wrap a line after a ',' or ';'.
|
||||
segs = [seg for seg in re.split(r'([^,;]+[,;]?)', line.strip()) if seg != '']
|
||||
cur_line = '' # The current line without leading spaces.
|
||||
for seg in segs:
|
||||
# If the line is still too long, wrap at a space.
|
||||
while cur_line == '' and len(seg.strip()) > max_len:
|
||||
seg = seg.lstrip()
|
||||
split_at = seg.rfind(' ', 0, max_len)
|
||||
output.append(prefix + seg[:split_at].strip() + line_concat)
|
||||
seg = seg[split_at + 1:]
|
||||
prefix = new_prefix
|
||||
max_len = new_max_len
|
||||
|
||||
if len((cur_line + seg).rstrip()) < max_len:
|
||||
cur_line = (cur_line + seg).lstrip()
|
||||
else:
|
||||
output.append(prefix + cur_line.rstrip() + line_concat)
|
||||
prefix = new_prefix
|
||||
max_len = new_max_len
|
||||
cur_line = seg.lstrip()
|
||||
if cur_line.strip() != '':
|
||||
output.append(prefix + cur_line.strip())
|
||||
|
||||
|
||||
def WrapPreprocessorDirective(line, output):
|
||||
WrapCode(line, ' \\', output)
|
||||
|
||||
|
||||
def WrapPlainCode(line, output):
|
||||
WrapCode(line, '', output)
|
||||
|
||||
|
||||
def IsMultiLineIWYUPragma(line):
|
||||
return re.search(r'/\* IWYU pragma: ', line)
|
||||
|
||||
|
||||
def IsHeaderGuardIncludeOrOneLineIWYUPragma(line):
|
||||
return (re.match(r'^#(ifndef|define|endif\s*//)\s*[\w_]+\s*$', line) or
|
||||
re.match(r'^#include\s', line) or
|
||||
# Don't break IWYU pragmas, either; that causes iwyu.py problems.
|
||||
re.search(r'// IWYU pragma: ', line))
|
||||
|
||||
|
||||
def WrapLongLine(line, output):
|
||||
line = line.rstrip()
|
||||
if len(line) <= 80:
|
||||
output.append(line)
|
||||
elif IsSingleLineComment(line):
|
||||
if IsHeaderGuardIncludeOrOneLineIWYUPragma(line):
|
||||
# The style guide made an exception to allow long header guard lines,
|
||||
# includes and IWYU pragmas.
|
||||
output.append(line)
|
||||
else:
|
||||
WrapComment(line, output)
|
||||
elif IsInPreprocessorDirective(output, line):
|
||||
if IsHeaderGuardIncludeOrOneLineIWYUPragma(line):
|
||||
# The style guide made an exception to allow long header guard lines,
|
||||
# includes and IWYU pragmas.
|
||||
output.append(line)
|
||||
else:
|
||||
WrapPreprocessorDirective(line, output)
|
||||
elif IsMultiLineIWYUPragma(line):
|
||||
output.append(line)
|
||||
else:
|
||||
WrapPlainCode(line, output)
|
||||
|
||||
|
||||
def BeautifyCode(string):
|
||||
lines = string.splitlines()
|
||||
output = []
|
||||
for line in lines:
|
||||
WrapLongLine(line, output)
|
||||
output2 = [line.rstrip() for line in output]
|
||||
return '\n'.join(output2) + '\n'
|
||||
|
||||
|
||||
def ConvertFromPumpSource(src_text):
|
||||
"""Return the text generated from the given Pump source text."""
|
||||
ast = ParseToAST(StripMetaComments(src_text))
|
||||
output = Output()
|
||||
RunCode(Env(), ast, output)
|
||||
return BeautifyCode(output.string)
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) == 1:
|
||||
print __doc__
|
||||
sys.exit(1)
|
||||
|
||||
file_path = argv[-1]
|
||||
output_str = ConvertFromPumpSource(file(file_path, 'r').read())
|
||||
if file_path.endswith('.pump'):
|
||||
output_file_path = file_path[:-5]
|
||||
else:
|
||||
output_file_path = '-'
|
||||
if output_file_path == '-':
|
||||
print output_str,
|
||||
else:
|
||||
output_file = file(output_file_path, 'w')
|
||||
output_file.write('// This file was GENERATED by command:\n')
|
||||
output_file.write('// %s %s\n' %
|
||||
(os.path.basename(__file__), os.path.basename(file_path)))
|
||||
output_file.write('// DO NOT EDIT BY HAND!!!\n\n')
|
||||
output_file.write(output_str)
|
||||
output_file.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv)
|
158
3rdparty/gtest/scripts/release_docs.py
vendored
Normal file
158
3rdparty/gtest/scripts/release_docs.py
vendored
Normal file
@ -0,0 +1,158 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2013 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.
|
||||
|
||||
"""Script for branching Google Test/Mock wiki pages for a new version.
|
||||
|
||||
SYNOPSIS
|
||||
release_docs.py NEW_RELEASE_VERSION
|
||||
|
||||
Google Test and Google Mock's external user documentation is in
|
||||
interlinked wiki files. When we release a new version of
|
||||
Google Test or Google Mock, we need to branch the wiki files
|
||||
such that users of a specific version of Google Test/Mock can
|
||||
look up documenation relevant for that version. This script
|
||||
automates that process by:
|
||||
|
||||
- branching the current wiki pages (which document the
|
||||
behavior of the SVN trunk head) to pages for the specified
|
||||
version (e.g. branching FAQ.wiki to V2_6_FAQ.wiki when
|
||||
NEW_RELEASE_VERSION is 2.6);
|
||||
- updating the links in the branched files to point to the branched
|
||||
version (e.g. a link in V2_6_FAQ.wiki that pointed to
|
||||
Primer.wiki#Anchor will now point to V2_6_Primer.wiki#Anchor).
|
||||
|
||||
NOTE: NEW_RELEASE_VERSION must be a NEW version number for
|
||||
which the wiki pages don't yet exist; otherwise you'll get SVN
|
||||
errors like "svn: Path 'V1_7_PumpManual.wiki' is not a
|
||||
directory" when running the script.
|
||||
|
||||
EXAMPLE
|
||||
$ cd PATH/TO/GTEST_SVN_WORKSPACE/trunk
|
||||
$ scripts/release_docs.py 2.6 # create wiki pages for v2.6
|
||||
$ svn status # verify the file list
|
||||
$ svn diff # verify the file contents
|
||||
$ svn commit -m "release wiki pages for v2.6"
|
||||
"""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
import common
|
||||
|
||||
|
||||
# Wiki pages that shouldn't be branched for every gtest/gmock release.
|
||||
GTEST_UNVERSIONED_WIKIS = ['DevGuide.wiki']
|
||||
GMOCK_UNVERSIONED_WIKIS = [
|
||||
'DesignDoc.wiki',
|
||||
'DevGuide.wiki',
|
||||
'KnownIssues.wiki'
|
||||
]
|
||||
|
||||
|
||||
def DropWikiSuffix(wiki_filename):
|
||||
"""Removes the .wiki suffix (if any) from the given filename."""
|
||||
|
||||
return (wiki_filename[:-len('.wiki')] if wiki_filename.endswith('.wiki')
|
||||
else wiki_filename)
|
||||
|
||||
|
||||
class WikiBrancher(object):
|
||||
"""Branches ..."""
|
||||
|
||||
def __init__(self, dot_version):
|
||||
self.project, svn_root_path = common.GetSvnInfo()
|
||||
if self.project not in ('googletest', 'googlemock'):
|
||||
sys.exit('This script must be run in a gtest or gmock SVN workspace.')
|
||||
self.wiki_dir = svn_root_path + '/wiki'
|
||||
# Turn '2.6' to 'V2_6_'.
|
||||
self.version_prefix = 'V' + dot_version.replace('.', '_') + '_'
|
||||
self.files_to_branch = self.GetFilesToBranch()
|
||||
page_names = [DropWikiSuffix(f) for f in self.files_to_branch]
|
||||
# A link to Foo.wiki is in one of the following forms:
|
||||
# [Foo words]
|
||||
# [Foo#Anchor words]
|
||||
# [http://code.google.com/.../wiki/Foo words]
|
||||
# [http://code.google.com/.../wiki/Foo#Anchor words]
|
||||
# We want to replace 'Foo' with 'V2_6_Foo' in the above cases.
|
||||
self.search_for_re = re.compile(
|
||||
# This regex matches either
|
||||
# [Foo
|
||||
# or
|
||||
# /wiki/Foo
|
||||
# followed by a space or a #, where Foo is the name of an
|
||||
# unversioned wiki page.
|
||||
r'(\[|/wiki/)(%s)([ #])' % '|'.join(page_names))
|
||||
self.replace_with = r'\1%s\2\3' % (self.version_prefix,)
|
||||
|
||||
def GetFilesToBranch(self):
|
||||
"""Returns a list of .wiki file names that need to be branched."""
|
||||
|
||||
unversioned_wikis = (GTEST_UNVERSIONED_WIKIS if self.project == 'googletest'
|
||||
else GMOCK_UNVERSIONED_WIKIS)
|
||||
return [f for f in os.listdir(self.wiki_dir)
|
||||
if (f.endswith('.wiki') and
|
||||
not re.match(r'^V\d', f) and # Excluded versioned .wiki files.
|
||||
f not in unversioned_wikis)]
|
||||
|
||||
def BranchFiles(self):
|
||||
"""Branches the .wiki files needed to be branched."""
|
||||
|
||||
print 'Branching %d .wiki files:' % (len(self.files_to_branch),)
|
||||
os.chdir(self.wiki_dir)
|
||||
for f in self.files_to_branch:
|
||||
command = 'svn cp %s %s%s' % (f, self.version_prefix, f)
|
||||
print command
|
||||
os.system(command)
|
||||
|
||||
def UpdateLinksInBranchedFiles(self):
|
||||
|
||||
for f in self.files_to_branch:
|
||||
source_file = os.path.join(self.wiki_dir, f)
|
||||
versioned_file = os.path.join(self.wiki_dir, self.version_prefix + f)
|
||||
print 'Updating links in %s.' % (versioned_file,)
|
||||
text = file(source_file, 'r').read()
|
||||
new_text = self.search_for_re.sub(self.replace_with, text)
|
||||
file(versioned_file, 'w').write(new_text)
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 2:
|
||||
sys.exit(__doc__)
|
||||
|
||||
brancher = WikiBrancher(sys.argv[1])
|
||||
brancher.BranchFiles()
|
||||
brancher.UpdateLinksInBranchedFiles()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
1387
3rdparty/gtest/scripts/upload.py
vendored
Normal file
1387
3rdparty/gtest/scripts/upload.py
vendored
Normal file
File diff suppressed because it is too large
Load Diff
78
3rdparty/gtest/scripts/upload_gtest.py
vendored
Normal file
78
3rdparty/gtest/scripts/upload_gtest.py
vendored
Normal file
@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2009, 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.
|
||||
|
||||
"""upload_gtest.py v0.1.0 -- uploads a Google Test patch for review.
|
||||
|
||||
This simple wrapper passes all command line flags and
|
||||
--cc=googletestframework@googlegroups.com to upload.py.
|
||||
|
||||
USAGE: upload_gtest.py [options for upload.py]
|
||||
"""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
CC_FLAG = '--cc='
|
||||
GTEST_GROUP = 'googletestframework@googlegroups.com'
|
||||
|
||||
|
||||
def main():
|
||||
# Finds the path to upload.py, assuming it is in the same directory
|
||||
# as this file.
|
||||
my_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
upload_py_path = os.path.join(my_dir, 'upload.py')
|
||||
|
||||
# Adds Google Test discussion group to the cc line if it's not there
|
||||
# already.
|
||||
upload_py_argv = [upload_py_path]
|
||||
found_cc_flag = False
|
||||
for arg in sys.argv[1:]:
|
||||
if arg.startswith(CC_FLAG):
|
||||
found_cc_flag = True
|
||||
cc_line = arg[len(CC_FLAG):]
|
||||
cc_list = [addr for addr in cc_line.split(',') if addr]
|
||||
if GTEST_GROUP not in cc_list:
|
||||
cc_list.append(GTEST_GROUP)
|
||||
upload_py_argv.append(CC_FLAG + ','.join(cc_list))
|
||||
else:
|
||||
upload_py_argv.append(arg)
|
||||
|
||||
if not found_cc_flag:
|
||||
upload_py_argv.append(CC_FLAG + GTEST_GROUP)
|
||||
|
||||
# Invokes upload.py with the modified command line flags.
|
||||
os.execv(upload_py_path, upload_py_argv)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
48
3rdparty/gtest/src/gtest-all.cc
vendored
Normal file
48
3rdparty/gtest/src/gtest-all.cc
vendored
Normal file
@ -0,0 +1,48 @@
|
||||
// Copyright 2008, 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.
|
||||
|
||||
//
|
||||
// Google C++ Testing and Mocking Framework (Google Test)
|
||||
//
|
||||
// Sometimes it's desirable to build Google Test by compiling a single file.
|
||||
// This file serves this purpose.
|
||||
|
||||
// This line ensures that gtest.h can be compiled on its own, even
|
||||
// when it's fused.
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
// The following lines pull in the real gtest *.cc files.
|
||||
#include "src/gtest.cc"
|
||||
#include "src/gtest-death-test.cc"
|
||||
#include "src/gtest-filepath.cc"
|
||||
#include "src/gtest-matchers.cc"
|
||||
#include "src/gtest-port.cc"
|
||||
#include "src/gtest-printers.cc"
|
||||
#include "src/gtest-test-part.cc"
|
||||
#include "src/gtest-typed-test.cc"
|
1653
3rdparty/gtest/src/gtest-death-test.cc
vendored
Normal file
1653
3rdparty/gtest/src/gtest-death-test.cc
vendored
Normal file
File diff suppressed because it is too large
Load Diff
379
3rdparty/gtest/src/gtest-filepath.cc
vendored
Normal file
379
3rdparty/gtest/src/gtest-filepath.cc
vendored
Normal file
@ -0,0 +1,379 @@
|
||||
// Copyright 2008, 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.
|
||||
|
||||
#include "gtest/internal/gtest-filepath.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
#include "gtest/gtest-message.h"
|
||||
|
||||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
# include <windows.h>
|
||||
#elif GTEST_OS_WINDOWS
|
||||
# include <direct.h>
|
||||
# include <io.h>
|
||||
#else
|
||||
# include <limits.h>
|
||||
# include <climits> // Some Linux distributions define PATH_MAX here.
|
||||
#endif // GTEST_OS_WINDOWS_MOBILE
|
||||
|
||||
#include "gtest/internal/gtest-string.h"
|
||||
|
||||
#if GTEST_OS_WINDOWS
|
||||
# define GTEST_PATH_MAX_ _MAX_PATH
|
||||
#elif defined(PATH_MAX)
|
||||
# define GTEST_PATH_MAX_ PATH_MAX
|
||||
#elif defined(_XOPEN_PATH_MAX)
|
||||
# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
|
||||
#else
|
||||
# define GTEST_PATH_MAX_ _POSIX_PATH_MAX
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
#if GTEST_OS_WINDOWS
|
||||
// On Windows, '\\' is the standard path separator, but many tools and the
|
||||
// Windows API also accept '/' as an alternate path separator. Unless otherwise
|
||||
// noted, a file path can contain either kind of path separators, or a mixture
|
||||
// of them.
|
||||
const char kPathSeparator = '\\';
|
||||
const char kAlternatePathSeparator = '/';
|
||||
const char kAlternatePathSeparatorString[] = "/";
|
||||
# if GTEST_OS_WINDOWS_MOBILE
|
||||
// Windows CE doesn't have a current directory. You should not use
|
||||
// the current directory in tests on Windows CE, but this at least
|
||||
// provides a reasonable fallback.
|
||||
const char kCurrentDirectoryString[] = "\\";
|
||||
// Windows CE doesn't define INVALID_FILE_ATTRIBUTES
|
||||
const DWORD kInvalidFileAttributes = 0xffffffff;
|
||||
# else
|
||||
const char kCurrentDirectoryString[] = ".\\";
|
||||
# endif // GTEST_OS_WINDOWS_MOBILE
|
||||
#else
|
||||
const char kPathSeparator = '/';
|
||||
const char kCurrentDirectoryString[] = "./";
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
|
||||
// Returns whether the given character is a valid path separator.
|
||||
static bool IsPathSeparator(char c) {
|
||||
#if GTEST_HAS_ALT_PATH_SEP_
|
||||
return (c == kPathSeparator) || (c == kAlternatePathSeparator);
|
||||
#else
|
||||
return c == kPathSeparator;
|
||||
#endif
|
||||
}
|
||||
|
||||
// Returns the current working directory, or "" if unsuccessful.
|
||||
FilePath FilePath::GetCurrentDir() {
|
||||
#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
|
||||
GTEST_OS_WINDOWS_RT || ARDUINO || defined(ESP_PLATFORM)
|
||||
// These platforms do not have a current directory, so we just return
|
||||
// something reasonable.
|
||||
return FilePath(kCurrentDirectoryString);
|
||||
#elif GTEST_OS_WINDOWS
|
||||
char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
|
||||
return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);
|
||||
#else
|
||||
char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
|
||||
char* result = getcwd(cwd, sizeof(cwd));
|
||||
# if GTEST_OS_NACL
|
||||
// getcwd will likely fail in NaCl due to the sandbox, so return something
|
||||
// reasonable. The user may have provided a shim implementation for getcwd,
|
||||
// however, so fallback only when failure is detected.
|
||||
return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);
|
||||
# endif // GTEST_OS_NACL
|
||||
return FilePath(result == nullptr ? "" : cwd);
|
||||
#endif // GTEST_OS_WINDOWS_MOBILE
|
||||
}
|
||||
|
||||
// Returns a copy of the FilePath with the case-insensitive extension removed.
|
||||
// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
|
||||
// FilePath("dir/file"). If a case-insensitive extension is not
|
||||
// found, returns a copy of the original FilePath.
|
||||
FilePath FilePath::RemoveExtension(const char* extension) const {
|
||||
const std::string dot_extension = std::string(".") + extension;
|
||||
if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
|
||||
return FilePath(pathname_.substr(
|
||||
0, pathname_.length() - dot_extension.length()));
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Returns a pointer to the last occurrence of a valid path separator in
|
||||
// the FilePath. On Windows, for example, both '/' and '\' are valid path
|
||||
// separators. Returns NULL if no path separator was found.
|
||||
const char* FilePath::FindLastPathSeparator() const {
|
||||
const char* const last_sep = strrchr(c_str(), kPathSeparator);
|
||||
#if GTEST_HAS_ALT_PATH_SEP_
|
||||
const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
|
||||
// Comparing two pointers of which only one is NULL is undefined.
|
||||
if (last_alt_sep != nullptr &&
|
||||
(last_sep == nullptr || last_alt_sep > last_sep)) {
|
||||
return last_alt_sep;
|
||||
}
|
||||
#endif
|
||||
return last_sep;
|
||||
}
|
||||
|
||||
// Returns a copy of the FilePath with the directory part removed.
|
||||
// Example: FilePath("path/to/file").RemoveDirectoryName() returns
|
||||
// FilePath("file"). If there is no directory part ("just_a_file"), it returns
|
||||
// the FilePath unmodified. If there is no file part ("just_a_dir/") it
|
||||
// returns an empty FilePath ("").
|
||||
// On Windows platform, '\' is the path separator, otherwise it is '/'.
|
||||
FilePath FilePath::RemoveDirectoryName() const {
|
||||
const char* const last_sep = FindLastPathSeparator();
|
||||
return last_sep ? FilePath(last_sep + 1) : *this;
|
||||
}
|
||||
|
||||
// RemoveFileName returns the directory path with the filename removed.
|
||||
// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
|
||||
// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
|
||||
// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
|
||||
// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
|
||||
// On Windows platform, '\' is the path separator, otherwise it is '/'.
|
||||
FilePath FilePath::RemoveFileName() const {
|
||||
const char* const last_sep = FindLastPathSeparator();
|
||||
std::string dir;
|
||||
if (last_sep) {
|
||||
dir = std::string(c_str(), static_cast<size_t>(last_sep + 1 - c_str()));
|
||||
} else {
|
||||
dir = kCurrentDirectoryString;
|
||||
}
|
||||
return FilePath(dir);
|
||||
}
|
||||
|
||||
// Helper functions for naming files in a directory for xml output.
|
||||
|
||||
// Given directory = "dir", base_name = "test", number = 0,
|
||||
// extension = "xml", returns "dir/test.xml". If number is greater
|
||||
// than zero (e.g., 12), returns "dir/test_12.xml".
|
||||
// On Windows platform, uses \ as the separator rather than /.
|
||||
FilePath FilePath::MakeFileName(const FilePath& directory,
|
||||
const FilePath& base_name,
|
||||
int number,
|
||||
const char* extension) {
|
||||
std::string file;
|
||||
if (number == 0) {
|
||||
file = base_name.string() + "." + extension;
|
||||
} else {
|
||||
file = base_name.string() + "_" + StreamableToString(number)
|
||||
+ "." + extension;
|
||||
}
|
||||
return ConcatPaths(directory, FilePath(file));
|
||||
}
|
||||
|
||||
// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
|
||||
// On Windows, uses \ as the separator rather than /.
|
||||
FilePath FilePath::ConcatPaths(const FilePath& directory,
|
||||
const FilePath& relative_path) {
|
||||
if (directory.IsEmpty())
|
||||
return relative_path;
|
||||
const FilePath dir(directory.RemoveTrailingPathSeparator());
|
||||
return FilePath(dir.string() + kPathSeparator + relative_path.string());
|
||||
}
|
||||
|
||||
// Returns true if pathname describes something findable in the file-system,
|
||||
// either a file, directory, or whatever.
|
||||
bool FilePath::FileOrDirectoryExists() const {
|
||||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
|
||||
const DWORD attributes = GetFileAttributes(unicode);
|
||||
delete [] unicode;
|
||||
return attributes != kInvalidFileAttributes;
|
||||
#else
|
||||
posix::StatStruct file_stat;
|
||||
return posix::Stat(pathname_.c_str(), &file_stat) == 0;
|
||||
#endif // GTEST_OS_WINDOWS_MOBILE
|
||||
}
|
||||
|
||||
// Returns true if pathname describes a directory in the file-system
|
||||
// that exists.
|
||||
bool FilePath::DirectoryExists() const {
|
||||
bool result = false;
|
||||
#if GTEST_OS_WINDOWS
|
||||
// Don't strip off trailing separator if path is a root directory on
|
||||
// Windows (like "C:\\").
|
||||
const FilePath& path(IsRootDirectory() ? *this :
|
||||
RemoveTrailingPathSeparator());
|
||||
#else
|
||||
const FilePath& path(*this);
|
||||
#endif
|
||||
|
||||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
|
||||
const DWORD attributes = GetFileAttributes(unicode);
|
||||
delete [] unicode;
|
||||
if ((attributes != kInvalidFileAttributes) &&
|
||||
(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
|
||||
result = true;
|
||||
}
|
||||
#else
|
||||
posix::StatStruct file_stat;
|
||||
result = posix::Stat(path.c_str(), &file_stat) == 0 &&
|
||||
posix::IsDir(file_stat);
|
||||
#endif // GTEST_OS_WINDOWS_MOBILE
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Returns true if pathname describes a root directory. (Windows has one
|
||||
// root directory per disk drive.)
|
||||
bool FilePath::IsRootDirectory() const {
|
||||
#if GTEST_OS_WINDOWS
|
||||
return pathname_.length() == 3 && IsAbsolutePath();
|
||||
#else
|
||||
return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
|
||||
#endif
|
||||
}
|
||||
|
||||
// Returns true if pathname describes an absolute path.
|
||||
bool FilePath::IsAbsolutePath() const {
|
||||
const char* const name = pathname_.c_str();
|
||||
#if GTEST_OS_WINDOWS
|
||||
return pathname_.length() >= 3 &&
|
||||
((name[0] >= 'a' && name[0] <= 'z') ||
|
||||
(name[0] >= 'A' && name[0] <= 'Z')) &&
|
||||
name[1] == ':' &&
|
||||
IsPathSeparator(name[2]);
|
||||
#else
|
||||
return IsPathSeparator(name[0]);
|
||||
#endif
|
||||
}
|
||||
|
||||
// Returns a pathname for a file that does not currently exist. The pathname
|
||||
// will be directory/base_name.extension or
|
||||
// directory/base_name_<number>.extension if directory/base_name.extension
|
||||
// already exists. The number will be incremented until a pathname is found
|
||||
// that does not already exist.
|
||||
// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
|
||||
// There could be a race condition if two or more processes are calling this
|
||||
// function at the same time -- they could both pick the same filename.
|
||||
FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
|
||||
const FilePath& base_name,
|
||||
const char* extension) {
|
||||
FilePath full_pathname;
|
||||
int number = 0;
|
||||
do {
|
||||
full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
|
||||
} while (full_pathname.FileOrDirectoryExists());
|
||||
return full_pathname;
|
||||
}
|
||||
|
||||
// Returns true if FilePath ends with a path separator, which indicates that
|
||||
// it is intended to represent a directory. Returns false otherwise.
|
||||
// This does NOT check that a directory (or file) actually exists.
|
||||
bool FilePath::IsDirectory() const {
|
||||
return !pathname_.empty() &&
|
||||
IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
|
||||
}
|
||||
|
||||
// Create directories so that path exists. Returns true if successful or if
|
||||
// the directories already exist; returns false if unable to create directories
|
||||
// for any reason.
|
||||
bool FilePath::CreateDirectoriesRecursively() const {
|
||||
if (!this->IsDirectory()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (pathname_.length() == 0 || this->DirectoryExists()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
|
||||
return parent.CreateDirectoriesRecursively() && this->CreateFolder();
|
||||
}
|
||||
|
||||
// Create the directory so that path exists. Returns true if successful or
|
||||
// if the directory already exists; returns false if unable to create the
|
||||
// directory for any reason, including if the parent directory does not
|
||||
// exist. Not named "CreateDirectory" because that's a macro on Windows.
|
||||
bool FilePath::CreateFolder() const {
|
||||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
FilePath removed_sep(this->RemoveTrailingPathSeparator());
|
||||
LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
|
||||
int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
|
||||
delete [] unicode;
|
||||
#elif GTEST_OS_WINDOWS
|
||||
int result = _mkdir(pathname_.c_str());
|
||||
#else
|
||||
int result = mkdir(pathname_.c_str(), 0777);
|
||||
#endif // GTEST_OS_WINDOWS_MOBILE
|
||||
|
||||
if (result == -1) {
|
||||
return this->DirectoryExists(); // An error is OK if the directory exists.
|
||||
}
|
||||
return true; // No error.
|
||||
}
|
||||
|
||||
// If input name has a trailing separator character, remove it and return the
|
||||
// name, otherwise return the name string unmodified.
|
||||
// On Windows platform, uses \ as the separator, other platforms use /.
|
||||
FilePath FilePath::RemoveTrailingPathSeparator() const {
|
||||
return IsDirectory()
|
||||
? FilePath(pathname_.substr(0, pathname_.length() - 1))
|
||||
: *this;
|
||||
}
|
||||
|
||||
// Removes any redundant separators that might be in the pathname.
|
||||
// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
|
||||
// redundancies that might be in a pathname involving "." or "..".
|
||||
void FilePath::Normalize() {
|
||||
if (pathname_.c_str() == nullptr) {
|
||||
pathname_ = "";
|
||||
return;
|
||||
}
|
||||
const char* src = pathname_.c_str();
|
||||
char* const dest = new char[pathname_.length() + 1];
|
||||
char* dest_ptr = dest;
|
||||
memset(dest_ptr, 0, pathname_.length() + 1);
|
||||
|
||||
while (*src != '\0') {
|
||||
*dest_ptr = *src;
|
||||
if (!IsPathSeparator(*src)) {
|
||||
src++;
|
||||
} else {
|
||||
#if GTEST_HAS_ALT_PATH_SEP_
|
||||
if (*dest_ptr == kAlternatePathSeparator) {
|
||||
*dest_ptr = kPathSeparator;
|
||||
}
|
||||
#endif
|
||||
while (IsPathSeparator(*src))
|
||||
src++;
|
||||
}
|
||||
dest_ptr++;
|
||||
}
|
||||
*dest_ptr = '\0';
|
||||
pathname_ = dest;
|
||||
delete[] dest;
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
1211
3rdparty/gtest/src/gtest-internal-inl.h
vendored
Normal file
1211
3rdparty/gtest/src/gtest-internal-inl.h
vendored
Normal file
File diff suppressed because it is too large
Load Diff
97
3rdparty/gtest/src/gtest-matchers.cc
vendored
Normal file
97
3rdparty/gtest/src/gtest-matchers.cc
vendored
Normal file
@ -0,0 +1,97 @@
|
||||
// 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.
|
||||
|
||||
// The Google C++ Testing and Mocking Framework (Google Test)
|
||||
//
|
||||
// This file implements just enough of the matcher interface to allow
|
||||
// EXPECT_DEATH and friends to accept a matcher argument.
|
||||
|
||||
#include "gtest/internal/gtest-internal.h"
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
#include "gtest/gtest-matchers.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace testing {
|
||||
|
||||
// Constructs a matcher that matches a const std::string& whose value is
|
||||
// equal to s.
|
||||
Matcher<const std::string&>::Matcher(const std::string& s) { *this = Eq(s); }
|
||||
|
||||
// Constructs a matcher that matches a const std::string& whose value is
|
||||
// equal to s.
|
||||
Matcher<const std::string&>::Matcher(const char* s) {
|
||||
*this = Eq(std::string(s));
|
||||
}
|
||||
|
||||
// Constructs a matcher that matches a std::string whose value is equal to
|
||||
// s.
|
||||
Matcher<std::string>::Matcher(const std::string& s) { *this = Eq(s); }
|
||||
|
||||
// Constructs a matcher that matches a std::string whose value is equal to
|
||||
// s.
|
||||
Matcher<std::string>::Matcher(const char* s) { *this = Eq(std::string(s)); }
|
||||
|
||||
#if GTEST_HAS_ABSL
|
||||
// Constructs a matcher that matches a const absl::string_view& whose value is
|
||||
// equal to s.
|
||||
Matcher<const absl::string_view&>::Matcher(const std::string& s) {
|
||||
*this = Eq(s);
|
||||
}
|
||||
|
||||
// Constructs a matcher that matches a const absl::string_view& whose value is
|
||||
// equal to s.
|
||||
Matcher<const absl::string_view&>::Matcher(const char* s) {
|
||||
*this = Eq(std::string(s));
|
||||
}
|
||||
|
||||
// Constructs a matcher that matches a const absl::string_view& whose value is
|
||||
// equal to s.
|
||||
Matcher<const absl::string_view&>::Matcher(absl::string_view s) {
|
||||
*this = Eq(std::string(s));
|
||||
}
|
||||
|
||||
// Constructs a matcher that matches a absl::string_view whose value is equal to
|
||||
// s.
|
||||
Matcher<absl::string_view>::Matcher(const std::string& s) { *this = Eq(s); }
|
||||
|
||||
// Constructs a matcher that matches a absl::string_view whose value is equal to
|
||||
// s.
|
||||
Matcher<absl::string_view>::Matcher(const char* s) {
|
||||
*this = Eq(std::string(s));
|
||||
}
|
||||
|
||||
// Constructs a matcher that matches a absl::string_view whose value is equal to
|
||||
// s.
|
||||
Matcher<absl::string_view>::Matcher(absl::string_view s) {
|
||||
*this = Eq(std::string(s));
|
||||
}
|
||||
#endif // GTEST_HAS_ABSL
|
||||
|
||||
} // namespace testing
|
1399
3rdparty/gtest/src/gtest-port.cc
vendored
Normal file
1399
3rdparty/gtest/src/gtest-port.cc
vendored
Normal file
File diff suppressed because it is too large
Load Diff
442
3rdparty/gtest/src/gtest-printers.cc
vendored
Normal file
442
3rdparty/gtest/src/gtest-printers.cc
vendored
Normal file
@ -0,0 +1,442 @@
|
||||
// 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.
|
||||
|
||||
|
||||
// Google Test - The Google C++ Testing and Mocking Framework
|
||||
//
|
||||
// This file implements a universal value printer that can print a
|
||||
// value of any type T:
|
||||
//
|
||||
// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
|
||||
//
|
||||
// It uses the << operator when possible, and prints the bytes in the
|
||||
// object otherwise. A user can override its behavior for a class
|
||||
// type Foo by defining either operator<<(::std::ostream&, const Foo&)
|
||||
// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
|
||||
// defines Foo.
|
||||
|
||||
#include "gtest/gtest-printers.h"
|
||||
#include <stdio.h>
|
||||
#include <cctype>
|
||||
#include <cwchar>
|
||||
#include <ostream> // NOLINT
|
||||
#include <string>
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
#include "src/gtest-internal-inl.h"
|
||||
|
||||
namespace testing {
|
||||
|
||||
namespace {
|
||||
|
||||
using ::std::ostream;
|
||||
|
||||
// Prints a segment of bytes in the given object.
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
|
||||
void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
|
||||
size_t count, ostream* os) {
|
||||
char text[5] = "";
|
||||
for (size_t i = 0; i != count; i++) {
|
||||
const size_t j = start + i;
|
||||
if (i != 0) {
|
||||
// Organizes the bytes into groups of 2 for easy parsing by
|
||||
// human.
|
||||
if ((j % 2) == 0)
|
||||
*os << ' ';
|
||||
else
|
||||
*os << '-';
|
||||
}
|
||||
GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
|
||||
*os << text;
|
||||
}
|
||||
}
|
||||
|
||||
// Prints the bytes in the given value to the given ostream.
|
||||
void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
|
||||
ostream* os) {
|
||||
// Tells the user how big the object is.
|
||||
*os << count << "-byte object <";
|
||||
|
||||
const size_t kThreshold = 132;
|
||||
const size_t kChunkSize = 64;
|
||||
// If the object size is bigger than kThreshold, we'll have to omit
|
||||
// some details by printing only the first and the last kChunkSize
|
||||
// bytes.
|
||||
if (count < kThreshold) {
|
||||
PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
|
||||
} else {
|
||||
PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
|
||||
*os << " ... ";
|
||||
// Rounds up to 2-byte boundary.
|
||||
const size_t resume_pos = (count - kChunkSize + 1)/2*2;
|
||||
PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
|
||||
}
|
||||
*os << ">";
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
namespace internal2 {
|
||||
|
||||
// Delegates to PrintBytesInObjectToImpl() to print the bytes in the
|
||||
// given object. The delegation simplifies the implementation, which
|
||||
// uses the << operator and thus is easier done outside of the
|
||||
// ::testing::internal namespace, which contains a << operator that
|
||||
// sometimes conflicts with the one in STL.
|
||||
void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
|
||||
ostream* os) {
|
||||
PrintBytesInObjectToImpl(obj_bytes, count, os);
|
||||
}
|
||||
|
||||
} // namespace internal2
|
||||
|
||||
namespace internal {
|
||||
|
||||
// Depending on the value of a char (or wchar_t), we print it in one
|
||||
// of three formats:
|
||||
// - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
|
||||
// - as a hexadecimal escape sequence (e.g. '\x7F'), or
|
||||
// - as a special escape sequence (e.g. '\r', '\n').
|
||||
enum CharFormat {
|
||||
kAsIs,
|
||||
kHexEscape,
|
||||
kSpecialEscape
|
||||
};
|
||||
|
||||
// Returns true if c is a printable ASCII character. We test the
|
||||
// value of c directly instead of calling isprint(), which is buggy on
|
||||
// Windows Mobile.
|
||||
inline bool IsPrintableAscii(wchar_t c) {
|
||||
return 0x20 <= c && c <= 0x7E;
|
||||
}
|
||||
|
||||
// Prints a wide or narrow char c as a character literal without the
|
||||
// quotes, escaping it when necessary; returns how c was formatted.
|
||||
// The template argument UnsignedChar is the unsigned version of Char,
|
||||
// which is the type of c.
|
||||
template <typename UnsignedChar, typename Char>
|
||||
static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
|
||||
wchar_t w_c = static_cast<wchar_t>(c);
|
||||
switch (w_c) {
|
||||
case L'\0':
|
||||
*os << "\\0";
|
||||
break;
|
||||
case L'\'':
|
||||
*os << "\\'";
|
||||
break;
|
||||
case L'\\':
|
||||
*os << "\\\\";
|
||||
break;
|
||||
case L'\a':
|
||||
*os << "\\a";
|
||||
break;
|
||||
case L'\b':
|
||||
*os << "\\b";
|
||||
break;
|
||||
case L'\f':
|
||||
*os << "\\f";
|
||||
break;
|
||||
case L'\n':
|
||||
*os << "\\n";
|
||||
break;
|
||||
case L'\r':
|
||||
*os << "\\r";
|
||||
break;
|
||||
case L'\t':
|
||||
*os << "\\t";
|
||||
break;
|
||||
case L'\v':
|
||||
*os << "\\v";
|
||||
break;
|
||||
default:
|
||||
if (IsPrintableAscii(w_c)) {
|
||||
*os << static_cast<char>(c);
|
||||
return kAsIs;
|
||||
} else {
|
||||
ostream::fmtflags flags = os->flags();
|
||||
*os << "\\x" << std::hex << std::uppercase
|
||||
<< static_cast<int>(static_cast<UnsignedChar>(c));
|
||||
os->flags(flags);
|
||||
return kHexEscape;
|
||||
}
|
||||
}
|
||||
return kSpecialEscape;
|
||||
}
|
||||
|
||||
// Prints a wchar_t c as if it's part of a string literal, escaping it when
|
||||
// necessary; returns how c was formatted.
|
||||
static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
|
||||
switch (c) {
|
||||
case L'\'':
|
||||
*os << "'";
|
||||
return kAsIs;
|
||||
case L'"':
|
||||
*os << "\\\"";
|
||||
return kSpecialEscape;
|
||||
default:
|
||||
return PrintAsCharLiteralTo<wchar_t>(c, os);
|
||||
}
|
||||
}
|
||||
|
||||
// Prints a char c as if it's part of a string literal, escaping it when
|
||||
// necessary; returns how c was formatted.
|
||||
static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
|
||||
return PrintAsStringLiteralTo(
|
||||
static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
|
||||
}
|
||||
|
||||
// Prints a wide or narrow character c and its code. '\0' is printed
|
||||
// as "'\\0'", other unprintable characters are also properly escaped
|
||||
// using the standard C++ escape sequence. The template argument
|
||||
// UnsignedChar is the unsigned version of Char, which is the type of c.
|
||||
template <typename UnsignedChar, typename Char>
|
||||
void PrintCharAndCodeTo(Char c, ostream* os) {
|
||||
// First, print c as a literal in the most readable form we can find.
|
||||
*os << ((sizeof(c) > 1) ? "L'" : "'");
|
||||
const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
|
||||
*os << "'";
|
||||
|
||||
// To aid user debugging, we also print c's code in decimal, unless
|
||||
// it's 0 (in which case c was printed as '\\0', making the code
|
||||
// obvious).
|
||||
if (c == 0)
|
||||
return;
|
||||
*os << " (" << static_cast<int>(c);
|
||||
|
||||
// For more convenience, we print c's code again in hexadecimal,
|
||||
// unless c was already printed in the form '\x##' or the code is in
|
||||
// [1, 9].
|
||||
if (format == kHexEscape || (1 <= c && c <= 9)) {
|
||||
// Do nothing.
|
||||
} else {
|
||||
*os << ", 0x" << String::FormatHexInt(static_cast<int>(c));
|
||||
}
|
||||
*os << ")";
|
||||
}
|
||||
|
||||
void PrintTo(unsigned char c, ::std::ostream* os) {
|
||||
PrintCharAndCodeTo<unsigned char>(c, os);
|
||||
}
|
||||
void PrintTo(signed char c, ::std::ostream* os) {
|
||||
PrintCharAndCodeTo<unsigned char>(c, os);
|
||||
}
|
||||
|
||||
// Prints a wchar_t as a symbol if it is printable or as its internal
|
||||
// code otherwise and also as its code. L'\0' is printed as "L'\\0'".
|
||||
void PrintTo(wchar_t wc, ostream* os) {
|
||||
PrintCharAndCodeTo<wchar_t>(wc, os);
|
||||
}
|
||||
|
||||
// Prints the given array of characters to the ostream. CharType must be either
|
||||
// char or wchar_t.
|
||||
// The array starts at begin, the length is len, it may include '\0' characters
|
||||
// and may not be NUL-terminated.
|
||||
template <typename CharType>
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
|
||||
static CharFormat PrintCharsAsStringTo(
|
||||
const CharType* begin, size_t len, ostream* os) {
|
||||
const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
|
||||
*os << kQuoteBegin;
|
||||
bool is_previous_hex = false;
|
||||
CharFormat print_format = kAsIs;
|
||||
for (size_t index = 0; index < len; ++index) {
|
||||
const CharType cur = begin[index];
|
||||
if (is_previous_hex && IsXDigit(cur)) {
|
||||
// Previous character is of '\x..' form and this character can be
|
||||
// interpreted as another hexadecimal digit in its number. Break string to
|
||||
// disambiguate.
|
||||
*os << "\" " << kQuoteBegin;
|
||||
}
|
||||
is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
|
||||
// Remember if any characters required hex escaping.
|
||||
if (is_previous_hex) {
|
||||
print_format = kHexEscape;
|
||||
}
|
||||
}
|
||||
*os << "\"";
|
||||
return print_format;
|
||||
}
|
||||
|
||||
// Prints a (const) char/wchar_t array of 'len' elements, starting at address
|
||||
// 'begin'. CharType must be either char or wchar_t.
|
||||
template <typename CharType>
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
|
||||
static void UniversalPrintCharArray(
|
||||
const CharType* begin, size_t len, ostream* os) {
|
||||
// The code
|
||||
// const char kFoo[] = "foo";
|
||||
// generates an array of 4, not 3, elements, with the last one being '\0'.
|
||||
//
|
||||
// Therefore when printing a char array, we don't print the last element if
|
||||
// it's '\0', such that the output matches the string literal as it's
|
||||
// written in the source code.
|
||||
if (len > 0 && begin[len - 1] == '\0') {
|
||||
PrintCharsAsStringTo(begin, len - 1, os);
|
||||
return;
|
||||
}
|
||||
|
||||
// If, however, the last element in the array is not '\0', e.g.
|
||||
// const char kFoo[] = { 'f', 'o', 'o' };
|
||||
// we must print the entire array. We also print a message to indicate
|
||||
// that the array is not NUL-terminated.
|
||||
PrintCharsAsStringTo(begin, len, os);
|
||||
*os << " (no terminating NUL)";
|
||||
}
|
||||
|
||||
// Prints a (const) char array of 'len' elements, starting at address 'begin'.
|
||||
void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
|
||||
UniversalPrintCharArray(begin, len, os);
|
||||
}
|
||||
|
||||
// Prints a (const) wchar_t array of 'len' elements, starting at address
|
||||
// 'begin'.
|
||||
void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
|
||||
UniversalPrintCharArray(begin, len, os);
|
||||
}
|
||||
|
||||
// Prints the given C string to the ostream.
|
||||
void PrintTo(const char* s, ostream* os) {
|
||||
if (s == nullptr) {
|
||||
*os << "NULL";
|
||||
} else {
|
||||
*os << ImplicitCast_<const void*>(s) << " pointing to ";
|
||||
PrintCharsAsStringTo(s, strlen(s), os);
|
||||
}
|
||||
}
|
||||
|
||||
// MSVC compiler can be configured to define whar_t as a typedef
|
||||
// of unsigned short. Defining an overload for const wchar_t* in that case
|
||||
// would cause pointers to unsigned shorts be printed as wide strings,
|
||||
// possibly accessing more memory than intended and causing invalid
|
||||
// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
|
||||
// wchar_t is implemented as a native type.
|
||||
#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
|
||||
// Prints the given wide C string to the ostream.
|
||||
void PrintTo(const wchar_t* s, ostream* os) {
|
||||
if (s == nullptr) {
|
||||
*os << "NULL";
|
||||
} else {
|
||||
*os << ImplicitCast_<const void*>(s) << " pointing to ";
|
||||
PrintCharsAsStringTo(s, wcslen(s), os);
|
||||
}
|
||||
}
|
||||
#endif // wchar_t is native
|
||||
|
||||
namespace {
|
||||
|
||||
bool ContainsUnprintableControlCodes(const char* str, size_t length) {
|
||||
const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
|
||||
|
||||
for (size_t i = 0; i < length; i++) {
|
||||
unsigned char ch = *s++;
|
||||
if (std::iscntrl(ch)) {
|
||||
switch (ch) {
|
||||
case '\t':
|
||||
case '\n':
|
||||
case '\r':
|
||||
break;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; }
|
||||
|
||||
bool IsValidUTF8(const char* str, size_t length) {
|
||||
const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
|
||||
|
||||
for (size_t i = 0; i < length;) {
|
||||
unsigned char lead = s[i++];
|
||||
|
||||
if (lead <= 0x7f) {
|
||||
continue; // single-byte character (ASCII) 0..7F
|
||||
}
|
||||
if (lead < 0xc2) {
|
||||
return false; // trail byte or non-shortest form
|
||||
} else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
|
||||
++i; // 2-byte character
|
||||
} else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
|
||||
IsUTF8TrailByte(s[i]) &&
|
||||
IsUTF8TrailByte(s[i + 1]) &&
|
||||
// check for non-shortest form and surrogate
|
||||
(lead != 0xe0 || s[i] >= 0xa0) &&
|
||||
(lead != 0xed || s[i] < 0xa0)) {
|
||||
i += 2; // 3-byte character
|
||||
} else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
|
||||
IsUTF8TrailByte(s[i]) &&
|
||||
IsUTF8TrailByte(s[i + 1]) &&
|
||||
IsUTF8TrailByte(s[i + 2]) &&
|
||||
// check for non-shortest form
|
||||
(lead != 0xf0 || s[i] >= 0x90) &&
|
||||
(lead != 0xf4 || s[i] < 0x90)) {
|
||||
i += 3; // 4-byte character
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
|
||||
if (!ContainsUnprintableControlCodes(str, length) &&
|
||||
IsValidUTF8(str, length)) {
|
||||
*os << "\n As Text: \"" << str << "\"";
|
||||
}
|
||||
}
|
||||
|
||||
} // anonymous namespace
|
||||
|
||||
void PrintStringTo(const ::std::string& s, ostream* os) {
|
||||
if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
|
||||
if (GTEST_FLAG(print_utf8)) {
|
||||
ConditionalPrintAsText(s.data(), s.size(), os);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if GTEST_HAS_STD_WSTRING
|
||||
void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
|
||||
PrintCharsAsStringTo(s.data(), s.size(), os);
|
||||
}
|
||||
#endif // GTEST_HAS_STD_WSTRING
|
||||
|
||||
} // namespace internal
|
||||
|
||||
} // namespace testing
|
104
3rdparty/gtest/src/gtest-test-part.cc
vendored
Normal file
104
3rdparty/gtest/src/gtest-test-part.cc
vendored
Normal file
@ -0,0 +1,104 @@
|
||||
// Copyright 2008, 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.
|
||||
|
||||
//
|
||||
// The Google C++ Testing and Mocking Framework (Google Test)
|
||||
|
||||
#include "gtest/gtest-test-part.h"
|
||||
#include "src/gtest-internal-inl.h"
|
||||
|
||||
namespace testing {
|
||||
|
||||
using internal::GetUnitTestImpl;
|
||||
|
||||
// Gets the summary of the failure message by omitting the stack trace
|
||||
// in it.
|
||||
std::string TestPartResult::ExtractSummary(const char* message) {
|
||||
const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
|
||||
return stack_trace == nullptr ? message : std::string(message, stack_trace);
|
||||
}
|
||||
|
||||
// Prints a TestPartResult object.
|
||||
std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
|
||||
return os << result.file_name() << ":" << result.line_number() << ": "
|
||||
<< (result.type() == TestPartResult::kSuccess
|
||||
? "Success"
|
||||
: result.type() == TestPartResult::kSkip
|
||||
? "Skipped"
|
||||
: result.type() == TestPartResult::kFatalFailure
|
||||
? "Fatal failure"
|
||||
: "Non-fatal failure")
|
||||
<< ":\n"
|
||||
<< result.message() << std::endl;
|
||||
}
|
||||
|
||||
// Appends a TestPartResult to the array.
|
||||
void TestPartResultArray::Append(const TestPartResult& result) {
|
||||
array_.push_back(result);
|
||||
}
|
||||
|
||||
// Returns the TestPartResult at the given index (0-based).
|
||||
const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
|
||||
if (index < 0 || index >= size()) {
|
||||
printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
|
||||
internal::posix::Abort();
|
||||
}
|
||||
|
||||
return array_[static_cast<size_t>(index)];
|
||||
}
|
||||
|
||||
// Returns the number of TestPartResult objects in the array.
|
||||
int TestPartResultArray::size() const {
|
||||
return static_cast<int>(array_.size());
|
||||
}
|
||||
|
||||
namespace internal {
|
||||
|
||||
HasNewFatalFailureHelper::HasNewFatalFailureHelper()
|
||||
: has_new_fatal_failure_(false),
|
||||
original_reporter_(GetUnitTestImpl()->
|
||||
GetTestPartResultReporterForCurrentThread()) {
|
||||
GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
|
||||
}
|
||||
|
||||
HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
|
||||
GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
|
||||
original_reporter_);
|
||||
}
|
||||
|
||||
void HasNewFatalFailureHelper::ReportTestPartResult(
|
||||
const TestPartResult& result) {
|
||||
if (result.fatally_failed())
|
||||
has_new_fatal_failure_ = true;
|
||||
original_reporter_->ReportTestPartResult(result);
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
|
||||
} // namespace testing
|
118
3rdparty/gtest/src/gtest-typed-test.cc
vendored
Normal file
118
3rdparty/gtest/src/gtest-typed-test.cc
vendored
Normal file
@ -0,0 +1,118 @@
|
||||
// Copyright 2008 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.
|
||||
|
||||
|
||||
#include "gtest/gtest-typed-test.h"
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
// Skips to the first non-space char in str. Returns an empty string if str
|
||||
// contains only whitespace characters.
|
||||
static const char* SkipSpaces(const char* str) {
|
||||
while (IsSpace(*str))
|
||||
str++;
|
||||
return str;
|
||||
}
|
||||
|
||||
static std::vector<std::string> SplitIntoTestNames(const char* src) {
|
||||
std::vector<std::string> name_vec;
|
||||
src = SkipSpaces(src);
|
||||
for (; src != nullptr; src = SkipComma(src)) {
|
||||
name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));
|
||||
}
|
||||
return name_vec;
|
||||
}
|
||||
|
||||
// Verifies that registered_tests match the test names in
|
||||
// registered_tests_; returns registered_tests if successful, or
|
||||
// aborts the program otherwise.
|
||||
const char* TypedTestSuitePState::VerifyRegisteredTestNames(
|
||||
const char* file, int line, const char* registered_tests) {
|
||||
typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
|
||||
registered_ = true;
|
||||
|
||||
std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);
|
||||
|
||||
Message errors;
|
||||
|
||||
std::set<std::string> tests;
|
||||
for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
|
||||
name_it != name_vec.end(); ++name_it) {
|
||||
const std::string& name = *name_it;
|
||||
if (tests.count(name) != 0) {
|
||||
errors << "Test " << name << " is listed more than once.\n";
|
||||
continue;
|
||||
}
|
||||
|
||||
bool found = false;
|
||||
for (RegisteredTestIter it = registered_tests_.begin();
|
||||
it != registered_tests_.end();
|
||||
++it) {
|
||||
if (name == it->first) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (found) {
|
||||
tests.insert(name);
|
||||
} else {
|
||||
errors << "No test named " << name
|
||||
<< " can be found in this test suite.\n";
|
||||
}
|
||||
}
|
||||
|
||||
for (RegisteredTestIter it = registered_tests_.begin();
|
||||
it != registered_tests_.end();
|
||||
++it) {
|
||||
if (tests.count(it->first) == 0) {
|
||||
errors << "You forgot to list test " << it->first << ".\n";
|
||||
}
|
||||
}
|
||||
|
||||
const std::string& errors_str = errors.GetString();
|
||||
if (errors_str != "") {
|
||||
fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
|
||||
errors_str.c_str());
|
||||
fflush(stderr);
|
||||
posix::Abort();
|
||||
}
|
||||
|
||||
return registered_tests;
|
||||
}
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
6177
3rdparty/gtest/src/gtest.cc
vendored
Normal file
6177
3rdparty/gtest/src/gtest.cc
vendored
Normal file
File diff suppressed because it is too large
Load Diff
47
3rdparty/gtest/src/gtest_main.cc
vendored
Normal file
47
3rdparty/gtest/src/gtest_main.cc
vendored
Normal file
@ -0,0 +1,47 @@
|
||||
// Copyright 2006, 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.
|
||||
|
||||
#include <cstdio>
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#ifdef ARDUINO
|
||||
void setup() {
|
||||
testing::InitGoogleTest();
|
||||
}
|
||||
|
||||
void loop() { RUN_ALL_TESTS(); }
|
||||
|
||||
#else
|
||||
|
||||
GTEST_API_ int main(int argc, char **argv) {
|
||||
printf("Running main() from %s\n", __FILE__);
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
#endif
|
521
3rdparty/gtest/test/BUILD.bazel
vendored
Normal file
521
3rdparty/gtest/test/BUILD.bazel
vendored
Normal file
@ -0,0 +1,521 @@
|
||||
# Copyright 2017 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: misterg@google.com (Gennadiy Civil)
|
||||
#
|
||||
# Bazel BUILD for The Google C++ Testing Framework (Google Test)
|
||||
|
||||
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_test")
|
||||
load("@rules_python//python:defs.bzl", "py_library", "py_test")
|
||||
|
||||
licenses(["notice"])
|
||||
|
||||
#on windows exclude gtest-tuple.h
|
||||
cc_test(
|
||||
name = "gtest_all_test",
|
||||
size = "small",
|
||||
srcs = glob(
|
||||
include = [
|
||||
"gtest-*.cc",
|
||||
"googletest-*.cc",
|
||||
"*.h",
|
||||
"googletest/include/gtest/**/*.h",
|
||||
],
|
||||
exclude = [
|
||||
"gtest-unittest-api_test.cc",
|
||||
"googletest/src/gtest-all.cc",
|
||||
"gtest_all_test.cc",
|
||||
"gtest-death-test_ex_test.cc",
|
||||
"gtest-listener_test.cc",
|
||||
"gtest-unittest-api_test.cc",
|
||||
"googletest-param-test-test.cc",
|
||||
"googletest-catch-exceptions-test_.cc",
|
||||
"googletest-color-test_.cc",
|
||||
"googletest-env-var-test_.cc",
|
||||
"googletest-filter-unittest_.cc",
|
||||
"googletest-break-on-failure-unittest_.cc",
|
||||
"googletest-listener-test.cc",
|
||||
"googletest-output-test_.cc",
|
||||
"googletest-list-tests-unittest_.cc",
|
||||
"googletest-shuffle-test_.cc",
|
||||
"googletest-uninitialized-test_.cc",
|
||||
"googletest-death-test_ex_test.cc",
|
||||
"googletest-param-test-test",
|
||||
"googletest-throw-on-failure-test_.cc",
|
||||
"googletest-param-test-invalid-name1-test_.cc",
|
||||
"googletest-param-test-invalid-name2-test_.cc",
|
||||
],
|
||||
) + select({
|
||||
"//:windows": [],
|
||||
"//conditions:default": [],
|
||||
}),
|
||||
copts = select({
|
||||
"//:windows": ["-DGTEST_USE_OWN_TR1_TUPLE=0"],
|
||||
"//conditions:default": ["-DGTEST_USE_OWN_TR1_TUPLE=1"],
|
||||
}),
|
||||
includes = [
|
||||
"googletest",
|
||||
"googletest/include",
|
||||
"googletest/include/internal",
|
||||
"googletest/test",
|
||||
],
|
||||
linkopts = select({
|
||||
"//:windows": [],
|
||||
"//conditions:default": ["-pthread"],
|
||||
}),
|
||||
deps = ["//:gtest_main"],
|
||||
)
|
||||
|
||||
# Tests death tests.
|
||||
cc_test(
|
||||
name = "googletest-death-test-test",
|
||||
size = "medium",
|
||||
srcs = ["googletest-death-test-test.cc"],
|
||||
deps = ["//:gtest_main"],
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "gtest_test_macro_stack_footprint_test",
|
||||
size = "small",
|
||||
srcs = ["gtest_test_macro_stack_footprint_test.cc"],
|
||||
deps = ["//:gtest"],
|
||||
)
|
||||
|
||||
#These googletest tests have their own main()
|
||||
cc_test(
|
||||
name = "googletest-listener-test",
|
||||
size = "small",
|
||||
srcs = ["googletest-listener-test.cc"],
|
||||
deps = ["//:gtest_main"],
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "gtest-unittest-api_test",
|
||||
size = "small",
|
||||
srcs = [
|
||||
"gtest-unittest-api_test.cc",
|
||||
],
|
||||
deps = [
|
||||
"//:gtest",
|
||||
],
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "googletest-param-test-test",
|
||||
size = "small",
|
||||
srcs = [
|
||||
"googletest-param-test-test.cc",
|
||||
"googletest-param-test-test.h",
|
||||
"googletest-param-test2-test.cc",
|
||||
],
|
||||
deps = ["//:gtest"],
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "gtest_unittest",
|
||||
size = "small",
|
||||
srcs = ["gtest_unittest.cc"],
|
||||
args = ["--heap_check=strict"],
|
||||
shard_count = 2,
|
||||
deps = ["//:gtest_main"],
|
||||
)
|
||||
|
||||
# Py tests
|
||||
|
||||
py_library(
|
||||
name = "gtest_test_utils",
|
||||
testonly = 1,
|
||||
srcs = ["gtest_test_utils.py"],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "gtest_help_test_",
|
||||
testonly = 1,
|
||||
srcs = ["gtest_help_test_.cc"],
|
||||
deps = ["//:gtest_main"],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "gtest_help_test",
|
||||
size = "small",
|
||||
srcs = ["gtest_help_test.py"],
|
||||
data = [":gtest_help_test_"],
|
||||
deps = [":gtest_test_utils"],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "googletest-output-test_",
|
||||
testonly = 1,
|
||||
srcs = ["googletest-output-test_.cc"],
|
||||
deps = ["//:gtest"],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "googletest-output-test",
|
||||
size = "small",
|
||||
srcs = ["googletest-output-test.py"],
|
||||
args = select({
|
||||
"//:has_absl": [],
|
||||
"//conditions:default": ["--no_stacktrace_support"],
|
||||
}),
|
||||
data = [
|
||||
"googletest-output-test-golden-lin.txt",
|
||||
":googletest-output-test_",
|
||||
],
|
||||
deps = [":gtest_test_utils"],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "googletest-color-test_",
|
||||
testonly = 1,
|
||||
srcs = ["googletest-color-test_.cc"],
|
||||
deps = ["//:gtest"],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "googletest-color-test",
|
||||
size = "small",
|
||||
srcs = ["googletest-color-test.py"],
|
||||
data = [":googletest-color-test_"],
|
||||
deps = [":gtest_test_utils"],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "googletest-env-var-test_",
|
||||
testonly = 1,
|
||||
srcs = ["googletest-env-var-test_.cc"],
|
||||
deps = ["//:gtest"],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "googletest-env-var-test",
|
||||
size = "medium",
|
||||
srcs = ["googletest-env-var-test.py"],
|
||||
data = [":googletest-env-var-test_"],
|
||||
deps = [":gtest_test_utils"],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "googletest-filter-unittest_",
|
||||
testonly = 1,
|
||||
srcs = ["googletest-filter-unittest_.cc"],
|
||||
deps = ["//:gtest"],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "googletest-filter-unittest",
|
||||
size = "medium",
|
||||
srcs = ["googletest-filter-unittest.py"],
|
||||
data = [":googletest-filter-unittest_"],
|
||||
deps = [":gtest_test_utils"],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "googletest-break-on-failure-unittest_",
|
||||
testonly = 1,
|
||||
srcs = ["googletest-break-on-failure-unittest_.cc"],
|
||||
deps = ["//:gtest"],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "googletest-break-on-failure-unittest",
|
||||
size = "small",
|
||||
srcs = ["googletest-break-on-failure-unittest.py"],
|
||||
data = [":googletest-break-on-failure-unittest_"],
|
||||
deps = [":gtest_test_utils"],
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "gtest_assert_by_exception_test",
|
||||
size = "small",
|
||||
srcs = ["gtest_assert_by_exception_test.cc"],
|
||||
deps = ["//:gtest"],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "googletest-throw-on-failure-test_",
|
||||
testonly = 1,
|
||||
srcs = ["googletest-throw-on-failure-test_.cc"],
|
||||
deps = ["//:gtest"],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "googletest-throw-on-failure-test",
|
||||
size = "small",
|
||||
srcs = ["googletest-throw-on-failure-test.py"],
|
||||
data = [":googletest-throw-on-failure-test_"],
|
||||
deps = [":gtest_test_utils"],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "googletest-list-tests-unittest_",
|
||||
testonly = 1,
|
||||
srcs = ["googletest-list-tests-unittest_.cc"],
|
||||
deps = ["//:gtest"],
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "gtest_skip_test",
|
||||
size = "small",
|
||||
srcs = ["gtest_skip_test.cc"],
|
||||
deps = ["//:gtest_main"],
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "gtest_skip_in_environment_setup_test",
|
||||
size = "small",
|
||||
srcs = ["gtest_skip_in_environment_setup_test.cc"],
|
||||
deps = ["//:gtest_main"],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "gtest_skip_environment_check_output_test",
|
||||
size = "small",
|
||||
srcs = ["gtest_skip_environment_check_output_test.py"],
|
||||
data = [
|
||||
":gtest_skip_in_environment_setup_test",
|
||||
],
|
||||
deps = [":gtest_test_utils"],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "googletest-list-tests-unittest",
|
||||
size = "small",
|
||||
srcs = ["googletest-list-tests-unittest.py"],
|
||||
data = [":googletest-list-tests-unittest_"],
|
||||
deps = [":gtest_test_utils"],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "googletest-shuffle-test_",
|
||||
srcs = ["googletest-shuffle-test_.cc"],
|
||||
deps = ["//:gtest"],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "googletest-shuffle-test",
|
||||
size = "small",
|
||||
srcs = ["googletest-shuffle-test.py"],
|
||||
data = [":googletest-shuffle-test_"],
|
||||
deps = [":gtest_test_utils"],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "googletest-catch-exceptions-no-ex-test_",
|
||||
testonly = 1,
|
||||
srcs = ["googletest-catch-exceptions-test_.cc"],
|
||||
deps = ["//:gtest_main"],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "googletest-catch-exceptions-ex-test_",
|
||||
testonly = 1,
|
||||
srcs = ["googletest-catch-exceptions-test_.cc"],
|
||||
copts = ["-fexceptions"],
|
||||
deps = ["//:gtest_main"],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "googletest-catch-exceptions-test",
|
||||
size = "small",
|
||||
srcs = ["googletest-catch-exceptions-test.py"],
|
||||
data = [
|
||||
":googletest-catch-exceptions-ex-test_",
|
||||
":googletest-catch-exceptions-no-ex-test_",
|
||||
],
|
||||
deps = [":gtest_test_utils"],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "gtest_xml_output_unittest_",
|
||||
testonly = 1,
|
||||
srcs = ["gtest_xml_output_unittest_.cc"],
|
||||
deps = ["//:gtest"],
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "gtest_no_test_unittest",
|
||||
size = "small",
|
||||
srcs = ["gtest_no_test_unittest.cc"],
|
||||
deps = ["//:gtest"],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "gtest_xml_output_unittest",
|
||||
size = "small",
|
||||
srcs = [
|
||||
"gtest_xml_output_unittest.py",
|
||||
"gtest_xml_test_utils.py",
|
||||
],
|
||||
args = select({
|
||||
"//:has_absl": [],
|
||||
"//conditions:default": ["--no_stacktrace_support"],
|
||||
}),
|
||||
data = [
|
||||
# We invoke gtest_no_test_unittest to verify the XML output
|
||||
# when the test program contains no test definition.
|
||||
":gtest_no_test_unittest",
|
||||
":gtest_xml_output_unittest_",
|
||||
],
|
||||
deps = [":gtest_test_utils"],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "gtest_xml_outfile1_test_",
|
||||
testonly = 1,
|
||||
srcs = ["gtest_xml_outfile1_test_.cc"],
|
||||
deps = ["//:gtest_main"],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "gtest_xml_outfile2_test_",
|
||||
testonly = 1,
|
||||
srcs = ["gtest_xml_outfile2_test_.cc"],
|
||||
deps = ["//:gtest_main"],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "gtest_xml_outfiles_test",
|
||||
size = "small",
|
||||
srcs = [
|
||||
"gtest_xml_outfiles_test.py",
|
||||
"gtest_xml_test_utils.py",
|
||||
],
|
||||
data = [
|
||||
":gtest_xml_outfile1_test_",
|
||||
":gtest_xml_outfile2_test_",
|
||||
],
|
||||
deps = [":gtest_test_utils"],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "googletest-uninitialized-test_",
|
||||
testonly = 1,
|
||||
srcs = ["googletest-uninitialized-test_.cc"],
|
||||
deps = ["//:gtest"],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "googletest-uninitialized-test",
|
||||
size = "medium",
|
||||
srcs = ["googletest-uninitialized-test.py"],
|
||||
data = ["googletest-uninitialized-test_"],
|
||||
deps = [":gtest_test_utils"],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "gtest_testbridge_test_",
|
||||
testonly = 1,
|
||||
srcs = ["gtest_testbridge_test_.cc"],
|
||||
deps = ["//:gtest_main"],
|
||||
)
|
||||
|
||||
# Tests that filtering via testbridge works
|
||||
py_test(
|
||||
name = "gtest_testbridge_test",
|
||||
size = "small",
|
||||
srcs = ["gtest_testbridge_test.py"],
|
||||
data = [":gtest_testbridge_test_"],
|
||||
deps = [":gtest_test_utils"],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "googletest-json-outfiles-test",
|
||||
size = "small",
|
||||
srcs = [
|
||||
"googletest-json-outfiles-test.py",
|
||||
"gtest_json_test_utils.py",
|
||||
],
|
||||
data = [
|
||||
":gtest_xml_outfile1_test_",
|
||||
":gtest_xml_outfile2_test_",
|
||||
],
|
||||
deps = [":gtest_test_utils"],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "googletest-json-output-unittest",
|
||||
size = "medium",
|
||||
srcs = [
|
||||
"googletest-json-output-unittest.py",
|
||||
"gtest_json_test_utils.py",
|
||||
],
|
||||
args = select({
|
||||
"//:has_absl": [],
|
||||
"//conditions:default": ["--no_stacktrace_support"],
|
||||
}),
|
||||
data = [
|
||||
# We invoke gtest_no_test_unittest to verify the JSON output
|
||||
# when the test program contains no test definition.
|
||||
":gtest_no_test_unittest",
|
||||
":gtest_xml_output_unittest_",
|
||||
],
|
||||
deps = [":gtest_test_utils"],
|
||||
)
|
||||
|
||||
# Verifies interaction of death tests and exceptions.
|
||||
cc_test(
|
||||
name = "googletest-death-test_ex_catch_test",
|
||||
size = "medium",
|
||||
srcs = ["googletest-death-test_ex_test.cc"],
|
||||
copts = ["-fexceptions"],
|
||||
defines = ["GTEST_ENABLE_CATCH_EXCEPTIONS_=1"],
|
||||
deps = ["//:gtest"],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "googletest-param-test-invalid-name1-test_",
|
||||
testonly = 1,
|
||||
srcs = ["googletest-param-test-invalid-name1-test_.cc"],
|
||||
deps = ["//:gtest"],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "googletest-param-test-invalid-name2-test_",
|
||||
testonly = 1,
|
||||
srcs = ["googletest-param-test-invalid-name2-test_.cc"],
|
||||
deps = ["//:gtest"],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "googletest-param-test-invalid-name1-test",
|
||||
size = "small",
|
||||
srcs = ["googletest-param-test-invalid-name1-test.py"],
|
||||
data = [":googletest-param-test-invalid-name1-test_"],
|
||||
deps = [":gtest_test_utils"],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "googletest-param-test-invalid-name2-test",
|
||||
size = "small",
|
||||
srcs = ["googletest-param-test-invalid-name2-test.py"],
|
||||
data = [":googletest-param-test-invalid-name2-test_"],
|
||||
deps = [":gtest_test_utils"],
|
||||
)
|
208
3rdparty/gtest/test/googletest-break-on-failure-unittest.py
vendored
Normal file
208
3rdparty/gtest/test/googletest-break-on-failure-unittest.py
vendored
Normal file
@ -0,0 +1,208 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2006, 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.
|
||||
|
||||
"""Unit test for Google Test's break-on-failure mode.
|
||||
|
||||
A user can ask Google Test to seg-fault when an assertion fails, using
|
||||
either the GTEST_BREAK_ON_FAILURE environment variable or the
|
||||
--gtest_break_on_failure flag. This script tests such functionality
|
||||
by invoking googletest-break-on-failure-unittest_ (a program written with
|
||||
Google Test) with different environments and command line flags.
|
||||
"""
|
||||
|
||||
import os
|
||||
import gtest_test_utils
|
||||
|
||||
# Constants.
|
||||
|
||||
IS_WINDOWS = os.name == 'nt'
|
||||
|
||||
# The environment variable for enabling/disabling the break-on-failure mode.
|
||||
BREAK_ON_FAILURE_ENV_VAR = 'GTEST_BREAK_ON_FAILURE'
|
||||
|
||||
# The command line flag for enabling/disabling the break-on-failure mode.
|
||||
BREAK_ON_FAILURE_FLAG = 'gtest_break_on_failure'
|
||||
|
||||
# The environment variable for enabling/disabling the throw-on-failure mode.
|
||||
THROW_ON_FAILURE_ENV_VAR = 'GTEST_THROW_ON_FAILURE'
|
||||
|
||||
# The environment variable for enabling/disabling the catch-exceptions mode.
|
||||
CATCH_EXCEPTIONS_ENV_VAR = 'GTEST_CATCH_EXCEPTIONS'
|
||||
|
||||
# Path to the googletest-break-on-failure-unittest_ program.
|
||||
EXE_PATH = gtest_test_utils.GetTestExecutablePath(
|
||||
'googletest-break-on-failure-unittest_')
|
||||
|
||||
|
||||
environ = gtest_test_utils.environ
|
||||
SetEnvVar = gtest_test_utils.SetEnvVar
|
||||
|
||||
# Tests in this file run a Google-Test-based test program and expect it
|
||||
# to terminate prematurely. Therefore they are incompatible with
|
||||
# the premature-exit-file protocol by design. Unset the
|
||||
# premature-exit filepath to prevent Google Test from creating
|
||||
# the file.
|
||||
SetEnvVar(gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None)
|
||||
|
||||
|
||||
def Run(command):
|
||||
"""Runs a command; returns 1 if it was killed by a signal, or 0 otherwise."""
|
||||
|
||||
p = gtest_test_utils.Subprocess(command, env=environ)
|
||||
if p.terminated_by_signal:
|
||||
return 1
|
||||
else:
|
||||
return 0
|
||||
|
||||
|
||||
# The tests.
|
||||
|
||||
|
||||
class GTestBreakOnFailureUnitTest(gtest_test_utils.TestCase):
|
||||
"""Tests using the GTEST_BREAK_ON_FAILURE environment variable or
|
||||
the --gtest_break_on_failure flag to turn assertion failures into
|
||||
segmentation faults.
|
||||
"""
|
||||
|
||||
def RunAndVerify(self, env_var_value, flag_value, expect_seg_fault):
|
||||
"""Runs googletest-break-on-failure-unittest_ and verifies that it does
|
||||
(or does not) have a seg-fault.
|
||||
|
||||
Args:
|
||||
env_var_value: value of the GTEST_BREAK_ON_FAILURE environment
|
||||
variable; None if the variable should be unset.
|
||||
flag_value: value of the --gtest_break_on_failure flag;
|
||||
None if the flag should not be present.
|
||||
expect_seg_fault: 1 if the program is expected to generate a seg-fault;
|
||||
0 otherwise.
|
||||
"""
|
||||
|
||||
SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, env_var_value)
|
||||
|
||||
if env_var_value is None:
|
||||
env_var_value_msg = ' is not set'
|
||||
else:
|
||||
env_var_value_msg = '=' + env_var_value
|
||||
|
||||
if flag_value is None:
|
||||
flag = ''
|
||||
elif flag_value == '0':
|
||||
flag = '--%s=0' % BREAK_ON_FAILURE_FLAG
|
||||
else:
|
||||
flag = '--%s' % BREAK_ON_FAILURE_FLAG
|
||||
|
||||
command = [EXE_PATH]
|
||||
if flag:
|
||||
command.append(flag)
|
||||
|
||||
if expect_seg_fault:
|
||||
should_or_not = 'should'
|
||||
else:
|
||||
should_or_not = 'should not'
|
||||
|
||||
has_seg_fault = Run(command)
|
||||
|
||||
SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, None)
|
||||
|
||||
msg = ('when %s%s, an assertion failure in "%s" %s cause a seg-fault.' %
|
||||
(BREAK_ON_FAILURE_ENV_VAR, env_var_value_msg, ' '.join(command),
|
||||
should_or_not))
|
||||
self.assert_(has_seg_fault == expect_seg_fault, msg)
|
||||
|
||||
def testDefaultBehavior(self):
|
||||
"""Tests the behavior of the default mode."""
|
||||
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value=None,
|
||||
expect_seg_fault=0)
|
||||
|
||||
def testEnvVar(self):
|
||||
"""Tests using the GTEST_BREAK_ON_FAILURE environment variable."""
|
||||
|
||||
self.RunAndVerify(env_var_value='0',
|
||||
flag_value=None,
|
||||
expect_seg_fault=0)
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value=None,
|
||||
expect_seg_fault=1)
|
||||
|
||||
def testFlag(self):
|
||||
"""Tests using the --gtest_break_on_failure flag."""
|
||||
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value='0',
|
||||
expect_seg_fault=0)
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
|
||||
def testFlagOverridesEnvVar(self):
|
||||
"""Tests that the flag overrides the environment variable."""
|
||||
|
||||
self.RunAndVerify(env_var_value='0',
|
||||
flag_value='0',
|
||||
expect_seg_fault=0)
|
||||
self.RunAndVerify(env_var_value='0',
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value='0',
|
||||
expect_seg_fault=0)
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
|
||||
def testBreakOnFailureOverridesThrowOnFailure(self):
|
||||
"""Tests that gtest_break_on_failure overrides gtest_throw_on_failure."""
|
||||
|
||||
SetEnvVar(THROW_ON_FAILURE_ENV_VAR, '1')
|
||||
try:
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
finally:
|
||||
SetEnvVar(THROW_ON_FAILURE_ENV_VAR, None)
|
||||
|
||||
if IS_WINDOWS:
|
||||
def testCatchExceptionsDoesNotInterfere(self):
|
||||
"""Tests that gtest_catch_exceptions doesn't interfere."""
|
||||
|
||||
SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, '1')
|
||||
try:
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
finally:
|
||||
SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, None)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
86
3rdparty/gtest/test/googletest-break-on-failure-unittest_.cc
vendored
Normal file
86
3rdparty/gtest/test/googletest-break-on-failure-unittest_.cc
vendored
Normal file
@ -0,0 +1,86 @@
|
||||
// Copyright 2006, 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.
|
||||
|
||||
|
||||
// Unit test for Google Test's break-on-failure mode.
|
||||
//
|
||||
// A user can ask Google Test to seg-fault when an assertion fails, using
|
||||
// either the GTEST_BREAK_ON_FAILURE environment variable or the
|
||||
// --gtest_break_on_failure flag. This file is used for testing such
|
||||
// functionality.
|
||||
//
|
||||
// This program will be invoked from a Python unit test. It is
|
||||
// expected to fail. Don't run it directly.
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#if GTEST_OS_WINDOWS
|
||||
# include <windows.h>
|
||||
# include <stdlib.h>
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
|
||||
// A test that's expected to fail.
|
||||
TEST(Foo, Bar) {
|
||||
EXPECT_EQ(2, 3);
|
||||
}
|
||||
|
||||
#if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE
|
||||
// On Windows Mobile global exception handlers are not supported.
|
||||
LONG WINAPI ExitWithExceptionCode(
|
||||
struct _EXCEPTION_POINTERS* exception_pointers) {
|
||||
exit(exception_pointers->ExceptionRecord->ExceptionCode);
|
||||
}
|
||||
#endif
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
#if GTEST_OS_WINDOWS
|
||||
// Suppresses display of the Windows error dialog upon encountering
|
||||
// a general protection fault (segment violation).
|
||||
SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS);
|
||||
|
||||
# if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE
|
||||
|
||||
// The default unhandled exception filter does not always exit
|
||||
// with the exception code as exit code - for example it exits with
|
||||
// 0 for EXCEPTION_ACCESS_VIOLATION and 1 for EXCEPTION_BREAKPOINT
|
||||
// if the application is compiled in debug mode. Thus we use our own
|
||||
// filter which always exits with the exception code for unhandled
|
||||
// exceptions.
|
||||
SetUnhandledExceptionFilter(ExitWithExceptionCode);
|
||||
|
||||
# endif
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
236
3rdparty/gtest/test/googletest-catch-exceptions-test.py
vendored
Normal file
236
3rdparty/gtest/test/googletest-catch-exceptions-test.py
vendored
Normal file
@ -0,0 +1,236 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2010 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.
|
||||
|
||||
"""Tests Google Test's exception catching behavior.
|
||||
|
||||
This script invokes googletest-catch-exceptions-test_ and
|
||||
googletest-catch-exceptions-ex-test_ (programs written with
|
||||
Google Test) and verifies their output.
|
||||
"""
|
||||
|
||||
import gtest_test_utils
|
||||
|
||||
# Constants.
|
||||
FLAG_PREFIX = '--gtest_'
|
||||
LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests'
|
||||
NO_CATCH_EXCEPTIONS_FLAG = FLAG_PREFIX + 'catch_exceptions=0'
|
||||
FILTER_FLAG = FLAG_PREFIX + 'filter'
|
||||
|
||||
# Path to the googletest-catch-exceptions-ex-test_ binary, compiled with
|
||||
# exceptions enabled.
|
||||
EX_EXE_PATH = gtest_test_utils.GetTestExecutablePath(
|
||||
'googletest-catch-exceptions-ex-test_')
|
||||
|
||||
# Path to the googletest-catch-exceptions-test_ binary, compiled with
|
||||
# exceptions disabled.
|
||||
EXE_PATH = gtest_test_utils.GetTestExecutablePath(
|
||||
'googletest-catch-exceptions-no-ex-test_')
|
||||
|
||||
environ = gtest_test_utils.environ
|
||||
SetEnvVar = gtest_test_utils.SetEnvVar
|
||||
|
||||
# Tests in this file run a Google-Test-based test program and expect it
|
||||
# to terminate prematurely. Therefore they are incompatible with
|
||||
# the premature-exit-file protocol by design. Unset the
|
||||
# premature-exit filepath to prevent Google Test from creating
|
||||
# the file.
|
||||
SetEnvVar(gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None)
|
||||
|
||||
TEST_LIST = gtest_test_utils.Subprocess(
|
||||
[EXE_PATH, LIST_TESTS_FLAG], env=environ).output
|
||||
|
||||
SUPPORTS_SEH_EXCEPTIONS = 'ThrowsSehException' in TEST_LIST
|
||||
|
||||
if SUPPORTS_SEH_EXCEPTIONS:
|
||||
BINARY_OUTPUT = gtest_test_utils.Subprocess([EXE_PATH], env=environ).output
|
||||
|
||||
EX_BINARY_OUTPUT = gtest_test_utils.Subprocess(
|
||||
[EX_EXE_PATH], env=environ).output
|
||||
|
||||
|
||||
# The tests.
|
||||
if SUPPORTS_SEH_EXCEPTIONS:
|
||||
# pylint:disable-msg=C6302
|
||||
class CatchSehExceptionsTest(gtest_test_utils.TestCase):
|
||||
"""Tests exception-catching behavior."""
|
||||
|
||||
|
||||
def TestSehExceptions(self, test_output):
|
||||
self.assert_('SEH exception with code 0x2a thrown '
|
||||
'in the test fixture\'s constructor'
|
||||
in test_output)
|
||||
self.assert_('SEH exception with code 0x2a thrown '
|
||||
'in the test fixture\'s destructor'
|
||||
in test_output)
|
||||
self.assert_('SEH exception with code 0x2a thrown in SetUpTestSuite()'
|
||||
in test_output)
|
||||
self.assert_('SEH exception with code 0x2a thrown in TearDownTestSuite()'
|
||||
in test_output)
|
||||
self.assert_('SEH exception with code 0x2a thrown in SetUp()'
|
||||
in test_output)
|
||||
self.assert_('SEH exception with code 0x2a thrown in TearDown()'
|
||||
in test_output)
|
||||
self.assert_('SEH exception with code 0x2a thrown in the test body'
|
||||
in test_output)
|
||||
|
||||
def testCatchesSehExceptionsWithCxxExceptionsEnabled(self):
|
||||
self.TestSehExceptions(EX_BINARY_OUTPUT)
|
||||
|
||||
def testCatchesSehExceptionsWithCxxExceptionsDisabled(self):
|
||||
self.TestSehExceptions(BINARY_OUTPUT)
|
||||
|
||||
|
||||
class CatchCxxExceptionsTest(gtest_test_utils.TestCase):
|
||||
"""Tests C++ exception-catching behavior.
|
||||
|
||||
Tests in this test case verify that:
|
||||
* C++ exceptions are caught and logged as C++ (not SEH) exceptions
|
||||
* Exception thrown affect the remainder of the test work flow in the
|
||||
expected manner.
|
||||
"""
|
||||
|
||||
def testCatchesCxxExceptionsInFixtureConstructor(self):
|
||||
self.assertTrue(
|
||||
'C++ exception with description '
|
||||
'"Standard C++ exception" thrown '
|
||||
'in the test fixture\'s constructor' in EX_BINARY_OUTPUT,
|
||||
EX_BINARY_OUTPUT)
|
||||
self.assert_('unexpected' not in EX_BINARY_OUTPUT,
|
||||
'This failure belongs in this test only if '
|
||||
'"CxxExceptionInConstructorTest" (no quotes) '
|
||||
'appears on the same line as words "called unexpectedly"')
|
||||
|
||||
if ('CxxExceptionInDestructorTest.ThrowsExceptionInDestructor' in
|
||||
EX_BINARY_OUTPUT):
|
||||
|
||||
def testCatchesCxxExceptionsInFixtureDestructor(self):
|
||||
self.assertTrue(
|
||||
'C++ exception with description '
|
||||
'"Standard C++ exception" thrown '
|
||||
'in the test fixture\'s destructor' in EX_BINARY_OUTPUT,
|
||||
EX_BINARY_OUTPUT)
|
||||
self.assertTrue(
|
||||
'CxxExceptionInDestructorTest::TearDownTestSuite() '
|
||||
'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
|
||||
def testCatchesCxxExceptionsInSetUpTestCase(self):
|
||||
self.assertTrue(
|
||||
'C++ exception with description "Standard C++ exception"'
|
||||
' thrown in SetUpTestSuite()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
self.assertTrue(
|
||||
'CxxExceptionInConstructorTest::TearDownTestSuite() '
|
||||
'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
self.assertTrue(
|
||||
'CxxExceptionInSetUpTestSuiteTest constructor '
|
||||
'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
self.assertTrue(
|
||||
'CxxExceptionInSetUpTestSuiteTest destructor '
|
||||
'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
self.assertTrue(
|
||||
'CxxExceptionInSetUpTestSuiteTest::SetUp() '
|
||||
'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
self.assertTrue(
|
||||
'CxxExceptionInSetUpTestSuiteTest::TearDown() '
|
||||
'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
self.assertTrue(
|
||||
'CxxExceptionInSetUpTestSuiteTest test body '
|
||||
'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
|
||||
def testCatchesCxxExceptionsInTearDownTestCase(self):
|
||||
self.assertTrue(
|
||||
'C++ exception with description "Standard C++ exception"'
|
||||
' thrown in TearDownTestSuite()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
|
||||
def testCatchesCxxExceptionsInSetUp(self):
|
||||
self.assertTrue(
|
||||
'C++ exception with description "Standard C++ exception"'
|
||||
' thrown in SetUp()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
self.assertTrue(
|
||||
'CxxExceptionInSetUpTest::TearDownTestSuite() '
|
||||
'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
self.assertTrue(
|
||||
'CxxExceptionInSetUpTest destructor '
|
||||
'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
self.assertTrue(
|
||||
'CxxExceptionInSetUpTest::TearDown() '
|
||||
'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
self.assert_('unexpected' not in EX_BINARY_OUTPUT,
|
||||
'This failure belongs in this test only if '
|
||||
'"CxxExceptionInSetUpTest" (no quotes) '
|
||||
'appears on the same line as words "called unexpectedly"')
|
||||
|
||||
def testCatchesCxxExceptionsInTearDown(self):
|
||||
self.assertTrue(
|
||||
'C++ exception with description "Standard C++ exception"'
|
||||
' thrown in TearDown()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
self.assertTrue(
|
||||
'CxxExceptionInTearDownTest::TearDownTestSuite() '
|
||||
'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
self.assertTrue(
|
||||
'CxxExceptionInTearDownTest destructor '
|
||||
'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
|
||||
def testCatchesCxxExceptionsInTestBody(self):
|
||||
self.assertTrue(
|
||||
'C++ exception with description "Standard C++ exception"'
|
||||
' thrown in the test body' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
self.assertTrue(
|
||||
'CxxExceptionInTestBodyTest::TearDownTestSuite() '
|
||||
'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
self.assertTrue(
|
||||
'CxxExceptionInTestBodyTest destructor '
|
||||
'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
self.assertTrue(
|
||||
'CxxExceptionInTestBodyTest::TearDown() '
|
||||
'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
|
||||
|
||||
def testCatchesNonStdCxxExceptions(self):
|
||||
self.assertTrue(
|
||||
'Unknown C++ exception thrown in the test body' in EX_BINARY_OUTPUT,
|
||||
EX_BINARY_OUTPUT)
|
||||
|
||||
def testUnhandledCxxExceptionsAbortTheProgram(self):
|
||||
# Filters out SEH exception tests on Windows. Unhandled SEH exceptions
|
||||
# cause tests to show pop-up windows there.
|
||||
FITLER_OUT_SEH_TESTS_FLAG = FILTER_FLAG + '=-*Seh*'
|
||||
# By default, Google Test doesn't catch the exceptions.
|
||||
uncaught_exceptions_ex_binary_output = gtest_test_utils.Subprocess(
|
||||
[EX_EXE_PATH,
|
||||
NO_CATCH_EXCEPTIONS_FLAG,
|
||||
FITLER_OUT_SEH_TESTS_FLAG],
|
||||
env=environ).output
|
||||
|
||||
self.assert_('Unhandled C++ exception terminating the program'
|
||||
in uncaught_exceptions_ex_binary_output)
|
||||
self.assert_('unexpected' not in uncaught_exceptions_ex_binary_output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
293
3rdparty/gtest/test/googletest-catch-exceptions-test_.cc
vendored
Normal file
293
3rdparty/gtest/test/googletest-catch-exceptions-test_.cc
vendored
Normal file
@ -0,0 +1,293 @@
|
||||
// Copyright 2010, 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.
|
||||
|
||||
//
|
||||
// Tests for Google Test itself. Tests in this file throw C++ or SEH
|
||||
// exceptions, and the output is verified by
|
||||
// googletest-catch-exceptions-test.py.
|
||||
|
||||
#include <stdio.h> // NOLINT
|
||||
#include <stdlib.h> // For exit().
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#if GTEST_HAS_SEH
|
||||
# include <windows.h>
|
||||
#endif
|
||||
|
||||
#if GTEST_HAS_EXCEPTIONS
|
||||
# include <exception> // For set_terminate().
|
||||
# include <stdexcept>
|
||||
#endif
|
||||
|
||||
using testing::Test;
|
||||
|
||||
#if GTEST_HAS_SEH
|
||||
|
||||
class SehExceptionInConstructorTest : public Test {
|
||||
public:
|
||||
SehExceptionInConstructorTest() { RaiseException(42, 0, 0, NULL); }
|
||||
};
|
||||
|
||||
TEST_F(SehExceptionInConstructorTest, ThrowsExceptionInConstructor) {}
|
||||
|
||||
class SehExceptionInDestructorTest : public Test {
|
||||
public:
|
||||
~SehExceptionInDestructorTest() { RaiseException(42, 0, 0, NULL); }
|
||||
};
|
||||
|
||||
TEST_F(SehExceptionInDestructorTest, ThrowsExceptionInDestructor) {}
|
||||
|
||||
class SehExceptionInSetUpTestSuiteTest : public Test {
|
||||
public:
|
||||
static void SetUpTestSuite() { RaiseException(42, 0, 0, NULL); }
|
||||
};
|
||||
|
||||
TEST_F(SehExceptionInSetUpTestSuiteTest, ThrowsExceptionInSetUpTestSuite) {}
|
||||
|
||||
class SehExceptionInTearDownTestSuiteTest : public Test {
|
||||
public:
|
||||
static void TearDownTestSuite() { RaiseException(42, 0, 0, NULL); }
|
||||
};
|
||||
|
||||
TEST_F(SehExceptionInTearDownTestSuiteTest,
|
||||
ThrowsExceptionInTearDownTestSuite) {}
|
||||
|
||||
class SehExceptionInSetUpTest : public Test {
|
||||
protected:
|
||||
virtual void SetUp() { RaiseException(42, 0, 0, NULL); }
|
||||
};
|
||||
|
||||
TEST_F(SehExceptionInSetUpTest, ThrowsExceptionInSetUp) {}
|
||||
|
||||
class SehExceptionInTearDownTest : public Test {
|
||||
protected:
|
||||
virtual void TearDown() { RaiseException(42, 0, 0, NULL); }
|
||||
};
|
||||
|
||||
TEST_F(SehExceptionInTearDownTest, ThrowsExceptionInTearDown) {}
|
||||
|
||||
TEST(SehExceptionTest, ThrowsSehException) {
|
||||
RaiseException(42, 0, 0, NULL);
|
||||
}
|
||||
|
||||
#endif // GTEST_HAS_SEH
|
||||
|
||||
#if GTEST_HAS_EXCEPTIONS
|
||||
|
||||
class CxxExceptionInConstructorTest : public Test {
|
||||
public:
|
||||
CxxExceptionInConstructorTest() {
|
||||
// Without this macro VC++ complains about unreachable code at the end of
|
||||
// the constructor.
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
|
||||
throw std::runtime_error("Standard C++ exception"));
|
||||
}
|
||||
|
||||
static void TearDownTestSuite() {
|
||||
printf("%s",
|
||||
"CxxExceptionInConstructorTest::TearDownTestSuite() "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
protected:
|
||||
~CxxExceptionInConstructorTest() override {
|
||||
ADD_FAILURE() << "CxxExceptionInConstructorTest destructor "
|
||||
<< "called unexpectedly.";
|
||||
}
|
||||
|
||||
void SetUp() override {
|
||||
ADD_FAILURE() << "CxxExceptionInConstructorTest::SetUp() "
|
||||
<< "called unexpectedly.";
|
||||
}
|
||||
|
||||
void TearDown() override {
|
||||
ADD_FAILURE() << "CxxExceptionInConstructorTest::TearDown() "
|
||||
<< "called unexpectedly.";
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(CxxExceptionInConstructorTest, ThrowsExceptionInConstructor) {
|
||||
ADD_FAILURE() << "CxxExceptionInConstructorTest test body "
|
||||
<< "called unexpectedly.";
|
||||
}
|
||||
|
||||
class CxxExceptionInSetUpTestSuiteTest : public Test {
|
||||
public:
|
||||
CxxExceptionInSetUpTestSuiteTest() {
|
||||
printf("%s",
|
||||
"CxxExceptionInSetUpTestSuiteTest constructor "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
static void SetUpTestSuite() {
|
||||
throw std::runtime_error("Standard C++ exception");
|
||||
}
|
||||
|
||||
static void TearDownTestSuite() {
|
||||
printf("%s",
|
||||
"CxxExceptionInSetUpTestSuiteTest::TearDownTestSuite() "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
protected:
|
||||
~CxxExceptionInSetUpTestSuiteTest() override {
|
||||
printf("%s",
|
||||
"CxxExceptionInSetUpTestSuiteTest destructor "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
void SetUp() override {
|
||||
printf("%s",
|
||||
"CxxExceptionInSetUpTestSuiteTest::SetUp() "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
void TearDown() override {
|
||||
printf("%s",
|
||||
"CxxExceptionInSetUpTestSuiteTest::TearDown() "
|
||||
"called as expected.\n");
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(CxxExceptionInSetUpTestSuiteTest, ThrowsExceptionInSetUpTestSuite) {
|
||||
printf("%s",
|
||||
"CxxExceptionInSetUpTestSuiteTest test body "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
class CxxExceptionInTearDownTestSuiteTest : public Test {
|
||||
public:
|
||||
static void TearDownTestSuite() {
|
||||
throw std::runtime_error("Standard C++ exception");
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(CxxExceptionInTearDownTestSuiteTest,
|
||||
ThrowsExceptionInTearDownTestSuite) {}
|
||||
|
||||
class CxxExceptionInSetUpTest : public Test {
|
||||
public:
|
||||
static void TearDownTestSuite() {
|
||||
printf("%s",
|
||||
"CxxExceptionInSetUpTest::TearDownTestSuite() "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
protected:
|
||||
~CxxExceptionInSetUpTest() override {
|
||||
printf("%s",
|
||||
"CxxExceptionInSetUpTest destructor "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
void SetUp() override { throw std::runtime_error("Standard C++ exception"); }
|
||||
|
||||
void TearDown() override {
|
||||
printf("%s",
|
||||
"CxxExceptionInSetUpTest::TearDown() "
|
||||
"called as expected.\n");
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(CxxExceptionInSetUpTest, ThrowsExceptionInSetUp) {
|
||||
ADD_FAILURE() << "CxxExceptionInSetUpTest test body "
|
||||
<< "called unexpectedly.";
|
||||
}
|
||||
|
||||
class CxxExceptionInTearDownTest : public Test {
|
||||
public:
|
||||
static void TearDownTestSuite() {
|
||||
printf("%s",
|
||||
"CxxExceptionInTearDownTest::TearDownTestSuite() "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
protected:
|
||||
~CxxExceptionInTearDownTest() override {
|
||||
printf("%s",
|
||||
"CxxExceptionInTearDownTest destructor "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
void TearDown() override {
|
||||
throw std::runtime_error("Standard C++ exception");
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(CxxExceptionInTearDownTest, ThrowsExceptionInTearDown) {}
|
||||
|
||||
class CxxExceptionInTestBodyTest : public Test {
|
||||
public:
|
||||
static void TearDownTestSuite() {
|
||||
printf("%s",
|
||||
"CxxExceptionInTestBodyTest::TearDownTestSuite() "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
protected:
|
||||
~CxxExceptionInTestBodyTest() override {
|
||||
printf("%s",
|
||||
"CxxExceptionInTestBodyTest destructor "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
void TearDown() override {
|
||||
printf("%s",
|
||||
"CxxExceptionInTestBodyTest::TearDown() "
|
||||
"called as expected.\n");
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(CxxExceptionInTestBodyTest, ThrowsStdCxxException) {
|
||||
throw std::runtime_error("Standard C++ exception");
|
||||
}
|
||||
|
||||
TEST(CxxExceptionTest, ThrowsNonStdCxxException) {
|
||||
throw "C-string";
|
||||
}
|
||||
|
||||
// This terminate handler aborts the program using exit() rather than abort().
|
||||
// This avoids showing pop-ups on Windows systems and core dumps on Unix-like
|
||||
// ones.
|
||||
void TerminateHandler() {
|
||||
fprintf(stderr, "%s\n", "Unhandled C++ exception terminating the program.");
|
||||
fflush(nullptr);
|
||||
exit(3);
|
||||
}
|
||||
|
||||
#endif // GTEST_HAS_EXCEPTIONS
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
#if GTEST_HAS_EXCEPTIONS
|
||||
std::set_terminate(&TerminateHandler);
|
||||
#endif
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
127
3rdparty/gtest/test/googletest-color-test.py
vendored
Normal file
127
3rdparty/gtest/test/googletest-color-test.py
vendored
Normal file
@ -0,0 +1,127 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2008, 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.
|
||||
|
||||
"""Verifies that Google Test correctly determines whether to use colors."""
|
||||
|
||||
import os
|
||||
import gtest_test_utils
|
||||
|
||||
IS_WINDOWS = os.name == 'nt'
|
||||
|
||||
COLOR_ENV_VAR = 'GTEST_COLOR'
|
||||
COLOR_FLAG = 'gtest_color'
|
||||
COMMAND = gtest_test_utils.GetTestExecutablePath('googletest-color-test_')
|
||||
|
||||
|
||||
def SetEnvVar(env_var, value):
|
||||
"""Sets the env variable to 'value'; unsets it when 'value' is None."""
|
||||
|
||||
if value is not None:
|
||||
os.environ[env_var] = value
|
||||
elif env_var in os.environ:
|
||||
del os.environ[env_var]
|
||||
|
||||
|
||||
def UsesColor(term, color_env_var, color_flag):
|
||||
"""Runs googletest-color-test_ and returns its exit code."""
|
||||
|
||||
SetEnvVar('TERM', term)
|
||||
SetEnvVar(COLOR_ENV_VAR, color_env_var)
|
||||
|
||||
if color_flag is None:
|
||||
args = []
|
||||
else:
|
||||
args = ['--%s=%s' % (COLOR_FLAG, color_flag)]
|
||||
p = gtest_test_utils.Subprocess([COMMAND] + args)
|
||||
return not p.exited or p.exit_code
|
||||
|
||||
|
||||
class GTestColorTest(gtest_test_utils.TestCase):
|
||||
def testNoEnvVarNoFlag(self):
|
||||
"""Tests the case when there's neither GTEST_COLOR nor --gtest_color."""
|
||||
|
||||
if not IS_WINDOWS:
|
||||
self.assert_(not UsesColor('dumb', None, None))
|
||||
self.assert_(not UsesColor('emacs', None, None))
|
||||
self.assert_(not UsesColor('xterm-mono', None, None))
|
||||
self.assert_(not UsesColor('unknown', None, None))
|
||||
self.assert_(not UsesColor(None, None, None))
|
||||
self.assert_(UsesColor('linux', None, None))
|
||||
self.assert_(UsesColor('cygwin', None, None))
|
||||
self.assert_(UsesColor('xterm', None, None))
|
||||
self.assert_(UsesColor('xterm-color', None, None))
|
||||
self.assert_(UsesColor('xterm-256color', None, None))
|
||||
|
||||
def testFlagOnly(self):
|
||||
"""Tests the case when there's --gtest_color but not GTEST_COLOR."""
|
||||
|
||||
self.assert_(not UsesColor('dumb', None, 'no'))
|
||||
self.assert_(not UsesColor('xterm-color', None, 'no'))
|
||||
if not IS_WINDOWS:
|
||||
self.assert_(not UsesColor('emacs', None, 'auto'))
|
||||
self.assert_(UsesColor('xterm', None, 'auto'))
|
||||
self.assert_(UsesColor('dumb', None, 'yes'))
|
||||
self.assert_(UsesColor('xterm', None, 'yes'))
|
||||
|
||||
def testEnvVarOnly(self):
|
||||
"""Tests the case when there's GTEST_COLOR but not --gtest_color."""
|
||||
|
||||
self.assert_(not UsesColor('dumb', 'no', None))
|
||||
self.assert_(not UsesColor('xterm-color', 'no', None))
|
||||
if not IS_WINDOWS:
|
||||
self.assert_(not UsesColor('dumb', 'auto', None))
|
||||
self.assert_(UsesColor('xterm-color', 'auto', None))
|
||||
self.assert_(UsesColor('dumb', 'yes', None))
|
||||
self.assert_(UsesColor('xterm-color', 'yes', None))
|
||||
|
||||
def testEnvVarAndFlag(self):
|
||||
"""Tests the case when there are both GTEST_COLOR and --gtest_color."""
|
||||
|
||||
self.assert_(not UsesColor('xterm-color', 'no', 'no'))
|
||||
self.assert_(UsesColor('dumb', 'no', 'yes'))
|
||||
self.assert_(UsesColor('xterm-color', 'no', 'auto'))
|
||||
|
||||
def testAliasesOfYesAndNo(self):
|
||||
"""Tests using aliases in specifying --gtest_color."""
|
||||
|
||||
self.assert_(UsesColor('dumb', None, 'true'))
|
||||
self.assert_(UsesColor('dumb', None, 'YES'))
|
||||
self.assert_(UsesColor('dumb', None, 'T'))
|
||||
self.assert_(UsesColor('dumb', None, '1'))
|
||||
|
||||
self.assert_(not UsesColor('xterm', None, 'f'))
|
||||
self.assert_(not UsesColor('xterm', None, 'false'))
|
||||
self.assert_(not UsesColor('xterm', None, '0'))
|
||||
self.assert_(not UsesColor('xterm', None, 'unknown'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
62
3rdparty/gtest/test/googletest-color-test_.cc
vendored
Normal file
62
3rdparty/gtest/test/googletest-color-test_.cc
vendored
Normal file
@ -0,0 +1,62 @@
|
||||
// Copyright 2008, 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.
|
||||
|
||||
|
||||
// A helper program for testing how Google Test determines whether to use
|
||||
// colors in the output. It prints "YES" and returns 1 if Google Test
|
||||
// decides to use colors, and prints "NO" and returns 0 otherwise.
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
#include "src/gtest-internal-inl.h"
|
||||
|
||||
using testing::internal::ShouldUseColor;
|
||||
|
||||
// The purpose of this is to ensure that the UnitTest singleton is
|
||||
// created before main() is entered, and thus that ShouldUseColor()
|
||||
// works the same way as in a real Google-Test-based test. We don't actual
|
||||
// run the TEST itself.
|
||||
TEST(GTestColorTest, Dummy) {
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
|
||||
if (ShouldUseColor(true)) {
|
||||
// Google Test decides to use colors in the output (assuming it
|
||||
// goes to a TTY).
|
||||
printf("YES\n");
|
||||
return 1;
|
||||
} else {
|
||||
// Google Test decides not to use colors in the output.
|
||||
printf("NO\n");
|
||||
return 0;
|
||||
}
|
||||
}
|
1516
3rdparty/gtest/test/googletest-death-test-test.cc
vendored
Normal file
1516
3rdparty/gtest/test/googletest-death-test-test.cc
vendored
Normal file
File diff suppressed because it is too large
Load Diff
92
3rdparty/gtest/test/googletest-death-test_ex_test.cc
vendored
Normal file
92
3rdparty/gtest/test/googletest-death-test_ex_test.cc
vendored
Normal file
@ -0,0 +1,92 @@
|
||||
// Copyright 2010, 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.
|
||||
|
||||
//
|
||||
// Tests that verify interaction of exceptions and death tests.
|
||||
|
||||
#include "gtest/gtest-death-test.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#if GTEST_HAS_DEATH_TEST
|
||||
|
||||
# if GTEST_HAS_SEH
|
||||
# include <windows.h> // For RaiseException().
|
||||
# endif
|
||||
|
||||
# include "gtest/gtest-spi.h"
|
||||
|
||||
# if GTEST_HAS_EXCEPTIONS
|
||||
|
||||
# include <exception> // For std::exception.
|
||||
|
||||
// Tests that death tests report thrown exceptions as failures and that the
|
||||
// exceptions do not escape death test macros.
|
||||
TEST(CxxExceptionDeathTest, ExceptionIsFailure) {
|
||||
try {
|
||||
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw 1, ""), "threw an exception");
|
||||
} catch (...) { // NOLINT
|
||||
FAIL() << "An exception escaped a death test macro invocation "
|
||||
<< "with catch_exceptions "
|
||||
<< (testing::GTEST_FLAG(catch_exceptions) ? "enabled" : "disabled");
|
||||
}
|
||||
}
|
||||
|
||||
class TestException : public std::exception {
|
||||
public:
|
||||
const char* what() const throw() override { return "exceptional message"; }
|
||||
};
|
||||
|
||||
TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) {
|
||||
// Verifies that the exception message is quoted in the failure text.
|
||||
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""),
|
||||
"exceptional message");
|
||||
// Verifies that the location is mentioned in the failure text.
|
||||
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""),
|
||||
__FILE__);
|
||||
}
|
||||
# endif // GTEST_HAS_EXCEPTIONS
|
||||
|
||||
# if GTEST_HAS_SEH
|
||||
// Tests that enabling interception of SEH exceptions with the
|
||||
// catch_exceptions flag does not interfere with SEH exceptions being
|
||||
// treated as death by death tests.
|
||||
TEST(SehExceptionDeasTest, CatchExceptionsDoesNotInterfere) {
|
||||
EXPECT_DEATH(RaiseException(42, 0x0, 0, NULL), "")
|
||||
<< "with catch_exceptions "
|
||||
<< (testing::GTEST_FLAG(catch_exceptions) ? "enabled" : "disabled");
|
||||
}
|
||||
# endif
|
||||
|
||||
#endif // GTEST_HAS_DEATH_TEST
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
testing::GTEST_FLAG(catch_exceptions) = GTEST_ENABLE_CATCH_EXCEPTIONS_ != 0;
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
117
3rdparty/gtest/test/googletest-env-var-test.py
vendored
Normal file
117
3rdparty/gtest/test/googletest-env-var-test.py
vendored
Normal file
@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2008, 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.
|
||||
|
||||
"""Verifies that Google Test correctly parses environment variables."""
|
||||
|
||||
import os
|
||||
import gtest_test_utils
|
||||
|
||||
|
||||
IS_WINDOWS = os.name == 'nt'
|
||||
IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'
|
||||
|
||||
COMMAND = gtest_test_utils.GetTestExecutablePath('googletest-env-var-test_')
|
||||
|
||||
environ = os.environ.copy()
|
||||
|
||||
|
||||
def AssertEq(expected, actual):
|
||||
if expected != actual:
|
||||
print('Expected: %s' % (expected,))
|
||||
print(' Actual: %s' % (actual,))
|
||||
raise AssertionError
|
||||
|
||||
|
||||
def SetEnvVar(env_var, value):
|
||||
"""Sets the env variable to 'value'; unsets it when 'value' is None."""
|
||||
|
||||
if value is not None:
|
||||
environ[env_var] = value
|
||||
elif env_var in environ:
|
||||
del environ[env_var]
|
||||
|
||||
|
||||
def GetFlag(flag):
|
||||
"""Runs googletest-env-var-test_ and returns its output."""
|
||||
|
||||
args = [COMMAND]
|
||||
if flag is not None:
|
||||
args += [flag]
|
||||
return gtest_test_utils.Subprocess(args, env=environ).output
|
||||
|
||||
|
||||
def TestFlag(flag, test_val, default_val):
|
||||
"""Verifies that the given flag is affected by the corresponding env var."""
|
||||
|
||||
env_var = 'GTEST_' + flag.upper()
|
||||
SetEnvVar(env_var, test_val)
|
||||
AssertEq(test_val, GetFlag(flag))
|
||||
SetEnvVar(env_var, None)
|
||||
AssertEq(default_val, GetFlag(flag))
|
||||
|
||||
|
||||
class GTestEnvVarTest(gtest_test_utils.TestCase):
|
||||
|
||||
def testEnvVarAffectsFlag(self):
|
||||
"""Tests that environment variable should affect the corresponding flag."""
|
||||
|
||||
TestFlag('break_on_failure', '1', '0')
|
||||
TestFlag('color', 'yes', 'auto')
|
||||
TestFlag('filter', 'FooTest.Bar', '*')
|
||||
SetEnvVar('XML_OUTPUT_FILE', None) # For 'output' test
|
||||
TestFlag('output', 'xml:tmp/foo.xml', '')
|
||||
TestFlag('print_time', '0', '1')
|
||||
TestFlag('repeat', '999', '1')
|
||||
TestFlag('throw_on_failure', '1', '0')
|
||||
TestFlag('death_test_style', 'threadsafe', 'fast')
|
||||
TestFlag('catch_exceptions', '0', '1')
|
||||
|
||||
if IS_LINUX:
|
||||
TestFlag('death_test_use_fork', '1', '0')
|
||||
TestFlag('stack_trace_depth', '0', '100')
|
||||
|
||||
|
||||
def testXmlOutputFile(self):
|
||||
"""Tests that $XML_OUTPUT_FILE affects the output flag."""
|
||||
|
||||
SetEnvVar('GTEST_OUTPUT', None)
|
||||
SetEnvVar('XML_OUTPUT_FILE', 'tmp/bar.xml')
|
||||
AssertEq('xml:tmp/bar.xml', GetFlag('output'))
|
||||
|
||||
def testXmlOutputFileOverride(self):
|
||||
"""Tests that $XML_OUTPUT_FILE is overridden by $GTEST_OUTPUT."""
|
||||
|
||||
SetEnvVar('GTEST_OUTPUT', 'xml:tmp/foo.xml')
|
||||
SetEnvVar('XML_OUTPUT_FILE', 'tmp/bar.xml')
|
||||
AssertEq('xml:tmp/foo.xml', GetFlag('output'))
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
122
3rdparty/gtest/test/googletest-env-var-test_.cc
vendored
Normal file
122
3rdparty/gtest/test/googletest-env-var-test_.cc
vendored
Normal file
@ -0,0 +1,122 @@
|
||||
// Copyright 2008, 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.
|
||||
|
||||
|
||||
// A helper program for testing that Google Test parses the environment
|
||||
// variables correctly.
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
#include "src/gtest-internal-inl.h"
|
||||
|
||||
using ::std::cout;
|
||||
|
||||
namespace testing {
|
||||
|
||||
// The purpose of this is to make the test more realistic by ensuring
|
||||
// that the UnitTest singleton is created before main() is entered.
|
||||
// We don't actual run the TEST itself.
|
||||
TEST(GTestEnvVarTest, Dummy) {
|
||||
}
|
||||
|
||||
void PrintFlag(const char* flag) {
|
||||
if (strcmp(flag, "break_on_failure") == 0) {
|
||||
cout << GTEST_FLAG(break_on_failure);
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcmp(flag, "catch_exceptions") == 0) {
|
||||
cout << GTEST_FLAG(catch_exceptions);
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcmp(flag, "color") == 0) {
|
||||
cout << GTEST_FLAG(color);
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcmp(flag, "death_test_style") == 0) {
|
||||
cout << GTEST_FLAG(death_test_style);
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcmp(flag, "death_test_use_fork") == 0) {
|
||||
cout << GTEST_FLAG(death_test_use_fork);
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcmp(flag, "filter") == 0) {
|
||||
cout << GTEST_FLAG(filter);
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcmp(flag, "output") == 0) {
|
||||
cout << GTEST_FLAG(output);
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcmp(flag, "print_time") == 0) {
|
||||
cout << GTEST_FLAG(print_time);
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcmp(flag, "repeat") == 0) {
|
||||
cout << GTEST_FLAG(repeat);
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcmp(flag, "stack_trace_depth") == 0) {
|
||||
cout << GTEST_FLAG(stack_trace_depth);
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcmp(flag, "throw_on_failure") == 0) {
|
||||
cout << GTEST_FLAG(throw_on_failure);
|
||||
return;
|
||||
}
|
||||
|
||||
cout << "Invalid flag name " << flag
|
||||
<< ". Valid names are break_on_failure, color, filter, etc.\n";
|
||||
exit(1);
|
||||
}
|
||||
|
||||
} // namespace testing
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
|
||||
if (argc != 2) {
|
||||
cout << "Usage: googletest-env-var-test_ NAME_OF_FLAG\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
testing::PrintFlag(argv[1]);
|
||||
return 0;
|
||||
}
|
649
3rdparty/gtest/test/googletest-filepath-test.cc
vendored
Normal file
649
3rdparty/gtest/test/googletest-filepath-test.cc
vendored
Normal file
@ -0,0 +1,649 @@
|
||||
// Copyright 2008, 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.
|
||||
//
|
||||
// Google Test filepath utilities
|
||||
//
|
||||
// This file tests classes and functions used internally by
|
||||
// Google Test. They are subject to change without notice.
|
||||
//
|
||||
// This file is #included from gtest-internal.h.
|
||||
// Do not #include this file anywhere else!
|
||||
|
||||
#include "gtest/internal/gtest-filepath.h"
|
||||
#include "gtest/gtest.h"
|
||||
#include "src/gtest-internal-inl.h"
|
||||
|
||||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
# include <windows.h> // NOLINT
|
||||
#elif GTEST_OS_WINDOWS
|
||||
# include <direct.h> // NOLINT
|
||||
#endif // GTEST_OS_WINDOWS_MOBILE
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
namespace {
|
||||
|
||||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
|
||||
// Windows CE doesn't have the remove C function.
|
||||
int remove(const char* path) {
|
||||
LPCWSTR wpath = String::AnsiToUtf16(path);
|
||||
int ret = DeleteFile(wpath) ? 0 : -1;
|
||||
delete [] wpath;
|
||||
return ret;
|
||||
}
|
||||
// Windows CE doesn't have the _rmdir C function.
|
||||
int _rmdir(const char* path) {
|
||||
FilePath filepath(path);
|
||||
LPCWSTR wpath = String::AnsiToUtf16(
|
||||
filepath.RemoveTrailingPathSeparator().c_str());
|
||||
int ret = RemoveDirectory(wpath) ? 0 : -1;
|
||||
delete [] wpath;
|
||||
return ret;
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
TEST(GetCurrentDirTest, ReturnsCurrentDir) {
|
||||
const FilePath original_dir = FilePath::GetCurrentDir();
|
||||
EXPECT_FALSE(original_dir.IsEmpty());
|
||||
|
||||
posix::ChDir(GTEST_PATH_SEP_);
|
||||
const FilePath cwd = FilePath::GetCurrentDir();
|
||||
posix::ChDir(original_dir.c_str());
|
||||
|
||||
# if GTEST_OS_WINDOWS || GTEST_OS_OS2
|
||||
|
||||
// Skips the ":".
|
||||
const char* const cwd_without_drive = strchr(cwd.c_str(), ':');
|
||||
ASSERT_TRUE(cwd_without_drive != NULL);
|
||||
EXPECT_STREQ(GTEST_PATH_SEP_, cwd_without_drive + 1);
|
||||
|
||||
# else
|
||||
|
||||
EXPECT_EQ(GTEST_PATH_SEP_, cwd.string());
|
||||
|
||||
# endif
|
||||
}
|
||||
|
||||
#endif // GTEST_OS_WINDOWS_MOBILE
|
||||
|
||||
TEST(IsEmptyTest, ReturnsTrueForEmptyPath) {
|
||||
EXPECT_TRUE(FilePath("").IsEmpty());
|
||||
}
|
||||
|
||||
TEST(IsEmptyTest, ReturnsFalseForNonEmptyPath) {
|
||||
EXPECT_FALSE(FilePath("a").IsEmpty());
|
||||
EXPECT_FALSE(FilePath(".").IsEmpty());
|
||||
EXPECT_FALSE(FilePath("a/b").IsEmpty());
|
||||
EXPECT_FALSE(FilePath("a\\b\\").IsEmpty());
|
||||
}
|
||||
|
||||
// RemoveDirectoryName "" -> ""
|
||||
TEST(RemoveDirectoryNameTest, WhenEmptyName) {
|
||||
EXPECT_EQ("", FilePath("").RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
// RemoveDirectoryName "afile" -> "afile"
|
||||
TEST(RemoveDirectoryNameTest, ButNoDirectory) {
|
||||
EXPECT_EQ("afile",
|
||||
FilePath("afile").RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
// RemoveDirectoryName "/afile" -> "afile"
|
||||
TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileName) {
|
||||
EXPECT_EQ("afile",
|
||||
FilePath(GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
// RemoveDirectoryName "adir/" -> ""
|
||||
TEST(RemoveDirectoryNameTest, WhereThereIsNoFileName) {
|
||||
EXPECT_EQ("",
|
||||
FilePath("adir" GTEST_PATH_SEP_).RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
// RemoveDirectoryName "adir/afile" -> "afile"
|
||||
TEST(RemoveDirectoryNameTest, ShouldGiveFileName) {
|
||||
EXPECT_EQ("afile",
|
||||
FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
// RemoveDirectoryName "adir/subdir/afile" -> "afile"
|
||||
TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) {
|
||||
EXPECT_EQ("afile",
|
||||
FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
|
||||
.RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
#if GTEST_HAS_ALT_PATH_SEP_
|
||||
|
||||
// Tests that RemoveDirectoryName() works with the alternate separator
|
||||
// on Windows.
|
||||
|
||||
// RemoveDirectoryName("/afile") -> "afile"
|
||||
TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileNameForAlternateSeparator) {
|
||||
EXPECT_EQ("afile", FilePath("/afile").RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
// RemoveDirectoryName("adir/") -> ""
|
||||
TEST(RemoveDirectoryNameTest, WhereThereIsNoFileNameForAlternateSeparator) {
|
||||
EXPECT_EQ("", FilePath("adir/").RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
// RemoveDirectoryName("adir/afile") -> "afile"
|
||||
TEST(RemoveDirectoryNameTest, ShouldGiveFileNameForAlternateSeparator) {
|
||||
EXPECT_EQ("afile", FilePath("adir/afile").RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
// RemoveDirectoryName("adir/subdir/afile") -> "afile"
|
||||
TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileNameForAlternateSeparator) {
|
||||
EXPECT_EQ("afile",
|
||||
FilePath("adir/subdir/afile").RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
// RemoveFileName "" -> "./"
|
||||
TEST(RemoveFileNameTest, EmptyName) {
|
||||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
// On Windows CE, we use the root as the current directory.
|
||||
EXPECT_EQ(GTEST_PATH_SEP_, FilePath("").RemoveFileName().string());
|
||||
#else
|
||||
EXPECT_EQ("." GTEST_PATH_SEP_, FilePath("").RemoveFileName().string());
|
||||
#endif
|
||||
}
|
||||
|
||||
// RemoveFileName "adir/" -> "adir/"
|
||||
TEST(RemoveFileNameTest, ButNoFile) {
|
||||
EXPECT_EQ("adir" GTEST_PATH_SEP_,
|
||||
FilePath("adir" GTEST_PATH_SEP_).RemoveFileName().string());
|
||||
}
|
||||
|
||||
// RemoveFileName "adir/afile" -> "adir/"
|
||||
TEST(RemoveFileNameTest, GivesDirName) {
|
||||
EXPECT_EQ("adir" GTEST_PATH_SEP_,
|
||||
FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveFileName().string());
|
||||
}
|
||||
|
||||
// RemoveFileName "adir/subdir/afile" -> "adir/subdir/"
|
||||
TEST(RemoveFileNameTest, GivesDirAndSubDirName) {
|
||||
EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_,
|
||||
FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
|
||||
.RemoveFileName().string());
|
||||
}
|
||||
|
||||
// RemoveFileName "/afile" -> "/"
|
||||
TEST(RemoveFileNameTest, GivesRootDir) {
|
||||
EXPECT_EQ(GTEST_PATH_SEP_,
|
||||
FilePath(GTEST_PATH_SEP_ "afile").RemoveFileName().string());
|
||||
}
|
||||
|
||||
#if GTEST_HAS_ALT_PATH_SEP_
|
||||
|
||||
// Tests that RemoveFileName() works with the alternate separator on
|
||||
// Windows.
|
||||
|
||||
// RemoveFileName("adir/") -> "adir/"
|
||||
TEST(RemoveFileNameTest, ButNoFileForAlternateSeparator) {
|
||||
EXPECT_EQ("adir" GTEST_PATH_SEP_,
|
||||
FilePath("adir/").RemoveFileName().string());
|
||||
}
|
||||
|
||||
// RemoveFileName("adir/afile") -> "adir/"
|
||||
TEST(RemoveFileNameTest, GivesDirNameForAlternateSeparator) {
|
||||
EXPECT_EQ("adir" GTEST_PATH_SEP_,
|
||||
FilePath("adir/afile").RemoveFileName().string());
|
||||
}
|
||||
|
||||
// RemoveFileName("adir/subdir/afile") -> "adir/subdir/"
|
||||
TEST(RemoveFileNameTest, GivesDirAndSubDirNameForAlternateSeparator) {
|
||||
EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_,
|
||||
FilePath("adir/subdir/afile").RemoveFileName().string());
|
||||
}
|
||||
|
||||
// RemoveFileName("/afile") -> "\"
|
||||
TEST(RemoveFileNameTest, GivesRootDirForAlternateSeparator) {
|
||||
EXPECT_EQ(GTEST_PATH_SEP_, FilePath("/afile").RemoveFileName().string());
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
TEST(MakeFileNameTest, GenerateWhenNumberIsZero) {
|
||||
FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"),
|
||||
0, "xml");
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
|
||||
}
|
||||
|
||||
TEST(MakeFileNameTest, GenerateFileNameNumberGtZero) {
|
||||
FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"),
|
||||
12, "xml");
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string());
|
||||
}
|
||||
|
||||
TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberIsZero) {
|
||||
FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_),
|
||||
FilePath("bar"), 0, "xml");
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
|
||||
}
|
||||
|
||||
TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberGtZero) {
|
||||
FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_),
|
||||
FilePath("bar"), 12, "xml");
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string());
|
||||
}
|
||||
|
||||
TEST(MakeFileNameTest, GenerateWhenNumberIsZeroAndDirIsEmpty) {
|
||||
FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"),
|
||||
0, "xml");
|
||||
EXPECT_EQ("bar.xml", actual.string());
|
||||
}
|
||||
|
||||
TEST(MakeFileNameTest, GenerateWhenNumberIsNotZeroAndDirIsEmpty) {
|
||||
FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"),
|
||||
14, "xml");
|
||||
EXPECT_EQ("bar_14.xml", actual.string());
|
||||
}
|
||||
|
||||
TEST(ConcatPathsTest, WorksWhenDirDoesNotEndWithPathSep) {
|
||||
FilePath actual = FilePath::ConcatPaths(FilePath("foo"),
|
||||
FilePath("bar.xml"));
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
|
||||
}
|
||||
|
||||
TEST(ConcatPathsTest, WorksWhenPath1EndsWithPathSep) {
|
||||
FilePath actual = FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_),
|
||||
FilePath("bar.xml"));
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
|
||||
}
|
||||
|
||||
TEST(ConcatPathsTest, Path1BeingEmpty) {
|
||||
FilePath actual = FilePath::ConcatPaths(FilePath(""),
|
||||
FilePath("bar.xml"));
|
||||
EXPECT_EQ("bar.xml", actual.string());
|
||||
}
|
||||
|
||||
TEST(ConcatPathsTest, Path2BeingEmpty) {
|
||||
FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath(""));
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_, actual.string());
|
||||
}
|
||||
|
||||
TEST(ConcatPathsTest, BothPathBeingEmpty) {
|
||||
FilePath actual = FilePath::ConcatPaths(FilePath(""),
|
||||
FilePath(""));
|
||||
EXPECT_EQ("", actual.string());
|
||||
}
|
||||
|
||||
TEST(ConcatPathsTest, Path1ContainsPathSep) {
|
||||
FilePath actual = FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_ "bar"),
|
||||
FilePath("foobar.xml"));
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "foobar.xml",
|
||||
actual.string());
|
||||
}
|
||||
|
||||
TEST(ConcatPathsTest, Path2ContainsPathSep) {
|
||||
FilePath actual = FilePath::ConcatPaths(
|
||||
FilePath("foo" GTEST_PATH_SEP_),
|
||||
FilePath("bar" GTEST_PATH_SEP_ "bar.xml"));
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "bar.xml",
|
||||
actual.string());
|
||||
}
|
||||
|
||||
TEST(ConcatPathsTest, Path2EndsWithPathSep) {
|
||||
FilePath actual = FilePath::ConcatPaths(FilePath("foo"),
|
||||
FilePath("bar" GTEST_PATH_SEP_));
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_, actual.string());
|
||||
}
|
||||
|
||||
// RemoveTrailingPathSeparator "" -> ""
|
||||
TEST(RemoveTrailingPathSeparatorTest, EmptyString) {
|
||||
EXPECT_EQ("", FilePath("").RemoveTrailingPathSeparator().string());
|
||||
}
|
||||
|
||||
// RemoveTrailingPathSeparator "foo" -> "foo"
|
||||
TEST(RemoveTrailingPathSeparatorTest, FileNoSlashString) {
|
||||
EXPECT_EQ("foo", FilePath("foo").RemoveTrailingPathSeparator().string());
|
||||
}
|
||||
|
||||
// RemoveTrailingPathSeparator "foo/" -> "foo"
|
||||
TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) {
|
||||
EXPECT_EQ("foo",
|
||||
FilePath("foo" GTEST_PATH_SEP_).RemoveTrailingPathSeparator().string());
|
||||
#if GTEST_HAS_ALT_PATH_SEP_
|
||||
EXPECT_EQ("foo", FilePath("foo/").RemoveTrailingPathSeparator().string());
|
||||
#endif
|
||||
}
|
||||
|
||||
// RemoveTrailingPathSeparator "foo/bar/" -> "foo/bar/"
|
||||
TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveLastSeparator) {
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
|
||||
FilePath("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_)
|
||||
.RemoveTrailingPathSeparator().string());
|
||||
}
|
||||
|
||||
// RemoveTrailingPathSeparator "foo/bar" -> "foo/bar"
|
||||
TEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) {
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
|
||||
FilePath("foo" GTEST_PATH_SEP_ "bar")
|
||||
.RemoveTrailingPathSeparator().string());
|
||||
}
|
||||
|
||||
TEST(DirectoryTest, RootDirectoryExists) {
|
||||
#if GTEST_OS_WINDOWS // We are on Windows.
|
||||
char current_drive[_MAX_PATH]; // NOLINT
|
||||
current_drive[0] = static_cast<char>(_getdrive() + 'A' - 1);
|
||||
current_drive[1] = ':';
|
||||
current_drive[2] = '\\';
|
||||
current_drive[3] = '\0';
|
||||
EXPECT_TRUE(FilePath(current_drive).DirectoryExists());
|
||||
#else
|
||||
EXPECT_TRUE(FilePath("/").DirectoryExists());
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
}
|
||||
|
||||
#if GTEST_OS_WINDOWS
|
||||
TEST(DirectoryTest, RootOfWrongDriveDoesNotExists) {
|
||||
const int saved_drive_ = _getdrive();
|
||||
// Find a drive that doesn't exist. Start with 'Z' to avoid common ones.
|
||||
for (char drive = 'Z'; drive >= 'A'; drive--)
|
||||
if (_chdrive(drive - 'A' + 1) == -1) {
|
||||
char non_drive[_MAX_PATH]; // NOLINT
|
||||
non_drive[0] = drive;
|
||||
non_drive[1] = ':';
|
||||
non_drive[2] = '\\';
|
||||
non_drive[3] = '\0';
|
||||
EXPECT_FALSE(FilePath(non_drive).DirectoryExists());
|
||||
break;
|
||||
}
|
||||
_chdrive(saved_drive_);
|
||||
}
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
|
||||
#if !GTEST_OS_WINDOWS_MOBILE
|
||||
// Windows CE _does_ consider an empty directory to exist.
|
||||
TEST(DirectoryTest, EmptyPathDirectoryDoesNotExist) {
|
||||
EXPECT_FALSE(FilePath("").DirectoryExists());
|
||||
}
|
||||
#endif // !GTEST_OS_WINDOWS_MOBILE
|
||||
|
||||
TEST(DirectoryTest, CurrentDirectoryExists) {
|
||||
#if GTEST_OS_WINDOWS // We are on Windows.
|
||||
# ifndef _WIN32_CE // Windows CE doesn't have a current directory.
|
||||
|
||||
EXPECT_TRUE(FilePath(".").DirectoryExists());
|
||||
EXPECT_TRUE(FilePath(".\\").DirectoryExists());
|
||||
|
||||
# endif // _WIN32_CE
|
||||
#else
|
||||
EXPECT_TRUE(FilePath(".").DirectoryExists());
|
||||
EXPECT_TRUE(FilePath("./").DirectoryExists());
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
}
|
||||
|
||||
// "foo/bar" == foo//bar" == "foo///bar"
|
||||
TEST(NormalizeTest, MultipleConsecutiveSepaparatorsInMidstring) {
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
|
||||
FilePath("foo" GTEST_PATH_SEP_ "bar").string());
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
|
||||
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
|
||||
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_
|
||||
GTEST_PATH_SEP_ "bar").string());
|
||||
}
|
||||
|
||||
// "/bar" == //bar" == "///bar"
|
||||
TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringStart) {
|
||||
EXPECT_EQ(GTEST_PATH_SEP_ "bar",
|
||||
FilePath(GTEST_PATH_SEP_ "bar").string());
|
||||
EXPECT_EQ(GTEST_PATH_SEP_ "bar",
|
||||
FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
|
||||
EXPECT_EQ(GTEST_PATH_SEP_ "bar",
|
||||
FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
|
||||
}
|
||||
|
||||
// "foo/" == foo//" == "foo///"
|
||||
TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) {
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_,
|
||||
FilePath("foo" GTEST_PATH_SEP_).string());
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_,
|
||||
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_,
|
||||
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
|
||||
}
|
||||
|
||||
#if GTEST_HAS_ALT_PATH_SEP_
|
||||
|
||||
// Tests that separators at the end of the string are normalized
|
||||
// regardless of their combination (e.g. "foo\" =="foo/\" ==
|
||||
// "foo\\/").
|
||||
TEST(NormalizeTest, MixAlternateSeparatorAtStringEnd) {
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_,
|
||||
FilePath("foo/").string());
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_,
|
||||
FilePath("foo" GTEST_PATH_SEP_ "/").string());
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_,
|
||||
FilePath("foo//" GTEST_PATH_SEP_).string());
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
TEST(AssignmentOperatorTest, DefaultAssignedToNonDefault) {
|
||||
FilePath default_path;
|
||||
FilePath non_default_path("path");
|
||||
non_default_path = default_path;
|
||||
EXPECT_EQ("", non_default_path.string());
|
||||
EXPECT_EQ("", default_path.string()); // RHS var is unchanged.
|
||||
}
|
||||
|
||||
TEST(AssignmentOperatorTest, NonDefaultAssignedToDefault) {
|
||||
FilePath non_default_path("path");
|
||||
FilePath default_path;
|
||||
default_path = non_default_path;
|
||||
EXPECT_EQ("path", default_path.string());
|
||||
EXPECT_EQ("path", non_default_path.string()); // RHS var is unchanged.
|
||||
}
|
||||
|
||||
TEST(AssignmentOperatorTest, ConstAssignedToNonConst) {
|
||||
const FilePath const_default_path("const_path");
|
||||
FilePath non_default_path("path");
|
||||
non_default_path = const_default_path;
|
||||
EXPECT_EQ("const_path", non_default_path.string());
|
||||
}
|
||||
|
||||
class DirectoryCreationTest : public Test {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
testdata_path_.Set(FilePath(
|
||||
TempDir() + GetCurrentExecutableName().string() +
|
||||
"_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_));
|
||||
testdata_file_.Set(testdata_path_.RemoveTrailingPathSeparator());
|
||||
|
||||
unique_file0_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"),
|
||||
0, "txt"));
|
||||
unique_file1_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"),
|
||||
1, "txt"));
|
||||
|
||||
remove(testdata_file_.c_str());
|
||||
remove(unique_file0_.c_str());
|
||||
remove(unique_file1_.c_str());
|
||||
posix::RmDir(testdata_path_.c_str());
|
||||
}
|
||||
|
||||
void TearDown() override {
|
||||
remove(testdata_file_.c_str());
|
||||
remove(unique_file0_.c_str());
|
||||
remove(unique_file1_.c_str());
|
||||
posix::RmDir(testdata_path_.c_str());
|
||||
}
|
||||
|
||||
void CreateTextFile(const char* filename) {
|
||||
FILE* f = posix::FOpen(filename, "w");
|
||||
fprintf(f, "text\n");
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
// Strings representing a directory and a file, with identical paths
|
||||
// except for the trailing separator character that distinquishes
|
||||
// a directory named 'test' from a file named 'test'. Example names:
|
||||
FilePath testdata_path_; // "/tmp/directory_creation/test/"
|
||||
FilePath testdata_file_; // "/tmp/directory_creation/test"
|
||||
FilePath unique_file0_; // "/tmp/directory_creation/test/unique.txt"
|
||||
FilePath unique_file1_; // "/tmp/directory_creation/test/unique_1.txt"
|
||||
};
|
||||
|
||||
TEST_F(DirectoryCreationTest, CreateDirectoriesRecursively) {
|
||||
EXPECT_FALSE(testdata_path_.DirectoryExists()) << testdata_path_.string();
|
||||
EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively());
|
||||
EXPECT_TRUE(testdata_path_.DirectoryExists());
|
||||
}
|
||||
|
||||
TEST_F(DirectoryCreationTest, CreateDirectoriesForAlreadyExistingPath) {
|
||||
EXPECT_FALSE(testdata_path_.DirectoryExists()) << testdata_path_.string();
|
||||
EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively());
|
||||
// Call 'create' again... should still succeed.
|
||||
EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively());
|
||||
}
|
||||
|
||||
TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) {
|
||||
FilePath file_path(FilePath::GenerateUniqueFileName(testdata_path_,
|
||||
FilePath("unique"), "txt"));
|
||||
EXPECT_EQ(unique_file0_.string(), file_path.string());
|
||||
EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file not there
|
||||
|
||||
testdata_path_.CreateDirectoriesRecursively();
|
||||
EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file still not there
|
||||
CreateTextFile(file_path.c_str());
|
||||
EXPECT_TRUE(file_path.FileOrDirectoryExists());
|
||||
|
||||
FilePath file_path2(FilePath::GenerateUniqueFileName(testdata_path_,
|
||||
FilePath("unique"), "txt"));
|
||||
EXPECT_EQ(unique_file1_.string(), file_path2.string());
|
||||
EXPECT_FALSE(file_path2.FileOrDirectoryExists()); // file not there
|
||||
CreateTextFile(file_path2.c_str());
|
||||
EXPECT_TRUE(file_path2.FileOrDirectoryExists());
|
||||
}
|
||||
|
||||
TEST_F(DirectoryCreationTest, CreateDirectoriesFail) {
|
||||
// force a failure by putting a file where we will try to create a directory.
|
||||
CreateTextFile(testdata_file_.c_str());
|
||||
EXPECT_TRUE(testdata_file_.FileOrDirectoryExists());
|
||||
EXPECT_FALSE(testdata_file_.DirectoryExists());
|
||||
EXPECT_FALSE(testdata_file_.CreateDirectoriesRecursively());
|
||||
}
|
||||
|
||||
TEST(NoDirectoryCreationTest, CreateNoDirectoriesForDefaultXmlFile) {
|
||||
const FilePath test_detail_xml("test_detail.xml");
|
||||
EXPECT_FALSE(test_detail_xml.CreateDirectoriesRecursively());
|
||||
}
|
||||
|
||||
TEST(FilePathTest, DefaultConstructor) {
|
||||
FilePath fp;
|
||||
EXPECT_EQ("", fp.string());
|
||||
}
|
||||
|
||||
TEST(FilePathTest, CharAndCopyConstructors) {
|
||||
const FilePath fp("spicy");
|
||||
EXPECT_EQ("spicy", fp.string());
|
||||
|
||||
const FilePath fp_copy(fp);
|
||||
EXPECT_EQ("spicy", fp_copy.string());
|
||||
}
|
||||
|
||||
TEST(FilePathTest, StringConstructor) {
|
||||
const FilePath fp(std::string("cider"));
|
||||
EXPECT_EQ("cider", fp.string());
|
||||
}
|
||||
|
||||
TEST(FilePathTest, Set) {
|
||||
const FilePath apple("apple");
|
||||
FilePath mac("mac");
|
||||
mac.Set(apple); // Implement Set() since overloading operator= is forbidden.
|
||||
EXPECT_EQ("apple", mac.string());
|
||||
EXPECT_EQ("apple", apple.string());
|
||||
}
|
||||
|
||||
TEST(FilePathTest, ToString) {
|
||||
const FilePath file("drink");
|
||||
EXPECT_EQ("drink", file.string());
|
||||
}
|
||||
|
||||
TEST(FilePathTest, RemoveExtension) {
|
||||
EXPECT_EQ("app", FilePath("app.cc").RemoveExtension("cc").string());
|
||||
EXPECT_EQ("app", FilePath("app.exe").RemoveExtension("exe").string());
|
||||
EXPECT_EQ("APP", FilePath("APP.EXE").RemoveExtension("exe").string());
|
||||
}
|
||||
|
||||
TEST(FilePathTest, RemoveExtensionWhenThereIsNoExtension) {
|
||||
EXPECT_EQ("app", FilePath("app").RemoveExtension("exe").string());
|
||||
}
|
||||
|
||||
TEST(FilePathTest, IsDirectory) {
|
||||
EXPECT_FALSE(FilePath("cola").IsDirectory());
|
||||
EXPECT_TRUE(FilePath("koala" GTEST_PATH_SEP_).IsDirectory());
|
||||
#if GTEST_HAS_ALT_PATH_SEP_
|
||||
EXPECT_TRUE(FilePath("koala/").IsDirectory());
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST(FilePathTest, IsAbsolutePath) {
|
||||
EXPECT_FALSE(FilePath("is" GTEST_PATH_SEP_ "relative").IsAbsolutePath());
|
||||
EXPECT_FALSE(FilePath("").IsAbsolutePath());
|
||||
#if GTEST_OS_WINDOWS
|
||||
EXPECT_TRUE(FilePath("c:\\" GTEST_PATH_SEP_ "is_not"
|
||||
GTEST_PATH_SEP_ "relative").IsAbsolutePath());
|
||||
EXPECT_FALSE(FilePath("c:foo" GTEST_PATH_SEP_ "bar").IsAbsolutePath());
|
||||
EXPECT_TRUE(FilePath("c:/" GTEST_PATH_SEP_ "is_not"
|
||||
GTEST_PATH_SEP_ "relative").IsAbsolutePath());
|
||||
#else
|
||||
EXPECT_TRUE(FilePath(GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
|
||||
.IsAbsolutePath());
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
}
|
||||
|
||||
TEST(FilePathTest, IsRootDirectory) {
|
||||
#if GTEST_OS_WINDOWS
|
||||
EXPECT_TRUE(FilePath("a:\\").IsRootDirectory());
|
||||
EXPECT_TRUE(FilePath("Z:/").IsRootDirectory());
|
||||
EXPECT_TRUE(FilePath("e://").IsRootDirectory());
|
||||
EXPECT_FALSE(FilePath("").IsRootDirectory());
|
||||
EXPECT_FALSE(FilePath("b:").IsRootDirectory());
|
||||
EXPECT_FALSE(FilePath("b:a").IsRootDirectory());
|
||||
EXPECT_FALSE(FilePath("8:/").IsRootDirectory());
|
||||
EXPECT_FALSE(FilePath("c|/").IsRootDirectory());
|
||||
#else
|
||||
EXPECT_TRUE(FilePath("/").IsRootDirectory());
|
||||
EXPECT_TRUE(FilePath("//").IsRootDirectory());
|
||||
EXPECT_FALSE(FilePath("").IsRootDirectory());
|
||||
EXPECT_FALSE(FilePath("\\").IsRootDirectory());
|
||||
EXPECT_FALSE(FilePath("/x").IsRootDirectory());
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace internal
|
||||
} // namespace testing
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user