diff --git a/.build-variables b/.build-variables new file mode 160000 index 00000000000..f8fad0dbbf6 --- /dev/null +++ b/.build-variables @@ -0,0 +1 @@ +Subproject commit f8fad0dbbf6c821e1ae6e254e1ed203e93815a94 diff --git a/docs/testing/doctest_quickstart.md b/docs/testing/doctest_quickstart.md new file mode 100644 index 00000000000..fd16a2bdc7d --- /dev/null +++ b/docs/testing/doctest_quickstart.md @@ -0,0 +1,11 @@ +# doctest quickstart + +This repository uses a header-only doctest setup with a thin helpers/compat layer. +- Enable: `autobuild configure -c RelWithDebInfoOS -- -DLL_TESTS=ON` +- Build targets: `llcommon_doctest`, `llmath_doctest`, `llcorehttp_doctest` +- Run: `ctest -C RelWithDebInfo -R "(llcommon_doctest|llmath_doctest|llcorehttp_doctest)" -V` + +Notes: +- Hand-authored tests are marked with `// DOCTEST_SKIP_AUTOGEN` to keep the generator idempotent. +- `LL_CHECK_*` helpers provide clearer output for floats, buffers, wide strings, and ranges. +- HTTP fake layer provides zero-latency transport, monotonic clock, per-handle queued responses (redirects/retries/cancels) — tests stay network/IO-free. diff --git a/indra/CMakeLists.txt b/indra/CMakeLists.txt index 8fde58fa43c..6f043d7d7bd 100644 --- a/indra/CMakeLists.txt +++ b/indra/CMakeLists.txt @@ -24,6 +24,8 @@ project(${ROOT_PROJECT_NAME}) set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake" "${CMAKE_CURRENT_BINARY_DIR}") +enable_testing() + include(conanbuildinfo OPTIONAL RESULT_VARIABLE USE_CONAN ) if( USE_CONAN ) set( USE_CONAN ON ) @@ -147,4 +149,3 @@ if (LL_TESTS) # individual apps can add themselves as dependencies add_subdirectory(${INTEGRATION_TESTS_PREFIX}integration_tests) endif (LL_TESTS) - diff --git a/indra/cmake/CMakeLists.txt b/indra/cmake/CMakeLists.txt index 2ba282bdb78..0b6028637e9 100644 --- a/indra/cmake/CMakeLists.txt +++ b/indra/cmake/CMakeLists.txt @@ -22,6 +22,7 @@ set(cmake_SOURCE_FILES DeploySharedLibs.cmake Discord.cmake DragDrop.cmake + Doctest.cmake EXPAT.cmake FindAutobuild.cmake FreeType.cmake diff --git a/indra/cmake/Doctest.cmake b/indra/cmake/Doctest.cmake new file mode 100644 index 00000000000..94f7da95500 --- /dev/null +++ b/indra/cmake/Doctest.cmake @@ -0,0 +1,6 @@ +# -*- cmake -*- +include_guard(GLOBAL) + +if(NOT DEFINED DOCTEST_INCLUDE_DIR) + set(DOCTEST_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/extern/doctest") +endif() diff --git a/indra/extern/doctest/LICENSE b/indra/extern/doctest/LICENSE new file mode 100644 index 00000000000..878e3dd1331 --- /dev/null +++ b/indra/extern/doctest/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016-2024 Viktor Kirilov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/indra/extern/doctest/doctest.h b/indra/extern/doctest/doctest.h new file mode 100644 index 00000000000..fd556c61d28 --- /dev/null +++ b/indra/extern/doctest/doctest.h @@ -0,0 +1,7140 @@ +/** + * @file doctest.h + * @date 2025-02-18 + * @brief Vendored third-party (MIT) + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +/* + * Vendored third-party file: doctest.h + * SPDX-License-Identifier: MIT + * Original project: https://github.com/doctest/doctest + * See license at: indra/extern/doctest/LICENSE + */ + +// ====================================================================== lgtm [cpp/missing-header-guard] +// == DO NOT MODIFY THIS FILE BY HAND - IT IS AUTO GENERATED BY CMAKE! == +// ====================================================================== +// +// doctest.h - the lightest feature-rich C++ single-header testing framework for unit tests and TDD +// +// Copyright (c) 2016-2023 Viktor Kirilov +// +// Distributed under the MIT Software License +// See accompanying file LICENSE.txt or copy at +// https://opensource.org/licenses/MIT +// +// The documentation can be found at the library's page: +// https://github.com/doctest/doctest/blob/master/doc/markdown/readme.md +// +// ================================================================================================= +// ================================================================================================= +// ================================================================================================= +// +// The library is heavily influenced by Catch - https://github.com/catchorg/Catch2 +// which uses the Boost Software License - Version 1.0 +// see here - https://github.com/catchorg/Catch2/blob/master/LICENSE.txt +// +// The concept of subcases (sections in Catch) and expression decomposition are from there. +// Some parts of the code are taken directly: +// - stringification - the detection of "ostream& operator<<(ostream&, const T&)" and StringMaker<> +// - the Approx() helper class for floating point comparison +// - colors in the console +// - breaking into a debugger +// - signal / SEH handling +// - timer +// - XmlWriter class - thanks to Phil Nash for allowing the direct reuse (AKA copy/paste) +// +// The expression decomposing templates are taken from lest - https://github.com/martinmoene/lest +// which uses the Boost Software License - Version 1.0 +// see here - https://github.com/martinmoene/lest/blob/master/LICENSE.txt +// +// ================================================================================================= +// ================================================================================================= +// ================================================================================================= + +#ifndef DOCTEST_LIBRARY_INCLUDED +#define DOCTEST_LIBRARY_INCLUDED + +// ================================================================================================= +// == VERSION ====================================================================================== +// ================================================================================================= + +#define DOCTEST_VERSION_MAJOR 2 +#define DOCTEST_VERSION_MINOR 4 +#define DOCTEST_VERSION_PATCH 11 + +// util we need here +#define DOCTEST_TOSTR_IMPL(x) #x +#define DOCTEST_TOSTR(x) DOCTEST_TOSTR_IMPL(x) + +#define DOCTEST_VERSION_STR \ + DOCTEST_TOSTR(DOCTEST_VERSION_MAJOR) "." \ + DOCTEST_TOSTR(DOCTEST_VERSION_MINOR) "." \ + DOCTEST_TOSTR(DOCTEST_VERSION_PATCH) + +#define DOCTEST_VERSION \ + (DOCTEST_VERSION_MAJOR * 10000 + DOCTEST_VERSION_MINOR * 100 + DOCTEST_VERSION_PATCH) + +// ================================================================================================= +// == COMPILER VERSION ============================================================================= +// ================================================================================================= + +// ideas for the version stuff are taken from here: https://github.com/cxxstuff/cxx_detect + +#ifdef _MSC_VER +#define DOCTEST_CPLUSPLUS _MSVC_LANG +#else +#define DOCTEST_CPLUSPLUS __cplusplus +#endif + +#define DOCTEST_COMPILER(MAJOR, MINOR, PATCH) ((MAJOR)*10000000 + (MINOR)*100000 + (PATCH)) + +// GCC/Clang and GCC/MSVC are mutually exclusive, but Clang/MSVC are not because of clang-cl... +#if defined(_MSC_VER) && defined(_MSC_FULL_VER) +#if _MSC_VER == _MSC_FULL_VER / 10000 +#define DOCTEST_MSVC DOCTEST_COMPILER(_MSC_VER / 100, _MSC_VER % 100, _MSC_FULL_VER % 10000) +#else // MSVC +#define DOCTEST_MSVC \ + DOCTEST_COMPILER(_MSC_VER / 100, (_MSC_FULL_VER / 100000) % 100, _MSC_FULL_VER % 100000) +#endif // MSVC +#endif // MSVC +#if defined(__clang__) && defined(__clang_minor__) && defined(__clang_patchlevel__) +#define DOCTEST_CLANG DOCTEST_COMPILER(__clang_major__, __clang_minor__, __clang_patchlevel__) +#elif defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) && \ + !defined(__INTEL_COMPILER) +#define DOCTEST_GCC DOCTEST_COMPILER(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) +#endif // GCC +#if defined(__INTEL_COMPILER) +#define DOCTEST_ICC DOCTEST_COMPILER(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) +#endif // ICC + +#ifndef DOCTEST_MSVC +#define DOCTEST_MSVC 0 +#endif // DOCTEST_MSVC +#ifndef DOCTEST_CLANG +#define DOCTEST_CLANG 0 +#endif // DOCTEST_CLANG +#ifndef DOCTEST_GCC +#define DOCTEST_GCC 0 +#endif // DOCTEST_GCC +#ifndef DOCTEST_ICC +#define DOCTEST_ICC 0 +#endif // DOCTEST_ICC + +// ================================================================================================= +// == COMPILER WARNINGS HELPERS ==================================================================== +// ================================================================================================= + +#if DOCTEST_CLANG && !DOCTEST_ICC +#define DOCTEST_PRAGMA_TO_STR(x) _Pragma(#x) +#define DOCTEST_CLANG_SUPPRESS_WARNING_PUSH _Pragma("clang diagnostic push") +#define DOCTEST_CLANG_SUPPRESS_WARNING(w) DOCTEST_PRAGMA_TO_STR(clang diagnostic ignored w) +#define DOCTEST_CLANG_SUPPRESS_WARNING_POP _Pragma("clang diagnostic pop") +#define DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH(w) \ + DOCTEST_CLANG_SUPPRESS_WARNING_PUSH DOCTEST_CLANG_SUPPRESS_WARNING(w) +#else // DOCTEST_CLANG +#define DOCTEST_CLANG_SUPPRESS_WARNING_PUSH +#define DOCTEST_CLANG_SUPPRESS_WARNING(w) +#define DOCTEST_CLANG_SUPPRESS_WARNING_POP +#define DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH(w) +#endif // DOCTEST_CLANG + +#if DOCTEST_GCC +#define DOCTEST_PRAGMA_TO_STR(x) _Pragma(#x) +#define DOCTEST_GCC_SUPPRESS_WARNING_PUSH _Pragma("GCC diagnostic push") +#define DOCTEST_GCC_SUPPRESS_WARNING(w) DOCTEST_PRAGMA_TO_STR(GCC diagnostic ignored w) +#define DOCTEST_GCC_SUPPRESS_WARNING_POP _Pragma("GCC diagnostic pop") +#define DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(w) \ + DOCTEST_GCC_SUPPRESS_WARNING_PUSH DOCTEST_GCC_SUPPRESS_WARNING(w) +#else // DOCTEST_GCC +#define DOCTEST_GCC_SUPPRESS_WARNING_PUSH +#define DOCTEST_GCC_SUPPRESS_WARNING(w) +#define DOCTEST_GCC_SUPPRESS_WARNING_POP +#define DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(w) +#endif // DOCTEST_GCC + +#if DOCTEST_MSVC +#define DOCTEST_MSVC_SUPPRESS_WARNING_PUSH __pragma(warning(push)) +#define DOCTEST_MSVC_SUPPRESS_WARNING(w) __pragma(warning(disable : w)) +#define DOCTEST_MSVC_SUPPRESS_WARNING_POP __pragma(warning(pop)) +#define DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(w) \ + DOCTEST_MSVC_SUPPRESS_WARNING_PUSH DOCTEST_MSVC_SUPPRESS_WARNING(w) +#else // DOCTEST_MSVC +#define DOCTEST_MSVC_SUPPRESS_WARNING_PUSH +#define DOCTEST_MSVC_SUPPRESS_WARNING(w) +#define DOCTEST_MSVC_SUPPRESS_WARNING_POP +#define DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(w) +#endif // DOCTEST_MSVC + +// ================================================================================================= +// == COMPILER WARNINGS ============================================================================ +// ================================================================================================= + +// both the header and the implementation suppress all of these, +// so it only makes sense to aggregate them like so +#define DOCTEST_SUPPRESS_COMMON_WARNINGS_PUSH \ + DOCTEST_CLANG_SUPPRESS_WARNING_PUSH \ + DOCTEST_CLANG_SUPPRESS_WARNING("-Wunknown-pragmas") \ + DOCTEST_CLANG_SUPPRESS_WARNING("-Wweak-vtables") \ + DOCTEST_CLANG_SUPPRESS_WARNING("-Wpadded") \ + DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-prototypes") \ + DOCTEST_CLANG_SUPPRESS_WARNING("-Wc++98-compat") \ + DOCTEST_CLANG_SUPPRESS_WARNING("-Wc++98-compat-pedantic") \ + \ + DOCTEST_GCC_SUPPRESS_WARNING_PUSH \ + DOCTEST_GCC_SUPPRESS_WARNING("-Wunknown-pragmas") \ + DOCTEST_GCC_SUPPRESS_WARNING("-Wpragmas") \ + DOCTEST_GCC_SUPPRESS_WARNING("-Weffc++") \ + DOCTEST_GCC_SUPPRESS_WARNING("-Wstrict-overflow") \ + DOCTEST_GCC_SUPPRESS_WARNING("-Wstrict-aliasing") \ + DOCTEST_GCC_SUPPRESS_WARNING("-Wmissing-declarations") \ + DOCTEST_GCC_SUPPRESS_WARNING("-Wuseless-cast") \ + DOCTEST_GCC_SUPPRESS_WARNING("-Wnoexcept") \ + \ + DOCTEST_MSVC_SUPPRESS_WARNING_PUSH \ + /* these 4 also disabled globally via cmake: */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4514) /* unreferenced inline function has been removed */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4571) /* SEH related */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4710) /* function not inlined */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4711) /* function selected for inline expansion*/ \ + /* common ones */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4616) /* invalid compiler warning */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4619) /* invalid compiler warning */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4996) /* The compiler encountered a deprecated declaration */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4706) /* assignment within conditional expression */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4512) /* 'class' : assignment operator could not be generated */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4127) /* conditional expression is constant */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4820) /* padding */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4625) /* copy constructor was implicitly deleted */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4626) /* assignment operator was implicitly deleted */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5027) /* move assignment operator implicitly deleted */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5026) /* move constructor was implicitly deleted */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4640) /* construction of local static object not thread-safe */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5045) /* Spectre mitigation for memory load */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5264) /* 'variable-name': 'const' variable is not used */ \ + /* static analysis */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(26439) /* Function may not throw. Declare it 'noexcept' */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(26495) /* Always initialize a member variable */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(26451) /* Arithmetic overflow ... */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(26444) /* Avoid unnamed objects with custom ctor and dtor... */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(26812) /* Prefer 'enum class' over 'enum' */ + +#define DOCTEST_SUPPRESS_COMMON_WARNINGS_POP \ + DOCTEST_CLANG_SUPPRESS_WARNING_POP \ + DOCTEST_GCC_SUPPRESS_WARNING_POP \ + DOCTEST_MSVC_SUPPRESS_WARNING_POP + +DOCTEST_SUPPRESS_COMMON_WARNINGS_PUSH + +DOCTEST_CLANG_SUPPRESS_WARNING_PUSH +DOCTEST_CLANG_SUPPRESS_WARNING("-Wnon-virtual-dtor") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wdeprecated") + +DOCTEST_GCC_SUPPRESS_WARNING_PUSH +DOCTEST_GCC_SUPPRESS_WARNING("-Wctor-dtor-privacy") +DOCTEST_GCC_SUPPRESS_WARNING("-Wnon-virtual-dtor") +DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-promo") + +DOCTEST_MSVC_SUPPRESS_WARNING_PUSH +DOCTEST_MSVC_SUPPRESS_WARNING(4623) // default constructor was implicitly defined as deleted + +#define DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_BEGIN \ + DOCTEST_MSVC_SUPPRESS_WARNING_PUSH \ + DOCTEST_MSVC_SUPPRESS_WARNING(4548) /* before comma no effect; expected side - effect */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4265) /* virtual functions, but destructor is not virtual */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4986) /* exception specification does not match previous */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4350) /* 'member1' called instead of 'member2' */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4668) /* not defined as a preprocessor macro */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4365) /* signed/unsigned mismatch */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4774) /* format string not a string literal */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4820) /* padding */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4625) /* copy constructor was implicitly deleted */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4626) /* assignment operator was implicitly deleted */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5027) /* move assignment operator implicitly deleted */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5026) /* move constructor was implicitly deleted */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4623) /* default constructor was implicitly deleted */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5039) /* pointer to pot. throwing function passed to extern C */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5045) /* Spectre mitigation for memory load */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5105) /* macro producing 'defined' has undefined behavior */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(4738) /* storing float result in memory, loss of performance */ \ + DOCTEST_MSVC_SUPPRESS_WARNING(5262) /* implicit fall-through */ + +#define DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_END DOCTEST_MSVC_SUPPRESS_WARNING_POP + +// ================================================================================================= +// == FEATURE DETECTION ============================================================================ +// ================================================================================================= + +// general compiler feature support table: https://en.cppreference.com/w/cpp/compiler_support +// MSVC C++11 feature support table: https://msdn.microsoft.com/en-us/library/hh567368.aspx +// GCC C++11 feature support table: https://gcc.gnu.org/projects/cxx-status.html +// MSVC version table: +// https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B#Internal_version_numbering +// MSVC++ 14.3 (17) _MSC_VER == 1930 (Visual Studio 2022) +// MSVC++ 14.2 (16) _MSC_VER == 1920 (Visual Studio 2019) +// MSVC++ 14.1 (15) _MSC_VER == 1910 (Visual Studio 2017) +// MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015) +// MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013) +// MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012) +// MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010) +// MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008) +// MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005) + +// Universal Windows Platform support +#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) +#define DOCTEST_CONFIG_NO_WINDOWS_SEH +#endif // WINAPI_FAMILY +#if DOCTEST_MSVC && !defined(DOCTEST_CONFIG_WINDOWS_SEH) +#define DOCTEST_CONFIG_WINDOWS_SEH +#endif // MSVC +#if defined(DOCTEST_CONFIG_NO_WINDOWS_SEH) && defined(DOCTEST_CONFIG_WINDOWS_SEH) +#undef DOCTEST_CONFIG_WINDOWS_SEH +#endif // DOCTEST_CONFIG_NO_WINDOWS_SEH + +#if !defined(_WIN32) && !defined(__QNX__) && !defined(DOCTEST_CONFIG_POSIX_SIGNALS) && \ + !defined(__EMSCRIPTEN__) && !defined(__wasi__) +#define DOCTEST_CONFIG_POSIX_SIGNALS +#endif // _WIN32 +#if defined(DOCTEST_CONFIG_NO_POSIX_SIGNALS) && defined(DOCTEST_CONFIG_POSIX_SIGNALS) +#undef DOCTEST_CONFIG_POSIX_SIGNALS +#endif // DOCTEST_CONFIG_NO_POSIX_SIGNALS + +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS +#if !defined(__cpp_exceptions) && !defined(__EXCEPTIONS) && !defined(_CPPUNWIND) \ + || defined(__wasi__) +#define DOCTEST_CONFIG_NO_EXCEPTIONS +#endif // no exceptions +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + +#ifdef DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS +#define DOCTEST_CONFIG_NO_EXCEPTIONS +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS + +#if defined(DOCTEST_CONFIG_NO_EXCEPTIONS) && !defined(DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS) +#define DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS && !DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS + +#ifdef __wasi__ +#define DOCTEST_CONFIG_NO_MULTITHREADING +#endif + +#if defined(DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN) && !defined(DOCTEST_CONFIG_IMPLEMENT) +#define DOCTEST_CONFIG_IMPLEMENT +#endif // DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN + +#if defined(_WIN32) || defined(__CYGWIN__) +#if DOCTEST_MSVC +#define DOCTEST_SYMBOL_EXPORT __declspec(dllexport) +#define DOCTEST_SYMBOL_IMPORT __declspec(dllimport) +#else // MSVC +#define DOCTEST_SYMBOL_EXPORT __attribute__((dllexport)) +#define DOCTEST_SYMBOL_IMPORT __attribute__((dllimport)) +#endif // MSVC +#else // _WIN32 +#define DOCTEST_SYMBOL_EXPORT __attribute__((visibility("default"))) +#define DOCTEST_SYMBOL_IMPORT +#endif // _WIN32 + +#ifdef DOCTEST_CONFIG_IMPLEMENTATION_IN_DLL +#ifdef DOCTEST_CONFIG_IMPLEMENT +#define DOCTEST_INTERFACE DOCTEST_SYMBOL_EXPORT +#else // DOCTEST_CONFIG_IMPLEMENT +#define DOCTEST_INTERFACE DOCTEST_SYMBOL_IMPORT +#endif // DOCTEST_CONFIG_IMPLEMENT +#else // DOCTEST_CONFIG_IMPLEMENTATION_IN_DLL +#define DOCTEST_INTERFACE +#endif // DOCTEST_CONFIG_IMPLEMENTATION_IN_DLL + +// needed for extern template instantiations +// see https://github.com/fmtlib/fmt/issues/2228 +#if DOCTEST_MSVC +#define DOCTEST_INTERFACE_DECL +#define DOCTEST_INTERFACE_DEF DOCTEST_INTERFACE +#else // DOCTEST_MSVC +#define DOCTEST_INTERFACE_DECL DOCTEST_INTERFACE +#define DOCTEST_INTERFACE_DEF +#endif // DOCTEST_MSVC + +#define DOCTEST_EMPTY + +#if DOCTEST_MSVC +#define DOCTEST_NOINLINE __declspec(noinline) +#define DOCTEST_UNUSED +#define DOCTEST_ALIGNMENT(x) +#elif DOCTEST_CLANG && DOCTEST_CLANG < DOCTEST_COMPILER(3, 5, 0) +#define DOCTEST_NOINLINE +#define DOCTEST_UNUSED +#define DOCTEST_ALIGNMENT(x) +#else +#define DOCTEST_NOINLINE __attribute__((noinline)) +#define DOCTEST_UNUSED __attribute__((unused)) +#define DOCTEST_ALIGNMENT(x) __attribute__((aligned(x))) +#endif + +#ifdef DOCTEST_CONFIG_NO_CONTRADICTING_INLINE +#define DOCTEST_INLINE_NOINLINE inline +#else +#define DOCTEST_INLINE_NOINLINE inline DOCTEST_NOINLINE +#endif + +#ifndef DOCTEST_NORETURN +#if DOCTEST_MSVC && (DOCTEST_MSVC < DOCTEST_COMPILER(19, 0, 0)) +#define DOCTEST_NORETURN +#else // DOCTEST_MSVC +#define DOCTEST_NORETURN [[noreturn]] +#endif // DOCTEST_MSVC +#endif // DOCTEST_NORETURN + +#ifndef DOCTEST_NOEXCEPT +#if DOCTEST_MSVC && (DOCTEST_MSVC < DOCTEST_COMPILER(19, 0, 0)) +#define DOCTEST_NOEXCEPT +#else // DOCTEST_MSVC +#define DOCTEST_NOEXCEPT noexcept +#endif // DOCTEST_MSVC +#endif // DOCTEST_NOEXCEPT + +#ifndef DOCTEST_CONSTEXPR +#if DOCTEST_MSVC && (DOCTEST_MSVC < DOCTEST_COMPILER(19, 0, 0)) +#define DOCTEST_CONSTEXPR const +#define DOCTEST_CONSTEXPR_FUNC inline +#else // DOCTEST_MSVC +#define DOCTEST_CONSTEXPR constexpr +#define DOCTEST_CONSTEXPR_FUNC constexpr +#endif // DOCTEST_MSVC +#endif // DOCTEST_CONSTEXPR + +#ifndef DOCTEST_NO_SANITIZE_INTEGER +#if DOCTEST_CLANG >= DOCTEST_COMPILER(3, 7, 0) +#define DOCTEST_NO_SANITIZE_INTEGER __attribute__((no_sanitize("integer"))) +#else +#define DOCTEST_NO_SANITIZE_INTEGER +#endif +#endif // DOCTEST_NO_SANITIZE_INTEGER + +// ================================================================================================= +// == FEATURE DETECTION END ======================================================================== +// ================================================================================================= + +#define DOCTEST_DECLARE_INTERFACE(name) \ + virtual ~name(); \ + name() = default; \ + name(const name&) = delete; \ + name(name&&) = delete; \ + name& operator=(const name&) = delete; \ + name& operator=(name&&) = delete; + +#define DOCTEST_DEFINE_INTERFACE(name) \ + name::~name() = default; + +// internal macros for string concatenation and anonymous variable name generation +#define DOCTEST_CAT_IMPL(s1, s2) s1##s2 +#define DOCTEST_CAT(s1, s2) DOCTEST_CAT_IMPL(s1, s2) +#ifdef __COUNTER__ // not standard and may be missing for some compilers +#define DOCTEST_ANONYMOUS(x) DOCTEST_CAT(x, __COUNTER__) +#else // __COUNTER__ +#define DOCTEST_ANONYMOUS(x) DOCTEST_CAT(x, __LINE__) +#endif // __COUNTER__ + +#ifndef DOCTEST_CONFIG_ASSERTION_PARAMETERS_BY_VALUE +#define DOCTEST_REF_WRAP(x) x& +#else // DOCTEST_CONFIG_ASSERTION_PARAMETERS_BY_VALUE +#define DOCTEST_REF_WRAP(x) x +#endif // DOCTEST_CONFIG_ASSERTION_PARAMETERS_BY_VALUE + +// not using __APPLE__ because... this is how Catch does it +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED +#define DOCTEST_PLATFORM_MAC +#elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#define DOCTEST_PLATFORM_IPHONE +#elif defined(_WIN32) +#define DOCTEST_PLATFORM_WINDOWS +#elif defined(__wasi__) +#define DOCTEST_PLATFORM_WASI +#else // DOCTEST_PLATFORM +#define DOCTEST_PLATFORM_LINUX +#endif // DOCTEST_PLATFORM + +namespace doctest { namespace detail { + static DOCTEST_CONSTEXPR int consume(const int*, int) noexcept { return 0; } +}} + +#define DOCTEST_GLOBAL_NO_WARNINGS(var, ...) \ + DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wglobal-constructors") \ + static const int var = doctest::detail::consume(&var, __VA_ARGS__); \ + DOCTEST_CLANG_SUPPRESS_WARNING_POP + +#ifndef DOCTEST_BREAK_INTO_DEBUGGER +// should probably take a look at https://github.com/scottt/debugbreak +#ifdef DOCTEST_PLATFORM_LINUX +#if defined(__GNUC__) && (defined(__i386) || defined(__x86_64)) +// Break at the location of the failing check if possible +#define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("int $3\n" : :) // NOLINT(hicpp-no-assembler) +#else +#include +#define DOCTEST_BREAK_INTO_DEBUGGER() raise(SIGTRAP) +#endif +#elif defined(DOCTEST_PLATFORM_MAC) +#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__i386) +#define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("int $3\n" : :) // NOLINT(hicpp-no-assembler) +#elif defined(__ppc__) || defined(__ppc64__) +// https://www.cocoawithlove.com/2008/03/break-into-debugger.html +#define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n": : : "memory","r0","r3","r4") // NOLINT(hicpp-no-assembler) +#else +#define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("brk #0"); // NOLINT(hicpp-no-assembler) +#endif +#elif DOCTEST_MSVC +#define DOCTEST_BREAK_INTO_DEBUGGER() __debugbreak() +#elif defined(__MINGW32__) +DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wredundant-decls") +extern "C" __declspec(dllimport) void __stdcall DebugBreak(); +DOCTEST_GCC_SUPPRESS_WARNING_POP +#define DOCTEST_BREAK_INTO_DEBUGGER() ::DebugBreak() +#else // linux +#define DOCTEST_BREAK_INTO_DEBUGGER() (static_cast(0)) +#endif // linux +#endif // DOCTEST_BREAK_INTO_DEBUGGER + +// this is kept here for backwards compatibility since the config option was changed +#ifdef DOCTEST_CONFIG_USE_IOSFWD +#ifndef DOCTEST_CONFIG_USE_STD_HEADERS +#define DOCTEST_CONFIG_USE_STD_HEADERS +#endif +#endif // DOCTEST_CONFIG_USE_IOSFWD + +// for clang - always include ciso646 (which drags some std stuff) because +// we want to check if we are using libc++ with the _LIBCPP_VERSION macro in +// which case we don't want to forward declare stuff from std - for reference: +// https://github.com/doctest/doctest/issues/126 +// https://github.com/doctest/doctest/issues/356 +#if DOCTEST_CLANG +#include +#endif // clang + +#ifdef _LIBCPP_VERSION +#ifndef DOCTEST_CONFIG_USE_STD_HEADERS +#define DOCTEST_CONFIG_USE_STD_HEADERS +#endif +#endif // _LIBCPP_VERSION + +#ifdef DOCTEST_CONFIG_USE_STD_HEADERS +#ifndef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS +#define DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS +#endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS +DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_BEGIN +#include +#include +#include +DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_END +#else // DOCTEST_CONFIG_USE_STD_HEADERS + +// Forward declaring 'X' in namespace std is not permitted by the C++ Standard. +DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4643) + +namespace std { // NOLINT(cert-dcl58-cpp) +typedef decltype(nullptr) nullptr_t; // NOLINT(modernize-use-using) +typedef decltype(sizeof(void*)) size_t; // NOLINT(modernize-use-using) +template +struct char_traits; +template <> +struct char_traits; +template +class basic_ostream; // NOLINT(fuchsia-virtual-inheritance) +typedef basic_ostream> ostream; // NOLINT(modernize-use-using) +template +// NOLINTNEXTLINE +basic_ostream& operator<<(basic_ostream&, const char*); +template +class basic_istream; +typedef basic_istream> istream; // NOLINT(modernize-use-using) +template +class tuple; +#if DOCTEST_MSVC >= DOCTEST_COMPILER(19, 20, 0) +// see this issue on why this is needed: https://github.com/doctest/doctest/issues/183 +template +class allocator; +template +class basic_string; +using string = basic_string, allocator>; +#endif // VS 2019 +} // namespace std + +DOCTEST_MSVC_SUPPRESS_WARNING_POP + +#endif // DOCTEST_CONFIG_USE_STD_HEADERS + +#ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS +#include +#endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS + +namespace doctest { + +using std::size_t; + +DOCTEST_INTERFACE extern bool is_running_in_test; + +#ifndef DOCTEST_CONFIG_STRING_SIZE_TYPE +#define DOCTEST_CONFIG_STRING_SIZE_TYPE unsigned +#endif + +// A 24 byte string class (can be as small as 17 for x64 and 13 for x86) that can hold strings with length +// of up to 23 chars on the stack before going on the heap - the last byte of the buffer is used for: +// - "is small" bit - the highest bit - if "0" then it is small - otherwise its "1" (128) +// - if small - capacity left before going on the heap - using the lowest 5 bits +// - if small - 2 bits are left unused - the second and third highest ones +// - if small - acts as a null terminator if strlen() is 23 (24 including the null terminator) +// and the "is small" bit remains "0" ("as well as the capacity left") so its OK +// Idea taken from this lecture about the string implementation of facebook/folly - fbstring +// https://www.youtube.com/watch?v=kPR8h4-qZdk +// TODO: +// - optimizations - like not deleting memory unnecessarily in operator= and etc. +// - resize/reserve/clear +// - replace +// - back/front +// - iterator stuff +// - find & friends +// - push_back/pop_back +// - assign/insert/erase +// - relational operators as free functions - taking const char* as one of the params +class DOCTEST_INTERFACE String +{ +public: + using size_type = DOCTEST_CONFIG_STRING_SIZE_TYPE; + +private: + static DOCTEST_CONSTEXPR size_type len = 24; //!OCLINT avoid private static members + static DOCTEST_CONSTEXPR size_type last = len - 1; //!OCLINT avoid private static members + + struct view // len should be more than sizeof(view) - because of the final byte for flags + { + char* ptr; + size_type size; + size_type capacity; + }; + + union + { + char buf[len]; // NOLINT(*-avoid-c-arrays) + view data; + }; + + char* allocate(size_type sz); + + bool isOnStack() const noexcept { return (buf[last] & 128) == 0; } + void setOnHeap() noexcept; + void setLast(size_type in = last) noexcept; + void setSize(size_type sz) noexcept; + + void copy(const String& other); + +public: + static DOCTEST_CONSTEXPR size_type npos = static_cast(-1); + + String() noexcept; + ~String(); + + // cppcheck-suppress noExplicitConstructor + String(const char* in); + String(const char* in, size_type in_size); + + String(std::istream& in, size_type in_size); + + String(const String& other); + String& operator=(const String& other); + + String& operator+=(const String& other); + + String(String&& other) noexcept; + String& operator=(String&& other) noexcept; + + char operator[](size_type i) const; + char& operator[](size_type i); + + // the only functions I'm willing to leave in the interface - available for inlining + const char* c_str() const { return const_cast(this)->c_str(); } // NOLINT + char* c_str() { + if (isOnStack()) { + return reinterpret_cast(buf); + } + return data.ptr; + } + + size_type size() const; + size_type capacity() const; + + String substr(size_type pos, size_type cnt = npos) &&; + String substr(size_type pos, size_type cnt = npos) const &; + + size_type find(char ch, size_type pos = 0) const; + size_type rfind(char ch, size_type pos = npos) const; + + int compare(const char* other, bool no_case = false) const; + int compare(const String& other, bool no_case = false) const; + +friend DOCTEST_INTERFACE std::ostream& operator<<(std::ostream& s, const String& in); +}; + +DOCTEST_INTERFACE String operator+(const String& lhs, const String& rhs); + +DOCTEST_INTERFACE bool operator==(const String& lhs, const String& rhs); +DOCTEST_INTERFACE bool operator!=(const String& lhs, const String& rhs); +DOCTEST_INTERFACE bool operator<(const String& lhs, const String& rhs); +DOCTEST_INTERFACE bool operator>(const String& lhs, const String& rhs); +DOCTEST_INTERFACE bool operator<=(const String& lhs, const String& rhs); +DOCTEST_INTERFACE bool operator>=(const String& lhs, const String& rhs); + +class DOCTEST_INTERFACE Contains { +public: + explicit Contains(const String& string); + + bool checkWith(const String& other) const; + + String string; +}; + +DOCTEST_INTERFACE String toString(const Contains& in); + +DOCTEST_INTERFACE bool operator==(const String& lhs, const Contains& rhs); +DOCTEST_INTERFACE bool operator==(const Contains& lhs, const String& rhs); +DOCTEST_INTERFACE bool operator!=(const String& lhs, const Contains& rhs); +DOCTEST_INTERFACE bool operator!=(const Contains& lhs, const String& rhs); + +namespace Color { + enum Enum + { + None = 0, + White, + Red, + Green, + Blue, + Cyan, + Yellow, + Grey, + + Bright = 0x10, + + BrightRed = Bright | Red, + BrightGreen = Bright | Green, + LightGrey = Bright | Grey, + BrightWhite = Bright | White + }; + + DOCTEST_INTERFACE std::ostream& operator<<(std::ostream& s, Color::Enum code); +} // namespace Color + +namespace assertType { + enum Enum + { + // macro traits + + is_warn = 1, + is_check = 2 * is_warn, + is_require = 2 * is_check, + + is_normal = 2 * is_require, + is_throws = 2 * is_normal, + is_throws_as = 2 * is_throws, + is_throws_with = 2 * is_throws_as, + is_nothrow = 2 * is_throws_with, + + is_false = 2 * is_nothrow, + is_unary = 2 * is_false, // not checked anywhere - used just to distinguish the types + + is_eq = 2 * is_unary, + is_ne = 2 * is_eq, + + is_lt = 2 * is_ne, + is_gt = 2 * is_lt, + + is_ge = 2 * is_gt, + is_le = 2 * is_ge, + + // macro types + + DT_WARN = is_normal | is_warn, + DT_CHECK = is_normal | is_check, + DT_REQUIRE = is_normal | is_require, + + DT_WARN_FALSE = is_normal | is_false | is_warn, + DT_CHECK_FALSE = is_normal | is_false | is_check, + DT_REQUIRE_FALSE = is_normal | is_false | is_require, + + DT_WARN_THROWS = is_throws | is_warn, + DT_CHECK_THROWS = is_throws | is_check, + DT_REQUIRE_THROWS = is_throws | is_require, + + DT_WARN_THROWS_AS = is_throws_as | is_warn, + DT_CHECK_THROWS_AS = is_throws_as | is_check, + DT_REQUIRE_THROWS_AS = is_throws_as | is_require, + + DT_WARN_THROWS_WITH = is_throws_with | is_warn, + DT_CHECK_THROWS_WITH = is_throws_with | is_check, + DT_REQUIRE_THROWS_WITH = is_throws_with | is_require, + + DT_WARN_THROWS_WITH_AS = is_throws_with | is_throws_as | is_warn, + DT_CHECK_THROWS_WITH_AS = is_throws_with | is_throws_as | is_check, + DT_REQUIRE_THROWS_WITH_AS = is_throws_with | is_throws_as | is_require, + + DT_WARN_NOTHROW = is_nothrow | is_warn, + DT_CHECK_NOTHROW = is_nothrow | is_check, + DT_REQUIRE_NOTHROW = is_nothrow | is_require, + + DT_WARN_EQ = is_normal | is_eq | is_warn, + DT_CHECK_EQ = is_normal | is_eq | is_check, + DT_REQUIRE_EQ = is_normal | is_eq | is_require, + + DT_WARN_NE = is_normal | is_ne | is_warn, + DT_CHECK_NE = is_normal | is_ne | is_check, + DT_REQUIRE_NE = is_normal | is_ne | is_require, + + DT_WARN_GT = is_normal | is_gt | is_warn, + DT_CHECK_GT = is_normal | is_gt | is_check, + DT_REQUIRE_GT = is_normal | is_gt | is_require, + + DT_WARN_LT = is_normal | is_lt | is_warn, + DT_CHECK_LT = is_normal | is_lt | is_check, + DT_REQUIRE_LT = is_normal | is_lt | is_require, + + DT_WARN_GE = is_normal | is_ge | is_warn, + DT_CHECK_GE = is_normal | is_ge | is_check, + DT_REQUIRE_GE = is_normal | is_ge | is_require, + + DT_WARN_LE = is_normal | is_le | is_warn, + DT_CHECK_LE = is_normal | is_le | is_check, + DT_REQUIRE_LE = is_normal | is_le | is_require, + + DT_WARN_UNARY = is_normal | is_unary | is_warn, + DT_CHECK_UNARY = is_normal | is_unary | is_check, + DT_REQUIRE_UNARY = is_normal | is_unary | is_require, + + DT_WARN_UNARY_FALSE = is_normal | is_false | is_unary | is_warn, + DT_CHECK_UNARY_FALSE = is_normal | is_false | is_unary | is_check, + DT_REQUIRE_UNARY_FALSE = is_normal | is_false | is_unary | is_require, + }; +} // namespace assertType + +DOCTEST_INTERFACE const char* assertString(assertType::Enum at); +DOCTEST_INTERFACE const char* failureString(assertType::Enum at); +DOCTEST_INTERFACE const char* skipPathFromFilename(const char* file); + +struct DOCTEST_INTERFACE TestCaseData +{ + String m_file; // the file in which the test was registered (using String - see #350) + unsigned m_line; // the line where the test was registered + const char* m_name; // name of the test case + const char* m_test_suite; // the test suite in which the test was added + const char* m_description; + bool m_skip; + bool m_no_breaks; + bool m_no_output; + bool m_may_fail; + bool m_should_fail; + int m_expected_failures; + double m_timeout; +}; + +struct DOCTEST_INTERFACE AssertData +{ + // common - for all asserts + const TestCaseData* m_test_case; + assertType::Enum m_at; + const char* m_file; + int m_line; + const char* m_expr; + bool m_failed; + + // exception-related - for all asserts + bool m_threw; + String m_exception; + + // for normal asserts + String m_decomp; + + // for specific exception-related asserts + bool m_threw_as; + const char* m_exception_type; + + class DOCTEST_INTERFACE StringContains { + private: + Contains content; + bool isContains; + + public: + StringContains(const String& str) : content(str), isContains(false) { } + StringContains(Contains cntn) : content(static_cast(cntn)), isContains(true) { } + + bool check(const String& str) { return isContains ? (content == str) : (content.string == str); } + + operator const String&() const { return content.string; } + + const char* c_str() const { return content.string.c_str(); } + } m_exception_string; + + AssertData(assertType::Enum at, const char* file, int line, const char* expr, + const char* exception_type, const StringContains& exception_string); +}; + +struct DOCTEST_INTERFACE MessageData +{ + String m_string; + const char* m_file; + int m_line; + assertType::Enum m_severity; +}; + +struct DOCTEST_INTERFACE SubcaseSignature +{ + String m_name; + const char* m_file; + int m_line; + + bool operator==(const SubcaseSignature& other) const; + bool operator<(const SubcaseSignature& other) const; +}; + +struct DOCTEST_INTERFACE IContextScope +{ + DOCTEST_DECLARE_INTERFACE(IContextScope) + virtual void stringify(std::ostream*) const = 0; +}; + +namespace detail { + struct DOCTEST_INTERFACE TestCase; +} // namespace detail + +struct ContextOptions //!OCLINT too many fields +{ + std::ostream* cout = nullptr; // stdout stream + String binary_name; // the test binary name + + const detail::TestCase* currentTest = nullptr; + + // == parameters from the command line + String out; // output filename + String order_by; // how tests should be ordered + unsigned rand_seed; // the seed for rand ordering + + unsigned first; // the first (matching) test to be executed + unsigned last; // the last (matching) test to be executed + + int abort_after; // stop tests after this many failed assertions + int subcase_filter_levels; // apply the subcase filters for the first N levels + + bool success; // include successful assertions in output + bool case_sensitive; // if filtering should be case sensitive + bool exit; // if the program should be exited after the tests are ran/whatever + bool duration; // print the time duration of each test case + bool minimal; // minimal console output (only test failures) + bool quiet; // no console output + bool no_throw; // to skip exceptions-related assertion macros + bool no_exitcode; // if the framework should return 0 as the exitcode + bool no_run; // to not run the tests at all (can be done with an "*" exclude) + bool no_intro; // to not print the intro of the framework + bool no_version; // to not print the version of the framework + bool no_colors; // if output to the console should be colorized + bool force_colors; // forces the use of colors even when a tty cannot be detected + bool no_breaks; // to not break into the debugger + bool no_skip; // don't skip test cases which are marked to be skipped + bool gnu_file_line; // if line numbers should be surrounded with :x: and not (x): + bool no_path_in_filenames; // if the path to files should be removed from the output + bool no_line_numbers; // if source code line numbers should be omitted from the output + bool no_debug_output; // no output in the debug console when a debugger is attached + bool no_skipped_summary; // don't print "skipped" in the summary !!! UNDOCUMENTED !!! + bool no_time_in_output; // omit any time/timestamps from output !!! UNDOCUMENTED !!! + + bool help; // to print the help + bool version; // to print the version + bool count; // if only the count of matching tests is to be retrieved + bool list_test_cases; // to list all tests matching the filters + bool list_test_suites; // to list all suites matching the filters + bool list_reporters; // lists all registered reporters +}; + +namespace detail { + namespace types { +#ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS + using namespace std; +#else + template + struct enable_if { }; + + template + struct enable_if { using type = T; }; + + struct true_type { static DOCTEST_CONSTEXPR bool value = true; }; + struct false_type { static DOCTEST_CONSTEXPR bool value = false; }; + + template struct remove_reference { using type = T; }; + template struct remove_reference { using type = T; }; + template struct remove_reference { using type = T; }; + + template struct is_rvalue_reference : false_type { }; + template struct is_rvalue_reference : true_type { }; + + template struct remove_const { using type = T; }; + template struct remove_const { using type = T; }; + + // Compiler intrinsics + template struct is_enum { static DOCTEST_CONSTEXPR bool value = __is_enum(T); }; + template struct underlying_type { using type = __underlying_type(T); }; + + template struct is_pointer : false_type { }; + template struct is_pointer : true_type { }; + + template struct is_array : false_type { }; + // NOLINTNEXTLINE(*-avoid-c-arrays) + template struct is_array : true_type { }; +#endif + } + + // + template + T&& declval(); + + template + DOCTEST_CONSTEXPR_FUNC T&& forward(typename types::remove_reference::type& t) DOCTEST_NOEXCEPT { + return static_cast(t); + } + + template + DOCTEST_CONSTEXPR_FUNC T&& forward(typename types::remove_reference::type&& t) DOCTEST_NOEXCEPT { + return static_cast(t); + } + + template + struct deferred_false : types::false_type { }; + +// MSVS 2015 :( +#if !DOCTEST_CLANG && defined(_MSC_VER) && _MSC_VER <= 1900 + template + struct has_global_insertion_operator : types::false_type { }; + + template + struct has_global_insertion_operator(), declval()), void())> : types::true_type { }; + + template + struct has_insertion_operator { static DOCTEST_CONSTEXPR bool value = has_global_insertion_operator::value; }; + + template + struct insert_hack; + + template + struct insert_hack { + static void insert(std::ostream& os, const T& t) { ::operator<<(os, t); } + }; + + template + struct insert_hack { + static void insert(std::ostream& os, const T& t) { operator<<(os, t); } + }; + + template + using insert_hack_t = insert_hack::value>; +#else + template + struct has_insertion_operator : types::false_type { }; +#endif + + template + struct has_insertion_operator(), declval()), void())> : types::true_type { }; + + template + struct should_stringify_as_underlying_type { + static DOCTEST_CONSTEXPR bool value = detail::types::is_enum::value && !doctest::detail::has_insertion_operator::value; + }; + + DOCTEST_INTERFACE std::ostream* tlssPush(); + DOCTEST_INTERFACE String tlssPop(); + + template + struct StringMakerBase { + template + static String convert(const DOCTEST_REF_WRAP(T)) { +#ifdef DOCTEST_CONFIG_REQUIRE_STRINGIFICATION_FOR_ALL_USED_TYPES + static_assert(deferred_false::value, "No stringification detected for type T. See string conversion manual"); +#endif + return "{?}"; + } + }; + + template + struct filldata; + + template + void filloss(std::ostream* stream, const T& in) { + filldata::fill(stream, in); + } + + template + void filloss(std::ostream* stream, const T (&in)[N]) { // NOLINT(*-avoid-c-arrays) + // T[N], T(&)[N], T(&&)[N] have same behaviour. + // Hence remove reference. + filloss::type>(stream, in); + } + + template + String toStream(const T& in) { + std::ostream* stream = tlssPush(); + filloss(stream, in); + return tlssPop(); + } + + template <> + struct StringMakerBase { + template + static String convert(const DOCTEST_REF_WRAP(T) in) { + return toStream(in); + } + }; +} // namespace detail + +template +struct StringMaker : public detail::StringMakerBase< + detail::has_insertion_operator::value || detail::types::is_pointer::value || detail::types::is_array::value> +{}; + +#ifndef DOCTEST_STRINGIFY +#ifdef DOCTEST_CONFIG_DOUBLE_STRINGIFY +#define DOCTEST_STRINGIFY(...) toString(toString(__VA_ARGS__)) +#else +#define DOCTEST_STRINGIFY(...) toString(__VA_ARGS__) +#endif +#endif + +template +String toString() { +#if DOCTEST_CLANG == 0 && DOCTEST_GCC == 0 && DOCTEST_ICC == 0 + String ret = __FUNCSIG__; // class doctest::String __cdecl doctest::toString(void) + String::size_type beginPos = ret.find('<'); + return ret.substr(beginPos + 1, ret.size() - beginPos - static_cast(sizeof(">(void)"))); +#else + String ret = __PRETTY_FUNCTION__; // doctest::String toString() [with T = TYPE] + String::size_type begin = ret.find('=') + 2; + return ret.substr(begin, ret.size() - begin - 1); +#endif +} + +template ::value, bool>::type = true> +String toString(const DOCTEST_REF_WRAP(T) value) { + return StringMaker::convert(value); +} + +#ifdef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING +DOCTEST_INTERFACE String toString(const char* in); +#endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING + +#if DOCTEST_MSVC >= DOCTEST_COMPILER(19, 20, 0) +// see this issue on why this is needed: https://github.com/doctest/doctest/issues/183 +DOCTEST_INTERFACE String toString(const std::string& in); +#endif // VS 2019 + +DOCTEST_INTERFACE String toString(String in); + +DOCTEST_INTERFACE String toString(std::nullptr_t); + +DOCTEST_INTERFACE String toString(bool in); + +DOCTEST_INTERFACE String toString(float in); +DOCTEST_INTERFACE String toString(double in); +DOCTEST_INTERFACE String toString(double long in); + +DOCTEST_INTERFACE String toString(char in); +DOCTEST_INTERFACE String toString(char signed in); +DOCTEST_INTERFACE String toString(char unsigned in); +DOCTEST_INTERFACE String toString(short in); +DOCTEST_INTERFACE String toString(short unsigned in); +DOCTEST_INTERFACE String toString(signed in); +DOCTEST_INTERFACE String toString(unsigned in); +DOCTEST_INTERFACE String toString(long in); +DOCTEST_INTERFACE String toString(long unsigned in); +DOCTEST_INTERFACE String toString(long long in); +DOCTEST_INTERFACE String toString(long long unsigned in); + +template ::value, bool>::type = true> +String toString(const DOCTEST_REF_WRAP(T) value) { + using UT = typename detail::types::underlying_type::type; + return (DOCTEST_STRINGIFY(static_cast(value))); +} + +namespace detail { + template + struct filldata + { + static void fill(std::ostream* stream, const T& in) { +#if defined(_MSC_VER) && _MSC_VER <= 1900 + insert_hack_t::insert(*stream, in); +#else + operator<<(*stream, in); +#endif + } + }; + +DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4866) +// NOLINTBEGIN(*-avoid-c-arrays) + template + struct filldata { + static void fill(std::ostream* stream, const T(&in)[N]) { + *stream << "["; + for (size_t i = 0; i < N; i++) { + if (i != 0) { *stream << ", "; } + *stream << (DOCTEST_STRINGIFY(in[i])); + } + *stream << "]"; + } + }; +// NOLINTEND(*-avoid-c-arrays) +DOCTEST_MSVC_SUPPRESS_WARNING_POP + + // Specialized since we don't want the terminating null byte! +// NOLINTBEGIN(*-avoid-c-arrays) + template + struct filldata { + static void fill(std::ostream* stream, const char (&in)[N]) { + *stream << String(in, in[N - 1] ? N : N - 1); + } // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks) + }; +// NOLINTEND(*-avoid-c-arrays) + + template <> + struct filldata { + static void fill(std::ostream* stream, const void* in); + }; + + template + struct filldata { +DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4180) + static void fill(std::ostream* stream, const T* in) { +DOCTEST_MSVC_SUPPRESS_WARNING_POP +DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wmicrosoft-cast") + filldata::fill(stream, +#if DOCTEST_GCC == 0 || DOCTEST_GCC >= DOCTEST_COMPILER(4, 9, 0) + reinterpret_cast(in) +#else + *reinterpret_cast(&in) +#endif + ); +DOCTEST_CLANG_SUPPRESS_WARNING_POP + } + }; +} + +struct DOCTEST_INTERFACE Approx +{ + Approx(double value); + + Approx operator()(double value) const; + +#ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS + template + explicit Approx(const T& value, + typename detail::types::enable_if::value>::type* = + static_cast(nullptr)) { + *this = static_cast(value); + } +#endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS + + Approx& epsilon(double newEpsilon); + +#ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS + template + typename std::enable_if::value, Approx&>::type epsilon( + const T& newEpsilon) { + m_epsilon = static_cast(newEpsilon); + return *this; + } +#endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS + + Approx& scale(double newScale); + +#ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS + template + typename std::enable_if::value, Approx&>::type scale( + const T& newScale) { + m_scale = static_cast(newScale); + return *this; + } +#endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS + + // clang-format off + DOCTEST_INTERFACE friend bool operator==(double lhs, const Approx & rhs); + DOCTEST_INTERFACE friend bool operator==(const Approx & lhs, double rhs); + DOCTEST_INTERFACE friend bool operator!=(double lhs, const Approx & rhs); + DOCTEST_INTERFACE friend bool operator!=(const Approx & lhs, double rhs); + DOCTEST_INTERFACE friend bool operator<=(double lhs, const Approx & rhs); + DOCTEST_INTERFACE friend bool operator<=(const Approx & lhs, double rhs); + DOCTEST_INTERFACE friend bool operator>=(double lhs, const Approx & rhs); + DOCTEST_INTERFACE friend bool operator>=(const Approx & lhs, double rhs); + DOCTEST_INTERFACE friend bool operator< (double lhs, const Approx & rhs); + DOCTEST_INTERFACE friend bool operator< (const Approx & lhs, double rhs); + DOCTEST_INTERFACE friend bool operator> (double lhs, const Approx & rhs); + DOCTEST_INTERFACE friend bool operator> (const Approx & lhs, double rhs); + +#ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS +#define DOCTEST_APPROX_PREFIX \ + template friend typename std::enable_if::value, bool>::type + + DOCTEST_APPROX_PREFIX operator==(const T& lhs, const Approx& rhs) { return operator==(static_cast(lhs), rhs); } + DOCTEST_APPROX_PREFIX operator==(const Approx& lhs, const T& rhs) { return operator==(rhs, lhs); } + DOCTEST_APPROX_PREFIX operator!=(const T& lhs, const Approx& rhs) { return !operator==(lhs, rhs); } + DOCTEST_APPROX_PREFIX operator!=(const Approx& lhs, const T& rhs) { return !operator==(rhs, lhs); } + DOCTEST_APPROX_PREFIX operator<=(const T& lhs, const Approx& rhs) { return static_cast(lhs) < rhs.m_value || lhs == rhs; } + DOCTEST_APPROX_PREFIX operator<=(const Approx& lhs, const T& rhs) { return lhs.m_value < static_cast(rhs) || lhs == rhs; } + DOCTEST_APPROX_PREFIX operator>=(const T& lhs, const Approx& rhs) { return static_cast(lhs) > rhs.m_value || lhs == rhs; } + DOCTEST_APPROX_PREFIX operator>=(const Approx& lhs, const T& rhs) { return lhs.m_value > static_cast(rhs) || lhs == rhs; } + DOCTEST_APPROX_PREFIX operator< (const T& lhs, const Approx& rhs) { return static_cast(lhs) < rhs.m_value && lhs != rhs; } + DOCTEST_APPROX_PREFIX operator< (const Approx& lhs, const T& rhs) { return lhs.m_value < static_cast(rhs) && lhs != rhs; } + DOCTEST_APPROX_PREFIX operator> (const T& lhs, const Approx& rhs) { return static_cast(lhs) > rhs.m_value && lhs != rhs; } + DOCTEST_APPROX_PREFIX operator> (const Approx& lhs, const T& rhs) { return lhs.m_value > static_cast(rhs) && lhs != rhs; } +#undef DOCTEST_APPROX_PREFIX +#endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS + + // clang-format on + + double m_epsilon; + double m_scale; + double m_value; +}; + +DOCTEST_INTERFACE String toString(const Approx& in); + +DOCTEST_INTERFACE const ContextOptions* getContextOptions(); + +template +struct DOCTEST_INTERFACE_DECL IsNaN +{ + F value; bool flipped; + IsNaN(F f, bool flip = false) : value(f), flipped(flip) { } + IsNaN operator!() const { return { value, !flipped }; } + operator bool() const; +}; +#ifndef __MINGW32__ +extern template struct DOCTEST_INTERFACE_DECL IsNaN; +extern template struct DOCTEST_INTERFACE_DECL IsNaN; +extern template struct DOCTEST_INTERFACE_DECL IsNaN; +#endif +DOCTEST_INTERFACE String toString(IsNaN in); +DOCTEST_INTERFACE String toString(IsNaN in); +DOCTEST_INTERFACE String toString(IsNaN in); + +#ifndef DOCTEST_CONFIG_DISABLE + +namespace detail { + // clang-format off +#ifdef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING + template struct decay_array { using type = T; }; + template struct decay_array { using type = T*; }; + template struct decay_array { using type = T*; }; + + template struct not_char_pointer { static DOCTEST_CONSTEXPR int value = 1; }; + template<> struct not_char_pointer { static DOCTEST_CONSTEXPR int value = 0; }; + template<> struct not_char_pointer { static DOCTEST_CONSTEXPR int value = 0; }; + + template struct can_use_op : public not_char_pointer::type> {}; +#endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING + // clang-format on + + struct DOCTEST_INTERFACE TestFailureException + { + }; + + DOCTEST_INTERFACE bool checkIfShouldThrow(assertType::Enum at); + +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + DOCTEST_NORETURN +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + DOCTEST_INTERFACE void throwException(); + + struct DOCTEST_INTERFACE Subcase + { + SubcaseSignature m_signature; + bool m_entered = false; + + Subcase(const String& name, const char* file, int line); + Subcase(const Subcase&) = delete; + Subcase(Subcase&&) = delete; + Subcase& operator=(const Subcase&) = delete; + Subcase& operator=(Subcase&&) = delete; + ~Subcase(); + + operator bool() const; + + private: + bool checkFilters(); + }; + + template + String stringifyBinaryExpr(const DOCTEST_REF_WRAP(L) lhs, const char* op, + const DOCTEST_REF_WRAP(R) rhs) { + return (DOCTEST_STRINGIFY(lhs)) + op + (DOCTEST_STRINGIFY(rhs)); + } + +#if DOCTEST_CLANG && DOCTEST_CLANG < DOCTEST_COMPILER(3, 6, 0) +DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wunused-comparison") +#endif + +// This will check if there is any way it could find a operator like member or friend and uses it. +// If not it doesn't find the operator or if the operator at global scope is defined after +// this template, the template won't be instantiated due to SFINAE. Once the template is not +// instantiated it can look for global operator using normal conversions. +#ifdef __NVCC__ +#define SFINAE_OP(ret,op) ret +#else +#define SFINAE_OP(ret,op) decltype((void)(doctest::detail::declval() op doctest::detail::declval()),ret{}) +#endif + +#define DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(op, op_str, op_macro) \ + template \ + DOCTEST_NOINLINE SFINAE_OP(Result,op) operator op(R&& rhs) { \ + bool res = op_macro(doctest::detail::forward(lhs), doctest::detail::forward(rhs)); \ + if(m_at & assertType::is_false) \ + res = !res; \ + if(!res || doctest::getContextOptions()->success) \ + return Result(res, stringifyBinaryExpr(lhs, op_str, rhs)); \ + return Result(res); \ + } + + // more checks could be added - like in Catch: + // https://github.com/catchorg/Catch2/pull/1480/files + // https://github.com/catchorg/Catch2/pull/1481/files +#define DOCTEST_FORBIT_EXPRESSION(rt, op) \ + template \ + rt& operator op(const R&) { \ + static_assert(deferred_false::value, \ + "Expression Too Complex Please Rewrite As Binary Comparison!"); \ + return *this; \ + } + + struct DOCTEST_INTERFACE Result // NOLINT(*-member-init) + { + bool m_passed; + String m_decomp; + + Result() = default; // TODO: Why do we need this? (To remove NOLINT) + Result(bool passed, const String& decomposition = String()); + + // forbidding some expressions based on this table: https://en.cppreference.com/w/cpp/language/operator_precedence + DOCTEST_FORBIT_EXPRESSION(Result, &) + DOCTEST_FORBIT_EXPRESSION(Result, ^) + DOCTEST_FORBIT_EXPRESSION(Result, |) + DOCTEST_FORBIT_EXPRESSION(Result, &&) + DOCTEST_FORBIT_EXPRESSION(Result, ||) + DOCTEST_FORBIT_EXPRESSION(Result, ==) + DOCTEST_FORBIT_EXPRESSION(Result, !=) + DOCTEST_FORBIT_EXPRESSION(Result, <) + DOCTEST_FORBIT_EXPRESSION(Result, >) + DOCTEST_FORBIT_EXPRESSION(Result, <=) + DOCTEST_FORBIT_EXPRESSION(Result, >=) + DOCTEST_FORBIT_EXPRESSION(Result, =) + DOCTEST_FORBIT_EXPRESSION(Result, +=) + DOCTEST_FORBIT_EXPRESSION(Result, -=) + DOCTEST_FORBIT_EXPRESSION(Result, *=) + DOCTEST_FORBIT_EXPRESSION(Result, /=) + DOCTEST_FORBIT_EXPRESSION(Result, %=) + DOCTEST_FORBIT_EXPRESSION(Result, <<=) + DOCTEST_FORBIT_EXPRESSION(Result, >>=) + DOCTEST_FORBIT_EXPRESSION(Result, &=) + DOCTEST_FORBIT_EXPRESSION(Result, ^=) + DOCTEST_FORBIT_EXPRESSION(Result, |=) + }; + +#ifndef DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION + + DOCTEST_CLANG_SUPPRESS_WARNING_PUSH + DOCTEST_CLANG_SUPPRESS_WARNING("-Wsign-conversion") + DOCTEST_CLANG_SUPPRESS_WARNING("-Wsign-compare") + //DOCTEST_CLANG_SUPPRESS_WARNING("-Wdouble-promotion") + //DOCTEST_CLANG_SUPPRESS_WARNING("-Wconversion") + //DOCTEST_CLANG_SUPPRESS_WARNING("-Wfloat-equal") + + DOCTEST_GCC_SUPPRESS_WARNING_PUSH + DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-conversion") + DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-compare") + //DOCTEST_GCC_SUPPRESS_WARNING("-Wdouble-promotion") + //DOCTEST_GCC_SUPPRESS_WARNING("-Wconversion") + //DOCTEST_GCC_SUPPRESS_WARNING("-Wfloat-equal") + + DOCTEST_MSVC_SUPPRESS_WARNING_PUSH + // https://stackoverflow.com/questions/39479163 what's the difference between 4018 and 4389 + DOCTEST_MSVC_SUPPRESS_WARNING(4388) // signed/unsigned mismatch + DOCTEST_MSVC_SUPPRESS_WARNING(4389) // 'operator' : signed/unsigned mismatch + DOCTEST_MSVC_SUPPRESS_WARNING(4018) // 'expression' : signed/unsigned mismatch + //DOCTEST_MSVC_SUPPRESS_WARNING(4805) // 'operation' : unsafe mix of type 'type' and type 'type' in operation + +#endif // DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION + + // clang-format off +#ifndef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING +#define DOCTEST_COMPARISON_RETURN_TYPE bool +#else // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING +#define DOCTEST_COMPARISON_RETURN_TYPE typename types::enable_if::value || can_use_op::value, bool>::type + inline bool eq(const char* lhs, const char* rhs) { return String(lhs) == String(rhs); } + inline bool ne(const char* lhs, const char* rhs) { return String(lhs) != String(rhs); } + inline bool lt(const char* lhs, const char* rhs) { return String(lhs) < String(rhs); } + inline bool gt(const char* lhs, const char* rhs) { return String(lhs) > String(rhs); } + inline bool le(const char* lhs, const char* rhs) { return String(lhs) <= String(rhs); } + inline bool ge(const char* lhs, const char* rhs) { return String(lhs) >= String(rhs); } +#endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING + // clang-format on + +#define DOCTEST_RELATIONAL_OP(name, op) \ + template \ + DOCTEST_COMPARISON_RETURN_TYPE name(const DOCTEST_REF_WRAP(L) lhs, \ + const DOCTEST_REF_WRAP(R) rhs) { \ + return lhs op rhs; \ + } + + DOCTEST_RELATIONAL_OP(eq, ==) + DOCTEST_RELATIONAL_OP(ne, !=) + DOCTEST_RELATIONAL_OP(lt, <) + DOCTEST_RELATIONAL_OP(gt, >) + DOCTEST_RELATIONAL_OP(le, <=) + DOCTEST_RELATIONAL_OP(ge, >=) + +#ifndef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING +#define DOCTEST_CMP_EQ(l, r) l == r +#define DOCTEST_CMP_NE(l, r) l != r +#define DOCTEST_CMP_GT(l, r) l > r +#define DOCTEST_CMP_LT(l, r) l < r +#define DOCTEST_CMP_GE(l, r) l >= r +#define DOCTEST_CMP_LE(l, r) l <= r +#else // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING +#define DOCTEST_CMP_EQ(l, r) eq(l, r) +#define DOCTEST_CMP_NE(l, r) ne(l, r) +#define DOCTEST_CMP_GT(l, r) gt(l, r) +#define DOCTEST_CMP_LT(l, r) lt(l, r) +#define DOCTEST_CMP_GE(l, r) ge(l, r) +#define DOCTEST_CMP_LE(l, r) le(l, r) +#endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING + + template + // cppcheck-suppress copyCtorAndEqOperator + struct Expression_lhs + { + L lhs; + assertType::Enum m_at; + + explicit Expression_lhs(L&& in, assertType::Enum at) + : lhs(static_cast(in)) + , m_at(at) {} + + DOCTEST_NOINLINE operator Result() { +// this is needed only for MSVC 2015 +DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4800) // 'int': forcing value to bool + bool res = static_cast(lhs); +DOCTEST_MSVC_SUPPRESS_WARNING_POP + if(m_at & assertType::is_false) { //!OCLINT bitwise operator in conditional + res = !res; + } + + if(!res || getContextOptions()->success) { + return { res, (DOCTEST_STRINGIFY(lhs)) }; + } + return { res }; + } + + /* This is required for user-defined conversions from Expression_lhs to L */ + operator L() const { return lhs; } + + // clang-format off + DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(==, " == ", DOCTEST_CMP_EQ) //!OCLINT bitwise operator in conditional + DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(!=, " != ", DOCTEST_CMP_NE) //!OCLINT bitwise operator in conditional + DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(>, " > ", DOCTEST_CMP_GT) //!OCLINT bitwise operator in conditional + DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(<, " < ", DOCTEST_CMP_LT) //!OCLINT bitwise operator in conditional + DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(>=, " >= ", DOCTEST_CMP_GE) //!OCLINT bitwise operator in conditional + DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(<=, " <= ", DOCTEST_CMP_LE) //!OCLINT bitwise operator in conditional + // clang-format on + + // forbidding some expressions based on this table: https://en.cppreference.com/w/cpp/language/operator_precedence + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, &) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, ^) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, |) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, &&) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, ||) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, =) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, +=) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, -=) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, *=) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, /=) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, %=) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, <<=) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, >>=) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, &=) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, ^=) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, |=) + // these 2 are unfortunate because they should be allowed - they have higher precedence over the comparisons, but the + // ExpressionDecomposer class uses the left shift operator to capture the left operand of the binary expression... + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, <<) + DOCTEST_FORBIT_EXPRESSION(Expression_lhs, >>) + }; + +#ifndef DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION + + DOCTEST_CLANG_SUPPRESS_WARNING_POP + DOCTEST_MSVC_SUPPRESS_WARNING_POP + DOCTEST_GCC_SUPPRESS_WARNING_POP + +#endif // DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION + +#if DOCTEST_CLANG && DOCTEST_CLANG < DOCTEST_COMPILER(3, 6, 0) +DOCTEST_CLANG_SUPPRESS_WARNING_POP +#endif + + struct DOCTEST_INTERFACE ExpressionDecomposer + { + assertType::Enum m_at; + + ExpressionDecomposer(assertType::Enum at); + + // The right operator for capturing expressions is "<=" instead of "<<" (based on the operator precedence table) + // but then there will be warnings from GCC about "-Wparentheses" and since "_Pragma()" is problematic this will stay for now... + // https://github.com/catchorg/Catch2/issues/870 + // https://github.com/catchorg/Catch2/issues/565 + template + Expression_lhs operator<<(L&& operand) { + return Expression_lhs(static_cast(operand), m_at); + } + + template ::value,void >::type* = nullptr> + Expression_lhs operator<<(const L &operand) { + return Expression_lhs(operand, m_at); + } + }; + + struct DOCTEST_INTERFACE TestSuite + { + const char* m_test_suite = nullptr; + const char* m_description = nullptr; + bool m_skip = false; + bool m_no_breaks = false; + bool m_no_output = false; + bool m_may_fail = false; + bool m_should_fail = false; + int m_expected_failures = 0; + double m_timeout = 0; + + TestSuite& operator*(const char* in); + + template + TestSuite& operator*(const T& in) { + in.fill(*this); + return *this; + } + }; + + using funcType = void (*)(); + + struct DOCTEST_INTERFACE TestCase : public TestCaseData + { + funcType m_test; // a function pointer to the test case + + String m_type; // for templated test cases - gets appended to the real name + int m_template_id; // an ID used to distinguish between the different versions of a templated test case + String m_full_name; // contains the name (only for templated test cases!) + the template type + + TestCase(funcType test, const char* file, unsigned line, const TestSuite& test_suite, + const String& type = String(), int template_id = -1); + + TestCase(const TestCase& other); + TestCase(TestCase&&) = delete; + + DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(26434) // hides a non-virtual function + TestCase& operator=(const TestCase& other); + DOCTEST_MSVC_SUPPRESS_WARNING_POP + + TestCase& operator=(TestCase&&) = delete; + + TestCase& operator*(const char* in); + + template + TestCase& operator*(const T& in) { + in.fill(*this); + return *this; + } + + bool operator<(const TestCase& other) const; + + ~TestCase() = default; + }; + + // forward declarations of functions used by the macros + DOCTEST_INTERFACE int regTest(const TestCase& tc); + DOCTEST_INTERFACE int setTestSuite(const TestSuite& ts); + DOCTEST_INTERFACE bool isDebuggerActive(); + + template + int instantiationHelper(const T&) { return 0; } + + namespace binaryAssertComparison { + enum Enum + { + eq = 0, + ne, + gt, + lt, + ge, + le + }; + } // namespace binaryAssertComparison + + // clang-format off + template struct RelationalComparator { bool operator()(const DOCTEST_REF_WRAP(L), const DOCTEST_REF_WRAP(R) ) const { return false; } }; + +#define DOCTEST_BINARY_RELATIONAL_OP(n, op) \ + template struct RelationalComparator { bool operator()(const DOCTEST_REF_WRAP(L) lhs, const DOCTEST_REF_WRAP(R) rhs) const { return op(lhs, rhs); } }; + // clang-format on + + DOCTEST_BINARY_RELATIONAL_OP(0, doctest::detail::eq) + DOCTEST_BINARY_RELATIONAL_OP(1, doctest::detail::ne) + DOCTEST_BINARY_RELATIONAL_OP(2, doctest::detail::gt) + DOCTEST_BINARY_RELATIONAL_OP(3, doctest::detail::lt) + DOCTEST_BINARY_RELATIONAL_OP(4, doctest::detail::ge) + DOCTEST_BINARY_RELATIONAL_OP(5, doctest::detail::le) + + struct DOCTEST_INTERFACE ResultBuilder : public AssertData + { + ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr, + const char* exception_type = "", const String& exception_string = ""); + + ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr, + const char* exception_type, const Contains& exception_string); + + void setResult(const Result& res); + + template + DOCTEST_NOINLINE bool binary_assert(const DOCTEST_REF_WRAP(L) lhs, + const DOCTEST_REF_WRAP(R) rhs) { + m_failed = !RelationalComparator()(lhs, rhs); + if (m_failed || getContextOptions()->success) { + m_decomp = stringifyBinaryExpr(lhs, ", ", rhs); + } + return !m_failed; + } + + template + DOCTEST_NOINLINE bool unary_assert(const DOCTEST_REF_WRAP(L) val) { + m_failed = !val; + + if (m_at & assertType::is_false) { //!OCLINT bitwise operator in conditional + m_failed = !m_failed; + } + + if (m_failed || getContextOptions()->success) { + m_decomp = (DOCTEST_STRINGIFY(val)); + } + + return !m_failed; + } + + void translateException(); + + bool log(); + void react() const; + }; + + namespace assertAction { + enum Enum + { + nothing = 0, + dbgbreak = 1, + shouldthrow = 2 + }; + } // namespace assertAction + + DOCTEST_INTERFACE void failed_out_of_a_testing_context(const AssertData& ad); + + DOCTEST_INTERFACE bool decomp_assert(assertType::Enum at, const char* file, int line, + const char* expr, const Result& result); + +#define DOCTEST_ASSERT_OUT_OF_TESTS(decomp) \ + do { \ + if(!is_running_in_test) { \ + if(failed) { \ + ResultBuilder rb(at, file, line, expr); \ + rb.m_failed = failed; \ + rb.m_decomp = decomp; \ + failed_out_of_a_testing_context(rb); \ + if(isDebuggerActive() && !getContextOptions()->no_breaks) \ + DOCTEST_BREAK_INTO_DEBUGGER(); \ + if(checkIfShouldThrow(at)) \ + throwException(); \ + } \ + return !failed; \ + } \ + } while(false) + +#define DOCTEST_ASSERT_IN_TESTS(decomp) \ + ResultBuilder rb(at, file, line, expr); \ + rb.m_failed = failed; \ + if(rb.m_failed || getContextOptions()->success) \ + rb.m_decomp = decomp; \ + if(rb.log()) \ + DOCTEST_BREAK_INTO_DEBUGGER(); \ + if(rb.m_failed && checkIfShouldThrow(at)) \ + throwException() + + template + DOCTEST_NOINLINE bool binary_assert(assertType::Enum at, const char* file, int line, + const char* expr, const DOCTEST_REF_WRAP(L) lhs, + const DOCTEST_REF_WRAP(R) rhs) { + bool failed = !RelationalComparator()(lhs, rhs); + + // ################################################################################### + // IF THE DEBUGGER BREAKS HERE - GO 1 LEVEL UP IN THE CALLSTACK FOR THE FAILING ASSERT + // THIS IS THE EFFECT OF HAVING 'DOCTEST_CONFIG_SUPER_FAST_ASSERTS' DEFINED + // ################################################################################### + DOCTEST_ASSERT_OUT_OF_TESTS(stringifyBinaryExpr(lhs, ", ", rhs)); + DOCTEST_ASSERT_IN_TESTS(stringifyBinaryExpr(lhs, ", ", rhs)); + return !failed; + } + + template + DOCTEST_NOINLINE bool unary_assert(assertType::Enum at, const char* file, int line, + const char* expr, const DOCTEST_REF_WRAP(L) val) { + bool failed = !val; + + if(at & assertType::is_false) //!OCLINT bitwise operator in conditional + failed = !failed; + + // ################################################################################### + // IF THE DEBUGGER BREAKS HERE - GO 1 LEVEL UP IN THE CALLSTACK FOR THE FAILING ASSERT + // THIS IS THE EFFECT OF HAVING 'DOCTEST_CONFIG_SUPER_FAST_ASSERTS' DEFINED + // ################################################################################### + DOCTEST_ASSERT_OUT_OF_TESTS((DOCTEST_STRINGIFY(val))); + DOCTEST_ASSERT_IN_TESTS((DOCTEST_STRINGIFY(val))); + return !failed; + } + + struct DOCTEST_INTERFACE IExceptionTranslator + { + DOCTEST_DECLARE_INTERFACE(IExceptionTranslator) + virtual bool translate(String&) const = 0; + }; + + template + class ExceptionTranslator : public IExceptionTranslator //!OCLINT destructor of virtual class + { + public: + explicit ExceptionTranslator(String (*translateFunction)(T)) + : m_translateFunction(translateFunction) {} + + bool translate(String& res) const override { +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + try { + throw; // lgtm [cpp/rethrow-no-exception] + // cppcheck-suppress catchExceptionByValue + } catch(const T& ex) { + res = m_translateFunction(ex); //!OCLINT parameter reassignment + return true; + } catch(...) {} //!OCLINT - empty catch statement +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + static_cast(res); // to silence -Wunused-parameter + return false; + } + + private: + String (*m_translateFunction)(T); + }; + + DOCTEST_INTERFACE void registerExceptionTranslatorImpl(const IExceptionTranslator* et); + + // ContextScope base class used to allow implementing methods of ContextScope + // that don't depend on the template parameter in doctest.cpp. + struct DOCTEST_INTERFACE ContextScopeBase : public IContextScope { + ContextScopeBase(const ContextScopeBase&) = delete; + + ContextScopeBase& operator=(const ContextScopeBase&) = delete; + ContextScopeBase& operator=(ContextScopeBase&&) = delete; + + ~ContextScopeBase() override = default; + + protected: + ContextScopeBase(); + ContextScopeBase(ContextScopeBase&& other) noexcept; + + void destroy(); + bool need_to_destroy{true}; + }; + + template class ContextScope : public ContextScopeBase + { + L lambda_; + + public: + explicit ContextScope(const L &lambda) : lambda_(lambda) {} + explicit ContextScope(L&& lambda) : lambda_(static_cast(lambda)) { } + + ContextScope(const ContextScope&) = delete; + ContextScope(ContextScope&&) noexcept = default; + + ContextScope& operator=(const ContextScope&) = delete; + ContextScope& operator=(ContextScope&&) = delete; + + void stringify(std::ostream* s) const override { lambda_(s); } + + ~ContextScope() override { + if (need_to_destroy) { + destroy(); + } + } + }; + + struct DOCTEST_INTERFACE MessageBuilder : public MessageData + { + std::ostream* m_stream; + bool logged = false; + + MessageBuilder(const char* file, int line, assertType::Enum severity); + + MessageBuilder(const MessageBuilder&) = delete; + MessageBuilder(MessageBuilder&&) = delete; + + MessageBuilder& operator=(const MessageBuilder&) = delete; + MessageBuilder& operator=(MessageBuilder&&) = delete; + + ~MessageBuilder(); + + // the preferred way of chaining parameters for stringification +DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4866) + template + MessageBuilder& operator,(const T& in) { + *m_stream << (DOCTEST_STRINGIFY(in)); + return *this; + } +DOCTEST_MSVC_SUPPRESS_WARNING_POP + + // kept here just for backwards-compatibility - the comma operator should be preferred now + template + MessageBuilder& operator<<(const T& in) { return this->operator,(in); } + + // the `,` operator has the lowest operator precedence - if `<<` is used by the user then + // the `,` operator will be called last which is not what we want and thus the `*` operator + // is used first (has higher operator precedence compared to `<<`) so that we guarantee that + // an operator of the MessageBuilder class is called first before the rest of the parameters + template + MessageBuilder& operator*(const T& in) { return this->operator,(in); } + + bool log(); + void react(); + }; + + template + ContextScope MakeContextScope(const L &lambda) { + return ContextScope(lambda); + } +} // namespace detail + +#define DOCTEST_DEFINE_DECORATOR(name, type, def) \ + struct name \ + { \ + type data; \ + name(type in = def) \ + : data(in) {} \ + void fill(detail::TestCase& state) const { state.DOCTEST_CAT(m_, name) = data; } \ + void fill(detail::TestSuite& state) const { state.DOCTEST_CAT(m_, name) = data; } \ + } + +DOCTEST_DEFINE_DECORATOR(test_suite, const char*, ""); +DOCTEST_DEFINE_DECORATOR(description, const char*, ""); +DOCTEST_DEFINE_DECORATOR(skip, bool, true); +DOCTEST_DEFINE_DECORATOR(no_breaks, bool, true); +DOCTEST_DEFINE_DECORATOR(no_output, bool, true); +DOCTEST_DEFINE_DECORATOR(timeout, double, 0); +DOCTEST_DEFINE_DECORATOR(may_fail, bool, true); +DOCTEST_DEFINE_DECORATOR(should_fail, bool, true); +DOCTEST_DEFINE_DECORATOR(expected_failures, int, 0); + +template +int registerExceptionTranslator(String (*translateFunction)(T)) { + DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wexit-time-destructors") + static detail::ExceptionTranslator exceptionTranslator(translateFunction); + DOCTEST_CLANG_SUPPRESS_WARNING_POP + detail::registerExceptionTranslatorImpl(&exceptionTranslator); + return 0; +} + +} // namespace doctest + +// in a separate namespace outside of doctest because the DOCTEST_TEST_SUITE macro +// introduces an anonymous namespace in which getCurrentTestSuite gets overridden +namespace doctest_detail_test_suite_ns { +DOCTEST_INTERFACE doctest::detail::TestSuite& getCurrentTestSuite(); +} // namespace doctest_detail_test_suite_ns + +namespace doctest { +#else // DOCTEST_CONFIG_DISABLE +template +int registerExceptionTranslator(String (*)(T)) { + return 0; +} +#endif // DOCTEST_CONFIG_DISABLE + +namespace detail { + using assert_handler = void (*)(const AssertData&); + struct ContextState; +} // namespace detail + +class DOCTEST_INTERFACE Context +{ + detail::ContextState* p; + + void parseArgs(int argc, const char* const* argv, bool withDefaults = false); + +public: + explicit Context(int argc = 0, const char* const* argv = nullptr); + + Context(const Context&) = delete; + Context(Context&&) = delete; + + Context& operator=(const Context&) = delete; + Context& operator=(Context&&) = delete; + + ~Context(); // NOLINT(performance-trivially-destructible) + + void applyCommandLine(int argc, const char* const* argv); + + void addFilter(const char* filter, const char* value); + void clearFilters(); + void setOption(const char* option, bool value); + void setOption(const char* option, int value); + void setOption(const char* option, const char* value); + + bool shouldExit(); + + void setAsDefaultForAssertsOutOfTestCases(); + + void setAssertHandler(detail::assert_handler ah); + + void setCout(std::ostream* out); + + int run(); +}; + +namespace TestCaseFailureReason { + enum Enum + { + None = 0, + AssertFailure = 1, // an assertion has failed in the test case + Exception = 2, // test case threw an exception + Crash = 4, // a crash... + TooManyFailedAsserts = 8, // the abort-after option + Timeout = 16, // see the timeout decorator + ShouldHaveFailedButDidnt = 32, // see the should_fail decorator + ShouldHaveFailedAndDid = 64, // see the should_fail decorator + DidntFailExactlyNumTimes = 128, // see the expected_failures decorator + FailedExactlyNumTimes = 256, // see the expected_failures decorator + CouldHaveFailedAndDid = 512 // see the may_fail decorator + }; +} // namespace TestCaseFailureReason + +struct DOCTEST_INTERFACE CurrentTestCaseStats +{ + int numAssertsCurrentTest; + int numAssertsFailedCurrentTest; + double seconds; + int failure_flags; // use TestCaseFailureReason::Enum + bool testCaseSuccess; +}; + +struct DOCTEST_INTERFACE TestCaseException +{ + String error_string; + bool is_crash; +}; + +struct DOCTEST_INTERFACE TestRunStats +{ + unsigned numTestCases; + unsigned numTestCasesPassingFilters; + unsigned numTestSuitesPassingFilters; + unsigned numTestCasesFailed; + int numAsserts; + int numAssertsFailed; +}; + +struct QueryData +{ + const TestRunStats* run_stats = nullptr; + const TestCaseData** data = nullptr; + unsigned num_data = 0; +}; + +struct DOCTEST_INTERFACE IReporter +{ + // The constructor has to accept "const ContextOptions&" as a single argument + // which has most of the options for the run + a pointer to the stdout stream + // Reporter(const ContextOptions& in) + + // called when a query should be reported (listing test cases, printing the version, etc.) + virtual void report_query(const QueryData&) = 0; + + // called when the whole test run starts + virtual void test_run_start() = 0; + // called when the whole test run ends (caching a pointer to the input doesn't make sense here) + virtual void test_run_end(const TestRunStats&) = 0; + + // called when a test case is started (safe to cache a pointer to the input) + virtual void test_case_start(const TestCaseData&) = 0; + // called when a test case is reentered because of unfinished subcases (safe to cache a pointer to the input) + virtual void test_case_reenter(const TestCaseData&) = 0; + // called when a test case has ended + virtual void test_case_end(const CurrentTestCaseStats&) = 0; + + // called when an exception is thrown from the test case (or it crashes) + virtual void test_case_exception(const TestCaseException&) = 0; + + // called whenever a subcase is entered (don't cache pointers to the input) + virtual void subcase_start(const SubcaseSignature&) = 0; + // called whenever a subcase is exited (don't cache pointers to the input) + virtual void subcase_end() = 0; + + // called for each assert (don't cache pointers to the input) + virtual void log_assert(const AssertData&) = 0; + // called for each message (don't cache pointers to the input) + virtual void log_message(const MessageData&) = 0; + + // called when a test case is skipped either because it doesn't pass the filters, has a skip decorator + // or isn't in the execution range (between first and last) (safe to cache a pointer to the input) + virtual void test_case_skipped(const TestCaseData&) = 0; + + DOCTEST_DECLARE_INTERFACE(IReporter) + + // can obtain all currently active contexts and stringify them if one wishes to do so + static int get_num_active_contexts(); + static const IContextScope* const* get_active_contexts(); + + // can iterate through contexts which have been stringified automatically in their destructors when an exception has been thrown + static int get_num_stringified_contexts(); + static const String* get_stringified_contexts(); +}; + +namespace detail { + using reporterCreatorFunc = IReporter* (*)(const ContextOptions&); + + DOCTEST_INTERFACE void registerReporterImpl(const char* name, int prio, reporterCreatorFunc c, bool isReporter); + + template + IReporter* reporterCreator(const ContextOptions& o) { + return new Reporter(o); + } +} // namespace detail + +template +int registerReporter(const char* name, int priority, bool isReporter) { + detail::registerReporterImpl(name, priority, detail::reporterCreator, isReporter); + return 0; +} +} // namespace doctest + +#ifdef DOCTEST_CONFIG_ASSERTS_RETURN_VALUES +#define DOCTEST_FUNC_EMPTY [] { return false; }() +#else +#define DOCTEST_FUNC_EMPTY (void)0 +#endif + +// if registering is not disabled +#ifndef DOCTEST_CONFIG_DISABLE + +#ifdef DOCTEST_CONFIG_ASSERTS_RETURN_VALUES +#define DOCTEST_FUNC_SCOPE_BEGIN [&] +#define DOCTEST_FUNC_SCOPE_END () +#define DOCTEST_FUNC_SCOPE_RET(v) return v +#else +#define DOCTEST_FUNC_SCOPE_BEGIN do +#define DOCTEST_FUNC_SCOPE_END while(false) +#define DOCTEST_FUNC_SCOPE_RET(v) (void)0 +#endif + +// common code in asserts - for convenience +#define DOCTEST_ASSERT_LOG_REACT_RETURN(b) \ + if(b.log()) DOCTEST_BREAK_INTO_DEBUGGER(); \ + b.react(); \ + DOCTEST_FUNC_SCOPE_RET(!b.m_failed) + +#ifdef DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS +#define DOCTEST_WRAP_IN_TRY(x) x; +#else // DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS +#define DOCTEST_WRAP_IN_TRY(x) \ + try { \ + x; \ + } catch(...) { DOCTEST_RB.translateException(); } +#endif // DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS + +#ifdef DOCTEST_CONFIG_VOID_CAST_EXPRESSIONS +#define DOCTEST_CAST_TO_VOID(...) \ + DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wuseless-cast") \ + static_cast(__VA_ARGS__); \ + DOCTEST_GCC_SUPPRESS_WARNING_POP +#else // DOCTEST_CONFIG_VOID_CAST_EXPRESSIONS +#define DOCTEST_CAST_TO_VOID(...) __VA_ARGS__; +#endif // DOCTEST_CONFIG_VOID_CAST_EXPRESSIONS + +// registers the test by initializing a dummy var with a function +#define DOCTEST_REGISTER_FUNCTION(global_prefix, f, decorators) \ + global_prefix DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_VAR_), /* NOLINT */ \ + doctest::detail::regTest( \ + doctest::detail::TestCase( \ + f, __FILE__, __LINE__, \ + doctest_detail_test_suite_ns::getCurrentTestSuite()) * \ + decorators)) + +#define DOCTEST_IMPLEMENT_FIXTURE(der, base, func, decorators) \ + namespace { /* NOLINT */ \ + struct der : public base \ + { \ + void f(); \ + }; \ + static DOCTEST_INLINE_NOINLINE void func() { \ + der v; \ + v.f(); \ + } \ + DOCTEST_REGISTER_FUNCTION(DOCTEST_EMPTY, func, decorators) \ + } \ + DOCTEST_INLINE_NOINLINE void der::f() // NOLINT(misc-definitions-in-headers) + +#define DOCTEST_CREATE_AND_REGISTER_FUNCTION(f, decorators) \ + static void f(); \ + DOCTEST_REGISTER_FUNCTION(DOCTEST_EMPTY, f, decorators) \ + static void f() + +#define DOCTEST_CREATE_AND_REGISTER_FUNCTION_IN_CLASS(f, proxy, decorators) \ + static doctest::detail::funcType proxy() { return f; } \ + DOCTEST_REGISTER_FUNCTION(inline, proxy(), decorators) \ + static void f() + +// for registering tests +#define DOCTEST_TEST_CASE(decorators) \ + DOCTEST_CREATE_AND_REGISTER_FUNCTION(DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), decorators) + +// for registering tests in classes - requires C++17 for inline variables! +#if DOCTEST_CPLUSPLUS >= 201703L +#define DOCTEST_TEST_CASE_CLASS(decorators) \ + DOCTEST_CREATE_AND_REGISTER_FUNCTION_IN_CLASS(DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), \ + DOCTEST_ANONYMOUS(DOCTEST_ANON_PROXY_), \ + decorators) +#else // DOCTEST_TEST_CASE_CLASS +#define DOCTEST_TEST_CASE_CLASS(...) \ + TEST_CASES_CAN_BE_REGISTERED_IN_CLASSES_ONLY_IN_CPP17_MODE_OR_WITH_VS_2017_OR_NEWER +#endif // DOCTEST_TEST_CASE_CLASS + +// for registering tests with a fixture +#define DOCTEST_TEST_CASE_FIXTURE(c, decorators) \ + DOCTEST_IMPLEMENT_FIXTURE(DOCTEST_ANONYMOUS(DOCTEST_ANON_CLASS_), c, \ + DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), decorators) + +// for converting types to strings without the header and demangling +#define DOCTEST_TYPE_TO_STRING_AS(str, ...) \ + namespace doctest { \ + template <> \ + inline String toString<__VA_ARGS__>() { \ + return str; \ + } \ + } \ + static_assert(true, "") + +#define DOCTEST_TYPE_TO_STRING(...) DOCTEST_TYPE_TO_STRING_AS(#__VA_ARGS__, __VA_ARGS__) + +#define DOCTEST_TEST_CASE_TEMPLATE_DEFINE_IMPL(dec, T, iter, func) \ + template \ + static void func(); \ + namespace { /* NOLINT */ \ + template \ + struct iter; \ + template \ + struct iter> \ + { \ + iter(const char* file, unsigned line, int index) { \ + doctest::detail::regTest(doctest::detail::TestCase(func, file, line, \ + doctest_detail_test_suite_ns::getCurrentTestSuite(), \ + doctest::toString(), \ + int(line) * 1000 + index) \ + * dec); \ + iter>(file, line, index + 1); \ + } \ + }; \ + template <> \ + struct iter> \ + { \ + iter(const char*, unsigned, int) {} \ + }; \ + } \ + template \ + static void func() + +#define DOCTEST_TEST_CASE_TEMPLATE_DEFINE(dec, T, id) \ + DOCTEST_TEST_CASE_TEMPLATE_DEFINE_IMPL(dec, T, DOCTEST_CAT(id, ITERATOR), \ + DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_)) + +#define DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE_IMPL(id, anon, ...) \ + DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_CAT(anon, DUMMY), /* NOLINT(cert-err58-cpp, fuchsia-statically-constructed-objects) */ \ + doctest::detail::instantiationHelper( \ + DOCTEST_CAT(id, ITERATOR)<__VA_ARGS__>(__FILE__, __LINE__, 0))) + +#define DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id, ...) \ + DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE_IMPL(id, DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_), std::tuple<__VA_ARGS__>) \ + static_assert(true, "") + +#define DOCTEST_TEST_CASE_TEMPLATE_APPLY(id, ...) \ + DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE_IMPL(id, DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_), __VA_ARGS__) \ + static_assert(true, "") + +#define DOCTEST_TEST_CASE_TEMPLATE_IMPL(dec, T, anon, ...) \ + DOCTEST_TEST_CASE_TEMPLATE_DEFINE_IMPL(dec, T, DOCTEST_CAT(anon, ITERATOR), anon); \ + DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE_IMPL(anon, anon, std::tuple<__VA_ARGS__>) \ + template \ + static void anon() + +#define DOCTEST_TEST_CASE_TEMPLATE(dec, T, ...) \ + DOCTEST_TEST_CASE_TEMPLATE_IMPL(dec, T, DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_), __VA_ARGS__) + +// for subcases +#define DOCTEST_SUBCASE(name) \ + if(const doctest::detail::Subcase & DOCTEST_ANONYMOUS(DOCTEST_ANON_SUBCASE_) DOCTEST_UNUSED = \ + doctest::detail::Subcase(name, __FILE__, __LINE__)) + +// for grouping tests in test suites by using code blocks +#define DOCTEST_TEST_SUITE_IMPL(decorators, ns_name) \ + namespace ns_name { namespace doctest_detail_test_suite_ns { \ + static DOCTEST_NOINLINE doctest::detail::TestSuite& getCurrentTestSuite() noexcept { \ + DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4640) \ + DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wexit-time-destructors") \ + DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wmissing-field-initializers") \ + static doctest::detail::TestSuite data{}; \ + static bool inited = false; \ + DOCTEST_MSVC_SUPPRESS_WARNING_POP \ + DOCTEST_CLANG_SUPPRESS_WARNING_POP \ + DOCTEST_GCC_SUPPRESS_WARNING_POP \ + if(!inited) { \ + data* decorators; \ + inited = true; \ + } \ + return data; \ + } \ + } \ + } \ + namespace ns_name + +#define DOCTEST_TEST_SUITE(decorators) \ + DOCTEST_TEST_SUITE_IMPL(decorators, DOCTEST_ANONYMOUS(DOCTEST_ANON_SUITE_)) + +// for starting a testsuite block +#define DOCTEST_TEST_SUITE_BEGIN(decorators) \ + DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_VAR_), /* NOLINT(cert-err58-cpp) */ \ + doctest::detail::setTestSuite(doctest::detail::TestSuite() * decorators)) \ + static_assert(true, "") + +// for ending a testsuite block +#define DOCTEST_TEST_SUITE_END \ + DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_VAR_), /* NOLINT(cert-err58-cpp) */ \ + doctest::detail::setTestSuite(doctest::detail::TestSuite() * "")) \ + using DOCTEST_ANONYMOUS(DOCTEST_ANON_FOR_SEMICOLON_) = int + +// for registering exception translators +#define DOCTEST_REGISTER_EXCEPTION_TRANSLATOR_IMPL(translatorName, signature) \ + inline doctest::String translatorName(signature); \ + DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_TRANSLATOR_), /* NOLINT(cert-err58-cpp) */ \ + doctest::registerExceptionTranslator(translatorName)) \ + doctest::String translatorName(signature) + +#define DOCTEST_REGISTER_EXCEPTION_TRANSLATOR(signature) \ + DOCTEST_REGISTER_EXCEPTION_TRANSLATOR_IMPL(DOCTEST_ANONYMOUS(DOCTEST_ANON_TRANSLATOR_), \ + signature) + +// for registering reporters +#define DOCTEST_REGISTER_REPORTER(name, priority, reporter) \ + DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_REPORTER_), /* NOLINT(cert-err58-cpp) */ \ + doctest::registerReporter(name, priority, true)) \ + static_assert(true, "") + +// for registering listeners +#define DOCTEST_REGISTER_LISTENER(name, priority, reporter) \ + DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_REPORTER_), /* NOLINT(cert-err58-cpp) */ \ + doctest::registerReporter(name, priority, false)) \ + static_assert(true, "") + +// clang-format off +// for logging - disabling formatting because it's important to have these on 2 separate lines - see PR #557 +#define DOCTEST_INFO(...) \ + DOCTEST_INFO_IMPL(DOCTEST_ANONYMOUS(DOCTEST_CAPTURE_), \ + DOCTEST_ANONYMOUS(DOCTEST_CAPTURE_OTHER_), \ + __VA_ARGS__) +// clang-format on + +#define DOCTEST_INFO_IMPL(mb_name, s_name, ...) \ + auto DOCTEST_ANONYMOUS(DOCTEST_CAPTURE_) = doctest::detail::MakeContextScope( \ + [&](std::ostream* s_name) { \ + doctest::detail::MessageBuilder mb_name(__FILE__, __LINE__, doctest::assertType::is_warn); \ + mb_name.m_stream = s_name; \ + mb_name * __VA_ARGS__; \ + }) + +#define DOCTEST_CAPTURE(x) DOCTEST_INFO(#x " := ", x) + +#define DOCTEST_ADD_AT_IMPL(type, file, line, mb, ...) \ + DOCTEST_FUNC_SCOPE_BEGIN { \ + doctest::detail::MessageBuilder mb(file, line, doctest::assertType::type); \ + mb * __VA_ARGS__; \ + if(mb.log()) \ + DOCTEST_BREAK_INTO_DEBUGGER(); \ + mb.react(); \ + } DOCTEST_FUNC_SCOPE_END + +// clang-format off +#define DOCTEST_ADD_MESSAGE_AT(file, line, ...) DOCTEST_ADD_AT_IMPL(is_warn, file, line, DOCTEST_ANONYMOUS(DOCTEST_MESSAGE_), __VA_ARGS__) +#define DOCTEST_ADD_FAIL_CHECK_AT(file, line, ...) DOCTEST_ADD_AT_IMPL(is_check, file, line, DOCTEST_ANONYMOUS(DOCTEST_MESSAGE_), __VA_ARGS__) +#define DOCTEST_ADD_FAIL_AT(file, line, ...) DOCTEST_ADD_AT_IMPL(is_require, file, line, DOCTEST_ANONYMOUS(DOCTEST_MESSAGE_), __VA_ARGS__) +// clang-format on + +#define DOCTEST_MESSAGE(...) DOCTEST_ADD_MESSAGE_AT(__FILE__, __LINE__, __VA_ARGS__) +#define DOCTEST_FAIL_CHECK(...) DOCTEST_ADD_FAIL_CHECK_AT(__FILE__, __LINE__, __VA_ARGS__) +#define DOCTEST_FAIL(...) DOCTEST_ADD_FAIL_AT(__FILE__, __LINE__, __VA_ARGS__) + +#define DOCTEST_TO_LVALUE(...) __VA_ARGS__ // Not removed to keep backwards compatibility. + +#ifndef DOCTEST_CONFIG_SUPER_FAST_ASSERTS + +#define DOCTEST_ASSERT_IMPLEMENT_2(assert_type, ...) \ + DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Woverloaded-shift-op-parentheses") \ + /* NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) */ \ + doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ + __LINE__, #__VA_ARGS__); \ + DOCTEST_WRAP_IN_TRY(DOCTEST_RB.setResult( \ + doctest::detail::ExpressionDecomposer(doctest::assertType::assert_type) \ + << __VA_ARGS__)) /* NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) */ \ + DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB) \ + DOCTEST_CLANG_SUPPRESS_WARNING_POP + +#define DOCTEST_ASSERT_IMPLEMENT_1(assert_type, ...) \ + DOCTEST_FUNC_SCOPE_BEGIN { \ + DOCTEST_ASSERT_IMPLEMENT_2(assert_type, __VA_ARGS__); \ + } DOCTEST_FUNC_SCOPE_END // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks) + +#define DOCTEST_BINARY_ASSERT(assert_type, comp, ...) \ + DOCTEST_FUNC_SCOPE_BEGIN { \ + doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ + __LINE__, #__VA_ARGS__); \ + DOCTEST_WRAP_IN_TRY( \ + DOCTEST_RB.binary_assert( \ + __VA_ARGS__)) \ + DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ + } DOCTEST_FUNC_SCOPE_END + +#define DOCTEST_UNARY_ASSERT(assert_type, ...) \ + DOCTEST_FUNC_SCOPE_BEGIN { \ + doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ + __LINE__, #__VA_ARGS__); \ + DOCTEST_WRAP_IN_TRY(DOCTEST_RB.unary_assert(__VA_ARGS__)) \ + DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ + } DOCTEST_FUNC_SCOPE_END + +#else // DOCTEST_CONFIG_SUPER_FAST_ASSERTS + +// necessary for _MESSAGE +#define DOCTEST_ASSERT_IMPLEMENT_2 DOCTEST_ASSERT_IMPLEMENT_1 + +#define DOCTEST_ASSERT_IMPLEMENT_1(assert_type, ...) \ + DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Woverloaded-shift-op-parentheses") \ + doctest::detail::decomp_assert( \ + doctest::assertType::assert_type, __FILE__, __LINE__, #__VA_ARGS__, \ + doctest::detail::ExpressionDecomposer(doctest::assertType::assert_type) \ + << __VA_ARGS__) DOCTEST_CLANG_SUPPRESS_WARNING_POP + +#define DOCTEST_BINARY_ASSERT(assert_type, comparison, ...) \ + doctest::detail::binary_assert( \ + doctest::assertType::assert_type, __FILE__, __LINE__, #__VA_ARGS__, __VA_ARGS__) + +#define DOCTEST_UNARY_ASSERT(assert_type, ...) \ + doctest::detail::unary_assert(doctest::assertType::assert_type, __FILE__, __LINE__, \ + #__VA_ARGS__, __VA_ARGS__) + +#endif // DOCTEST_CONFIG_SUPER_FAST_ASSERTS + +#define DOCTEST_WARN(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_WARN, __VA_ARGS__) +#define DOCTEST_CHECK(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_CHECK, __VA_ARGS__) +#define DOCTEST_REQUIRE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_REQUIRE, __VA_ARGS__) +#define DOCTEST_WARN_FALSE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_WARN_FALSE, __VA_ARGS__) +#define DOCTEST_CHECK_FALSE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_CHECK_FALSE, __VA_ARGS__) +#define DOCTEST_REQUIRE_FALSE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_REQUIRE_FALSE, __VA_ARGS__) + +// clang-format off +#define DOCTEST_WARN_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_WARN, cond); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_CHECK_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_CHECK, cond); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_REQUIRE_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_REQUIRE, cond); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_WARN_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_WARN_FALSE, cond); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_CHECK_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_CHECK_FALSE, cond); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_REQUIRE_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_REQUIRE_FALSE, cond); } DOCTEST_FUNC_SCOPE_END +// clang-format on + +#define DOCTEST_WARN_EQ(...) DOCTEST_BINARY_ASSERT(DT_WARN_EQ, eq, __VA_ARGS__) +#define DOCTEST_CHECK_EQ(...) DOCTEST_BINARY_ASSERT(DT_CHECK_EQ, eq, __VA_ARGS__) +#define DOCTEST_REQUIRE_EQ(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_EQ, eq, __VA_ARGS__) +#define DOCTEST_WARN_NE(...) DOCTEST_BINARY_ASSERT(DT_WARN_NE, ne, __VA_ARGS__) +#define DOCTEST_CHECK_NE(...) DOCTEST_BINARY_ASSERT(DT_CHECK_NE, ne, __VA_ARGS__) +#define DOCTEST_REQUIRE_NE(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_NE, ne, __VA_ARGS__) +#define DOCTEST_WARN_GT(...) DOCTEST_BINARY_ASSERT(DT_WARN_GT, gt, __VA_ARGS__) +#define DOCTEST_CHECK_GT(...) DOCTEST_BINARY_ASSERT(DT_CHECK_GT, gt, __VA_ARGS__) +#define DOCTEST_REQUIRE_GT(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_GT, gt, __VA_ARGS__) +#define DOCTEST_WARN_LT(...) DOCTEST_BINARY_ASSERT(DT_WARN_LT, lt, __VA_ARGS__) +#define DOCTEST_CHECK_LT(...) DOCTEST_BINARY_ASSERT(DT_CHECK_LT, lt, __VA_ARGS__) +#define DOCTEST_REQUIRE_LT(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_LT, lt, __VA_ARGS__) +#define DOCTEST_WARN_GE(...) DOCTEST_BINARY_ASSERT(DT_WARN_GE, ge, __VA_ARGS__) +#define DOCTEST_CHECK_GE(...) DOCTEST_BINARY_ASSERT(DT_CHECK_GE, ge, __VA_ARGS__) +#define DOCTEST_REQUIRE_GE(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_GE, ge, __VA_ARGS__) +#define DOCTEST_WARN_LE(...) DOCTEST_BINARY_ASSERT(DT_WARN_LE, le, __VA_ARGS__) +#define DOCTEST_CHECK_LE(...) DOCTEST_BINARY_ASSERT(DT_CHECK_LE, le, __VA_ARGS__) +#define DOCTEST_REQUIRE_LE(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_LE, le, __VA_ARGS__) + +#define DOCTEST_WARN_UNARY(...) DOCTEST_UNARY_ASSERT(DT_WARN_UNARY, __VA_ARGS__) +#define DOCTEST_CHECK_UNARY(...) DOCTEST_UNARY_ASSERT(DT_CHECK_UNARY, __VA_ARGS__) +#define DOCTEST_REQUIRE_UNARY(...) DOCTEST_UNARY_ASSERT(DT_REQUIRE_UNARY, __VA_ARGS__) +#define DOCTEST_WARN_UNARY_FALSE(...) DOCTEST_UNARY_ASSERT(DT_WARN_UNARY_FALSE, __VA_ARGS__) +#define DOCTEST_CHECK_UNARY_FALSE(...) DOCTEST_UNARY_ASSERT(DT_CHECK_UNARY_FALSE, __VA_ARGS__) +#define DOCTEST_REQUIRE_UNARY_FALSE(...) DOCTEST_UNARY_ASSERT(DT_REQUIRE_UNARY_FALSE, __VA_ARGS__) + +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + +#define DOCTEST_ASSERT_THROWS_AS(expr, assert_type, message, ...) \ + DOCTEST_FUNC_SCOPE_BEGIN { \ + if(!doctest::getContextOptions()->no_throw) { \ + doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ + __LINE__, #expr, #__VA_ARGS__, message); \ + try { \ + DOCTEST_CAST_TO_VOID(expr) \ + } catch(const typename doctest::detail::types::remove_const< \ + typename doctest::detail::types::remove_reference<__VA_ARGS__>::type>::type&) {\ + DOCTEST_RB.translateException(); \ + DOCTEST_RB.m_threw_as = true; \ + } catch(...) { DOCTEST_RB.translateException(); } \ + DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ + } else { /* NOLINT(*-else-after-return) */ \ + DOCTEST_FUNC_SCOPE_RET(false); \ + } \ + } DOCTEST_FUNC_SCOPE_END + +#define DOCTEST_ASSERT_THROWS_WITH(expr, expr_str, assert_type, ...) \ + DOCTEST_FUNC_SCOPE_BEGIN { \ + if(!doctest::getContextOptions()->no_throw) { \ + doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ + __LINE__, expr_str, "", __VA_ARGS__); \ + try { \ + DOCTEST_CAST_TO_VOID(expr) \ + } catch(...) { DOCTEST_RB.translateException(); } \ + DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ + } else { /* NOLINT(*-else-after-return) */ \ + DOCTEST_FUNC_SCOPE_RET(false); \ + } \ + } DOCTEST_FUNC_SCOPE_END + +#define DOCTEST_ASSERT_NOTHROW(assert_type, ...) \ + DOCTEST_FUNC_SCOPE_BEGIN { \ + doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ + __LINE__, #__VA_ARGS__); \ + try { \ + DOCTEST_CAST_TO_VOID(__VA_ARGS__) \ + } catch(...) { DOCTEST_RB.translateException(); } \ + DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ + } DOCTEST_FUNC_SCOPE_END + +// clang-format off +#define DOCTEST_WARN_THROWS(...) DOCTEST_ASSERT_THROWS_WITH((__VA_ARGS__), #__VA_ARGS__, DT_WARN_THROWS, "") +#define DOCTEST_CHECK_THROWS(...) DOCTEST_ASSERT_THROWS_WITH((__VA_ARGS__), #__VA_ARGS__, DT_CHECK_THROWS, "") +#define DOCTEST_REQUIRE_THROWS(...) DOCTEST_ASSERT_THROWS_WITH((__VA_ARGS__), #__VA_ARGS__, DT_REQUIRE_THROWS, "") + +#define DOCTEST_WARN_THROWS_AS(expr, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_WARN_THROWS_AS, "", __VA_ARGS__) +#define DOCTEST_CHECK_THROWS_AS(expr, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_CHECK_THROWS_AS, "", __VA_ARGS__) +#define DOCTEST_REQUIRE_THROWS_AS(expr, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_REQUIRE_THROWS_AS, "", __VA_ARGS__) + +#define DOCTEST_WARN_THROWS_WITH(expr, ...) DOCTEST_ASSERT_THROWS_WITH(expr, #expr, DT_WARN_THROWS_WITH, __VA_ARGS__) +#define DOCTEST_CHECK_THROWS_WITH(expr, ...) DOCTEST_ASSERT_THROWS_WITH(expr, #expr, DT_CHECK_THROWS_WITH, __VA_ARGS__) +#define DOCTEST_REQUIRE_THROWS_WITH(expr, ...) DOCTEST_ASSERT_THROWS_WITH(expr, #expr, DT_REQUIRE_THROWS_WITH, __VA_ARGS__) + +#define DOCTEST_WARN_THROWS_WITH_AS(expr, message, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_WARN_THROWS_WITH_AS, message, __VA_ARGS__) +#define DOCTEST_CHECK_THROWS_WITH_AS(expr, message, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_CHECK_THROWS_WITH_AS, message, __VA_ARGS__) +#define DOCTEST_REQUIRE_THROWS_WITH_AS(expr, message, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_REQUIRE_THROWS_WITH_AS, message, __VA_ARGS__) + +#define DOCTEST_WARN_NOTHROW(...) DOCTEST_ASSERT_NOTHROW(DT_WARN_NOTHROW, __VA_ARGS__) +#define DOCTEST_CHECK_NOTHROW(...) DOCTEST_ASSERT_NOTHROW(DT_CHECK_NOTHROW, __VA_ARGS__) +#define DOCTEST_REQUIRE_NOTHROW(...) DOCTEST_ASSERT_NOTHROW(DT_REQUIRE_NOTHROW, __VA_ARGS__) + +#define DOCTEST_WARN_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_THROWS(expr); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_CHECK_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_THROWS(expr); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_REQUIRE_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_THROWS(expr); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_THROWS_AS(expr, ex); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_THROWS_AS(expr, ex); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_THROWS_AS(expr, ex); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_THROWS_WITH(expr, with); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_THROWS_WITH(expr, with); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_THROWS_WITH(expr, with); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_THROWS_WITH_AS(expr, with, ex); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_THROWS_WITH_AS(expr, with, ex); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, ex); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_WARN_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_NOTHROW(expr); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_CHECK_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_NOTHROW(expr); } DOCTEST_FUNC_SCOPE_END +#define DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_NOTHROW(expr); } DOCTEST_FUNC_SCOPE_END +// clang-format on + +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + +// ================================================================================================= +// == WHAT FOLLOWS IS VERSIONS OF THE MACROS THAT DO NOT DO ANY REGISTERING! == +// == THIS CAN BE ENABLED BY DEFINING DOCTEST_CONFIG_DISABLE GLOBALLY! == +// ================================================================================================= +#else // DOCTEST_CONFIG_DISABLE + +#define DOCTEST_IMPLEMENT_FIXTURE(der, base, func, name) \ + namespace /* NOLINT */ { \ + template \ + struct der : public base \ + { void f(); }; \ + } \ + template \ + inline void der::f() + +#define DOCTEST_CREATE_AND_REGISTER_FUNCTION(f, name) \ + template \ + static inline void f() + +// for registering tests +#define DOCTEST_TEST_CASE(name) \ + DOCTEST_CREATE_AND_REGISTER_FUNCTION(DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), name) + +// for registering tests in classes +#define DOCTEST_TEST_CASE_CLASS(name) \ + DOCTEST_CREATE_AND_REGISTER_FUNCTION(DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), name) + +// for registering tests with a fixture +#define DOCTEST_TEST_CASE_FIXTURE(x, name) \ + DOCTEST_IMPLEMENT_FIXTURE(DOCTEST_ANONYMOUS(DOCTEST_ANON_CLASS_), x, \ + DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), name) + +// for converting types to strings without the header and demangling +#define DOCTEST_TYPE_TO_STRING_AS(str, ...) static_assert(true, "") +#define DOCTEST_TYPE_TO_STRING(...) static_assert(true, "") + +// for typed tests +#define DOCTEST_TEST_CASE_TEMPLATE(name, type, ...) \ + template \ + inline void DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_)() + +#define DOCTEST_TEST_CASE_TEMPLATE_DEFINE(name, type, id) \ + template \ + inline void DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_)() + +#define DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id, ...) static_assert(true, "") +#define DOCTEST_TEST_CASE_TEMPLATE_APPLY(id, ...) static_assert(true, "") + +// for subcases +#define DOCTEST_SUBCASE(name) + +// for a testsuite block +#define DOCTEST_TEST_SUITE(name) namespace // NOLINT + +// for starting a testsuite block +#define DOCTEST_TEST_SUITE_BEGIN(name) static_assert(true, "") + +// for ending a testsuite block +#define DOCTEST_TEST_SUITE_END using DOCTEST_ANONYMOUS(DOCTEST_ANON_FOR_SEMICOLON_) = int + +#define DOCTEST_REGISTER_EXCEPTION_TRANSLATOR(signature) \ + template \ + static inline doctest::String DOCTEST_ANONYMOUS(DOCTEST_ANON_TRANSLATOR_)(signature) + +#define DOCTEST_REGISTER_REPORTER(name, priority, reporter) +#define DOCTEST_REGISTER_LISTENER(name, priority, reporter) + +#define DOCTEST_INFO(...) (static_cast(0)) +#define DOCTEST_CAPTURE(x) (static_cast(0)) +#define DOCTEST_ADD_MESSAGE_AT(file, line, ...) (static_cast(0)) +#define DOCTEST_ADD_FAIL_CHECK_AT(file, line, ...) (static_cast(0)) +#define DOCTEST_ADD_FAIL_AT(file, line, ...) (static_cast(0)) +#define DOCTEST_MESSAGE(...) (static_cast(0)) +#define DOCTEST_FAIL_CHECK(...) (static_cast(0)) +#define DOCTEST_FAIL(...) (static_cast(0)) + +#if defined(DOCTEST_CONFIG_EVALUATE_ASSERTS_EVEN_WHEN_DISABLED) \ + && defined(DOCTEST_CONFIG_ASSERTS_RETURN_VALUES) + +#define DOCTEST_WARN(...) [&] { return __VA_ARGS__; }() +#define DOCTEST_CHECK(...) [&] { return __VA_ARGS__; }() +#define DOCTEST_REQUIRE(...) [&] { return __VA_ARGS__; }() +#define DOCTEST_WARN_FALSE(...) [&] { return !(__VA_ARGS__); }() +#define DOCTEST_CHECK_FALSE(...) [&] { return !(__VA_ARGS__); }() +#define DOCTEST_REQUIRE_FALSE(...) [&] { return !(__VA_ARGS__); }() + +#define DOCTEST_WARN_MESSAGE(cond, ...) [&] { return cond; }() +#define DOCTEST_CHECK_MESSAGE(cond, ...) [&] { return cond; }() +#define DOCTEST_REQUIRE_MESSAGE(cond, ...) [&] { return cond; }() +#define DOCTEST_WARN_FALSE_MESSAGE(cond, ...) [&] { return !(cond); }() +#define DOCTEST_CHECK_FALSE_MESSAGE(cond, ...) [&] { return !(cond); }() +#define DOCTEST_REQUIRE_FALSE_MESSAGE(cond, ...) [&] { return !(cond); }() + +namespace doctest { +namespace detail { +#define DOCTEST_RELATIONAL_OP(name, op) \ + template \ + bool name(const DOCTEST_REF_WRAP(L) lhs, const DOCTEST_REF_WRAP(R) rhs) { return lhs op rhs; } + + DOCTEST_RELATIONAL_OP(eq, ==) + DOCTEST_RELATIONAL_OP(ne, !=) + DOCTEST_RELATIONAL_OP(lt, <) + DOCTEST_RELATIONAL_OP(gt, >) + DOCTEST_RELATIONAL_OP(le, <=) + DOCTEST_RELATIONAL_OP(ge, >=) +} // namespace detail +} // namespace doctest + +#define DOCTEST_WARN_EQ(...) [&] { return doctest::detail::eq(__VA_ARGS__); }() +#define DOCTEST_CHECK_EQ(...) [&] { return doctest::detail::eq(__VA_ARGS__); }() +#define DOCTEST_REQUIRE_EQ(...) [&] { return doctest::detail::eq(__VA_ARGS__); }() +#define DOCTEST_WARN_NE(...) [&] { return doctest::detail::ne(__VA_ARGS__); }() +#define DOCTEST_CHECK_NE(...) [&] { return doctest::detail::ne(__VA_ARGS__); }() +#define DOCTEST_REQUIRE_NE(...) [&] { return doctest::detail::ne(__VA_ARGS__); }() +#define DOCTEST_WARN_LT(...) [&] { return doctest::detail::lt(__VA_ARGS__); }() +#define DOCTEST_CHECK_LT(...) [&] { return doctest::detail::lt(__VA_ARGS__); }() +#define DOCTEST_REQUIRE_LT(...) [&] { return doctest::detail::lt(__VA_ARGS__); }() +#define DOCTEST_WARN_GT(...) [&] { return doctest::detail::gt(__VA_ARGS__); }() +#define DOCTEST_CHECK_GT(...) [&] { return doctest::detail::gt(__VA_ARGS__); }() +#define DOCTEST_REQUIRE_GT(...) [&] { return doctest::detail::gt(__VA_ARGS__); }() +#define DOCTEST_WARN_LE(...) [&] { return doctest::detail::le(__VA_ARGS__); }() +#define DOCTEST_CHECK_LE(...) [&] { return doctest::detail::le(__VA_ARGS__); }() +#define DOCTEST_REQUIRE_LE(...) [&] { return doctest::detail::le(__VA_ARGS__); }() +#define DOCTEST_WARN_GE(...) [&] { return doctest::detail::ge(__VA_ARGS__); }() +#define DOCTEST_CHECK_GE(...) [&] { return doctest::detail::ge(__VA_ARGS__); }() +#define DOCTEST_REQUIRE_GE(...) [&] { return doctest::detail::ge(__VA_ARGS__); }() +#define DOCTEST_WARN_UNARY(...) [&] { return __VA_ARGS__; }() +#define DOCTEST_CHECK_UNARY(...) [&] { return __VA_ARGS__; }() +#define DOCTEST_REQUIRE_UNARY(...) [&] { return __VA_ARGS__; }() +#define DOCTEST_WARN_UNARY_FALSE(...) [&] { return !(__VA_ARGS__); }() +#define DOCTEST_CHECK_UNARY_FALSE(...) [&] { return !(__VA_ARGS__); }() +#define DOCTEST_REQUIRE_UNARY_FALSE(...) [&] { return !(__VA_ARGS__); }() + +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + +#define DOCTEST_WARN_THROWS_WITH(expr, with, ...) [] { static_assert(false, "Exception translation is not available when doctest is disabled."); return false; }() +#define DOCTEST_CHECK_THROWS_WITH(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) +#define DOCTEST_REQUIRE_THROWS_WITH(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) +#define DOCTEST_WARN_THROWS_WITH_AS(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) +#define DOCTEST_CHECK_THROWS_WITH_AS(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) +#define DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) + +#define DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) +#define DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) +#define DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) +#define DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) +#define DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) +#define DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) + +#define DOCTEST_WARN_THROWS(...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() +#define DOCTEST_CHECK_THROWS(...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() +#define DOCTEST_REQUIRE_THROWS(...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() +#define DOCTEST_WARN_THROWS_AS(expr, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() +#define DOCTEST_CHECK_THROWS_AS(expr, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() +#define DOCTEST_REQUIRE_THROWS_AS(expr, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() +#define DOCTEST_WARN_NOTHROW(...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() +#define DOCTEST_CHECK_NOTHROW(...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() +#define DOCTEST_REQUIRE_NOTHROW(...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() + +#define DOCTEST_WARN_THROWS_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() +#define DOCTEST_CHECK_THROWS_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() +#define DOCTEST_REQUIRE_THROWS_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() +#define DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() +#define DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() +#define DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() +#define DOCTEST_WARN_NOTHROW_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() +#define DOCTEST_CHECK_NOTHROW_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() +#define DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() + +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + +#else // DOCTEST_CONFIG_EVALUATE_ASSERTS_EVEN_WHEN_DISABLED + +#define DOCTEST_WARN(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_FALSE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_FALSE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_FALSE(...) DOCTEST_FUNC_EMPTY + +#define DOCTEST_WARN_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY + +#define DOCTEST_WARN_EQ(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_EQ(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_EQ(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_NE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_NE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_NE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_GT(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_GT(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_GT(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_LT(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_LT(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_LT(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_GE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_GE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_GE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_LE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_LE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_LE(...) DOCTEST_FUNC_EMPTY + +#define DOCTEST_WARN_UNARY(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_UNARY(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_UNARY(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_UNARY_FALSE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_UNARY_FALSE(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_UNARY_FALSE(...) DOCTEST_FUNC_EMPTY + +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + +#define DOCTEST_WARN_THROWS(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_THROWS(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_THROWS(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_THROWS_AS(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_THROWS_AS(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_THROWS_AS(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_THROWS_WITH(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_THROWS_WITH(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_THROWS_WITH(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_THROWS_WITH_AS(expr, with, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_THROWS_WITH_AS(expr, with, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_NOTHROW(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_NOTHROW(...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_NOTHROW(...) DOCTEST_FUNC_EMPTY + +#define DOCTEST_WARN_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_WARN_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_CHECK_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY +#define DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY + +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + +#endif // DOCTEST_CONFIG_EVALUATE_ASSERTS_EVEN_WHEN_DISABLED + +#endif // DOCTEST_CONFIG_DISABLE + +#ifdef DOCTEST_CONFIG_NO_EXCEPTIONS + +#ifdef DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS +#define DOCTEST_EXCEPTION_EMPTY_FUNC DOCTEST_FUNC_EMPTY +#else // DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS +#define DOCTEST_EXCEPTION_EMPTY_FUNC [] { static_assert(false, "Exceptions are disabled! " \ + "Use DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS if you want to compile with exceptions disabled."); return false; }() + +#undef DOCTEST_REQUIRE +#undef DOCTEST_REQUIRE_FALSE +#undef DOCTEST_REQUIRE_MESSAGE +#undef DOCTEST_REQUIRE_FALSE_MESSAGE +#undef DOCTEST_REQUIRE_EQ +#undef DOCTEST_REQUIRE_NE +#undef DOCTEST_REQUIRE_GT +#undef DOCTEST_REQUIRE_LT +#undef DOCTEST_REQUIRE_GE +#undef DOCTEST_REQUIRE_LE +#undef DOCTEST_REQUIRE_UNARY +#undef DOCTEST_REQUIRE_UNARY_FALSE + +#define DOCTEST_REQUIRE DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_FALSE DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_MESSAGE DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_FALSE_MESSAGE DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_EQ DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_NE DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_GT DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_LT DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_GE DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_LE DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_UNARY DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_UNARY_FALSE DOCTEST_EXCEPTION_EMPTY_FUNC + +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS + +#define DOCTEST_WARN_THROWS(...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_THROWS(...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_THROWS(...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_WARN_THROWS_AS(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_THROWS_AS(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_THROWS_AS(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_WARN_THROWS_WITH(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_THROWS_WITH(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_THROWS_WITH(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_WARN_THROWS_WITH_AS(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_THROWS_WITH_AS(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_WARN_NOTHROW(...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_NOTHROW(...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_NOTHROW(...) DOCTEST_EXCEPTION_EMPTY_FUNC + +#define DOCTEST_WARN_THROWS_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_THROWS_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_THROWS_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_WARN_NOTHROW_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_CHECK_NOTHROW_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC +#define DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC + +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + +// clang-format off +// KEPT FOR BACKWARDS COMPATIBILITY - FORWARDING TO THE RIGHT MACROS +#define DOCTEST_FAST_WARN_EQ DOCTEST_WARN_EQ +#define DOCTEST_FAST_CHECK_EQ DOCTEST_CHECK_EQ +#define DOCTEST_FAST_REQUIRE_EQ DOCTEST_REQUIRE_EQ +#define DOCTEST_FAST_WARN_NE DOCTEST_WARN_NE +#define DOCTEST_FAST_CHECK_NE DOCTEST_CHECK_NE +#define DOCTEST_FAST_REQUIRE_NE DOCTEST_REQUIRE_NE +#define DOCTEST_FAST_WARN_GT DOCTEST_WARN_GT +#define DOCTEST_FAST_CHECK_GT DOCTEST_CHECK_GT +#define DOCTEST_FAST_REQUIRE_GT DOCTEST_REQUIRE_GT +#define DOCTEST_FAST_WARN_LT DOCTEST_WARN_LT +#define DOCTEST_FAST_CHECK_LT DOCTEST_CHECK_LT +#define DOCTEST_FAST_REQUIRE_LT DOCTEST_REQUIRE_LT +#define DOCTEST_FAST_WARN_GE DOCTEST_WARN_GE +#define DOCTEST_FAST_CHECK_GE DOCTEST_CHECK_GE +#define DOCTEST_FAST_REQUIRE_GE DOCTEST_REQUIRE_GE +#define DOCTEST_FAST_WARN_LE DOCTEST_WARN_LE +#define DOCTEST_FAST_CHECK_LE DOCTEST_CHECK_LE +#define DOCTEST_FAST_REQUIRE_LE DOCTEST_REQUIRE_LE + +#define DOCTEST_FAST_WARN_UNARY DOCTEST_WARN_UNARY +#define DOCTEST_FAST_CHECK_UNARY DOCTEST_CHECK_UNARY +#define DOCTEST_FAST_REQUIRE_UNARY DOCTEST_REQUIRE_UNARY +#define DOCTEST_FAST_WARN_UNARY_FALSE DOCTEST_WARN_UNARY_FALSE +#define DOCTEST_FAST_CHECK_UNARY_FALSE DOCTEST_CHECK_UNARY_FALSE +#define DOCTEST_FAST_REQUIRE_UNARY_FALSE DOCTEST_REQUIRE_UNARY_FALSE + +#define DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE(id, ...) DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id,__VA_ARGS__) +// clang-format on + +// BDD style macros +// clang-format off +#define DOCTEST_SCENARIO(name) DOCTEST_TEST_CASE(" Scenario: " name) +#define DOCTEST_SCENARIO_CLASS(name) DOCTEST_TEST_CASE_CLASS(" Scenario: " name) +#define DOCTEST_SCENARIO_TEMPLATE(name, T, ...) DOCTEST_TEST_CASE_TEMPLATE(" Scenario: " name, T, __VA_ARGS__) +#define DOCTEST_SCENARIO_TEMPLATE_DEFINE(name, T, id) DOCTEST_TEST_CASE_TEMPLATE_DEFINE(" Scenario: " name, T, id) + +#define DOCTEST_GIVEN(name) DOCTEST_SUBCASE(" Given: " name) +#define DOCTEST_WHEN(name) DOCTEST_SUBCASE(" When: " name) +#define DOCTEST_AND_WHEN(name) DOCTEST_SUBCASE("And when: " name) +#define DOCTEST_THEN(name) DOCTEST_SUBCASE(" Then: " name) +#define DOCTEST_AND_THEN(name) DOCTEST_SUBCASE(" And: " name) +// clang-format on + +// == SHORT VERSIONS OF THE MACROS +#ifndef DOCTEST_CONFIG_NO_SHORT_MACRO_NAMES + +#define TEST_CASE(name) DOCTEST_TEST_CASE(name) +#define TEST_CASE_CLASS(name) DOCTEST_TEST_CASE_CLASS(name) +#define TEST_CASE_FIXTURE(x, name) DOCTEST_TEST_CASE_FIXTURE(x, name) +#define TYPE_TO_STRING_AS(str, ...) DOCTEST_TYPE_TO_STRING_AS(str, __VA_ARGS__) +#define TYPE_TO_STRING(...) DOCTEST_TYPE_TO_STRING(__VA_ARGS__) +#define TEST_CASE_TEMPLATE(name, T, ...) DOCTEST_TEST_CASE_TEMPLATE(name, T, __VA_ARGS__) +#define TEST_CASE_TEMPLATE_DEFINE(name, T, id) DOCTEST_TEST_CASE_TEMPLATE_DEFINE(name, T, id) +#define TEST_CASE_TEMPLATE_INVOKE(id, ...) DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id, __VA_ARGS__) +#define TEST_CASE_TEMPLATE_APPLY(id, ...) DOCTEST_TEST_CASE_TEMPLATE_APPLY(id, __VA_ARGS__) +#define SUBCASE(name) DOCTEST_SUBCASE(name) +#define TEST_SUITE(decorators) DOCTEST_TEST_SUITE(decorators) +#define TEST_SUITE_BEGIN(name) DOCTEST_TEST_SUITE_BEGIN(name) +#define TEST_SUITE_END DOCTEST_TEST_SUITE_END +#define REGISTER_EXCEPTION_TRANSLATOR(signature) DOCTEST_REGISTER_EXCEPTION_TRANSLATOR(signature) +#define REGISTER_REPORTER(name, priority, reporter) DOCTEST_REGISTER_REPORTER(name, priority, reporter) +#define REGISTER_LISTENER(name, priority, reporter) DOCTEST_REGISTER_LISTENER(name, priority, reporter) +#define INFO(...) DOCTEST_INFO(__VA_ARGS__) +#define CAPTURE(x) DOCTEST_CAPTURE(x) +#define ADD_MESSAGE_AT(file, line, ...) DOCTEST_ADD_MESSAGE_AT(file, line, __VA_ARGS__) +#define ADD_FAIL_CHECK_AT(file, line, ...) DOCTEST_ADD_FAIL_CHECK_AT(file, line, __VA_ARGS__) +#define ADD_FAIL_AT(file, line, ...) DOCTEST_ADD_FAIL_AT(file, line, __VA_ARGS__) +#define MESSAGE(...) DOCTEST_MESSAGE(__VA_ARGS__) +#define FAIL_CHECK(...) DOCTEST_FAIL_CHECK(__VA_ARGS__) +#define FAIL(...) DOCTEST_FAIL(__VA_ARGS__) +#define TO_LVALUE(...) DOCTEST_TO_LVALUE(__VA_ARGS__) + +#define WARN(...) DOCTEST_WARN(__VA_ARGS__) +#define WARN_FALSE(...) DOCTEST_WARN_FALSE(__VA_ARGS__) +#define WARN_THROWS(...) DOCTEST_WARN_THROWS(__VA_ARGS__) +#define WARN_THROWS_AS(expr, ...) DOCTEST_WARN_THROWS_AS(expr, __VA_ARGS__) +#define WARN_THROWS_WITH(expr, ...) DOCTEST_WARN_THROWS_WITH(expr, __VA_ARGS__) +#define WARN_THROWS_WITH_AS(expr, with, ...) DOCTEST_WARN_THROWS_WITH_AS(expr, with, __VA_ARGS__) +#define WARN_NOTHROW(...) DOCTEST_WARN_NOTHROW(__VA_ARGS__) +#define CHECK(...) DOCTEST_CHECK(__VA_ARGS__) +#define CHECK_FALSE(...) DOCTEST_CHECK_FALSE(__VA_ARGS__) +#define CHECK_THROWS(...) DOCTEST_CHECK_THROWS(__VA_ARGS__) +#define CHECK_THROWS_AS(expr, ...) DOCTEST_CHECK_THROWS_AS(expr, __VA_ARGS__) +#define CHECK_THROWS_WITH(expr, ...) DOCTEST_CHECK_THROWS_WITH(expr, __VA_ARGS__) +#define CHECK_THROWS_WITH_AS(expr, with, ...) DOCTEST_CHECK_THROWS_WITH_AS(expr, with, __VA_ARGS__) +#define CHECK_NOTHROW(...) DOCTEST_CHECK_NOTHROW(__VA_ARGS__) +#define REQUIRE(...) DOCTEST_REQUIRE(__VA_ARGS__) +#define REQUIRE_FALSE(...) DOCTEST_REQUIRE_FALSE(__VA_ARGS__) +#define REQUIRE_THROWS(...) DOCTEST_REQUIRE_THROWS(__VA_ARGS__) +#define REQUIRE_THROWS_AS(expr, ...) DOCTEST_REQUIRE_THROWS_AS(expr, __VA_ARGS__) +#define REQUIRE_THROWS_WITH(expr, ...) DOCTEST_REQUIRE_THROWS_WITH(expr, __VA_ARGS__) +#define REQUIRE_THROWS_WITH_AS(expr, with, ...) DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, __VA_ARGS__) +#define REQUIRE_NOTHROW(...) DOCTEST_REQUIRE_NOTHROW(__VA_ARGS__) + +#define WARN_MESSAGE(cond, ...) DOCTEST_WARN_MESSAGE(cond, __VA_ARGS__) +#define WARN_FALSE_MESSAGE(cond, ...) DOCTEST_WARN_FALSE_MESSAGE(cond, __VA_ARGS__) +#define WARN_THROWS_MESSAGE(expr, ...) DOCTEST_WARN_THROWS_MESSAGE(expr, __VA_ARGS__) +#define WARN_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, __VA_ARGS__) +#define WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, __VA_ARGS__) +#define WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, __VA_ARGS__) +#define WARN_NOTHROW_MESSAGE(expr, ...) DOCTEST_WARN_NOTHROW_MESSAGE(expr, __VA_ARGS__) +#define CHECK_MESSAGE(cond, ...) DOCTEST_CHECK_MESSAGE(cond, __VA_ARGS__) +#define CHECK_FALSE_MESSAGE(cond, ...) DOCTEST_CHECK_FALSE_MESSAGE(cond, __VA_ARGS__) +#define CHECK_THROWS_MESSAGE(expr, ...) DOCTEST_CHECK_THROWS_MESSAGE(expr, __VA_ARGS__) +#define CHECK_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, __VA_ARGS__) +#define CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, __VA_ARGS__) +#define CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, __VA_ARGS__) +#define CHECK_NOTHROW_MESSAGE(expr, ...) DOCTEST_CHECK_NOTHROW_MESSAGE(expr, __VA_ARGS__) +#define REQUIRE_MESSAGE(cond, ...) DOCTEST_REQUIRE_MESSAGE(cond, __VA_ARGS__) +#define REQUIRE_FALSE_MESSAGE(cond, ...) DOCTEST_REQUIRE_FALSE_MESSAGE(cond, __VA_ARGS__) +#define REQUIRE_THROWS_MESSAGE(expr, ...) DOCTEST_REQUIRE_THROWS_MESSAGE(expr, __VA_ARGS__) +#define REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, __VA_ARGS__) +#define REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, __VA_ARGS__) +#define REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, __VA_ARGS__) +#define REQUIRE_NOTHROW_MESSAGE(expr, ...) DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, __VA_ARGS__) + +#define SCENARIO(name) DOCTEST_SCENARIO(name) +#define SCENARIO_CLASS(name) DOCTEST_SCENARIO_CLASS(name) +#define SCENARIO_TEMPLATE(name, T, ...) DOCTEST_SCENARIO_TEMPLATE(name, T, __VA_ARGS__) +#define SCENARIO_TEMPLATE_DEFINE(name, T, id) DOCTEST_SCENARIO_TEMPLATE_DEFINE(name, T, id) +#define GIVEN(name) DOCTEST_GIVEN(name) +#define WHEN(name) DOCTEST_WHEN(name) +#define AND_WHEN(name) DOCTEST_AND_WHEN(name) +#define THEN(name) DOCTEST_THEN(name) +#define AND_THEN(name) DOCTEST_AND_THEN(name) + +#define WARN_EQ(...) DOCTEST_WARN_EQ(__VA_ARGS__) +#define CHECK_EQ(...) DOCTEST_CHECK_EQ(__VA_ARGS__) +#define REQUIRE_EQ(...) DOCTEST_REQUIRE_EQ(__VA_ARGS__) +#define WARN_NE(...) DOCTEST_WARN_NE(__VA_ARGS__) +#define CHECK_NE(...) DOCTEST_CHECK_NE(__VA_ARGS__) +#define REQUIRE_NE(...) DOCTEST_REQUIRE_NE(__VA_ARGS__) +#define WARN_GT(...) DOCTEST_WARN_GT(__VA_ARGS__) +#define CHECK_GT(...) DOCTEST_CHECK_GT(__VA_ARGS__) +#define REQUIRE_GT(...) DOCTEST_REQUIRE_GT(__VA_ARGS__) +#define WARN_LT(...) DOCTEST_WARN_LT(__VA_ARGS__) +#define CHECK_LT(...) DOCTEST_CHECK_LT(__VA_ARGS__) +#define REQUIRE_LT(...) DOCTEST_REQUIRE_LT(__VA_ARGS__) +#define WARN_GE(...) DOCTEST_WARN_GE(__VA_ARGS__) +#define CHECK_GE(...) DOCTEST_CHECK_GE(__VA_ARGS__) +#define REQUIRE_GE(...) DOCTEST_REQUIRE_GE(__VA_ARGS__) +#define WARN_LE(...) DOCTEST_WARN_LE(__VA_ARGS__) +#define CHECK_LE(...) DOCTEST_CHECK_LE(__VA_ARGS__) +#define REQUIRE_LE(...) DOCTEST_REQUIRE_LE(__VA_ARGS__) +#define WARN_UNARY(...) DOCTEST_WARN_UNARY(__VA_ARGS__) +#define CHECK_UNARY(...) DOCTEST_CHECK_UNARY(__VA_ARGS__) +#define REQUIRE_UNARY(...) DOCTEST_REQUIRE_UNARY(__VA_ARGS__) +#define WARN_UNARY_FALSE(...) DOCTEST_WARN_UNARY_FALSE(__VA_ARGS__) +#define CHECK_UNARY_FALSE(...) DOCTEST_CHECK_UNARY_FALSE(__VA_ARGS__) +#define REQUIRE_UNARY_FALSE(...) DOCTEST_REQUIRE_UNARY_FALSE(__VA_ARGS__) + +// KEPT FOR BACKWARDS COMPATIBILITY +#define FAST_WARN_EQ(...) DOCTEST_FAST_WARN_EQ(__VA_ARGS__) +#define FAST_CHECK_EQ(...) DOCTEST_FAST_CHECK_EQ(__VA_ARGS__) +#define FAST_REQUIRE_EQ(...) DOCTEST_FAST_REQUIRE_EQ(__VA_ARGS__) +#define FAST_WARN_NE(...) DOCTEST_FAST_WARN_NE(__VA_ARGS__) +#define FAST_CHECK_NE(...) DOCTEST_FAST_CHECK_NE(__VA_ARGS__) +#define FAST_REQUIRE_NE(...) DOCTEST_FAST_REQUIRE_NE(__VA_ARGS__) +#define FAST_WARN_GT(...) DOCTEST_FAST_WARN_GT(__VA_ARGS__) +#define FAST_CHECK_GT(...) DOCTEST_FAST_CHECK_GT(__VA_ARGS__) +#define FAST_REQUIRE_GT(...) DOCTEST_FAST_REQUIRE_GT(__VA_ARGS__) +#define FAST_WARN_LT(...) DOCTEST_FAST_WARN_LT(__VA_ARGS__) +#define FAST_CHECK_LT(...) DOCTEST_FAST_CHECK_LT(__VA_ARGS__) +#define FAST_REQUIRE_LT(...) DOCTEST_FAST_REQUIRE_LT(__VA_ARGS__) +#define FAST_WARN_GE(...) DOCTEST_FAST_WARN_GE(__VA_ARGS__) +#define FAST_CHECK_GE(...) DOCTEST_FAST_CHECK_GE(__VA_ARGS__) +#define FAST_REQUIRE_GE(...) DOCTEST_FAST_REQUIRE_GE(__VA_ARGS__) +#define FAST_WARN_LE(...) DOCTEST_FAST_WARN_LE(__VA_ARGS__) +#define FAST_CHECK_LE(...) DOCTEST_FAST_CHECK_LE(__VA_ARGS__) +#define FAST_REQUIRE_LE(...) DOCTEST_FAST_REQUIRE_LE(__VA_ARGS__) + +#define FAST_WARN_UNARY(...) DOCTEST_FAST_WARN_UNARY(__VA_ARGS__) +#define FAST_CHECK_UNARY(...) DOCTEST_FAST_CHECK_UNARY(__VA_ARGS__) +#define FAST_REQUIRE_UNARY(...) DOCTEST_FAST_REQUIRE_UNARY(__VA_ARGS__) +#define FAST_WARN_UNARY_FALSE(...) DOCTEST_FAST_WARN_UNARY_FALSE(__VA_ARGS__) +#define FAST_CHECK_UNARY_FALSE(...) DOCTEST_FAST_CHECK_UNARY_FALSE(__VA_ARGS__) +#define FAST_REQUIRE_UNARY_FALSE(...) DOCTEST_FAST_REQUIRE_UNARY_FALSE(__VA_ARGS__) + +#define TEST_CASE_TEMPLATE_INSTANTIATE(id, ...) DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE(id, __VA_ARGS__) + +#endif // DOCTEST_CONFIG_NO_SHORT_MACRO_NAMES + +#ifndef DOCTEST_CONFIG_DISABLE + +// this is here to clear the 'current test suite' for the current translation unit - at the top +DOCTEST_TEST_SUITE_END(); + +#endif // DOCTEST_CONFIG_DISABLE + +DOCTEST_CLANG_SUPPRESS_WARNING_POP +DOCTEST_MSVC_SUPPRESS_WARNING_POP +DOCTEST_GCC_SUPPRESS_WARNING_POP + +DOCTEST_SUPPRESS_COMMON_WARNINGS_POP + +#endif // DOCTEST_LIBRARY_INCLUDED + +#ifndef DOCTEST_SINGLE_HEADER +#define DOCTEST_SINGLE_HEADER +#endif // DOCTEST_SINGLE_HEADER + +#if defined(DOCTEST_CONFIG_IMPLEMENT) || !defined(DOCTEST_SINGLE_HEADER) + +#ifndef DOCTEST_SINGLE_HEADER +#include "doctest_fwd.h" +#endif // DOCTEST_SINGLE_HEADER + +DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wunused-macros") + +#ifndef DOCTEST_LIBRARY_IMPLEMENTATION +#define DOCTEST_LIBRARY_IMPLEMENTATION + +DOCTEST_CLANG_SUPPRESS_WARNING_POP + +DOCTEST_SUPPRESS_COMMON_WARNINGS_PUSH + +DOCTEST_CLANG_SUPPRESS_WARNING_PUSH +DOCTEST_CLANG_SUPPRESS_WARNING("-Wglobal-constructors") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wsign-conversion") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wshorten-64-to-32") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-variable-declarations") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wswitch") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wswitch-enum") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wcovered-switch-default") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-noreturn") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wdisabled-macro-expansion") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-braces") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-field-initializers") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wunused-member-function") +DOCTEST_CLANG_SUPPRESS_WARNING("-Wnonportable-system-include-path") + +DOCTEST_GCC_SUPPRESS_WARNING_PUSH +DOCTEST_GCC_SUPPRESS_WARNING("-Wconversion") +DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-conversion") +DOCTEST_GCC_SUPPRESS_WARNING("-Wmissing-field-initializers") +DOCTEST_GCC_SUPPRESS_WARNING("-Wmissing-braces") +DOCTEST_GCC_SUPPRESS_WARNING("-Wswitch") +DOCTEST_GCC_SUPPRESS_WARNING("-Wswitch-enum") +DOCTEST_GCC_SUPPRESS_WARNING("-Wswitch-default") +DOCTEST_GCC_SUPPRESS_WARNING("-Wunsafe-loop-optimizations") +DOCTEST_GCC_SUPPRESS_WARNING("-Wold-style-cast") +DOCTEST_GCC_SUPPRESS_WARNING("-Wunused-function") +DOCTEST_GCC_SUPPRESS_WARNING("-Wmultiple-inheritance") +DOCTEST_GCC_SUPPRESS_WARNING("-Wsuggest-attribute") + +DOCTEST_MSVC_SUPPRESS_WARNING_PUSH +DOCTEST_MSVC_SUPPRESS_WARNING(4267) // 'var' : conversion from 'x' to 'y', possible loss of data +DOCTEST_MSVC_SUPPRESS_WARNING(4530) // C++ exception handler used, but unwind semantics not enabled +DOCTEST_MSVC_SUPPRESS_WARNING(4577) // 'noexcept' used with no exception handling mode specified +DOCTEST_MSVC_SUPPRESS_WARNING(4774) // format string expected in argument is not a string literal +DOCTEST_MSVC_SUPPRESS_WARNING(4365) // conversion from 'int' to 'unsigned', signed/unsigned mismatch +DOCTEST_MSVC_SUPPRESS_WARNING(5039) // pointer to potentially throwing function passed to extern C +DOCTEST_MSVC_SUPPRESS_WARNING(4800) // forcing value to bool 'true' or 'false' (performance warning) +DOCTEST_MSVC_SUPPRESS_WARNING(5245) // unreferenced function with internal linkage has been removed + +DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_BEGIN + +// required includes - will go only in one translation unit! +#include +#include +#include +// borland (Embarcadero) compiler requires math.h and not cmath - https://github.com/doctest/doctest/pull/37 +#ifdef __BORLANDC__ +#include +#endif // __BORLANDC__ +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM +#include +#endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM +#include +#include +#include +#ifndef DOCTEST_CONFIG_NO_MULTITHREADING +#include +#include +#define DOCTEST_DECLARE_MUTEX(name) std::mutex name; +#define DOCTEST_DECLARE_STATIC_MUTEX(name) static DOCTEST_DECLARE_MUTEX(name) +#define DOCTEST_LOCK_MUTEX(name) std::lock_guard DOCTEST_ANONYMOUS(DOCTEST_ANON_LOCK_)(name); +#else // DOCTEST_CONFIG_NO_MULTITHREADING +#define DOCTEST_DECLARE_MUTEX(name) +#define DOCTEST_DECLARE_STATIC_MUTEX(name) +#define DOCTEST_LOCK_MUTEX(name) +#endif // DOCTEST_CONFIG_NO_MULTITHREADING +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef DOCTEST_PLATFORM_MAC +#include +#include +#include +#endif // DOCTEST_PLATFORM_MAC + +#ifdef DOCTEST_PLATFORM_WINDOWS + +// defines for a leaner windows.h +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#define DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN +#endif // WIN32_LEAN_AND_MEAN +#ifndef NOMINMAX +#define NOMINMAX +#define DOCTEST_UNDEF_NOMINMAX +#endif // NOMINMAX + +// not sure what AfxWin.h is for - here I do what Catch does +#ifdef __AFXDLL +#include +#else +#include +#endif +#include + +#else // DOCTEST_PLATFORM_WINDOWS + +#include +#include + +#endif // DOCTEST_PLATFORM_WINDOWS + +// this is a fix for https://github.com/doctest/doctest/issues/348 +// https://mail.gnome.org/archives/xml/2012-January/msg00000.html +#if !defined(HAVE_UNISTD_H) && !defined(STDOUT_FILENO) +#define STDOUT_FILENO fileno(stdout) +#endif // HAVE_UNISTD_H + +DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_END + +// counts the number of elements in a C array +#define DOCTEST_COUNTOF(x) (sizeof(x) / sizeof(x[0])) + +#ifdef DOCTEST_CONFIG_DISABLE +#define DOCTEST_BRANCH_ON_DISABLED(if_disabled, if_not_disabled) if_disabled +#else // DOCTEST_CONFIG_DISABLE +#define DOCTEST_BRANCH_ON_DISABLED(if_disabled, if_not_disabled) if_not_disabled +#endif // DOCTEST_CONFIG_DISABLE + +#ifndef DOCTEST_CONFIG_OPTIONS_PREFIX +#define DOCTEST_CONFIG_OPTIONS_PREFIX "dt-" +#endif + +#ifndef DOCTEST_THREAD_LOCAL +#if defined(DOCTEST_CONFIG_NO_MULTITHREADING) || DOCTEST_MSVC && (DOCTEST_MSVC < DOCTEST_COMPILER(19, 0, 0)) +#define DOCTEST_THREAD_LOCAL +#else // DOCTEST_MSVC +#define DOCTEST_THREAD_LOCAL thread_local +#endif // DOCTEST_MSVC +#endif // DOCTEST_THREAD_LOCAL + +#ifndef DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES +#define DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES 32 +#endif + +#ifndef DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE +#define DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE 64 +#endif + +#ifdef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS +#define DOCTEST_OPTIONS_PREFIX_DISPLAY DOCTEST_CONFIG_OPTIONS_PREFIX +#else +#define DOCTEST_OPTIONS_PREFIX_DISPLAY "" +#endif + +#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) +#define DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS +#endif + +#ifndef DOCTEST_CDECL +#define DOCTEST_CDECL __cdecl +#endif + +namespace doctest { + +bool is_running_in_test = false; + +namespace { + using namespace detail; + + template + DOCTEST_NORETURN void throw_exception(Ex const& e) { +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + throw e; +#else // DOCTEST_CONFIG_NO_EXCEPTIONS +#ifdef DOCTEST_CONFIG_HANDLE_EXCEPTION + DOCTEST_CONFIG_HANDLE_EXCEPTION(e); +#else // DOCTEST_CONFIG_HANDLE_EXCEPTION +#ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM + std::cerr << "doctest will terminate because it needed to throw an exception.\n" + << "The message was: " << e.what() << '\n'; +#endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM +#endif // DOCTEST_CONFIG_HANDLE_EXCEPTION + std::terminate(); +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + } + +#ifndef DOCTEST_INTERNAL_ERROR +#define DOCTEST_INTERNAL_ERROR(msg) \ + throw_exception(std::logic_error( \ + __FILE__ ":" DOCTEST_TOSTR(__LINE__) ": Internal doctest error: " msg)) +#endif // DOCTEST_INTERNAL_ERROR + + // case insensitive strcmp + int stricmp(const char* a, const char* b) { + for(;; a++, b++) { + const int d = tolower(*a) - tolower(*b); + if(d != 0 || !*a) + return d; + } + } + + struct Endianness + { + enum Arch + { + Big, + Little + }; + + static Arch which() { + int x = 1; + // casting any data pointer to char* is allowed + auto ptr = reinterpret_cast(&x); + if(*ptr) + return Little; + return Big; + } + }; +} // namespace + +namespace detail { + DOCTEST_THREAD_LOCAL class + { + std::vector stack; + std::stringstream ss; + + public: + std::ostream* push() { + stack.push_back(ss.tellp()); + return &ss; + } + + String pop() { + if (stack.empty()) + DOCTEST_INTERNAL_ERROR("TLSS was empty when trying to pop!"); + + std::streampos pos = stack.back(); + stack.pop_back(); + unsigned sz = static_cast(ss.tellp() - pos); + ss.rdbuf()->pubseekpos(pos, std::ios::in | std::ios::out); + return String(ss, sz); + } + } g_oss; + + std::ostream* tlssPush() { + return g_oss.push(); + } + + String tlssPop() { + return g_oss.pop(); + } + +#ifndef DOCTEST_CONFIG_DISABLE + +namespace timer_large_integer +{ + +#if defined(DOCTEST_PLATFORM_WINDOWS) + using type = ULONGLONG; +#else // DOCTEST_PLATFORM_WINDOWS + using type = std::uint64_t; +#endif // DOCTEST_PLATFORM_WINDOWS +} + +using ticks_t = timer_large_integer::type; + +#ifdef DOCTEST_CONFIG_GETCURRENTTICKS + ticks_t getCurrentTicks() { return DOCTEST_CONFIG_GETCURRENTTICKS(); } +#elif defined(DOCTEST_PLATFORM_WINDOWS) + ticks_t getCurrentTicks() { + static LARGE_INTEGER hz = { {0} }, hzo = { {0} }; + if(!hz.QuadPart) { + QueryPerformanceFrequency(&hz); + QueryPerformanceCounter(&hzo); + } + LARGE_INTEGER t; + QueryPerformanceCounter(&t); + return ((t.QuadPart - hzo.QuadPart) * LONGLONG(1000000)) / hz.QuadPart; + } +#else // DOCTEST_PLATFORM_WINDOWS + ticks_t getCurrentTicks() { + timeval t; + gettimeofday(&t, nullptr); + return static_cast(t.tv_sec) * 1000000 + static_cast(t.tv_usec); + } +#endif // DOCTEST_PLATFORM_WINDOWS + + struct Timer + { + void start() { m_ticks = getCurrentTicks(); } + unsigned int getElapsedMicroseconds() const { + return static_cast(getCurrentTicks() - m_ticks); + } + //unsigned int getElapsedMilliseconds() const { + // return static_cast(getElapsedMicroseconds() / 1000); + //} + double getElapsedSeconds() const { return static_cast(getCurrentTicks() - m_ticks) / 1000000.0; } + + private: + ticks_t m_ticks = 0; + }; + +#ifdef DOCTEST_CONFIG_NO_MULTITHREADING + template + using Atomic = T; +#else // DOCTEST_CONFIG_NO_MULTITHREADING + template + using Atomic = std::atomic; +#endif // DOCTEST_CONFIG_NO_MULTITHREADING + +#if defined(DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS) || defined(DOCTEST_CONFIG_NO_MULTITHREADING) + template + using MultiLaneAtomic = Atomic; +#else // DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS + // Provides a multilane implementation of an atomic variable that supports add, sub, load, + // store. Instead of using a single atomic variable, this splits up into multiple ones, + // each sitting on a separate cache line. The goal is to provide a speedup when most + // operations are modifying. It achieves this with two properties: + // + // * Multiple atomics are used, so chance of congestion from the same atomic is reduced. + // * Each atomic sits on a separate cache line, so false sharing is reduced. + // + // The disadvantage is that there is a small overhead due to the use of TLS, and load/store + // is slower because all atomics have to be accessed. + template + class MultiLaneAtomic + { + struct CacheLineAlignedAtomic + { + Atomic atomic{}; + char padding[DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE - sizeof(Atomic)]; + }; + CacheLineAlignedAtomic m_atomics[DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES]; + + static_assert(sizeof(CacheLineAlignedAtomic) == DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE, + "guarantee one atomic takes exactly one cache line"); + + public: + T operator++() DOCTEST_NOEXCEPT { return fetch_add(1) + 1; } + + T operator++(int) DOCTEST_NOEXCEPT { return fetch_add(1); } + + T fetch_add(T arg, std::memory_order order = std::memory_order_seq_cst) DOCTEST_NOEXCEPT { + return myAtomic().fetch_add(arg, order); + } + + T fetch_sub(T arg, std::memory_order order = std::memory_order_seq_cst) DOCTEST_NOEXCEPT { + return myAtomic().fetch_sub(arg, order); + } + + operator T() const DOCTEST_NOEXCEPT { return load(); } + + T load(std::memory_order order = std::memory_order_seq_cst) const DOCTEST_NOEXCEPT { + auto result = T(); + for(auto const& c : m_atomics) { + result += c.atomic.load(order); + } + return result; + } + + T operator=(T desired) DOCTEST_NOEXCEPT { // lgtm [cpp/assignment-does-not-return-this] + store(desired); + return desired; + } + + void store(T desired, std::memory_order order = std::memory_order_seq_cst) DOCTEST_NOEXCEPT { + // first value becomes desired", all others become 0. + for(auto& c : m_atomics) { + c.atomic.store(desired, order); + desired = {}; + } + } + + private: + // Each thread has a different atomic that it operates on. If more than NumLanes threads + // use this, some will use the same atomic. So performance will degrade a bit, but still + // everything will work. + // + // The logic here is a bit tricky. The call should be as fast as possible, so that there + // is minimal to no overhead in determining the correct atomic for the current thread. + // + // 1. A global static counter laneCounter counts continuously up. + // 2. Each successive thread will use modulo operation of that counter so it gets an atomic + // assigned in a round-robin fashion. + // 3. This tlsLaneIdx is stored in the thread local data, so it is directly available with + // little overhead. + Atomic& myAtomic() DOCTEST_NOEXCEPT { + static Atomic laneCounter; + DOCTEST_THREAD_LOCAL size_t tlsLaneIdx = + laneCounter++ % DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES; + + return m_atomics[tlsLaneIdx].atomic; + } + }; +#endif // DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS + + // this holds both parameters from the command line and runtime data for tests + struct ContextState : ContextOptions, TestRunStats, CurrentTestCaseStats + { + MultiLaneAtomic numAssertsCurrentTest_atomic; + MultiLaneAtomic numAssertsFailedCurrentTest_atomic; + + std::vector> filters = decltype(filters)(9); // 9 different filters + + std::vector reporters_currently_used; + + assert_handler ah = nullptr; + + Timer timer; + + std::vector stringifiedContexts; // logging from INFO() due to an exception + + // stuff for subcases + bool reachedLeaf; + std::vector subcaseStack; + std::vector nextSubcaseStack; + std::unordered_set fullyTraversedSubcases; + size_t currentSubcaseDepth; + Atomic shouldLogCurrentException; + + void resetRunData() { + numTestCases = 0; + numTestCasesPassingFilters = 0; + numTestSuitesPassingFilters = 0; + numTestCasesFailed = 0; + numAsserts = 0; + numAssertsFailed = 0; + numAssertsCurrentTest = 0; + numAssertsFailedCurrentTest = 0; + } + + void finalizeTestCaseData() { + seconds = timer.getElapsedSeconds(); + + // update the non-atomic counters + numAsserts += numAssertsCurrentTest_atomic; + numAssertsFailed += numAssertsFailedCurrentTest_atomic; + numAssertsCurrentTest = numAssertsCurrentTest_atomic; + numAssertsFailedCurrentTest = numAssertsFailedCurrentTest_atomic; + + if(numAssertsFailedCurrentTest) + failure_flags |= TestCaseFailureReason::AssertFailure; + + if(Approx(currentTest->m_timeout).epsilon(DBL_EPSILON) != 0 && + Approx(seconds).epsilon(DBL_EPSILON) > currentTest->m_timeout) + failure_flags |= TestCaseFailureReason::Timeout; + + if(currentTest->m_should_fail) { + if(failure_flags) { + failure_flags |= TestCaseFailureReason::ShouldHaveFailedAndDid; + } else { + failure_flags |= TestCaseFailureReason::ShouldHaveFailedButDidnt; + } + } else if(failure_flags && currentTest->m_may_fail) { + failure_flags |= TestCaseFailureReason::CouldHaveFailedAndDid; + } else if(currentTest->m_expected_failures > 0) { + if(numAssertsFailedCurrentTest == currentTest->m_expected_failures) { + failure_flags |= TestCaseFailureReason::FailedExactlyNumTimes; + } else { + failure_flags |= TestCaseFailureReason::DidntFailExactlyNumTimes; + } + } + + bool ok_to_fail = (TestCaseFailureReason::ShouldHaveFailedAndDid & failure_flags) || + (TestCaseFailureReason::CouldHaveFailedAndDid & failure_flags) || + (TestCaseFailureReason::FailedExactlyNumTimes & failure_flags); + + // if any subcase has failed - the whole test case has failed + testCaseSuccess = !(failure_flags && !ok_to_fail); + if(!testCaseSuccess) + numTestCasesFailed++; + } + }; + + ContextState* g_cs = nullptr; + + // used to avoid locks for the debug output + // TODO: figure out if this is indeed necessary/correct - seems like either there still + // could be a race or that there wouldn't be a race even if using the context directly + DOCTEST_THREAD_LOCAL bool g_no_colors; + +#endif // DOCTEST_CONFIG_DISABLE +} // namespace detail + +char* String::allocate(size_type sz) { + if (sz <= last) { + buf[sz] = '\0'; + setLast(last - sz); + return buf; + } else { + setOnHeap(); + data.size = sz; + data.capacity = data.size + 1; + data.ptr = new char[data.capacity]; + data.ptr[sz] = '\0'; + return data.ptr; + } +} + +void String::setOnHeap() noexcept { *reinterpret_cast(&buf[last]) = 128; } +void String::setLast(size_type in) noexcept { buf[last] = char(in); } +void String::setSize(size_type sz) noexcept { + if (isOnStack()) { buf[sz] = '\0'; setLast(last - sz); } + else { data.ptr[sz] = '\0'; data.size = sz; } +} + +void String::copy(const String& other) { + if(other.isOnStack()) { + memcpy(buf, other.buf, len); + } else { + memcpy(allocate(other.data.size), other.data.ptr, other.data.size); + } +} + +String::String() noexcept { + buf[0] = '\0'; + setLast(); +} + +String::~String() { + if(!isOnStack()) + delete[] data.ptr; +} // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks) + +String::String(const char* in) + : String(in, strlen(in)) {} + +String::String(const char* in, size_type in_size) { + memcpy(allocate(in_size), in, in_size); +} + +String::String(std::istream& in, size_type in_size) { + in.read(allocate(in_size), in_size); +} + +String::String(const String& other) { copy(other); } + +String& String::operator=(const String& other) { + if(this != &other) { + if(!isOnStack()) + delete[] data.ptr; + + copy(other); + } + + return *this; +} + +String& String::operator+=(const String& other) { + const size_type my_old_size = size(); + const size_type other_size = other.size(); + const size_type total_size = my_old_size + other_size; + if(isOnStack()) { + if(total_size < len) { + // append to the current stack space + memcpy(buf + my_old_size, other.c_str(), other_size + 1); + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) + setLast(last - total_size); + } else { + // alloc new chunk + char* temp = new char[total_size + 1]; + // copy current data to new location before writing in the union + memcpy(temp, buf, my_old_size); // skip the +1 ('\0') for speed + // update data in union + setOnHeap(); + data.size = total_size; + data.capacity = data.size + 1; + data.ptr = temp; + // transfer the rest of the data + memcpy(data.ptr + my_old_size, other.c_str(), other_size + 1); + } + } else { + if(data.capacity > total_size) { + // append to the current heap block + data.size = total_size; + memcpy(data.ptr + my_old_size, other.c_str(), other_size + 1); + } else { + // resize + data.capacity *= 2; + if(data.capacity <= total_size) + data.capacity = total_size + 1; + // alloc new chunk + char* temp = new char[data.capacity]; + // copy current data to new location before releasing it + memcpy(temp, data.ptr, my_old_size); // skip the +1 ('\0') for speed + // release old chunk + delete[] data.ptr; + // update the rest of the union members + data.size = total_size; + data.ptr = temp; + // transfer the rest of the data + memcpy(data.ptr + my_old_size, other.c_str(), other_size + 1); + } + } + + return *this; +} + +String::String(String&& other) noexcept { + memcpy(buf, other.buf, len); + other.buf[0] = '\0'; + other.setLast(); +} + +String& String::operator=(String&& other) noexcept { + if(this != &other) { + if(!isOnStack()) + delete[] data.ptr; + memcpy(buf, other.buf, len); + other.buf[0] = '\0'; + other.setLast(); + } + return *this; +} + +char String::operator[](size_type i) const { + return const_cast(this)->operator[](i); +} + +char& String::operator[](size_type i) { + if(isOnStack()) + return reinterpret_cast(buf)[i]; + return data.ptr[i]; +} + +DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wmaybe-uninitialized") +String::size_type String::size() const { + if(isOnStack()) + return last - (size_type(buf[last]) & 31); // using "last" would work only if "len" is 32 + return data.size; +} +DOCTEST_GCC_SUPPRESS_WARNING_POP + +String::size_type String::capacity() const { + if(isOnStack()) + return len; + return data.capacity; +} + +String String::substr(size_type pos, size_type cnt) && { + cnt = std::min(cnt, size() - 1 - pos); + char* cptr = c_str(); + memmove(cptr, cptr + pos, cnt); + setSize(cnt); + return std::move(*this); +} + +String String::substr(size_type pos, size_type cnt) const & { + cnt = std::min(cnt, size() - 1 - pos); + return String{ c_str() + pos, cnt }; +} + +String::size_type String::find(char ch, size_type pos) const { + const char* begin = c_str(); + const char* end = begin + size(); + const char* it = begin + pos; + for (; it < end && *it != ch; it++); + if (it < end) { return static_cast(it - begin); } + else { return npos; } +} + +String::size_type String::rfind(char ch, size_type pos) const { + const char* begin = c_str(); + const char* it = begin + std::min(pos, size() - 1); + for (; it >= begin && *it != ch; it--); + if (it >= begin) { return static_cast(it - begin); } + else { return npos; } +} + +int String::compare(const char* other, bool no_case) const { + if(no_case) + return doctest::stricmp(c_str(), other); + return std::strcmp(c_str(), other); +} + +int String::compare(const String& other, bool no_case) const { + return compare(other.c_str(), no_case); +} + +String operator+(const String& lhs, const String& rhs) { return String(lhs) += rhs; } + +bool operator==(const String& lhs, const String& rhs) { return lhs.compare(rhs) == 0; } +bool operator!=(const String& lhs, const String& rhs) { return lhs.compare(rhs) != 0; } +bool operator< (const String& lhs, const String& rhs) { return lhs.compare(rhs) < 0; } +bool operator> (const String& lhs, const String& rhs) { return lhs.compare(rhs) > 0; } +bool operator<=(const String& lhs, const String& rhs) { return (lhs != rhs) ? lhs.compare(rhs) < 0 : true; } +bool operator>=(const String& lhs, const String& rhs) { return (lhs != rhs) ? lhs.compare(rhs) > 0 : true; } + +std::ostream& operator<<(std::ostream& s, const String& in) { return s << in.c_str(); } + +Contains::Contains(const String& str) : string(str) { } + +bool Contains::checkWith(const String& other) const { + return strstr(other.c_str(), string.c_str()) != nullptr; +} + +String toString(const Contains& in) { + return "Contains( " + in.string + " )"; +} + +bool operator==(const String& lhs, const Contains& rhs) { return rhs.checkWith(lhs); } +bool operator==(const Contains& lhs, const String& rhs) { return lhs.checkWith(rhs); } +bool operator!=(const String& lhs, const Contains& rhs) { return !rhs.checkWith(lhs); } +bool operator!=(const Contains& lhs, const String& rhs) { return !lhs.checkWith(rhs); } + +namespace { + void color_to_stream(std::ostream&, Color::Enum) DOCTEST_BRANCH_ON_DISABLED({}, ;) +} // namespace + +namespace Color { + std::ostream& operator<<(std::ostream& s, Color::Enum code) { + color_to_stream(s, code); + return s; + } +} // namespace Color + +// clang-format off +const char* assertString(assertType::Enum at) { + DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4061) // enum 'x' in switch of enum 'y' is not explicitly handled + #define DOCTEST_GENERATE_ASSERT_TYPE_CASE(assert_type) case assertType::DT_ ## assert_type: return #assert_type + #define DOCTEST_GENERATE_ASSERT_TYPE_CASES(assert_type) \ + DOCTEST_GENERATE_ASSERT_TYPE_CASE(WARN_ ## assert_type); \ + DOCTEST_GENERATE_ASSERT_TYPE_CASE(CHECK_ ## assert_type); \ + DOCTEST_GENERATE_ASSERT_TYPE_CASE(REQUIRE_ ## assert_type) + switch(at) { + DOCTEST_GENERATE_ASSERT_TYPE_CASE(WARN); + DOCTEST_GENERATE_ASSERT_TYPE_CASE(CHECK); + DOCTEST_GENERATE_ASSERT_TYPE_CASE(REQUIRE); + + DOCTEST_GENERATE_ASSERT_TYPE_CASES(FALSE); + + DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS); + + DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS_AS); + + DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS_WITH); + + DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS_WITH_AS); + + DOCTEST_GENERATE_ASSERT_TYPE_CASES(NOTHROW); + + DOCTEST_GENERATE_ASSERT_TYPE_CASES(EQ); + DOCTEST_GENERATE_ASSERT_TYPE_CASES(NE); + DOCTEST_GENERATE_ASSERT_TYPE_CASES(GT); + DOCTEST_GENERATE_ASSERT_TYPE_CASES(LT); + DOCTEST_GENERATE_ASSERT_TYPE_CASES(GE); + DOCTEST_GENERATE_ASSERT_TYPE_CASES(LE); + + DOCTEST_GENERATE_ASSERT_TYPE_CASES(UNARY); + DOCTEST_GENERATE_ASSERT_TYPE_CASES(UNARY_FALSE); + + default: DOCTEST_INTERNAL_ERROR("Tried stringifying invalid assert type!"); + } + DOCTEST_MSVC_SUPPRESS_WARNING_POP +} +// clang-format on + +const char* failureString(assertType::Enum at) { + if(at & assertType::is_warn) //!OCLINT bitwise operator in conditional + return "WARNING"; + if(at & assertType::is_check) //!OCLINT bitwise operator in conditional + return "ERROR"; + if(at & assertType::is_require) //!OCLINT bitwise operator in conditional + return "FATAL ERROR"; + return ""; +} + +DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wnull-dereference") +DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wnull-dereference") +// depending on the current options this will remove the path of filenames +const char* skipPathFromFilename(const char* file) { +#ifndef DOCTEST_CONFIG_DISABLE + if(getContextOptions()->no_path_in_filenames) { + auto back = std::strrchr(file, '\\'); + auto forward = std::strrchr(file, '/'); + if(back || forward) { + if(back > forward) + forward = back; + return forward + 1; + } + } +#endif // DOCTEST_CONFIG_DISABLE + return file; +} +DOCTEST_CLANG_SUPPRESS_WARNING_POP +DOCTEST_GCC_SUPPRESS_WARNING_POP + +bool SubcaseSignature::operator==(const SubcaseSignature& other) const { + return m_line == other.m_line + && std::strcmp(m_file, other.m_file) == 0 + && m_name == other.m_name; +} + +bool SubcaseSignature::operator<(const SubcaseSignature& other) const { + if(m_line != other.m_line) + return m_line < other.m_line; + if(std::strcmp(m_file, other.m_file) != 0) + return std::strcmp(m_file, other.m_file) < 0; + return m_name.compare(other.m_name) < 0; +} + +DOCTEST_DEFINE_INTERFACE(IContextScope) + +namespace detail { + void filldata::fill(std::ostream* stream, const void* in) { + if (in) { *stream << in; } + else { *stream << "nullptr"; } + } + + template + String toStreamLit(T t) { + std::ostream* os = tlssPush(); + os->operator<<(t); + return tlssPop(); + } +} + +#ifdef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING +String toString(const char* in) { return String("\"") + (in ? in : "{null string}") + "\""; } +#endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING + +#if DOCTEST_MSVC >= DOCTEST_COMPILER(19, 20, 0) +// see this issue on why this is needed: https://github.com/doctest/doctest/issues/183 +String toString(const std::string& in) { return in.c_str(); } +#endif // VS 2019 + +String toString(String in) { return in; } + +String toString(std::nullptr_t) { return "nullptr"; } + +String toString(bool in) { return in ? "true" : "false"; } + +String toString(float in) { return toStreamLit(in); } +String toString(double in) { return toStreamLit(in); } +String toString(double long in) { return toStreamLit(in); } + +String toString(char in) { return toStreamLit(static_cast(in)); } +String toString(char signed in) { return toStreamLit(static_cast(in)); } +String toString(char unsigned in) { return toStreamLit(static_cast(in)); } +String toString(short in) { return toStreamLit(in); } +String toString(short unsigned in) { return toStreamLit(in); } +String toString(signed in) { return toStreamLit(in); } +String toString(unsigned in) { return toStreamLit(in); } +String toString(long in) { return toStreamLit(in); } +String toString(long unsigned in) { return toStreamLit(in); } +String toString(long long in) { return toStreamLit(in); } +String toString(long long unsigned in) { return toStreamLit(in); } + +Approx::Approx(double value) + : m_epsilon(static_cast(std::numeric_limits::epsilon()) * 100) + , m_scale(1.0) + , m_value(value) {} + +Approx Approx::operator()(double value) const { + Approx approx(value); + approx.epsilon(m_epsilon); + approx.scale(m_scale); + return approx; +} + +Approx& Approx::epsilon(double newEpsilon) { + m_epsilon = newEpsilon; + return *this; +} +Approx& Approx::scale(double newScale) { + m_scale = newScale; + return *this; +} + +bool operator==(double lhs, const Approx& rhs) { + // Thanks to Richard Harris for his help refining this formula + return std::fabs(lhs - rhs.m_value) < + rhs.m_epsilon * (rhs.m_scale + std::max(std::fabs(lhs), std::fabs(rhs.m_value))); +} +bool operator==(const Approx& lhs, double rhs) { return operator==(rhs, lhs); } +bool operator!=(double lhs, const Approx& rhs) { return !operator==(lhs, rhs); } +bool operator!=(const Approx& lhs, double rhs) { return !operator==(rhs, lhs); } +bool operator<=(double lhs, const Approx& rhs) { return lhs < rhs.m_value || lhs == rhs; } +bool operator<=(const Approx& lhs, double rhs) { return lhs.m_value < rhs || lhs == rhs; } +bool operator>=(double lhs, const Approx& rhs) { return lhs > rhs.m_value || lhs == rhs; } +bool operator>=(const Approx& lhs, double rhs) { return lhs.m_value > rhs || lhs == rhs; } +bool operator<(double lhs, const Approx& rhs) { return lhs < rhs.m_value && lhs != rhs; } +bool operator<(const Approx& lhs, double rhs) { return lhs.m_value < rhs && lhs != rhs; } +bool operator>(double lhs, const Approx& rhs) { return lhs > rhs.m_value && lhs != rhs; } +bool operator>(const Approx& lhs, double rhs) { return lhs.m_value > rhs && lhs != rhs; } + +String toString(const Approx& in) { + return "Approx( " + doctest::toString(in.m_value) + " )"; +} +const ContextOptions* getContextOptions() { return DOCTEST_BRANCH_ON_DISABLED(nullptr, g_cs); } + +DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4738) +template +IsNaN::operator bool() const { + return std::isnan(value) ^ flipped; +} +DOCTEST_MSVC_SUPPRESS_WARNING_POP +template struct DOCTEST_INTERFACE_DEF IsNaN; +template struct DOCTEST_INTERFACE_DEF IsNaN; +template struct DOCTEST_INTERFACE_DEF IsNaN; +template +String toString(IsNaN in) { return String(in.flipped ? "! " : "") + "IsNaN( " + doctest::toString(in.value) + " )"; } +String toString(IsNaN in) { return toString(in); } +String toString(IsNaN in) { return toString(in); } +String toString(IsNaN in) { return toString(in); } + +} // namespace doctest + +#ifdef DOCTEST_CONFIG_DISABLE +namespace doctest { +Context::Context(int, const char* const*) {} +Context::~Context() = default; +void Context::applyCommandLine(int, const char* const*) {} +void Context::addFilter(const char*, const char*) {} +void Context::clearFilters() {} +void Context::setOption(const char*, bool) {} +void Context::setOption(const char*, int) {} +void Context::setOption(const char*, const char*) {} +bool Context::shouldExit() { return false; } +void Context::setAsDefaultForAssertsOutOfTestCases() {} +void Context::setAssertHandler(detail::assert_handler) {} +void Context::setCout(std::ostream*) {} +int Context::run() { return 0; } + +int IReporter::get_num_active_contexts() { return 0; } +const IContextScope* const* IReporter::get_active_contexts() { return nullptr; } +int IReporter::get_num_stringified_contexts() { return 0; } +const String* IReporter::get_stringified_contexts() { return nullptr; } + +int registerReporter(const char*, int, IReporter*) { return 0; } + +} // namespace doctest +#else // DOCTEST_CONFIG_DISABLE + +#if !defined(DOCTEST_CONFIG_COLORS_NONE) +#if !defined(DOCTEST_CONFIG_COLORS_WINDOWS) && !defined(DOCTEST_CONFIG_COLORS_ANSI) +#ifdef DOCTEST_PLATFORM_WINDOWS +#define DOCTEST_CONFIG_COLORS_WINDOWS +#else // linux +#define DOCTEST_CONFIG_COLORS_ANSI +#endif // platform +#endif // DOCTEST_CONFIG_COLORS_WINDOWS && DOCTEST_CONFIG_COLORS_ANSI +#endif // DOCTEST_CONFIG_COLORS_NONE + +namespace doctest_detail_test_suite_ns { +// holds the current test suite +doctest::detail::TestSuite& getCurrentTestSuite() { + static doctest::detail::TestSuite data{}; + return data; +} +} // namespace doctest_detail_test_suite_ns + +namespace doctest { +namespace { + // the int (priority) is part of the key for automatic sorting - sadly one can register a + // reporter with a duplicate name and a different priority but hopefully that won't happen often :| + using reporterMap = std::map, reporterCreatorFunc>; + + reporterMap& getReporters() { + static reporterMap data; + return data; + } + reporterMap& getListeners() { + static reporterMap data; + return data; + } +} // namespace +namespace detail { +#define DOCTEST_ITERATE_THROUGH_REPORTERS(function, ...) \ + for(auto& curr_rep : g_cs->reporters_currently_used) \ + curr_rep->function(__VA_ARGS__) + + bool checkIfShouldThrow(assertType::Enum at) { + if(at & assertType::is_require) //!OCLINT bitwise operator in conditional + return true; + + if((at & assertType::is_check) //!OCLINT bitwise operator in conditional + && getContextOptions()->abort_after > 0 && + (g_cs->numAssertsFailed + g_cs->numAssertsFailedCurrentTest_atomic) >= + getContextOptions()->abort_after) + return true; + + return false; + } + +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + DOCTEST_NORETURN void throwException() { + g_cs->shouldLogCurrentException = false; + throw TestFailureException(); // NOLINT(hicpp-exception-baseclass) + } +#else // DOCTEST_CONFIG_NO_EXCEPTIONS + void throwException() {} +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS +} // namespace detail + +namespace { + using namespace detail; + // matching of a string against a wildcard mask (case sensitivity configurable) taken from + // https://www.codeproject.com/Articles/1088/Wildcard-string-compare-globbing + int wildcmp(const char* str, const char* wild, bool caseSensitive) { + const char* cp = str; + const char* mp = wild; + + while((*str) && (*wild != '*')) { + if((caseSensitive ? (*wild != *str) : (tolower(*wild) != tolower(*str))) && + (*wild != '?')) { + return 0; + } + wild++; + str++; + } + + while(*str) { + if(*wild == '*') { + if(!*++wild) { + return 1; + } + mp = wild; + cp = str + 1; + } else if((caseSensitive ? (*wild == *str) : (tolower(*wild) == tolower(*str))) || + (*wild == '?')) { + wild++; + str++; + } else { + wild = mp; //!OCLINT parameter reassignment + str = cp++; //!OCLINT parameter reassignment + } + } + + while(*wild == '*') { + wild++; + } + return !*wild; + } + + // checks if the name matches any of the filters (and can be configured what to do when empty) + bool matchesAny(const char* name, const std::vector& filters, bool matchEmpty, + bool caseSensitive) { + if (filters.empty() && matchEmpty) + return true; + for (auto& curr : filters) + if (wildcmp(name, curr.c_str(), caseSensitive)) + return true; + return false; + } + + DOCTEST_NO_SANITIZE_INTEGER + unsigned long long hash(unsigned long long a, unsigned long long b) { + return (a << 5) + b; + } + + // C string hash function (djb2) - taken from http://www.cse.yorku.ca/~oz/hash.html + DOCTEST_NO_SANITIZE_INTEGER + unsigned long long hash(const char* str) { + unsigned long long hash = 5381; + char c; + while ((c = *str++)) + hash = ((hash << 5) + hash) + c; // hash * 33 + c + return hash; + } + + unsigned long long hash(const SubcaseSignature& sig) { + return hash(hash(hash(sig.m_file), hash(sig.m_name.c_str())), sig.m_line); + } + + unsigned long long hash(const std::vector& sigs, size_t count) { + unsigned long long running = 0; + auto end = sigs.begin() + count; + for (auto it = sigs.begin(); it != end; it++) { + running = hash(running, hash(*it)); + } + return running; + } + + unsigned long long hash(const std::vector& sigs) { + unsigned long long running = 0; + for (const SubcaseSignature& sig : sigs) { + running = hash(running, hash(sig)); + } + return running; + } +} // namespace +namespace detail { + bool Subcase::checkFilters() { + if (g_cs->subcaseStack.size() < size_t(g_cs->subcase_filter_levels)) { + if (!matchesAny(m_signature.m_name.c_str(), g_cs->filters[6], true, g_cs->case_sensitive)) + return true; + if (matchesAny(m_signature.m_name.c_str(), g_cs->filters[7], false, g_cs->case_sensitive)) + return true; + } + return false; + } + + Subcase::Subcase(const String& name, const char* file, int line) + : m_signature({name, file, line}) { + if (!g_cs->reachedLeaf) { + if (g_cs->nextSubcaseStack.size() <= g_cs->subcaseStack.size() + || g_cs->nextSubcaseStack[g_cs->subcaseStack.size()] == m_signature) { + // Going down. + if (checkFilters()) { return; } + + g_cs->subcaseStack.push_back(m_signature); + g_cs->currentSubcaseDepth++; + m_entered = true; + DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_start, m_signature); + } + } else { + if (g_cs->subcaseStack[g_cs->currentSubcaseDepth] == m_signature) { + // This subcase is reentered via control flow. + g_cs->currentSubcaseDepth++; + m_entered = true; + DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_start, m_signature); + } else if (g_cs->nextSubcaseStack.size() <= g_cs->currentSubcaseDepth + && g_cs->fullyTraversedSubcases.find(hash(hash(g_cs->subcaseStack, g_cs->currentSubcaseDepth), hash(m_signature))) + == g_cs->fullyTraversedSubcases.end()) { + if (checkFilters()) { return; } + // This subcase is part of the one to be executed next. + g_cs->nextSubcaseStack.clear(); + g_cs->nextSubcaseStack.insert(g_cs->nextSubcaseStack.end(), + g_cs->subcaseStack.begin(), g_cs->subcaseStack.begin() + g_cs->currentSubcaseDepth); + g_cs->nextSubcaseStack.push_back(m_signature); + } + } + } + + DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4996) // std::uncaught_exception is deprecated in C++17 + DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") + DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") + + Subcase::~Subcase() { + if (m_entered) { + g_cs->currentSubcaseDepth--; + + if (!g_cs->reachedLeaf) { + // Leaf. + g_cs->fullyTraversedSubcases.insert(hash(g_cs->subcaseStack)); + g_cs->nextSubcaseStack.clear(); + g_cs->reachedLeaf = true; + } else if (g_cs->nextSubcaseStack.empty()) { + // All children are finished. + g_cs->fullyTraversedSubcases.insert(hash(g_cs->subcaseStack)); + } + +#if defined(__cpp_lib_uncaught_exceptions) && __cpp_lib_uncaught_exceptions >= 201411L && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200) + if(std::uncaught_exceptions() > 0 +#else + if(std::uncaught_exception() +#endif + && g_cs->shouldLogCurrentException) { + DOCTEST_ITERATE_THROUGH_REPORTERS( + test_case_exception, {"exception thrown in subcase - will translate later " + "when the whole test case has been exited (cannot " + "translate while there is an active exception)", + false}); + g_cs->shouldLogCurrentException = false; + } + + DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_end, DOCTEST_EMPTY); + } + } + + DOCTEST_CLANG_SUPPRESS_WARNING_POP + DOCTEST_GCC_SUPPRESS_WARNING_POP + DOCTEST_MSVC_SUPPRESS_WARNING_POP + + Subcase::operator bool() const { return m_entered; } + + Result::Result(bool passed, const String& decomposition) + : m_passed(passed) + , m_decomp(decomposition) {} + + ExpressionDecomposer::ExpressionDecomposer(assertType::Enum at) + : m_at(at) {} + + TestSuite& TestSuite::operator*(const char* in) { + m_test_suite = in; + return *this; + } + + TestCase::TestCase(funcType test, const char* file, unsigned line, const TestSuite& test_suite, + const String& type, int template_id) { + m_file = file; + m_line = line; + m_name = nullptr; // will be later overridden in operator* + m_test_suite = test_suite.m_test_suite; + m_description = test_suite.m_description; + m_skip = test_suite.m_skip; + m_no_breaks = test_suite.m_no_breaks; + m_no_output = test_suite.m_no_output; + m_may_fail = test_suite.m_may_fail; + m_should_fail = test_suite.m_should_fail; + m_expected_failures = test_suite.m_expected_failures; + m_timeout = test_suite.m_timeout; + + m_test = test; + m_type = type; + m_template_id = template_id; + } + + TestCase::TestCase(const TestCase& other) + : TestCaseData() { + *this = other; + } + + DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(26434) // hides a non-virtual function + TestCase& TestCase::operator=(const TestCase& other) { + TestCaseData::operator=(other); + m_test = other.m_test; + m_type = other.m_type; + m_template_id = other.m_template_id; + m_full_name = other.m_full_name; + + if(m_template_id != -1) + m_name = m_full_name.c_str(); + return *this; + } + DOCTEST_MSVC_SUPPRESS_WARNING_POP + + TestCase& TestCase::operator*(const char* in) { + m_name = in; + // make a new name with an appended type for templated test case + if(m_template_id != -1) { + m_full_name = String(m_name) + "<" + m_type + ">"; + // redirect the name to point to the newly constructed full name + m_name = m_full_name.c_str(); + } + return *this; + } + + bool TestCase::operator<(const TestCase& other) const { + // this will be used only to differentiate between test cases - not relevant for sorting + if(m_line != other.m_line) + return m_line < other.m_line; + const int name_cmp = strcmp(m_name, other.m_name); + if(name_cmp != 0) + return name_cmp < 0; + const int file_cmp = m_file.compare(other.m_file); + if(file_cmp != 0) + return file_cmp < 0; + return m_template_id < other.m_template_id; + } + + // all the registered tests + std::set& getRegisteredTests() { + static std::set data; + return data; + } +} // namespace detail +namespace { + using namespace detail; + // for sorting tests by file/line + bool fileOrderComparator(const TestCase* lhs, const TestCase* rhs) { + // this is needed because MSVC gives different case for drive letters + // for __FILE__ when evaluated in a header and a source file + const int res = lhs->m_file.compare(rhs->m_file, bool(DOCTEST_MSVC)); + if(res != 0) + return res < 0; + if(lhs->m_line != rhs->m_line) + return lhs->m_line < rhs->m_line; + return lhs->m_template_id < rhs->m_template_id; + } + + // for sorting tests by suite/file/line + bool suiteOrderComparator(const TestCase* lhs, const TestCase* rhs) { + const int res = std::strcmp(lhs->m_test_suite, rhs->m_test_suite); + if(res != 0) + return res < 0; + return fileOrderComparator(lhs, rhs); + } + + // for sorting tests by name/suite/file/line + bool nameOrderComparator(const TestCase* lhs, const TestCase* rhs) { + const int res = std::strcmp(lhs->m_name, rhs->m_name); + if(res != 0) + return res < 0; + return suiteOrderComparator(lhs, rhs); + } + + DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") + void color_to_stream(std::ostream& s, Color::Enum code) { + static_cast(s); // for DOCTEST_CONFIG_COLORS_NONE or DOCTEST_CONFIG_COLORS_WINDOWS + static_cast(code); // for DOCTEST_CONFIG_COLORS_NONE +#ifdef DOCTEST_CONFIG_COLORS_ANSI + if(g_no_colors || + (isatty(STDOUT_FILENO) == false && getContextOptions()->force_colors == false)) + return; + + auto col = ""; + // clang-format off + switch(code) { //!OCLINT missing break in switch statement / unnecessary default statement in covered switch statement + case Color::Red: col = "[0;31m"; break; + case Color::Green: col = "[0;32m"; break; + case Color::Blue: col = "[0;34m"; break; + case Color::Cyan: col = "[0;36m"; break; + case Color::Yellow: col = "[0;33m"; break; + case Color::Grey: col = "[1;30m"; break; + case Color::LightGrey: col = "[0;37m"; break; + case Color::BrightRed: col = "[1;31m"; break; + case Color::BrightGreen: col = "[1;32m"; break; + case Color::BrightWhite: col = "[1;37m"; break; + case Color::Bright: // invalid + case Color::None: + case Color::White: + default: col = "[0m"; + } + // clang-format on + s << "\033" << col; +#endif // DOCTEST_CONFIG_COLORS_ANSI + +#ifdef DOCTEST_CONFIG_COLORS_WINDOWS + if(g_no_colors || + (_isatty(_fileno(stdout)) == false && getContextOptions()->force_colors == false)) + return; + + static struct ConsoleHelper { + HANDLE stdoutHandle; + WORD origFgAttrs; + WORD origBgAttrs; + + ConsoleHelper() { + stdoutHandle = GetStdHandle(STD_OUTPUT_HANDLE); + CONSOLE_SCREEN_BUFFER_INFO csbiInfo; + GetConsoleScreenBufferInfo(stdoutHandle, &csbiInfo); + origFgAttrs = csbiInfo.wAttributes & ~(BACKGROUND_GREEN | BACKGROUND_RED | + BACKGROUND_BLUE | BACKGROUND_INTENSITY); + origBgAttrs = csbiInfo.wAttributes & ~(FOREGROUND_GREEN | FOREGROUND_RED | + FOREGROUND_BLUE | FOREGROUND_INTENSITY); + } + } ch; + +#define DOCTEST_SET_ATTR(x) SetConsoleTextAttribute(ch.stdoutHandle, x | ch.origBgAttrs) + + // clang-format off + switch (code) { + case Color::White: DOCTEST_SET_ATTR(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE); break; + case Color::Red: DOCTEST_SET_ATTR(FOREGROUND_RED); break; + case Color::Green: DOCTEST_SET_ATTR(FOREGROUND_GREEN); break; + case Color::Blue: DOCTEST_SET_ATTR(FOREGROUND_BLUE); break; + case Color::Cyan: DOCTEST_SET_ATTR(FOREGROUND_BLUE | FOREGROUND_GREEN); break; + case Color::Yellow: DOCTEST_SET_ATTR(FOREGROUND_RED | FOREGROUND_GREEN); break; + case Color::Grey: DOCTEST_SET_ATTR(0); break; + case Color::LightGrey: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY); break; + case Color::BrightRed: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY | FOREGROUND_RED); break; + case Color::BrightGreen: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY | FOREGROUND_GREEN); break; + case Color::BrightWhite: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE); break; + case Color::None: + case Color::Bright: // invalid + default: DOCTEST_SET_ATTR(ch.origFgAttrs); + } + // clang-format on +#endif // DOCTEST_CONFIG_COLORS_WINDOWS + } + DOCTEST_CLANG_SUPPRESS_WARNING_POP + + std::vector& getExceptionTranslators() { + static std::vector data; + return data; + } + + String translateActiveException() { +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + String res; + auto& translators = getExceptionTranslators(); + for(auto& curr : translators) + if(curr->translate(res)) + return res; + // clang-format off + DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wcatch-value") + try { + throw; + } catch(std::exception& ex) { + return ex.what(); + } catch(std::string& msg) { + return msg.c_str(); + } catch(const char* msg) { + return msg; + } catch(...) { + return "unknown exception"; + } + DOCTEST_GCC_SUPPRESS_WARNING_POP +// clang-format on +#else // DOCTEST_CONFIG_NO_EXCEPTIONS + return ""; +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + } +} // namespace + +namespace detail { + // used by the macros for registering tests + int regTest(const TestCase& tc) { + getRegisteredTests().insert(tc); + return 0; + } + + // sets the current test suite + int setTestSuite(const TestSuite& ts) { + doctest_detail_test_suite_ns::getCurrentTestSuite() = ts; + return 0; + } + +#ifdef DOCTEST_IS_DEBUGGER_ACTIVE + bool isDebuggerActive() { return DOCTEST_IS_DEBUGGER_ACTIVE(); } +#else // DOCTEST_IS_DEBUGGER_ACTIVE +#ifdef DOCTEST_PLATFORM_LINUX + class ErrnoGuard { + public: + ErrnoGuard() : m_oldErrno(errno) {} + ~ErrnoGuard() { errno = m_oldErrno; } + private: + int m_oldErrno; + }; + // See the comments in Catch2 for the reasoning behind this implementation: + // https://github.com/catchorg/Catch2/blob/v2.13.1/include/internal/catch_debugger.cpp#L79-L102 + bool isDebuggerActive() { + ErrnoGuard guard; + std::ifstream in("/proc/self/status"); + for(std::string line; std::getline(in, line);) { + static const int PREFIX_LEN = 11; + if(line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0) { + return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0'; + } + } + return false; + } +#elif defined(DOCTEST_PLATFORM_MAC) + // The following function is taken directly from the following technical note: + // https://developer.apple.com/library/archive/qa/qa1361/_index.html + // Returns true if the current process is being debugged (either + // running under the debugger or has a debugger attached post facto). + bool isDebuggerActive() { + int mib[4]; + kinfo_proc info; + size_t size; + // Initialize the flags so that, if sysctl fails for some bizarre + // reason, we get a predictable result. + info.kp_proc.p_flag = 0; + // Initialize mib, which tells sysctl the info we want, in this case + // we're looking for information about a specific process ID. + mib[0] = CTL_KERN; + mib[1] = KERN_PROC; + mib[2] = KERN_PROC_PID; + mib[3] = getpid(); + // Call sysctl. + size = sizeof(info); + if(sysctl(mib, DOCTEST_COUNTOF(mib), &info, &size, 0, 0) != 0) { + std::cerr << "\nCall to sysctl failed - unable to determine if debugger is active **\n"; + return false; + } + // We're being debugged if the P_TRACED flag is set. + return ((info.kp_proc.p_flag & P_TRACED) != 0); + } +#elif DOCTEST_MSVC || defined(__MINGW32__) || defined(__MINGW64__) + bool isDebuggerActive() { return ::IsDebuggerPresent() != 0; } +#else + bool isDebuggerActive() { return false; } +#endif // Platform +#endif // DOCTEST_IS_DEBUGGER_ACTIVE + + void registerExceptionTranslatorImpl(const IExceptionTranslator* et) { + if(std::find(getExceptionTranslators().begin(), getExceptionTranslators().end(), et) == + getExceptionTranslators().end()) + getExceptionTranslators().push_back(et); + } + + DOCTEST_THREAD_LOCAL std::vector g_infoContexts; // for logging with INFO() + + ContextScopeBase::ContextScopeBase() { + g_infoContexts.push_back(this); + } + + ContextScopeBase::ContextScopeBase(ContextScopeBase&& other) noexcept { + if (other.need_to_destroy) { + other.destroy(); + } + other.need_to_destroy = false; + g_infoContexts.push_back(this); + } + + DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4996) // std::uncaught_exception is deprecated in C++17 + DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") + DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") + + // destroy cannot be inlined into the destructor because that would mean calling stringify after + // ContextScope has been destroyed (base class destructors run after derived class destructors). + // Instead, ContextScope calls this method directly from its destructor. + void ContextScopeBase::destroy() { +#if defined(__cpp_lib_uncaught_exceptions) && __cpp_lib_uncaught_exceptions >= 201411L && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200) + if(std::uncaught_exceptions() > 0) { +#else + if(std::uncaught_exception()) { +#endif + std::ostringstream s; + this->stringify(&s); + g_cs->stringifiedContexts.push_back(s.str().c_str()); + } + g_infoContexts.pop_back(); + } + + DOCTEST_CLANG_SUPPRESS_WARNING_POP + DOCTEST_GCC_SUPPRESS_WARNING_POP + DOCTEST_MSVC_SUPPRESS_WARNING_POP +} // namespace detail +namespace { + using namespace detail; + +#if !defined(DOCTEST_CONFIG_POSIX_SIGNALS) && !defined(DOCTEST_CONFIG_WINDOWS_SEH) + struct FatalConditionHandler + { + static void reset() {} + static void allocateAltStackMem() {} + static void freeAltStackMem() {} + }; +#else // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH + + void reportFatal(const std::string&); + +#ifdef DOCTEST_PLATFORM_WINDOWS + + struct SignalDefs + { + DWORD id; + const char* name; + }; + // There is no 1-1 mapping between signals and windows exceptions. + // Windows can easily distinguish between SO and SigSegV, + // but SigInt, SigTerm, etc are handled differently. + SignalDefs signalDefs[] = { + {static_cast(EXCEPTION_ILLEGAL_INSTRUCTION), + "SIGILL - Illegal instruction signal"}, + {static_cast(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow"}, + {static_cast(EXCEPTION_ACCESS_VIOLATION), + "SIGSEGV - Segmentation violation signal"}, + {static_cast(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error"}, + }; + + struct FatalConditionHandler + { + static LONG CALLBACK handleException(PEXCEPTION_POINTERS ExceptionInfo) { + // Multiple threads may enter this filter/handler at once. We want the error message to be printed on the + // console just once no matter how many threads have crashed. + DOCTEST_DECLARE_STATIC_MUTEX(mutex) + static bool execute = true; + { + DOCTEST_LOCK_MUTEX(mutex) + if(execute) { + bool reported = false; + for(size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { + if(ExceptionInfo->ExceptionRecord->ExceptionCode == signalDefs[i].id) { + reportFatal(signalDefs[i].name); + reported = true; + break; + } + } + if(reported == false) + reportFatal("Unhandled SEH exception caught"); + if(isDebuggerActive() && !g_cs->no_breaks) + DOCTEST_BREAK_INTO_DEBUGGER(); + } + execute = false; + } + std::exit(EXIT_FAILURE); + } + + static void allocateAltStackMem() {} + static void freeAltStackMem() {} + + FatalConditionHandler() { + isSet = true; + // 32k seems enough for doctest to handle stack overflow, + // but the value was found experimentally, so there is no strong guarantee + guaranteeSize = 32 * 1024; + // Register an unhandled exception filter + previousTop = SetUnhandledExceptionFilter(handleException); + // Pass in guarantee size to be filled + SetThreadStackGuarantee(&guaranteeSize); + + // On Windows uncaught exceptions from another thread, exceptions from + // destructors, or calls to std::terminate are not a SEH exception + + // The terminal handler gets called when: + // - std::terminate is called FROM THE TEST RUNNER THREAD + // - an exception is thrown from a destructor FROM THE TEST RUNNER THREAD + original_terminate_handler = std::get_terminate(); + std::set_terminate([]() DOCTEST_NOEXCEPT { + reportFatal("Terminate handler called"); + if(isDebuggerActive() && !g_cs->no_breaks) + DOCTEST_BREAK_INTO_DEBUGGER(); + std::exit(EXIT_FAILURE); // explicitly exit - otherwise the SIGABRT handler may be called as well + }); + + // SIGABRT is raised when: + // - std::terminate is called FROM A DIFFERENT THREAD + // - an exception is thrown from a destructor FROM A DIFFERENT THREAD + // - an uncaught exception is thrown FROM A DIFFERENT THREAD + prev_sigabrt_handler = std::signal(SIGABRT, [](int signal) DOCTEST_NOEXCEPT { + if(signal == SIGABRT) { + reportFatal("SIGABRT - Abort (abnormal termination) signal"); + if(isDebuggerActive() && !g_cs->no_breaks) + DOCTEST_BREAK_INTO_DEBUGGER(); + std::exit(EXIT_FAILURE); + } + }); + + // The following settings are taken from google test, and more + // specifically from UnitTest::Run() inside of gtest.cc + + // the user does not want to see pop-up dialogs about crashes + prev_error_mode_1 = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | + SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); + // This forces the abort message to go to stderr in all circumstances. + prev_error_mode_2 = _set_error_mode(_OUT_TO_STDERR); + // In the debug version, Visual Studio pops up a separate dialog + // offering a choice to debug the aborted program - we want to disable that. + prev_abort_behavior = _set_abort_behavior(0x0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); + // In debug mode, the Windows CRT can crash with an assertion over invalid + // input (e.g. passing an invalid file descriptor). The default handling + // for these assertions is to pop up a dialog and wait for user input. + // Instead ask the CRT to dump such assertions to stderr non-interactively. + prev_report_mode = _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); + prev_report_file = _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); + } + + static void reset() { + if(isSet) { + // Unregister handler and restore the old guarantee + SetUnhandledExceptionFilter(previousTop); + SetThreadStackGuarantee(&guaranteeSize); + std::set_terminate(original_terminate_handler); + std::signal(SIGABRT, prev_sigabrt_handler); + SetErrorMode(prev_error_mode_1); + _set_error_mode(prev_error_mode_2); + _set_abort_behavior(prev_abort_behavior, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); + static_cast(_CrtSetReportMode(_CRT_ASSERT, prev_report_mode)); + static_cast(_CrtSetReportFile(_CRT_ASSERT, prev_report_file)); + isSet = false; + } + } + + ~FatalConditionHandler() { reset(); } + + private: + static UINT prev_error_mode_1; + static int prev_error_mode_2; + static unsigned int prev_abort_behavior; + static int prev_report_mode; + static _HFILE prev_report_file; + static void (DOCTEST_CDECL *prev_sigabrt_handler)(int); + static std::terminate_handler original_terminate_handler; + static bool isSet; + static ULONG guaranteeSize; + static LPTOP_LEVEL_EXCEPTION_FILTER previousTop; + }; + + UINT FatalConditionHandler::prev_error_mode_1; + int FatalConditionHandler::prev_error_mode_2; + unsigned int FatalConditionHandler::prev_abort_behavior; + int FatalConditionHandler::prev_report_mode; + _HFILE FatalConditionHandler::prev_report_file; + void (DOCTEST_CDECL *FatalConditionHandler::prev_sigabrt_handler)(int); + std::terminate_handler FatalConditionHandler::original_terminate_handler; + bool FatalConditionHandler::isSet = false; + ULONG FatalConditionHandler::guaranteeSize = 0; + LPTOP_LEVEL_EXCEPTION_FILTER FatalConditionHandler::previousTop = nullptr; + +#else // DOCTEST_PLATFORM_WINDOWS + + struct SignalDefs + { + int id; + const char* name; + }; + SignalDefs signalDefs[] = {{SIGINT, "SIGINT - Terminal interrupt signal"}, + {SIGILL, "SIGILL - Illegal instruction signal"}, + {SIGFPE, "SIGFPE - Floating point error signal"}, + {SIGSEGV, "SIGSEGV - Segmentation violation signal"}, + {SIGTERM, "SIGTERM - Termination request signal"}, + {SIGABRT, "SIGABRT - Abort (abnormal termination) signal"}}; + + struct FatalConditionHandler + { + static bool isSet; + static struct sigaction oldSigActions[DOCTEST_COUNTOF(signalDefs)]; + static stack_t oldSigStack; + static size_t altStackSize; + static char* altStackMem; + + static void handleSignal(int sig) { + const char* name = ""; + for(std::size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { + SignalDefs& def = signalDefs[i]; + if(sig == def.id) { + name = def.name; + break; + } + } + reset(); + reportFatal(name); + raise(sig); + } + + static void allocateAltStackMem() { + altStackMem = new char[altStackSize]; + } + + static void freeAltStackMem() { + delete[] altStackMem; + } + + FatalConditionHandler() { + isSet = true; + stack_t sigStack; + sigStack.ss_sp = altStackMem; + sigStack.ss_size = altStackSize; + sigStack.ss_flags = 0; + sigaltstack(&sigStack, &oldSigStack); + struct sigaction sa = {}; + sa.sa_handler = handleSignal; + sa.sa_flags = SA_ONSTACK; + for(std::size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { + sigaction(signalDefs[i].id, &sa, &oldSigActions[i]); + } + } + + ~FatalConditionHandler() { reset(); } + static void reset() { + if(isSet) { + // Set signals back to previous values -- hopefully nobody overwrote them in the meantime + for(std::size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { + sigaction(signalDefs[i].id, &oldSigActions[i], nullptr); + } + // Return the old stack + sigaltstack(&oldSigStack, nullptr); + isSet = false; + } + } + }; + + bool FatalConditionHandler::isSet = false; + struct sigaction FatalConditionHandler::oldSigActions[DOCTEST_COUNTOF(signalDefs)] = {}; + stack_t FatalConditionHandler::oldSigStack = {}; + size_t FatalConditionHandler::altStackSize = 4 * SIGSTKSZ; + char* FatalConditionHandler::altStackMem = nullptr; + +#endif // DOCTEST_PLATFORM_WINDOWS +#endif // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH + +} // namespace + +namespace { + using namespace detail; + +#ifdef DOCTEST_PLATFORM_WINDOWS +#define DOCTEST_OUTPUT_DEBUG_STRING(text) ::OutputDebugStringA(text) +#else + // TODO: integration with XCode and other IDEs +#define DOCTEST_OUTPUT_DEBUG_STRING(text) +#endif // Platform + + void addAssert(assertType::Enum at) { + if((at & assertType::is_warn) == 0) //!OCLINT bitwise operator in conditional + g_cs->numAssertsCurrentTest_atomic++; + } + + void addFailedAssert(assertType::Enum at) { + if((at & assertType::is_warn) == 0) //!OCLINT bitwise operator in conditional + g_cs->numAssertsFailedCurrentTest_atomic++; + } + +#if defined(DOCTEST_CONFIG_POSIX_SIGNALS) || defined(DOCTEST_CONFIG_WINDOWS_SEH) + void reportFatal(const std::string& message) { + g_cs->failure_flags |= TestCaseFailureReason::Crash; + + DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_exception, {message.c_str(), true}); + + while (g_cs->subcaseStack.size()) { + g_cs->subcaseStack.pop_back(); + DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_end, DOCTEST_EMPTY); + } + + g_cs->finalizeTestCaseData(); + + DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_end, *g_cs); + + DOCTEST_ITERATE_THROUGH_REPORTERS(test_run_end, *g_cs); + } +#endif // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH +} // namespace + +AssertData::AssertData(assertType::Enum at, const char* file, int line, const char* expr, + const char* exception_type, const StringContains& exception_string) + : m_test_case(g_cs->currentTest), m_at(at), m_file(file), m_line(line), m_expr(expr), + m_failed(true), m_threw(false), m_threw_as(false), m_exception_type(exception_type), + m_exception_string(exception_string) { +#if DOCTEST_MSVC + if (m_expr[0] == ' ') // this happens when variadic macros are disabled under MSVC + ++m_expr; +#endif // MSVC +} + +namespace detail { + ResultBuilder::ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr, + const char* exception_type, const String& exception_string) + : AssertData(at, file, line, expr, exception_type, exception_string) { } + + ResultBuilder::ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr, + const char* exception_type, const Contains& exception_string) + : AssertData(at, file, line, expr, exception_type, exception_string) { } + + void ResultBuilder::setResult(const Result& res) { + m_decomp = res.m_decomp; + m_failed = !res.m_passed; + } + + void ResultBuilder::translateException() { + m_threw = true; + m_exception = translateActiveException(); + } + + bool ResultBuilder::log() { + if(m_at & assertType::is_throws) { //!OCLINT bitwise operator in conditional + m_failed = !m_threw; + } else if((m_at & assertType::is_throws_as) && (m_at & assertType::is_throws_with)) { //!OCLINT + m_failed = !m_threw_as || !m_exception_string.check(m_exception); + } else if(m_at & assertType::is_throws_as) { //!OCLINT bitwise operator in conditional + m_failed = !m_threw_as; + } else if(m_at & assertType::is_throws_with) { //!OCLINT bitwise operator in conditional + m_failed = !m_exception_string.check(m_exception); + } else if(m_at & assertType::is_nothrow) { //!OCLINT bitwise operator in conditional + m_failed = m_threw; + } + + if(m_exception.size()) + m_exception = "\"" + m_exception + "\""; + + if(is_running_in_test) { + addAssert(m_at); + DOCTEST_ITERATE_THROUGH_REPORTERS(log_assert, *this); + + if(m_failed) + addFailedAssert(m_at); + } else if(m_failed) { + failed_out_of_a_testing_context(*this); + } + + return m_failed && isDebuggerActive() && !getContextOptions()->no_breaks && + (g_cs->currentTest == nullptr || !g_cs->currentTest->m_no_breaks); // break into debugger + } + + void ResultBuilder::react() const { + if(m_failed && checkIfShouldThrow(m_at)) + throwException(); + } + + void failed_out_of_a_testing_context(const AssertData& ad) { + if(g_cs->ah) + g_cs->ah(ad); + else + std::abort(); + } + + bool decomp_assert(assertType::Enum at, const char* file, int line, const char* expr, + const Result& result) { + bool failed = !result.m_passed; + + // ################################################################################### + // IF THE DEBUGGER BREAKS HERE - GO 1 LEVEL UP IN THE CALLSTACK FOR THE FAILING ASSERT + // THIS IS THE EFFECT OF HAVING 'DOCTEST_CONFIG_SUPER_FAST_ASSERTS' DEFINED + // ################################################################################### + DOCTEST_ASSERT_OUT_OF_TESTS(result.m_decomp); + DOCTEST_ASSERT_IN_TESTS(result.m_decomp); + return !failed; + } + + MessageBuilder::MessageBuilder(const char* file, int line, assertType::Enum severity) { + m_stream = tlssPush(); + m_file = file; + m_line = line; + m_severity = severity; + } + + MessageBuilder::~MessageBuilder() { + if (!logged) + tlssPop(); + } + + DOCTEST_DEFINE_INTERFACE(IExceptionTranslator) + + bool MessageBuilder::log() { + if (!logged) { + m_string = tlssPop(); + logged = true; + } + + DOCTEST_ITERATE_THROUGH_REPORTERS(log_message, *this); + + const bool isWarn = m_severity & assertType::is_warn; + + // warn is just a message in this context so we don't treat it as an assert + if(!isWarn) { + addAssert(m_severity); + addFailedAssert(m_severity); + } + + return isDebuggerActive() && !getContextOptions()->no_breaks && !isWarn && + (g_cs->currentTest == nullptr || !g_cs->currentTest->m_no_breaks); // break into debugger + } + + void MessageBuilder::react() { + if(m_severity & assertType::is_require) //!OCLINT bitwise operator in conditional + throwException(); + } +} // namespace detail +namespace { + using namespace detail; + + // clang-format off + +// ================================================================================================= +// The following code has been taken verbatim from Catch2/include/internal/catch_xmlwriter.h/cpp +// This is done so cherry-picking bug fixes is trivial - even the style/formatting is untouched. +// ================================================================================================= + + class XmlEncode { + public: + enum ForWhat { ForTextNodes, ForAttributes }; + + XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes ); + + void encodeTo( std::ostream& os ) const; + + friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ); + + private: + std::string m_str; + ForWhat m_forWhat; + }; + + class XmlWriter { + public: + + class ScopedElement { + public: + ScopedElement( XmlWriter* writer ); + + ScopedElement( ScopedElement&& other ) DOCTEST_NOEXCEPT; + ScopedElement& operator=( ScopedElement&& other ) DOCTEST_NOEXCEPT; + + ~ScopedElement(); + + ScopedElement& writeText( std::string const& text, bool indent = true ); + + template + ScopedElement& writeAttribute( std::string const& name, T const& attribute ) { + m_writer->writeAttribute( name, attribute ); + return *this; + } + + private: + mutable XmlWriter* m_writer = nullptr; + }; + +#ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM + XmlWriter( std::ostream& os = std::cout ); +#else // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM + XmlWriter( std::ostream& os ); +#endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM + ~XmlWriter(); + + XmlWriter( XmlWriter const& ) = delete; + XmlWriter& operator=( XmlWriter const& ) = delete; + + XmlWriter& startElement( std::string const& name ); + + ScopedElement scopedElement( std::string const& name ); + + XmlWriter& endElement(); + + XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ); + + XmlWriter& writeAttribute( std::string const& name, const char* attribute ); + + XmlWriter& writeAttribute( std::string const& name, bool attribute ); + + template + XmlWriter& writeAttribute( std::string const& name, T const& attribute ) { + std::stringstream rss; + rss << attribute; + return writeAttribute( name, rss.str() ); + } + + XmlWriter& writeText( std::string const& text, bool indent = true ); + + //XmlWriter& writeComment( std::string const& text ); + + //void writeStylesheetRef( std::string const& url ); + + //XmlWriter& writeBlankLine(); + + void ensureTagClosed(); + + void writeDeclaration(); + + private: + + void newlineIfNecessary(); + + bool m_tagIsOpen = false; + bool m_needsNewline = false; + std::vector m_tags; + std::string m_indent; + std::ostream& m_os; + }; + +// ================================================================================================= +// The following code has been taken verbatim from Catch2/include/internal/catch_xmlwriter.h/cpp +// This is done so cherry-picking bug fixes is trivial - even the style/formatting is untouched. +// ================================================================================================= + +using uchar = unsigned char; + +namespace { + + size_t trailingBytes(unsigned char c) { + if ((c & 0xE0) == 0xC0) { + return 2; + } + if ((c & 0xF0) == 0xE0) { + return 3; + } + if ((c & 0xF8) == 0xF0) { + return 4; + } + DOCTEST_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); + } + + uint32_t headerValue(unsigned char c) { + if ((c & 0xE0) == 0xC0) { + return c & 0x1F; + } + if ((c & 0xF0) == 0xE0) { + return c & 0x0F; + } + if ((c & 0xF8) == 0xF0) { + return c & 0x07; + } + DOCTEST_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); + } + + void hexEscapeChar(std::ostream& os, unsigned char c) { + std::ios_base::fmtflags f(os.flags()); + os << "\\x" + << std::uppercase << std::hex << std::setfill('0') << std::setw(2) + << static_cast(c); + os.flags(f); + } + +} // anonymous namespace + + XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat ) + : m_str( str ), + m_forWhat( forWhat ) + {} + + void XmlEncode::encodeTo( std::ostream& os ) const { + // Apostrophe escaping not necessary if we always use " to write attributes + // (see: https://www.w3.org/TR/xml/#syntax) + + for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) { + uchar c = m_str[idx]; + switch (c) { + case '<': os << "<"; break; + case '&': os << "&"; break; + + case '>': + // See: https://www.w3.org/TR/xml/#syntax + if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']') + os << ">"; + else + os << c; + break; + + case '\"': + if (m_forWhat == ForAttributes) + os << """; + else + os << c; + break; + + default: + // Check for control characters and invalid utf-8 + + // Escape control characters in standard ascii + // see https://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 + if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) { + hexEscapeChar(os, c); + break; + } + + // Plain ASCII: Write it to stream + if (c < 0x7F) { + os << c; + break; + } + + // UTF-8 territory + // Check if the encoding is valid and if it is not, hex escape bytes. + // Important: We do not check the exact decoded values for validity, only the encoding format + // First check that this bytes is a valid lead byte: + // This means that it is not encoded as 1111 1XXX + // Or as 10XX XXXX + if (c < 0xC0 || + c >= 0xF8) { + hexEscapeChar(os, c); + break; + } + + auto encBytes = trailingBytes(c); + // Are there enough bytes left to avoid accessing out-of-bounds memory? + if (idx + encBytes - 1 >= m_str.size()) { + hexEscapeChar(os, c); + break; + } + // The header is valid, check data + // The next encBytes bytes must together be a valid utf-8 + // This means: bitpattern 10XX XXXX and the extracted value is sane (ish) + bool valid = true; + uint32_t value = headerValue(c); + for (std::size_t n = 1; n < encBytes; ++n) { + uchar nc = m_str[idx + n]; + valid &= ((nc & 0xC0) == 0x80); + value = (value << 6) | (nc & 0x3F); + } + + if ( + // Wrong bit pattern of following bytes + (!valid) || + // Overlong encodings + (value < 0x80) || + ( value < 0x800 && encBytes > 2) || // removed "0x80 <= value &&" because redundant + (0x800 < value && value < 0x10000 && encBytes > 3) || + // Encoded value out of range + (value >= 0x110000) + ) { + hexEscapeChar(os, c); + break; + } + + // If we got here, this is in fact a valid(ish) utf-8 sequence + for (std::size_t n = 0; n < encBytes; ++n) { + os << m_str[idx + n]; + } + idx += encBytes - 1; + break; + } + } + } + + std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) { + xmlEncode.encodeTo( os ); + return os; + } + + XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer ) + : m_writer( writer ) + {} + + XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) DOCTEST_NOEXCEPT + : m_writer( other.m_writer ){ + other.m_writer = nullptr; + } + XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) DOCTEST_NOEXCEPT { + if ( m_writer ) { + m_writer->endElement(); + } + m_writer = other.m_writer; + other.m_writer = nullptr; + return *this; + } + + + XmlWriter::ScopedElement::~ScopedElement() { + if( m_writer ) + m_writer->endElement(); + } + + XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) { + m_writer->writeText( text, indent ); + return *this; + } + + XmlWriter::XmlWriter( std::ostream& os ) : m_os( os ) + { + // writeDeclaration(); // called explicitly by the reporters that use the writer class - see issue #627 + } + + XmlWriter::~XmlWriter() { + while( !m_tags.empty() ) + endElement(); + } + + XmlWriter& XmlWriter::startElement( std::string const& name ) { + ensureTagClosed(); + newlineIfNecessary(); + m_os << m_indent << '<' << name; + m_tags.push_back( name ); + m_indent += " "; + m_tagIsOpen = true; + return *this; + } + + XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) { + ScopedElement scoped( this ); + startElement( name ); + return scoped; + } + + XmlWriter& XmlWriter::endElement() { + newlineIfNecessary(); + m_indent = m_indent.substr( 0, m_indent.size()-2 ); + if( m_tagIsOpen ) { + m_os << "/>"; + m_tagIsOpen = false; + } + else { + m_os << m_indent << ""; + } + m_os << std::endl; + m_tags.pop_back(); + return *this; + } + + XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) { + if( !name.empty() && !attribute.empty() ) + m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"'; + return *this; + } + + XmlWriter& XmlWriter::writeAttribute( std::string const& name, const char* attribute ) { + if( !name.empty() && attribute && attribute[0] != '\0' ) + m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"'; + return *this; + } + + XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) { + m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"'; + return *this; + } + + XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) { + if( !text.empty() ){ + bool tagWasOpen = m_tagIsOpen; + ensureTagClosed(); + if( tagWasOpen && indent ) + m_os << m_indent; + m_os << XmlEncode( text ); + m_needsNewline = true; + } + return *this; + } + + //XmlWriter& XmlWriter::writeComment( std::string const& text ) { + // ensureTagClosed(); + // m_os << m_indent << ""; + // m_needsNewline = true; + // return *this; + //} + + //void XmlWriter::writeStylesheetRef( std::string const& url ) { + // m_os << "\n"; + //} + + //XmlWriter& XmlWriter::writeBlankLine() { + // ensureTagClosed(); + // m_os << '\n'; + // return *this; + //} + + void XmlWriter::ensureTagClosed() { + if( m_tagIsOpen ) { + m_os << ">" << std::endl; + m_tagIsOpen = false; + } + } + + void XmlWriter::writeDeclaration() { + m_os << "\n"; + } + + void XmlWriter::newlineIfNecessary() { + if( m_needsNewline ) { + m_os << std::endl; + m_needsNewline = false; + } + } + +// ================================================================================================= +// End of copy-pasted code from Catch +// ================================================================================================= + + // clang-format on + + struct XmlReporter : public IReporter + { + XmlWriter xml; + DOCTEST_DECLARE_MUTEX(mutex) + + // caching pointers/references to objects of these types - safe to do + const ContextOptions& opt; + const TestCaseData* tc = nullptr; + + XmlReporter(const ContextOptions& co) + : xml(*co.cout) + , opt(co) {} + + void log_contexts() { + int num_contexts = get_num_active_contexts(); + if(num_contexts) { + auto contexts = get_active_contexts(); + std::stringstream ss; + for(int i = 0; i < num_contexts; ++i) { + contexts[i]->stringify(&ss); + xml.scopedElement("Info").writeText(ss.str()); + ss.str(""); + } + } + } + + unsigned line(unsigned l) const { return opt.no_line_numbers ? 0 : l; } + + void test_case_start_impl(const TestCaseData& in) { + bool open_ts_tag = false; + if(tc != nullptr) { // we have already opened a test suite + if(std::strcmp(tc->m_test_suite, in.m_test_suite) != 0) { + xml.endElement(); + open_ts_tag = true; + } + } + else { + open_ts_tag = true; // first test case ==> first test suite + } + + if(open_ts_tag) { + xml.startElement("TestSuite"); + xml.writeAttribute("name", in.m_test_suite); + } + + tc = ∈ + xml.startElement("TestCase") + .writeAttribute("name", in.m_name) + .writeAttribute("filename", skipPathFromFilename(in.m_file.c_str())) + .writeAttribute("line", line(in.m_line)) + .writeAttribute("description", in.m_description); + + if(Approx(in.m_timeout) != 0) + xml.writeAttribute("timeout", in.m_timeout); + if(in.m_may_fail) + xml.writeAttribute("may_fail", true); + if(in.m_should_fail) + xml.writeAttribute("should_fail", true); + } + + // ========================================================================================= + // WHAT FOLLOWS ARE OVERRIDES OF THE VIRTUAL METHODS OF THE REPORTER INTERFACE + // ========================================================================================= + + void report_query(const QueryData& in) override { + test_run_start(); + if(opt.list_reporters) { + for(auto& curr : getListeners()) + xml.scopedElement("Listener") + .writeAttribute("priority", curr.first.first) + .writeAttribute("name", curr.first.second); + for(auto& curr : getReporters()) + xml.scopedElement("Reporter") + .writeAttribute("priority", curr.first.first) + .writeAttribute("name", curr.first.second); + } else if(opt.count || opt.list_test_cases) { + for(unsigned i = 0; i < in.num_data; ++i) { + xml.scopedElement("TestCase").writeAttribute("name", in.data[i]->m_name) + .writeAttribute("testsuite", in.data[i]->m_test_suite) + .writeAttribute("filename", skipPathFromFilename(in.data[i]->m_file.c_str())) + .writeAttribute("line", line(in.data[i]->m_line)) + .writeAttribute("skipped", in.data[i]->m_skip); + } + xml.scopedElement("OverallResultsTestCases") + .writeAttribute("unskipped", in.run_stats->numTestCasesPassingFilters); + } else if(opt.list_test_suites) { + for(unsigned i = 0; i < in.num_data; ++i) + xml.scopedElement("TestSuite").writeAttribute("name", in.data[i]->m_test_suite); + xml.scopedElement("OverallResultsTestCases") + .writeAttribute("unskipped", in.run_stats->numTestCasesPassingFilters); + xml.scopedElement("OverallResultsTestSuites") + .writeAttribute("unskipped", in.run_stats->numTestSuitesPassingFilters); + } + xml.endElement(); + } + + void test_run_start() override { + xml.writeDeclaration(); + + // remove .exe extension - mainly to have the same output on UNIX and Windows + std::string binary_name = skipPathFromFilename(opt.binary_name.c_str()); +#ifdef DOCTEST_PLATFORM_WINDOWS + if(binary_name.rfind(".exe") != std::string::npos) + binary_name = binary_name.substr(0, binary_name.length() - 4); +#endif // DOCTEST_PLATFORM_WINDOWS + + xml.startElement("doctest").writeAttribute("binary", binary_name); + if(opt.no_version == false) + xml.writeAttribute("version", DOCTEST_VERSION_STR); + + // only the consequential ones (TODO: filters) + xml.scopedElement("Options") + .writeAttribute("order_by", opt.order_by.c_str()) + .writeAttribute("rand_seed", opt.rand_seed) + .writeAttribute("first", opt.first) + .writeAttribute("last", opt.last) + .writeAttribute("abort_after", opt.abort_after) + .writeAttribute("subcase_filter_levels", opt.subcase_filter_levels) + .writeAttribute("case_sensitive", opt.case_sensitive) + .writeAttribute("no_throw", opt.no_throw) + .writeAttribute("no_skip", opt.no_skip); + } + + void test_run_end(const TestRunStats& p) override { + if(tc) // the TestSuite tag - only if there has been at least 1 test case + xml.endElement(); + + xml.scopedElement("OverallResultsAsserts") + .writeAttribute("successes", p.numAsserts - p.numAssertsFailed) + .writeAttribute("failures", p.numAssertsFailed); + + xml.startElement("OverallResultsTestCases") + .writeAttribute("successes", + p.numTestCasesPassingFilters - p.numTestCasesFailed) + .writeAttribute("failures", p.numTestCasesFailed); + if(opt.no_skipped_summary == false) + xml.writeAttribute("skipped", p.numTestCases - p.numTestCasesPassingFilters); + xml.endElement(); + + xml.endElement(); + } + + void test_case_start(const TestCaseData& in) override { + test_case_start_impl(in); + xml.ensureTagClosed(); + } + + void test_case_reenter(const TestCaseData&) override {} + + void test_case_end(const CurrentTestCaseStats& st) override { + xml.startElement("OverallResultsAsserts") + .writeAttribute("successes", + st.numAssertsCurrentTest - st.numAssertsFailedCurrentTest) + .writeAttribute("failures", st.numAssertsFailedCurrentTest) + .writeAttribute("test_case_success", st.testCaseSuccess); + if(opt.duration) + xml.writeAttribute("duration", st.seconds); + if(tc->m_expected_failures) + xml.writeAttribute("expected_failures", tc->m_expected_failures); + xml.endElement(); + + xml.endElement(); + } + + void test_case_exception(const TestCaseException& e) override { + DOCTEST_LOCK_MUTEX(mutex) + + xml.scopedElement("Exception") + .writeAttribute("crash", e.is_crash) + .writeText(e.error_string.c_str()); + } + + void subcase_start(const SubcaseSignature& in) override { + xml.startElement("SubCase") + .writeAttribute("name", in.m_name) + .writeAttribute("filename", skipPathFromFilename(in.m_file)) + .writeAttribute("line", line(in.m_line)); + xml.ensureTagClosed(); + } + + void subcase_end() override { xml.endElement(); } + + void log_assert(const AssertData& rb) override { + if(!rb.m_failed && !opt.success) + return; + + DOCTEST_LOCK_MUTEX(mutex) + + xml.startElement("Expression") + .writeAttribute("success", !rb.m_failed) + .writeAttribute("type", assertString(rb.m_at)) + .writeAttribute("filename", skipPathFromFilename(rb.m_file)) + .writeAttribute("line", line(rb.m_line)); + + xml.scopedElement("Original").writeText(rb.m_expr); + + if(rb.m_threw) + xml.scopedElement("Exception").writeText(rb.m_exception.c_str()); + + if(rb.m_at & assertType::is_throws_as) + xml.scopedElement("ExpectedException").writeText(rb.m_exception_type); + if(rb.m_at & assertType::is_throws_with) + xml.scopedElement("ExpectedExceptionString").writeText(rb.m_exception_string.c_str()); + if((rb.m_at & assertType::is_normal) && !rb.m_threw) + xml.scopedElement("Expanded").writeText(rb.m_decomp.c_str()); + + log_contexts(); + + xml.endElement(); + } + + void log_message(const MessageData& mb) override { + DOCTEST_LOCK_MUTEX(mutex) + + xml.startElement("Message") + .writeAttribute("type", failureString(mb.m_severity)) + .writeAttribute("filename", skipPathFromFilename(mb.m_file)) + .writeAttribute("line", line(mb.m_line)); + + xml.scopedElement("Text").writeText(mb.m_string.c_str()); + + log_contexts(); + + xml.endElement(); + } + + void test_case_skipped(const TestCaseData& in) override { + if(opt.no_skipped_summary == false) { + test_case_start_impl(in); + xml.writeAttribute("skipped", "true"); + xml.endElement(); + } + } + }; + + DOCTEST_REGISTER_REPORTER("xml", 0, XmlReporter); + + void fulltext_log_assert_to_stream(std::ostream& s, const AssertData& rb) { + if((rb.m_at & (assertType::is_throws_as | assertType::is_throws_with)) == + 0) //!OCLINT bitwise operator in conditional + s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << " ) " + << Color::None; + + if(rb.m_at & assertType::is_throws) { //!OCLINT bitwise operator in conditional + s << (rb.m_threw ? "threw as expected!" : "did NOT throw at all!") << "\n"; + } else if((rb.m_at & assertType::is_throws_as) && + (rb.m_at & assertType::is_throws_with)) { //!OCLINT + s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << ", \"" + << rb.m_exception_string.c_str() + << "\", " << rb.m_exception_type << " ) " << Color::None; + if(rb.m_threw) { + if(!rb.m_failed) { + s << "threw as expected!\n"; + } else { + s << "threw a DIFFERENT exception! (contents: " << rb.m_exception << ")\n"; + } + } else { + s << "did NOT throw at all!\n"; + } + } else if(rb.m_at & + assertType::is_throws_as) { //!OCLINT bitwise operator in conditional + s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << ", " + << rb.m_exception_type << " ) " << Color::None + << (rb.m_threw ? (rb.m_threw_as ? "threw as expected!" : + "threw a DIFFERENT exception: ") : + "did NOT throw at all!") + << Color::Cyan << rb.m_exception << "\n"; + } else if(rb.m_at & + assertType::is_throws_with) { //!OCLINT bitwise operator in conditional + s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << ", \"" + << rb.m_exception_string.c_str() + << "\" ) " << Color::None + << (rb.m_threw ? (!rb.m_failed ? "threw as expected!" : + "threw a DIFFERENT exception: ") : + "did NOT throw at all!") + << Color::Cyan << rb.m_exception << "\n"; + } else if(rb.m_at & assertType::is_nothrow) { //!OCLINT bitwise operator in conditional + s << (rb.m_threw ? "THREW exception: " : "didn't throw!") << Color::Cyan + << rb.m_exception << "\n"; + } else { + s << (rb.m_threw ? "THREW exception: " : + (!rb.m_failed ? "is correct!\n" : "is NOT correct!\n")); + if(rb.m_threw) + s << rb.m_exception << "\n"; + else + s << " values: " << assertString(rb.m_at) << "( " << rb.m_decomp << " )\n"; + } + } + + // TODO: + // - log_message() + // - respond to queries + // - honor remaining options + // - more attributes in tags + struct JUnitReporter : public IReporter + { + XmlWriter xml; + DOCTEST_DECLARE_MUTEX(mutex) + Timer timer; + std::vector deepestSubcaseStackNames; + + struct JUnitTestCaseData + { + static std::string getCurrentTimestamp() { + // Beware, this is not reentrant because of backward compatibility issues + // Also, UTC only, again because of backward compatibility (%z is C++11) + time_t rawtime; + std::time(&rawtime); + auto const timeStampSize = sizeof("2017-01-16T17:06:45Z"); + + std::tm timeInfo; +#ifdef DOCTEST_PLATFORM_WINDOWS + gmtime_s(&timeInfo, &rawtime); +#else // DOCTEST_PLATFORM_WINDOWS + gmtime_r(&rawtime, &timeInfo); +#endif // DOCTEST_PLATFORM_WINDOWS + + char timeStamp[timeStampSize]; + const char* const fmt = "%Y-%m-%dT%H:%M:%SZ"; + + std::strftime(timeStamp, timeStampSize, fmt, &timeInfo); + return std::string(timeStamp); + } + + struct JUnitTestMessage + { + JUnitTestMessage(const std::string& _message, const std::string& _type, const std::string& _details) + : message(_message), type(_type), details(_details) {} + + JUnitTestMessage(const std::string& _message, const std::string& _details) + : message(_message), type(), details(_details) {} + + std::string message, type, details; + }; + + struct JUnitTestCase + { + JUnitTestCase(const std::string& _classname, const std::string& _name) + : classname(_classname), name(_name), time(0), failures() {} + + std::string classname, name; + double time; + std::vector failures, errors; + }; + + void add(const std::string& classname, const std::string& name) { + testcases.emplace_back(classname, name); + } + + void appendSubcaseNamesToLastTestcase(std::vector nameStack) { + for(auto& curr: nameStack) + if(curr.size()) + testcases.back().name += std::string("/") + curr.c_str(); + } + + void addTime(double time) { + if(time < 1e-4) + time = 0; + testcases.back().time = time; + totalSeconds += time; + } + + void addFailure(const std::string& message, const std::string& type, const std::string& details) { + testcases.back().failures.emplace_back(message, type, details); + ++totalFailures; + } + + void addError(const std::string& message, const std::string& details) { + testcases.back().errors.emplace_back(message, details); + ++totalErrors; + } + + std::vector testcases; + double totalSeconds = 0; + int totalErrors = 0, totalFailures = 0; + }; + + JUnitTestCaseData testCaseData; + + // caching pointers/references to objects of these types - safe to do + const ContextOptions& opt; + const TestCaseData* tc = nullptr; + + JUnitReporter(const ContextOptions& co) + : xml(*co.cout) + , opt(co) {} + + unsigned line(unsigned l) const { return opt.no_line_numbers ? 0 : l; } + + // ========================================================================================= + // WHAT FOLLOWS ARE OVERRIDES OF THE VIRTUAL METHODS OF THE REPORTER INTERFACE + // ========================================================================================= + + void report_query(const QueryData&) override { + xml.writeDeclaration(); + } + + void test_run_start() override { + xml.writeDeclaration(); + } + + void test_run_end(const TestRunStats& p) override { + // remove .exe extension - mainly to have the same output on UNIX and Windows + std::string binary_name = skipPathFromFilename(opt.binary_name.c_str()); +#ifdef DOCTEST_PLATFORM_WINDOWS + if(binary_name.rfind(".exe") != std::string::npos) + binary_name = binary_name.substr(0, binary_name.length() - 4); +#endif // DOCTEST_PLATFORM_WINDOWS + xml.startElement("testsuites"); + xml.startElement("testsuite").writeAttribute("name", binary_name) + .writeAttribute("errors", testCaseData.totalErrors) + .writeAttribute("failures", testCaseData.totalFailures) + .writeAttribute("tests", p.numAsserts); + if(opt.no_time_in_output == false) { + xml.writeAttribute("time", testCaseData.totalSeconds); + xml.writeAttribute("timestamp", JUnitTestCaseData::getCurrentTimestamp()); + } + if(opt.no_version == false) + xml.writeAttribute("doctest_version", DOCTEST_VERSION_STR); + + for(const auto& testCase : testCaseData.testcases) { + xml.startElement("testcase") + .writeAttribute("classname", testCase.classname) + .writeAttribute("name", testCase.name); + if(opt.no_time_in_output == false) + xml.writeAttribute("time", testCase.time); + // This is not ideal, but it should be enough to mimic gtest's junit output. + xml.writeAttribute("status", "run"); + + for(const auto& failure : testCase.failures) { + xml.scopedElement("failure") + .writeAttribute("message", failure.message) + .writeAttribute("type", failure.type) + .writeText(failure.details, false); + } + + for(const auto& error : testCase.errors) { + xml.scopedElement("error") + .writeAttribute("message", error.message) + .writeText(error.details); + } + + xml.endElement(); + } + xml.endElement(); + xml.endElement(); + } + + void test_case_start(const TestCaseData& in) override { + testCaseData.add(skipPathFromFilename(in.m_file.c_str()), in.m_name); + timer.start(); + } + + void test_case_reenter(const TestCaseData& in) override { + testCaseData.addTime(timer.getElapsedSeconds()); + testCaseData.appendSubcaseNamesToLastTestcase(deepestSubcaseStackNames); + deepestSubcaseStackNames.clear(); + + timer.start(); + testCaseData.add(skipPathFromFilename(in.m_file.c_str()), in.m_name); + } + + void test_case_end(const CurrentTestCaseStats&) override { + testCaseData.addTime(timer.getElapsedSeconds()); + testCaseData.appendSubcaseNamesToLastTestcase(deepestSubcaseStackNames); + deepestSubcaseStackNames.clear(); + } + + void test_case_exception(const TestCaseException& e) override { + DOCTEST_LOCK_MUTEX(mutex) + testCaseData.addError("exception", e.error_string.c_str()); + } + + void subcase_start(const SubcaseSignature& in) override { + deepestSubcaseStackNames.push_back(in.m_name); + } + + void subcase_end() override {} + + void log_assert(const AssertData& rb) override { + if(!rb.m_failed) // report only failures & ignore the `success` option + return; + + DOCTEST_LOCK_MUTEX(mutex) + + std::ostringstream os; + os << skipPathFromFilename(rb.m_file) << (opt.gnu_file_line ? ":" : "(") + << line(rb.m_line) << (opt.gnu_file_line ? ":" : "):") << std::endl; + + fulltext_log_assert_to_stream(os, rb); + log_contexts(os); + testCaseData.addFailure(rb.m_decomp.c_str(), assertString(rb.m_at), os.str()); + } + + void log_message(const MessageData& mb) override { + if(mb.m_severity & assertType::is_warn) // report only failures + return; + + DOCTEST_LOCK_MUTEX(mutex) + + std::ostringstream os; + os << skipPathFromFilename(mb.m_file) << (opt.gnu_file_line ? ":" : "(") + << line(mb.m_line) << (opt.gnu_file_line ? ":" : "):") << std::endl; + + os << mb.m_string.c_str() << "\n"; + log_contexts(os); + + testCaseData.addFailure(mb.m_string.c_str(), + mb.m_severity & assertType::is_check ? "FAIL_CHECK" : "FAIL", os.str()); + } + + void test_case_skipped(const TestCaseData&) override {} + + void log_contexts(std::ostringstream& s) { + int num_contexts = get_num_active_contexts(); + if(num_contexts) { + auto contexts = get_active_contexts(); + + s << " logged: "; + for(int i = 0; i < num_contexts; ++i) { + s << (i == 0 ? "" : " "); + contexts[i]->stringify(&s); + s << std::endl; + } + } + } + }; + + DOCTEST_REGISTER_REPORTER("junit", 0, JUnitReporter); + + struct Whitespace + { + int nrSpaces; + explicit Whitespace(int nr) + : nrSpaces(nr) {} + }; + + std::ostream& operator<<(std::ostream& out, const Whitespace& ws) { + if(ws.nrSpaces != 0) + out << std::setw(ws.nrSpaces) << ' '; + return out; + } + + struct ConsoleReporter : public IReporter + { + std::ostream& s; + bool hasLoggedCurrentTestStart; + std::vector subcasesStack; + size_t currentSubcaseLevel; + DOCTEST_DECLARE_MUTEX(mutex) + + // caching pointers/references to objects of these types - safe to do + const ContextOptions& opt; + const TestCaseData* tc; + + ConsoleReporter(const ContextOptions& co) + : s(*co.cout) + , opt(co) {} + + ConsoleReporter(const ContextOptions& co, std::ostream& ostr) + : s(ostr) + , opt(co) {} + + // ========================================================================================= + // WHAT FOLLOWS ARE HELPERS USED BY THE OVERRIDES OF THE VIRTUAL METHODS OF THE INTERFACE + // ========================================================================================= + + void separator_to_stream() { + s << Color::Yellow + << "===============================================================================" + "\n"; + } + + const char* getSuccessOrFailString(bool success, assertType::Enum at, + const char* success_str) { + if(success) + return success_str; + return failureString(at); + } + + Color::Enum getSuccessOrFailColor(bool success, assertType::Enum at) { + return success ? Color::BrightGreen : + (at & assertType::is_warn) ? Color::Yellow : Color::Red; + } + + void successOrFailColoredStringToStream(bool success, assertType::Enum at, + const char* success_str = "SUCCESS") { + s << getSuccessOrFailColor(success, at) + << getSuccessOrFailString(success, at, success_str) << ": "; + } + + void log_contexts() { + int num_contexts = get_num_active_contexts(); + if(num_contexts) { + auto contexts = get_active_contexts(); + + s << Color::None << " logged: "; + for(int i = 0; i < num_contexts; ++i) { + s << (i == 0 ? "" : " "); + contexts[i]->stringify(&s); + s << "\n"; + } + } + + s << "\n"; + } + + // this was requested to be made virtual so users could override it + virtual void file_line_to_stream(const char* file, int line, + const char* tail = "") { + s << Color::LightGrey << skipPathFromFilename(file) << (opt.gnu_file_line ? ":" : "(") + << (opt.no_line_numbers ? 0 : line) // 0 or the real num depending on the option + << (opt.gnu_file_line ? ":" : "):") << tail; + } + + void logTestStart() { + if(hasLoggedCurrentTestStart) + return; + + separator_to_stream(); + file_line_to_stream(tc->m_file.c_str(), tc->m_line, "\n"); + if(tc->m_description) + s << Color::Yellow << "DESCRIPTION: " << Color::None << tc->m_description << "\n"; + if(tc->m_test_suite && tc->m_test_suite[0] != '\0') + s << Color::Yellow << "TEST SUITE: " << Color::None << tc->m_test_suite << "\n"; + if(strncmp(tc->m_name, " Scenario:", 11) != 0) + s << Color::Yellow << "TEST CASE: "; + s << Color::None << tc->m_name << "\n"; + + for(size_t i = 0; i < currentSubcaseLevel; ++i) { + if(subcasesStack[i].m_name[0] != '\0') + s << " " << subcasesStack[i].m_name << "\n"; + } + + if(currentSubcaseLevel != subcasesStack.size()) { + s << Color::Yellow << "\nDEEPEST SUBCASE STACK REACHED (DIFFERENT FROM THE CURRENT ONE):\n" << Color::None; + for(size_t i = 0; i < subcasesStack.size(); ++i) { + if(subcasesStack[i].m_name[0] != '\0') + s << " " << subcasesStack[i].m_name << "\n"; + } + } + + s << "\n"; + + hasLoggedCurrentTestStart = true; + } + + void printVersion() { + if(opt.no_version == false) + s << Color::Cyan << "[doctest] " << Color::None << "doctest version is \"" + << DOCTEST_VERSION_STR << "\"\n"; + } + + void printIntro() { + if(opt.no_intro == false) { + printVersion(); + s << Color::Cyan << "[doctest] " << Color::None + << "run with \"--" DOCTEST_OPTIONS_PREFIX_DISPLAY "help\" for options\n"; + } + } + + void printHelp() { + int sizePrefixDisplay = static_cast(strlen(DOCTEST_OPTIONS_PREFIX_DISPLAY)); + printVersion(); + // clang-format off + s << Color::Cyan << "[doctest]\n" << Color::None; + s << Color::Cyan << "[doctest] " << Color::None; + s << "boolean values: \"1/on/yes/true\" or \"0/off/no/false\"\n"; + s << Color::Cyan << "[doctest] " << Color::None; + s << "filter values: \"str1,str2,str3\" (comma separated strings)\n"; + s << Color::Cyan << "[doctest]\n" << Color::None; + s << Color::Cyan << "[doctest] " << Color::None; + s << "filters use wildcards for matching strings\n"; + s << Color::Cyan << "[doctest] " << Color::None; + s << "something passes a filter if any of the strings in a filter matches\n"; +#ifndef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS + s << Color::Cyan << "[doctest]\n" << Color::None; + s << Color::Cyan << "[doctest] " << Color::None; + s << "ALL FLAGS, OPTIONS AND FILTERS ALSO AVAILABLE WITH A \"" DOCTEST_CONFIG_OPTIONS_PREFIX "\" PREFIX!!!\n"; +#endif + s << Color::Cyan << "[doctest]\n" << Color::None; + s << Color::Cyan << "[doctest] " << Color::None; + s << "Query flags - the program quits after them. Available:\n\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "?, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "help, -" DOCTEST_OPTIONS_PREFIX_DISPLAY "h " + << Whitespace(sizePrefixDisplay*0) << "prints this message\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "v, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "version " + << Whitespace(sizePrefixDisplay*1) << "prints the version\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "c, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "count " + << Whitespace(sizePrefixDisplay*1) << "prints the number of matching tests\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ltc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "list-test-cases " + << Whitespace(sizePrefixDisplay*1) << "lists all matching tests by name\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "lts, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "list-test-suites " + << Whitespace(sizePrefixDisplay*1) << "lists all matching test suites\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "lr, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "list-reporters " + << Whitespace(sizePrefixDisplay*1) << "lists all registered reporters\n\n"; + // ================================================================================== << 79 + s << Color::Cyan << "[doctest] " << Color::None; + s << "The available / options/filters are:\n\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "tc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-case= " + << Whitespace(sizePrefixDisplay*1) << "filters tests by their name\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "tce, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-case-exclude= " + << Whitespace(sizePrefixDisplay*1) << "filters OUT tests by their name\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sf, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "source-file= " + << Whitespace(sizePrefixDisplay*1) << "filters tests by their file\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sfe, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "source-file-exclude= " + << Whitespace(sizePrefixDisplay*1) << "filters OUT tests by their file\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ts, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-suite= " + << Whitespace(sizePrefixDisplay*1) << "filters tests by their test suite\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "tse, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-suite-exclude= " + << Whitespace(sizePrefixDisplay*1) << "filters OUT tests by their test suite\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "subcase= " + << Whitespace(sizePrefixDisplay*1) << "filters subcases by their name\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sce, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "subcase-exclude= " + << Whitespace(sizePrefixDisplay*1) << "filters OUT subcases by their name\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "r, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "reporters= " + << Whitespace(sizePrefixDisplay*1) << "reporters to use (console is default)\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "o, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "out= " + << Whitespace(sizePrefixDisplay*1) << "output filename\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ob, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "order-by= " + << Whitespace(sizePrefixDisplay*1) << "how the tests should be ordered\n"; + s << Whitespace(sizePrefixDisplay*3) << " - [file/suite/name/rand/none]\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "rs, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "rand-seed= " + << Whitespace(sizePrefixDisplay*1) << "seed for random ordering\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "f, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "first= " + << Whitespace(sizePrefixDisplay*1) << "the first test passing the filters to\n"; + s << Whitespace(sizePrefixDisplay*3) << " execute - for range-based execution\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "l, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "last= " + << Whitespace(sizePrefixDisplay*1) << "the last test passing the filters to\n"; + s << Whitespace(sizePrefixDisplay*3) << " execute - for range-based execution\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "aa, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "abort-after= " + << Whitespace(sizePrefixDisplay*1) << "stop after failed assertions\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "scfl,--" DOCTEST_OPTIONS_PREFIX_DISPLAY "subcase-filter-levels= " + << Whitespace(sizePrefixDisplay*1) << "apply filters for the first levels\n"; + s << Color::Cyan << "\n[doctest] " << Color::None; + s << "Bool options - can be used like flags and true is assumed. Available:\n\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "s, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "success= " + << Whitespace(sizePrefixDisplay*1) << "include successful assertions in output\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "cs, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "case-sensitive= " + << Whitespace(sizePrefixDisplay*1) << "filters being treated as case sensitive\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "e, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "exit= " + << Whitespace(sizePrefixDisplay*1) << "exits after the tests finish\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "d, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "duration= " + << Whitespace(sizePrefixDisplay*1) << "prints the time duration of each test\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "m, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "minimal= " + << Whitespace(sizePrefixDisplay*1) << "minimal console output (only failures)\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "q, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "quiet= " + << Whitespace(sizePrefixDisplay*1) << "no console output\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nt, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-throw= " + << Whitespace(sizePrefixDisplay*1) << "skips exceptions-related assert checks\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ne, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-exitcode= " + << Whitespace(sizePrefixDisplay*1) << "returns (or exits) always with success\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nr, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-run= " + << Whitespace(sizePrefixDisplay*1) << "skips all runtime doctest operations\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ni, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-intro= " + << Whitespace(sizePrefixDisplay*1) << "omit the framework intro in the output\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nv, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-version= " + << Whitespace(sizePrefixDisplay*1) << "omit the framework version in the output\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-colors= " + << Whitespace(sizePrefixDisplay*1) << "disables colors in output\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "fc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "force-colors= " + << Whitespace(sizePrefixDisplay*1) << "use colors even when not in a tty\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nb, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-breaks= " + << Whitespace(sizePrefixDisplay*1) << "disables breakpoints in debuggers\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ns, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-skip= " + << Whitespace(sizePrefixDisplay*1) << "don't skip test cases marked as skip\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "gfl, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "gnu-file-line= " + << Whitespace(sizePrefixDisplay*1) << ":n: vs (n): for line numbers in output\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "npf, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-path-filenames= " + << Whitespace(sizePrefixDisplay*1) << "only filenames and no paths in output\n"; + s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nln, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-line-numbers= " + << Whitespace(sizePrefixDisplay*1) << "0 instead of real line numbers in output\n"; + // ================================================================================== << 79 + // clang-format on + + s << Color::Cyan << "\n[doctest] " << Color::None; + s << "for more information visit the project documentation\n\n"; + } + + void printRegisteredReporters() { + printVersion(); + auto printReporters = [this] (const reporterMap& reporters, const char* type) { + if(reporters.size()) { + s << Color::Cyan << "[doctest] " << Color::None << "listing all registered " << type << "\n"; + for(auto& curr : reporters) + s << "priority: " << std::setw(5) << curr.first.first + << " name: " << curr.first.second << "\n"; + } + }; + printReporters(getListeners(), "listeners"); + printReporters(getReporters(), "reporters"); + } + + // ========================================================================================= + // WHAT FOLLOWS ARE OVERRIDES OF THE VIRTUAL METHODS OF THE REPORTER INTERFACE + // ========================================================================================= + + void report_query(const QueryData& in) override { + if(opt.version) { + printVersion(); + } else if(opt.help) { + printHelp(); + } else if(opt.list_reporters) { + printRegisteredReporters(); + } else if(opt.count || opt.list_test_cases) { + if(opt.list_test_cases) { + s << Color::Cyan << "[doctest] " << Color::None + << "listing all test case names\n"; + separator_to_stream(); + } + + for(unsigned i = 0; i < in.num_data; ++i) + s << Color::None << in.data[i]->m_name << "\n"; + + separator_to_stream(); + + s << Color::Cyan << "[doctest] " << Color::None + << "unskipped test cases passing the current filters: " + << g_cs->numTestCasesPassingFilters << "\n"; + + } else if(opt.list_test_suites) { + s << Color::Cyan << "[doctest] " << Color::None << "listing all test suites\n"; + separator_to_stream(); + + for(unsigned i = 0; i < in.num_data; ++i) + s << Color::None << in.data[i]->m_test_suite << "\n"; + + separator_to_stream(); + + s << Color::Cyan << "[doctest] " << Color::None + << "unskipped test cases passing the current filters: " + << g_cs->numTestCasesPassingFilters << "\n"; + s << Color::Cyan << "[doctest] " << Color::None + << "test suites with unskipped test cases passing the current filters: " + << g_cs->numTestSuitesPassingFilters << "\n"; + } + } + + void test_run_start() override { + if(!opt.minimal) + printIntro(); + } + + void test_run_end(const TestRunStats& p) override { + if(opt.minimal && p.numTestCasesFailed == 0) + return; + + separator_to_stream(); + s << std::dec; + + auto totwidth = int(std::ceil(log10(static_cast(std::max(p.numTestCasesPassingFilters, static_cast(p.numAsserts))) + 1))); + auto passwidth = int(std::ceil(log10(static_cast(std::max(p.numTestCasesPassingFilters - p.numTestCasesFailed, static_cast(p.numAsserts - p.numAssertsFailed))) + 1))); + auto failwidth = int(std::ceil(log10(static_cast(std::max(p.numTestCasesFailed, static_cast(p.numAssertsFailed))) + 1))); + const bool anythingFailed = p.numTestCasesFailed > 0 || p.numAssertsFailed > 0; + s << Color::Cyan << "[doctest] " << Color::None << "test cases: " << std::setw(totwidth) + << p.numTestCasesPassingFilters << " | " + << ((p.numTestCasesPassingFilters == 0 || anythingFailed) ? Color::None : + Color::Green) + << std::setw(passwidth) << p.numTestCasesPassingFilters - p.numTestCasesFailed << " passed" + << Color::None << " | " << (p.numTestCasesFailed > 0 ? Color::Red : Color::None) + << std::setw(failwidth) << p.numTestCasesFailed << " failed" << Color::None << " |"; + if(opt.no_skipped_summary == false) { + const int numSkipped = p.numTestCases - p.numTestCasesPassingFilters; + s << " " << (numSkipped == 0 ? Color::None : Color::Yellow) << numSkipped + << " skipped" << Color::None; + } + s << "\n"; + s << Color::Cyan << "[doctest] " << Color::None << "assertions: " << std::setw(totwidth) + << p.numAsserts << " | " + << ((p.numAsserts == 0 || anythingFailed) ? Color::None : Color::Green) + << std::setw(passwidth) << (p.numAsserts - p.numAssertsFailed) << " passed" << Color::None + << " | " << (p.numAssertsFailed > 0 ? Color::Red : Color::None) << std::setw(failwidth) + << p.numAssertsFailed << " failed" << Color::None << " |\n"; + s << Color::Cyan << "[doctest] " << Color::None + << "Status: " << (p.numTestCasesFailed > 0 ? Color::Red : Color::Green) + << ((p.numTestCasesFailed > 0) ? "FAILURE!" : "SUCCESS!") << Color::None << std::endl; + } + + void test_case_start(const TestCaseData& in) override { + hasLoggedCurrentTestStart = false; + tc = ∈ + subcasesStack.clear(); + currentSubcaseLevel = 0; + } + + void test_case_reenter(const TestCaseData&) override { + subcasesStack.clear(); + } + + void test_case_end(const CurrentTestCaseStats& st) override { + if(tc->m_no_output) + return; + + // log the preamble of the test case only if there is something + // else to print - something other than that an assert has failed + if(opt.duration || + (st.failure_flags && st.failure_flags != static_cast(TestCaseFailureReason::AssertFailure))) + logTestStart(); + + if(opt.duration) + s << Color::None << std::setprecision(6) << std::fixed << st.seconds + << " s: " << tc->m_name << "\n"; + + if(st.failure_flags & TestCaseFailureReason::Timeout) + s << Color::Red << "Test case exceeded time limit of " << std::setprecision(6) + << std::fixed << tc->m_timeout << "!\n"; + + if(st.failure_flags & TestCaseFailureReason::ShouldHaveFailedButDidnt) { + s << Color::Red << "Should have failed but didn't! Marking it as failed!\n"; + } else if(st.failure_flags & TestCaseFailureReason::ShouldHaveFailedAndDid) { + s << Color::Yellow << "Failed as expected so marking it as not failed\n"; + } else if(st.failure_flags & TestCaseFailureReason::CouldHaveFailedAndDid) { + s << Color::Yellow << "Allowed to fail so marking it as not failed\n"; + } else if(st.failure_flags & TestCaseFailureReason::DidntFailExactlyNumTimes) { + s << Color::Red << "Didn't fail exactly " << tc->m_expected_failures + << " times so marking it as failed!\n"; + } else if(st.failure_flags & TestCaseFailureReason::FailedExactlyNumTimes) { + s << Color::Yellow << "Failed exactly " << tc->m_expected_failures + << " times as expected so marking it as not failed!\n"; + } + if(st.failure_flags & TestCaseFailureReason::TooManyFailedAsserts) { + s << Color::Red << "Aborting - too many failed asserts!\n"; + } + s << Color::None; // lgtm [cpp/useless-expression] + } + + void test_case_exception(const TestCaseException& e) override { + DOCTEST_LOCK_MUTEX(mutex) + if(tc->m_no_output) + return; + + logTestStart(); + + file_line_to_stream(tc->m_file.c_str(), tc->m_line, " "); + successOrFailColoredStringToStream(false, e.is_crash ? assertType::is_require : + assertType::is_check); + s << Color::Red << (e.is_crash ? "test case CRASHED: " : "test case THREW exception: ") + << Color::Cyan << e.error_string << "\n"; + + int num_stringified_contexts = get_num_stringified_contexts(); + if(num_stringified_contexts) { + auto stringified_contexts = get_stringified_contexts(); + s << Color::None << " logged: "; + for(int i = num_stringified_contexts; i > 0; --i) { + s << (i == num_stringified_contexts ? "" : " ") + << stringified_contexts[i - 1] << "\n"; + } + } + s << "\n" << Color::None; + } + + void subcase_start(const SubcaseSignature& subc) override { + subcasesStack.push_back(subc); + ++currentSubcaseLevel; + hasLoggedCurrentTestStart = false; + } + + void subcase_end() override { + --currentSubcaseLevel; + hasLoggedCurrentTestStart = false; + } + + void log_assert(const AssertData& rb) override { + if((!rb.m_failed && !opt.success) || tc->m_no_output) + return; + + DOCTEST_LOCK_MUTEX(mutex) + + logTestStart(); + + file_line_to_stream(rb.m_file, rb.m_line, " "); + successOrFailColoredStringToStream(!rb.m_failed, rb.m_at); + + fulltext_log_assert_to_stream(s, rb); + + log_contexts(); + } + + void log_message(const MessageData& mb) override { + if(tc->m_no_output) + return; + + DOCTEST_LOCK_MUTEX(mutex) + + logTestStart(); + + file_line_to_stream(mb.m_file, mb.m_line, " "); + s << getSuccessOrFailColor(false, mb.m_severity) + << getSuccessOrFailString(mb.m_severity & assertType::is_warn, mb.m_severity, + "MESSAGE") << ": "; + s << Color::None << mb.m_string << "\n"; + log_contexts(); + } + + void test_case_skipped(const TestCaseData&) override {} + }; + + DOCTEST_REGISTER_REPORTER("console", 0, ConsoleReporter); + +#ifdef DOCTEST_PLATFORM_WINDOWS + struct DebugOutputWindowReporter : public ConsoleReporter + { + DOCTEST_THREAD_LOCAL static std::ostringstream oss; + + DebugOutputWindowReporter(const ContextOptions& co) + : ConsoleReporter(co, oss) {} + +#define DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(func, type, arg) \ + void func(type arg) override { \ + bool with_col = g_no_colors; \ + g_no_colors = false; \ + ConsoleReporter::func(arg); \ + if(oss.tellp() != std::streampos{}) { \ + DOCTEST_OUTPUT_DEBUG_STRING(oss.str().c_str()); \ + oss.str(""); \ + } \ + g_no_colors = with_col; \ + } + + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_run_start, DOCTEST_EMPTY, DOCTEST_EMPTY) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_run_end, const TestRunStats&, in) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_start, const TestCaseData&, in) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_reenter, const TestCaseData&, in) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_end, const CurrentTestCaseStats&, in) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_exception, const TestCaseException&, in) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(subcase_start, const SubcaseSignature&, in) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(subcase_end, DOCTEST_EMPTY, DOCTEST_EMPTY) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(log_assert, const AssertData&, in) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(log_message, const MessageData&, in) + DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_skipped, const TestCaseData&, in) + }; + + DOCTEST_THREAD_LOCAL std::ostringstream DebugOutputWindowReporter::oss; +#endif // DOCTEST_PLATFORM_WINDOWS + + // the implementation of parseOption() + bool parseOptionImpl(int argc, const char* const* argv, const char* pattern, String* value) { + // going from the end to the beginning and stopping on the first occurrence from the end + for(int i = argc; i > 0; --i) { + auto index = i - 1; + auto temp = std::strstr(argv[index], pattern); + if(temp && (value || strlen(temp) == strlen(pattern))) { //!OCLINT prefer early exits and continue + // eliminate matches in which the chars before the option are not '-' + bool noBadCharsFound = true; + auto curr = argv[index]; + while(curr != temp) { + if(*curr++ != '-') { + noBadCharsFound = false; + break; + } + } + if(noBadCharsFound && argv[index][0] == '-') { + if(value) { + // parsing the value of an option + temp += strlen(pattern); + const unsigned len = strlen(temp); + if(len) { + *value = temp; + return true; + } + } else { + // just a flag - no value + return true; + } + } + } + } + return false; + } + + // parses an option and returns the string after the '=' character + bool parseOption(int argc, const char* const* argv, const char* pattern, String* value = nullptr, + const String& defaultVal = String()) { + if(value) + *value = defaultVal; +#ifndef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS + // offset (normally 3 for "dt-") to skip prefix + if(parseOptionImpl(argc, argv, pattern + strlen(DOCTEST_CONFIG_OPTIONS_PREFIX), value)) + return true; +#endif // DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS + return parseOptionImpl(argc, argv, pattern, value); + } + + // locates a flag on the command line + bool parseFlag(int argc, const char* const* argv, const char* pattern) { + return parseOption(argc, argv, pattern); + } + + // parses a comma separated list of words after a pattern in one of the arguments in argv + bool parseCommaSepArgs(int argc, const char* const* argv, const char* pattern, + std::vector& res) { + String filtersString; + if(parseOption(argc, argv, pattern, &filtersString)) { + // tokenize with "," as a separator, unless escaped with backslash + std::ostringstream s; + auto flush = [&s, &res]() { + auto string = s.str(); + if(string.size() > 0) { + res.push_back(string.c_str()); + } + s.str(""); + }; + + bool seenBackslash = false; + const char* current = filtersString.c_str(); + const char* end = current + strlen(current); + while(current != end) { + char character = *current++; + if(seenBackslash) { + seenBackslash = false; + if(character == ',' || character == '\\') { + s.put(character); + continue; + } + s.put('\\'); + } + if(character == '\\') { + seenBackslash = true; + } else if(character == ',') { + flush(); + } else { + s.put(character); + } + } + + if(seenBackslash) { + s.put('\\'); + } + flush(); + return true; + } + return false; + } + + enum optionType + { + option_bool, + option_int + }; + + // parses an int/bool option from the command line + bool parseIntOption(int argc, const char* const* argv, const char* pattern, optionType type, + int& res) { + String parsedValue; + if(!parseOption(argc, argv, pattern, &parsedValue)) + return false; + + if(type) { + // integer + // TODO: change this to use std::stoi or something else! currently it uses undefined behavior - assumes '0' on failed parse... + int theInt = std::atoi(parsedValue.c_str()); + if (theInt != 0) { + res = theInt; //!OCLINT parameter reassignment + return true; + } + } else { + // boolean + const char positive[][5] = { "1", "true", "on", "yes" }; // 5 - strlen("true") + 1 + const char negative[][6] = { "0", "false", "off", "no" }; // 6 - strlen("false") + 1 + + // if the value matches any of the positive/negative possibilities + for (unsigned i = 0; i < 4; i++) { + if (parsedValue.compare(positive[i], true) == 0) { + res = 1; //!OCLINT parameter reassignment + return true; + } + if (parsedValue.compare(negative[i], true) == 0) { + res = 0; //!OCLINT parameter reassignment + return true; + } + } + } + return false; + } +} // namespace + +Context::Context(int argc, const char* const* argv) + : p(new detail::ContextState) { + parseArgs(argc, argv, true); + if(argc) + p->binary_name = argv[0]; +} + +Context::~Context() { + if(g_cs == p) + g_cs = nullptr; + delete p; +} + +void Context::applyCommandLine(int argc, const char* const* argv) { + parseArgs(argc, argv); + if(argc) + p->binary_name = argv[0]; +} + +// parses args +void Context::parseArgs(int argc, const char* const* argv, bool withDefaults) { + using namespace detail; + + // clang-format off + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "source-file=", p->filters[0]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sf=", p->filters[0]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "source-file-exclude=",p->filters[1]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sfe=", p->filters[1]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-suite=", p->filters[2]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "ts=", p->filters[2]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-suite-exclude=", p->filters[3]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "tse=", p->filters[3]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-case=", p->filters[4]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "tc=", p->filters[4]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-case-exclude=", p->filters[5]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "tce=", p->filters[5]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "subcase=", p->filters[6]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sc=", p->filters[6]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "subcase-exclude=", p->filters[7]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sce=", p->filters[7]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "reporters=", p->filters[8]); + parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "r=", p->filters[8]); + // clang-format on + + int intRes = 0; + String strRes; + +#define DOCTEST_PARSE_AS_BOOL_OR_FLAG(name, sname, var, default) \ + if(parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name "=", option_bool, intRes) || \ + parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname "=", option_bool, intRes)) \ + p->var = static_cast(intRes); \ + else if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name) || \ + parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname)) \ + p->var = true; \ + else if(withDefaults) \ + p->var = default + +#define DOCTEST_PARSE_INT_OPTION(name, sname, var, default) \ + if(parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name "=", option_int, intRes) || \ + parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname "=", option_int, intRes)) \ + p->var = intRes; \ + else if(withDefaults) \ + p->var = default + +#define DOCTEST_PARSE_STR_OPTION(name, sname, var, default) \ + if(parseOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name "=", &strRes, default) || \ + parseOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname "=", &strRes, default) || \ + withDefaults) \ + p->var = strRes + + // clang-format off + DOCTEST_PARSE_STR_OPTION("out", "o", out, ""); + DOCTEST_PARSE_STR_OPTION("order-by", "ob", order_by, "file"); + DOCTEST_PARSE_INT_OPTION("rand-seed", "rs", rand_seed, 0); + + DOCTEST_PARSE_INT_OPTION("first", "f", first, 0); + DOCTEST_PARSE_INT_OPTION("last", "l", last, UINT_MAX); + + DOCTEST_PARSE_INT_OPTION("abort-after", "aa", abort_after, 0); + DOCTEST_PARSE_INT_OPTION("subcase-filter-levels", "scfl", subcase_filter_levels, INT_MAX); + + DOCTEST_PARSE_AS_BOOL_OR_FLAG("success", "s", success, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("case-sensitive", "cs", case_sensitive, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("exit", "e", exit, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("duration", "d", duration, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("minimal", "m", minimal, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("quiet", "q", quiet, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-throw", "nt", no_throw, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-exitcode", "ne", no_exitcode, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-run", "nr", no_run, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-intro", "ni", no_intro, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-version", "nv", no_version, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-colors", "nc", no_colors, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("force-colors", "fc", force_colors, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-breaks", "nb", no_breaks, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-skip", "ns", no_skip, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("gnu-file-line", "gfl", gnu_file_line, !bool(DOCTEST_MSVC)); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-path-filenames", "npf", no_path_in_filenames, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-line-numbers", "nln", no_line_numbers, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-debug-output", "ndo", no_debug_output, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-skipped-summary", "nss", no_skipped_summary, false); + DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-time-in-output", "ntio", no_time_in_output, false); + // clang-format on + + if(withDefaults) { + p->help = false; + p->version = false; + p->count = false; + p->list_test_cases = false; + p->list_test_suites = false; + p->list_reporters = false; + } + if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "help") || + parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "h") || + parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "?")) { + p->help = true; + p->exit = true; + } + if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "version") || + parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "v")) { + p->version = true; + p->exit = true; + } + if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "count") || + parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "c")) { + p->count = true; + p->exit = true; + } + if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "list-test-cases") || + parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "ltc")) { + p->list_test_cases = true; + p->exit = true; + } + if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "list-test-suites") || + parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "lts")) { + p->list_test_suites = true; + p->exit = true; + } + if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "list-reporters") || + parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "lr")) { + p->list_reporters = true; + p->exit = true; + } +} + +// allows the user to add procedurally to the filters from the command line +void Context::addFilter(const char* filter, const char* value) { setOption(filter, value); } + +// allows the user to clear all filters from the command line +void Context::clearFilters() { + for(auto& curr : p->filters) + curr.clear(); +} + +// allows the user to override procedurally the bool options from the command line +void Context::setOption(const char* option, bool value) { + setOption(option, value ? "true" : "false"); +} + +// allows the user to override procedurally the int options from the command line +void Context::setOption(const char* option, int value) { + setOption(option, toString(value).c_str()); +} + +// allows the user to override procedurally the string options from the command line +void Context::setOption(const char* option, const char* value) { + auto argv = String("-") + option + "=" + value; + auto lvalue = argv.c_str(); + parseArgs(1, &lvalue); +} + +// users should query this in their main() and exit the program if true +bool Context::shouldExit() { return p->exit; } + +void Context::setAsDefaultForAssertsOutOfTestCases() { g_cs = p; } + +void Context::setAssertHandler(detail::assert_handler ah) { p->ah = ah; } + +void Context::setCout(std::ostream* out) { p->cout = out; } + +static class DiscardOStream : public std::ostream +{ +private: + class : public std::streambuf + { + private: + // allowing some buffering decreases the amount of calls to overflow + char buf[1024]; + + protected: + std::streamsize xsputn(const char_type*, std::streamsize count) override { return count; } + + int_type overflow(int_type ch) override { + setp(std::begin(buf), std::end(buf)); + return traits_type::not_eof(ch); + } + } discardBuf; + +public: + DiscardOStream() + : std::ostream(&discardBuf) {} +} discardOut; + +// the main function that does all the filtering and test running +int Context::run() { + using namespace detail; + + // save the old context state in case such was setup - for using asserts out of a testing context + auto old_cs = g_cs; + // this is the current contest + g_cs = p; + is_running_in_test = true; + + g_no_colors = p->no_colors; + p->resetRunData(); + + std::fstream fstr; + if(p->cout == nullptr) { + if(p->quiet) { + p->cout = &discardOut; + } else if(p->out.size()) { + // to a file if specified + fstr.open(p->out.c_str(), std::fstream::out); + p->cout = &fstr; + } else { +#ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM + // stdout by default + p->cout = &std::cout; +#else // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM + return EXIT_FAILURE; +#endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM + } + } + + FatalConditionHandler::allocateAltStackMem(); + + auto cleanup_and_return = [&]() { + FatalConditionHandler::freeAltStackMem(); + + if(fstr.is_open()) + fstr.close(); + + // restore context + g_cs = old_cs; + is_running_in_test = false; + + // we have to free the reporters which were allocated when the run started + for(auto& curr : p->reporters_currently_used) + delete curr; + p->reporters_currently_used.clear(); + + if(p->numTestCasesFailed && !p->no_exitcode) + return EXIT_FAILURE; + return EXIT_SUCCESS; + }; + + // setup default reporter if none is given through the command line + if(p->filters[8].empty()) + p->filters[8].push_back("console"); + + // check to see if any of the registered reporters has been selected + for(auto& curr : getReporters()) { + if(matchesAny(curr.first.second.c_str(), p->filters[8], false, p->case_sensitive)) + p->reporters_currently_used.push_back(curr.second(*g_cs)); + } + + // TODO: check if there is nothing in reporters_currently_used + + // prepend all listeners + for(auto& curr : getListeners()) + p->reporters_currently_used.insert(p->reporters_currently_used.begin(), curr.second(*g_cs)); + +#ifdef DOCTEST_PLATFORM_WINDOWS + if(isDebuggerActive() && p->no_debug_output == false) + p->reporters_currently_used.push_back(new DebugOutputWindowReporter(*g_cs)); +#endif // DOCTEST_PLATFORM_WINDOWS + + // handle version, help and no_run + if(p->no_run || p->version || p->help || p->list_reporters) { + DOCTEST_ITERATE_THROUGH_REPORTERS(report_query, QueryData()); + + return cleanup_and_return(); + } + + std::vector testArray; + for(auto& curr : getRegisteredTests()) + testArray.push_back(&curr); + p->numTestCases = testArray.size(); + + // sort the collected records + if(!testArray.empty()) { + if(p->order_by.compare("file", true) == 0) { + std::sort(testArray.begin(), testArray.end(), fileOrderComparator); + } else if(p->order_by.compare("suite", true) == 0) { + std::sort(testArray.begin(), testArray.end(), suiteOrderComparator); + } else if(p->order_by.compare("name", true) == 0) { + std::sort(testArray.begin(), testArray.end(), nameOrderComparator); + } else if(p->order_by.compare("rand", true) == 0) { + std::srand(p->rand_seed); + + // random_shuffle implementation + const auto first = &testArray[0]; + for(size_t i = testArray.size() - 1; i > 0; --i) { + int idxToSwap = std::rand() % (i + 1); + + const auto temp = first[i]; + + first[i] = first[idxToSwap]; + first[idxToSwap] = temp; + } + } else if(p->order_by.compare("none", true) == 0) { + // means no sorting - beneficial for death tests which call into the executable + // with a specific test case in mind - we don't want to slow down the startup times + } + } + + std::set testSuitesPassingFilt; + + bool query_mode = p->count || p->list_test_cases || p->list_test_suites; + std::vector queryResults; + + if(!query_mode) + DOCTEST_ITERATE_THROUGH_REPORTERS(test_run_start, DOCTEST_EMPTY); + + // invoke the registered functions if they match the filter criteria (or just count them) + for(auto& curr : testArray) { + const auto& tc = *curr; + + bool skip_me = false; + if(tc.m_skip && !p->no_skip) + skip_me = true; + + if(!matchesAny(tc.m_file.c_str(), p->filters[0], true, p->case_sensitive)) + skip_me = true; + if(matchesAny(tc.m_file.c_str(), p->filters[1], false, p->case_sensitive)) + skip_me = true; + if(!matchesAny(tc.m_test_suite, p->filters[2], true, p->case_sensitive)) + skip_me = true; + if(matchesAny(tc.m_test_suite, p->filters[3], false, p->case_sensitive)) + skip_me = true; + if(!matchesAny(tc.m_name, p->filters[4], true, p->case_sensitive)) + skip_me = true; + if(matchesAny(tc.m_name, p->filters[5], false, p->case_sensitive)) + skip_me = true; + + if(!skip_me) + p->numTestCasesPassingFilters++; + + // skip the test if it is not in the execution range + if((p->last < p->numTestCasesPassingFilters && p->first <= p->last) || + (p->first > p->numTestCasesPassingFilters)) + skip_me = true; + + if(skip_me) { + if(!query_mode) + DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_skipped, tc); + continue; + } + + // do not execute the test if we are to only count the number of filter passing tests + if(p->count) + continue; + + // print the name of the test and don't execute it + if(p->list_test_cases) { + queryResults.push_back(&tc); + continue; + } + + // print the name of the test suite if not done already and don't execute it + if(p->list_test_suites) { + if((testSuitesPassingFilt.count(tc.m_test_suite) == 0) && tc.m_test_suite[0] != '\0') { + queryResults.push_back(&tc); + testSuitesPassingFilt.insert(tc.m_test_suite); + p->numTestSuitesPassingFilters++; + } + continue; + } + + // execute the test if it passes all the filtering + { + p->currentTest = &tc; + + p->failure_flags = TestCaseFailureReason::None; + p->seconds = 0; + + // reset atomic counters + p->numAssertsFailedCurrentTest_atomic = 0; + p->numAssertsCurrentTest_atomic = 0; + + p->fullyTraversedSubcases.clear(); + + DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_start, tc); + + p->timer.start(); + + bool run_test = true; + + do { + // reset some of the fields for subcases (except for the set of fully passed ones) + p->reachedLeaf = false; + // May not be empty if previous subcase exited via exception. + p->subcaseStack.clear(); + p->currentSubcaseDepth = 0; + + p->shouldLogCurrentException = true; + + // reset stuff for logging with INFO() + p->stringifiedContexts.clear(); + +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + try { +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS +// MSVC 2015 diagnoses fatalConditionHandler as unused (because reset() is a static method) +DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4101) // unreferenced local variable + FatalConditionHandler fatalConditionHandler; // Handle signals + // execute the test + tc.m_test(); + fatalConditionHandler.reset(); +DOCTEST_MSVC_SUPPRESS_WARNING_POP +#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS + } catch(const TestFailureException&) { + p->failure_flags |= TestCaseFailureReason::AssertFailure; + } catch(...) { + DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_exception, + {translateActiveException(), false}); + p->failure_flags |= TestCaseFailureReason::Exception; + } +#endif // DOCTEST_CONFIG_NO_EXCEPTIONS + + // exit this loop if enough assertions have failed - even if there are more subcases + if(p->abort_after > 0 && + p->numAssertsFailed + p->numAssertsFailedCurrentTest_atomic >= p->abort_after) { + run_test = false; + p->failure_flags |= TestCaseFailureReason::TooManyFailedAsserts; + } + + if(!p->nextSubcaseStack.empty() && run_test) + DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_reenter, tc); + if(p->nextSubcaseStack.empty()) + run_test = false; + } while(run_test); + + p->finalizeTestCaseData(); + + DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_end, *g_cs); + + p->currentTest = nullptr; + + // stop executing tests if enough assertions have failed + if(p->abort_after > 0 && p->numAssertsFailed >= p->abort_after) + break; + } + } + + if(!query_mode) { + DOCTEST_ITERATE_THROUGH_REPORTERS(test_run_end, *g_cs); + } else { + QueryData qdata; + qdata.run_stats = g_cs; + qdata.data = queryResults.data(); + qdata.num_data = unsigned(queryResults.size()); + DOCTEST_ITERATE_THROUGH_REPORTERS(report_query, qdata); + } + + return cleanup_and_return(); +} + +DOCTEST_DEFINE_INTERFACE(IReporter) + +int IReporter::get_num_active_contexts() { return detail::g_infoContexts.size(); } +const IContextScope* const* IReporter::get_active_contexts() { + return get_num_active_contexts() ? &detail::g_infoContexts[0] : nullptr; +} + +int IReporter::get_num_stringified_contexts() { return detail::g_cs->stringifiedContexts.size(); } +const String* IReporter::get_stringified_contexts() { + return get_num_stringified_contexts() ? &detail::g_cs->stringifiedContexts[0] : nullptr; +} + +namespace detail { + void registerReporterImpl(const char* name, int priority, reporterCreatorFunc c, bool isReporter) { + if(isReporter) + getReporters().insert(reporterMap::value_type(reporterMap::key_type(priority, name), c)); + else + getListeners().insert(reporterMap::value_type(reporterMap::key_type(priority, name), c)); + } +} // namespace detail + +} // namespace doctest + +#endif // DOCTEST_CONFIG_DISABLE + +#ifdef DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4007) // 'function' : must be 'attribute' - see issue #182 +int main(int argc, char** argv) { return doctest::Context(argc, argv).run(); } +DOCTEST_MSVC_SUPPRESS_WARNING_POP +#endif // DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN + +DOCTEST_CLANG_SUPPRESS_WARNING_POP +DOCTEST_MSVC_SUPPRESS_WARNING_POP +DOCTEST_GCC_SUPPRESS_WARNING_POP + +DOCTEST_SUPPRESS_COMMON_WARNINGS_POP + +#endif // DOCTEST_LIBRARY_IMPLEMENTATION +#endif // DOCTEST_CONFIG_IMPLEMENT + +#ifdef DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN +#undef WIN32_LEAN_AND_MEAN +#undef DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN +#endif // DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN + +#ifdef DOCTEST_UNDEF_NOMINMAX +#undef NOMINMAX +#undef DOCTEST_UNDEF_NOMINMAX +#endif // DOCTEST_UNDEF_NOMINMAX diff --git a/indra/llcommon/CMakeLists.txt b/indra/llcommon/CMakeLists.txt index 2de9deea701..9af8940ef4f 100644 --- a/indra/llcommon/CMakeLists.txt +++ b/indra/llcommon/CMakeLists.txt @@ -287,6 +287,7 @@ add_dependencies(llcommon stage_third_party_libs) if (LL_TESTS) include(LLAddBuildTest) + include(Doctest) SET(llcommon_TEST_SOURCE_FILES # unit-testing llcommon is not possible right now as the test-harness *itself* depends upon llcommon, causing a circular dependency. Add your 'unit' tests as integration tests for now. ) @@ -336,4 +337,6 @@ if (LL_TESTS) ## throwing and catching exceptions. ##LL_ADD_INTEGRATION_TEST(llexception "" "${test_libs}") + add_subdirectory(tests_doctest) + endif (LL_TESTS) diff --git a/indra/llcommon/tests_doctest/CMakeLists.txt b/indra/llcommon/tests_doctest/CMakeLists.txt new file mode 100644 index 00000000000..978a893c0c1 --- /dev/null +++ b/indra/llcommon/tests_doctest/CMakeLists.txt @@ -0,0 +1,23 @@ +file(GLOB LLCOMMON_DOCTEST_SOURCES + "${CMAKE_CURRENT_SOURCE_DIR}/*_doctest.cpp" +) + +add_executable(llcommon_doctest + ${LLCOMMON_DOCTEST_SOURCES} + ${CMAKE_SOURCE_DIR}/test/doctest_main.cpp +) + +target_include_directories(llcommon_doctest + PRIVATE + ${CMAKE_SOURCE_DIR} + ${DOCTEST_INCLUDE_DIR} + ${CMAKE_SOURCE_DIR}/test + ${CMAKE_SOURCE_DIR}/llcommon + ${CMAKE_SOURCE_DIR}/llcommon/tests +) + +target_link_libraries(llcommon_doctest + llcommon +) + +add_test(NAME llcommon_doctest COMMAND llcommon_doctest) diff --git a/indra/llcommon/tests_doctest/apply_test_doctest.cpp b/indra/llcommon/tests_doctest/apply_test_doctest.cpp new file mode 100644 index 00000000000..5ea52666a49 --- /dev/null +++ b/indra/llcommon/tests_doctest/apply_test_doctest.cpp @@ -0,0 +1,167 @@ +/** + * @file apply_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for apply + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from apply_test.cpp at 2025-10-16T18:47:16Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "apply.h" +#include +#include "llsd.h" +#include "llsdutil.h" +#include +#include +#include + +TUT_SUITE("llcommon") +{ + TUT_CASE("apply_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert apply_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // set_test_name("apply(tuple)"); + // LL::apply(statics::various, + // std::make_tuple(statics::b, statics::i, statics::f, statics::s, + // statics::uu, statics::dt, statics::uri, statics::bin)); + // ensure("apply(tuple) failed", statics::called); + // } + } + + TUT_CASE("apply_test::object_test_2") + { + DOCTEST_FAIL("TODO: convert apply_test.cpp::object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<2>() + // { + // set_test_name("apply(array)"); + // LL::apply(statics::ints, statics::fibs); + // ensure("apply(array) failed", statics::called); + // } + } + + TUT_CASE("apply_test::object_test_3") + { + DOCTEST_FAIL("TODO: convert apply_test.cpp::object::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<3>() + // { + // set_test_name("apply(vector)"); + // LL::apply(statics::strings, statics::quick); + // ensure("apply(vector) failed", statics::called); + // } + } + + TUT_CASE("apply_test::object_test_4") + { + DOCTEST_FAIL("TODO: convert apply_test.cpp::object::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<4>() + // { + // set_test_name("apply(LLSD())"); + // LL::apply(statics::voidfunc, LLSD()); + // ensure("apply(LLSD()) failed", statics::called); + // } + } + + TUT_CASE("apply_test::object_test_5") + { + DOCTEST_FAIL("TODO: convert apply_test.cpp::object::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<5>() + // { + // set_test_name("apply(fn(int), LLSD scalar)"); + // LL::apply(statics::intfunc, LLSD(statics::i)); + // ensure("apply(fn(int), LLSD scalar) failed", statics::called); + // } + } + + TUT_CASE("apply_test::object_test_6") + { + DOCTEST_FAIL("TODO: convert apply_test.cpp::object::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<6>() + // { + // set_test_name("apply(fn(LLSD), LLSD scalar)"); + // // This test verifies that LLSDParam doesn't send the compiler + // // into infinite recursion when the target is itself LLSD. + // LL::apply(statics::sdfunc, LLSD(statics::i)); + // ensure("apply(fn(LLSD), LLSD scalar) failed", statics::called); + // } + } + + TUT_CASE("apply_test::object_test_7") + { + DOCTEST_FAIL("TODO: convert apply_test.cpp::object::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<7>() + // { + // set_test_name("apply(LLSD array)"); + // LL::apply(statics::various, + // llsd::array(statics::b, statics::i, statics::f, statics::s, + // statics::uu, statics::dt, statics::uri, statics::bin)); + // ensure("apply(LLSD array) failed", statics::called); + // } + } + + TUT_CASE("apply_test::object_test_8") + { + DOCTEST_FAIL("TODO: convert apply_test.cpp::object::test<8> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<8>() + // { + // set_test_name("VAPPLY()"); + // // Make a std::array from statics::quick. We can't call a + // // variadic function with a data structure of dynamic length. + // std::array strray; + // for (size_t i = 0; i < strray.size(); ++i) + // strray[i] = statics::quick[i]; + // // This doesn't work: the compiler doesn't know which overload of + // // collect() to pass to LL::apply(). + // // LL::apply(statics::collect, strray); + // // That's what VAPPLY() is for. + // VAPPLY(statics::collect, strray); + // ensure("VAPPLY() failed", statics::called); + // ensure_equals("collected mismatch", statics::collected, statics::quick); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/bitpack_test_doctest.cpp b/indra/llcommon/tests_doctest/bitpack_test_doctest.cpp new file mode 100644 index 00000000000..76e14a54ba9 --- /dev/null +++ b/indra/llcommon/tests_doctest/bitpack_test_doctest.cpp @@ -0,0 +1,127 @@ +/** + * @file bitpack_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for bitpack + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from bitpack_test.cpp at 2025-10-16T18:47:16Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "../llbitpack.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("bitpack_test::bit_pack_object_t_test_1") + { + DOCTEST_FAIL("TODO: convert bitpack_test.cpp::bit_pack_object_t::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void bit_pack_object_t::test<1>() + // { + // U8 packbuffer[255]; + // U8 unpackbuffer[255]; + // int pack_bufsize = 0; + // int unpack_bufsize = 0; + + // LLBitPack bitpack(packbuffer, 255); + + // char str[] = "SecondLife is a 3D virtual world"; + // int len = sizeof(str); + // pack_bufsize = bitpack.bitPack((U8*) str, len*8); + // pack_bufsize = bitpack.flushBitPack(); + + // LLBitPack bitunpack(packbuffer, pack_bufsize*8); + // unpack_bufsize = bitunpack.bitUnpack(unpackbuffer, len*8); + // ensure("bitPack: unpack size should be same as string size prior to pack", len == unpack_bufsize); + // ensure_memory_matches("str->bitPack->bitUnpack should be equal to string", str, len, unpackbuffer, unpack_bufsize); + // } + } + + TUT_CASE("bitpack_test::bit_pack_object_t_test_2") + { + DOCTEST_FAIL("TODO: convert bitpack_test.cpp::bit_pack_object_t::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void bit_pack_object_t::test<2>() + // { + // U8 packbuffer[255]; + // U8 unpackbuffer[255]; + // int pack_bufsize = 0; + + // LLBitPack bitpack(packbuffer, 255); + + // char str[] = "SecondLife"; + // int len = sizeof(str); + // pack_bufsize = bitpack.bitPack((U8*) str, len*8); + // pack_bufsize = bitpack.flushBitPack(); + + // LLBitPack bitunpack(packbuffer, pack_bufsize*8); + // bitunpack.bitUnpack(&unpackbuffer[0], 8); + // ensure("bitPack: individual unpack: 0", unpackbuffer[0] == (U8) str[0]); + // bitunpack.bitUnpack(&unpackbuffer[0], 8); + // ensure("bitPack: individual unpack: 1", unpackbuffer[0] == (U8) str[1]); + // bitunpack.bitUnpack(&unpackbuffer[0], 8); + // ensure("bitPack: individual unpack: 2", unpackbuffer[0] == (U8) str[2]); + // bitunpack.bitUnpack(&unpackbuffer[0], 8); + // ensure("bitPack: individual unpack: 3", unpackbuffer[0] == (U8) str[3]); + // bitunpack.bitUnpack(&unpackbuffer[0], 8); + // ensure("bitPack: individual unpack: 4", unpackbuffer[0] == (U8) str[4]); + // bitunpack.bitUnpack(&unpackbuffer[0], 8); + // ensure("bitPack: individual unpack: 5", unpackbuffer[0] == (U8) str[5]); + // bitunpack.bitUnpack(unpackbuffer, 8*4); // Life + // ensure_memory_matches("bitPack: 4 bytes unpack:", unpackbuffer, 4, str+6, 4); + // } + } + + TUT_CASE("bitpack_test::bit_pack_object_t_test_3") + { + DOCTEST_FAIL("TODO: convert bitpack_test.cpp::bit_pack_object_t::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void bit_pack_object_t::test<3>() + // { + // U8 packbuffer[255]; + // int pack_bufsize = 0; + + // LLBitPack bitpack(packbuffer, 255); + // U32 num = 0x41fab67a; + // pack_bufsize = bitpack.bitPack((U8*)&num, 8*sizeof(U32)); + // pack_bufsize = bitpack.flushBitPack(); + + // LLBitPack bitunpack(packbuffer, pack_bufsize*8); + // U32 res = 0; + // // since packing and unpacking is done on same machine in the unit test run, + // // endianness should not matter + // bitunpack.bitUnpack((U8*) &res, sizeof(res)*8); + // ensure("U32->bitPack->bitUnpack->U32 should be equal", num == res); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/classic_callback_test_doctest.cpp b/indra/llcommon/tests_doctest/classic_callback_test_doctest.cpp new file mode 100644 index 00000000000..07e52bded85 --- /dev/null +++ b/indra/llcommon/tests_doctest/classic_callback_test_doctest.cpp @@ -0,0 +1,95 @@ +/** + * @file classic_callback_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for classic callback + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from classic_callback_test.cpp at 2025-10-16T18:47:16Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "classic_callback.h" +#include +#include + +TUT_SUITE("llcommon") +{ + TUT_CASE("classic_callback_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert classic_callback_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // set_test_name("ClassicCallback"); + // // engage someAPI(MyCallback()) + // auto ccb{ makeClassicCallback(MyCallback()) }; + // someAPI(ccb.get_callback(), ccb.get_userdata()); + // // Unfortunately, with the side effect confined to the bound + // // MyCallback instance, that call was invisible. Bind a reference to a + // // named instance by specifying a ref type. + // MyCallback mcb; + // ClassicCallback ccb2(mcb); + // someAPI(ccb2.get_callback(), ccb2.get_userdata()); + // ensure_equals("failed to call through ClassicCallback", mcb.mMsg, "called"); + + // // try with HeapClassicCallback + // mcb.mMsg.clear(); + // auto hcbp{ makeHeapClassicCallback(mcb) }; + // someAPI(hcbp->get_callback(), hcbp->get_userdata()); + // ensure_equals("failed to call through HeapClassicCallback", mcb.mMsg, "called"); + + // // lambda + // // The tricky thing here is that a lambda is an unspecified type, so + // // you can't declare a ClassicCallback. + // mcb.mMsg.clear(); + // auto xcb( + // makeClassicCallback( + // [&mcb](const char* msg, void*) + // { mcb.callback_with_extra("extra", msg); })); + // someAPI(xcb.get_callback(), xcb.get_userdata()); + // ensure_equals("failed to call lambda", mcb.mMsg, "extra called"); + + // // engage otherAPI(OtherCallback()) + // OtherCallback ocb; + // // Instead of specifying a reference type for the bound CALLBACK, as + // // with ccb2 above, you can alternatively move the callable object + // // into the ClassicCallback (of course AFTER any other reference). + // // That's why OtherCallback uses external data for its observable side + // // effect. + // auto occb{ makeClassicCallback(std::move(ocb)) }; + // std::string result{ otherAPI(occb.get_callback(), occb.get_userdata()) }; + // ensure_equals("failed to return callback result", result, "hello back!"); + // ensure_equals("failed to set int", sData.mi, 17); + // ensure_equals("failed to set string", sData.ms, "hello world"); + // ensure_equals("failed to set double", sData.mf, 3.0); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/commonmisc_test_doctest.cpp b/indra/llcommon/tests_doctest/commonmisc_test_doctest.cpp new file mode 100644 index 00000000000..14427972ec2 --- /dev/null +++ b/indra/llcommon/tests_doctest/commonmisc_test_doctest.cpp @@ -0,0 +1,722 @@ +/** + * @file commonmisc_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for commonmisc + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from commonmisc_test.cpp at 2025-10-16T18:47:16Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include +#include +#include +#include "linden_common.h" +#include "../llmemorystream.h" +#include "../llsd.h" +#include "../llsdserialize.h" +#include "../u64.h" +#include "../llhash.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("commonmisc_test::sd_object_test_1") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::sd_object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_object::test<1>() + // { + // std::ostringstream resp; + // resp << "{'connect':true, 'position':[r128,r128,r128], 'look_at':[r0,r1,r0], 'agent_access':'M', 'region_x':i8192, 'region_y':i8192}"; + // std::string str = resp.str(); + // LLMemoryStream mstr((U8*)str.c_str(), static_cast(str.size())); + // LLSD response; + // S32 count = LLSDSerialize::fromNotation(response, mstr, str.size()); + // ensure("stream parsed", response.isDefined()); + // ensure_equals("stream parse count", count, 13); + // ensure_equals("sd type", response.type(), LLSD::TypeMap); + // ensure_equals("map element count", response.size(), 6); + // ensure_equals("value connect", response["connect"].asBoolean(), true); + // ensure_equals("value region_x", response["region_x"].asInteger(),8192); + // ensure_equals("value region_y", response["region_y"].asInteger(),8192); + // } + } + + TUT_CASE("commonmisc_test::sd_object_test_2") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::sd_object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_object::test<2>() + // { + // const std::string decoded("random"); + // //const std::string encoded("cmFuZG9t\n"); + // const std::string streamed("b(6)\"random\""); + // typedef std::vector buf_t; + // buf_t buf; + // std::copy( + // decoded.begin(), + // decoded.end(), + // std::back_insert_iterator(buf)); + // LLSD sd; + // sd = buf; + // std::stringstream str; + // S32 count = LLSDSerialize::toNotation(sd, str); + // ensure_equals("output count", count, 1); + // std::string actual(str.str()); + // ensure_equals("formatted binary encoding", actual, streamed); + // sd.clear(); + // LLSDSerialize::fromNotation(sd, str, str.str().size()); + // std::vector after; + // after = sd.asBinary(); + // ensure_equals("binary decoded size", after.size(), decoded.size()); + // ensure("binary decoding", (0 == memcmp( + // &after[0], + // decoded.c_str(), + // decoded.size()))); + // } + } + + TUT_CASE("commonmisc_test::sd_object_test_3") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::sd_object::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_object::test<3>() + // { + // for(S32 i = 0; i < 100; ++i) + // { + // // gen up a starting point + // typedef std::vector buf_t; + // buf_t source; + // srand(i); /* Flawfinder: ignore */ + // S32 size = rand() % 1000 + 10; + // std::generate_n( + // std::back_insert_iterator(source), + // size, + // rand); + // LLSD sd(source); + // std::stringstream str; + // S32 count = LLSDSerialize::toNotation(sd, str); + // sd.clear(); + // ensure_equals("format count", count, 1); + // LLSD sd2; + // count = LLSDSerialize::fromNotation(sd2, str, str.str().size()); + // ensure_equals("parse count", count, 1); + // buf_t dest = sd2.asBinary(); + // str.str(""); + // str << "binary encoding size " << i; + // ensure_equals(str.str().c_str(), dest.size(), source.size()); + // str.str(""); + // str << "binary encoding " << i; + // ensure(str.str().c_str(), (source == dest)); + // } + // } + } + + TUT_CASE("commonmisc_test::sd_object_test_4") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::sd_object::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_object::test<4>() + // { + // std::ostringstream ostr; + // ostr << "{'task_id':u1fd77b79-a8e7-25a5-9454-02a4d948ba1c}\n" + // << "{\n\tname\tObject|\n}\n"; + // std::string expected = ostr.str(); + // std::stringstream serialized; + // serialized << "'" << LLSDNotationFormatter::escapeString(expected) + // << "'"; + // LLSD sd; + // S32 count = LLSDSerialize::fromNotation( + // sd, + // serialized, + // serialized.str().size()); + // ensure_equals("parse count", count, 1); + // ensure_equals("String streaming", sd.asString(), expected); + // } + } + + TUT_CASE("commonmisc_test::sd_object_test_5") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::sd_object::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_object::test<5>() + // { + // for(S32 i = 0; i < 100; ++i) + // { + // // gen up a starting point + // typedef std::vector buf_t; + // buf_t source; + // srand(666 + i); /* Flawfinder: ignore */ + // S32 size = rand() % 1000 + 10; + // std::generate_n( + // std::back_insert_iterator(source), + // size, + // rand); + // std::stringstream str; + // str << "b(" << size << ")\""; + // str.write((const char*)&source[0], size); + // str << "\""; + // LLSD sd; + // S32 count = LLSDSerialize::fromNotation(sd, str, str.str().size()); + // ensure_equals("binary parse", count, 1); + // buf_t actual = sd.asBinary(); + // ensure_equals("binary size", actual.size(), (size_t)size); + // ensure("binary data", (0 == memcmp(&source[0], &actual[0], size))); + // } + // } + } + + TUT_CASE("commonmisc_test::sd_object_test_6") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::sd_object::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_object::test<6>() + // { + // std::string expected("'{\"task_id\":u1fd77b79-a8e7-25a5-9454-02a4d948ba1c}'\t\n\t\t"); + // std::stringstream str; + // str << "s(" << expected.size() << ")'"; + // str.write(expected.c_str(), expected.size()); + // str << "'"; + // LLSD sd; + // S32 count = LLSDSerialize::fromNotation(sd, str, str.str().size()); + // ensure_equals("parse count", count, 1); + // std::string actual = sd.asString(); + // ensure_equals("string sizes", actual.size(), expected.size()); + // ensure_equals("string content", actual, expected); + // } + } + + TUT_CASE("commonmisc_test::sd_object_test_7") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::sd_object::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_object::test<7>() + // { + // std::string msg("come on in"); + // std::stringstream stream; + // stream << "{'connect':1, 'message':'" << msg << "'," + // << " 'position':[r45.65,r100.1,r25.5]," + // << " 'look_at':[r0,r1,r0]," + // << " 'agent_access':'PG'}"; + // LLSD sd; + // S32 count = LLSDSerialize::fromNotation( + // sd, + // stream, + // stream.str().size()); + // ensure_equals("parse count", count, 12); + // ensure_equals("bool value", sd["connect"].asBoolean(), true); + // ensure_equals("message value", sd["message"].asString(), msg); + // ensure_equals("pos x", sd["position"][0].asReal(), 45.65); + // ensure_equals("pos y", sd["position"][1].asReal(), 100.1); + // ensure_equals("pos z", sd["position"][2].asReal(), 25.5); + // ensure_equals("look x", sd["look_at"][0].asReal(), 0.0); + // ensure_equals("look y", sd["look_at"][1].asReal(), 1.0); + // ensure_equals("look z", sd["look_at"][2].asReal(), 0.0); + // } + } + + TUT_CASE("commonmisc_test::sd_object_test_8") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::sd_object::test<8> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_object::test<8>() + // { + // std::stringstream resp; + // resp << "{'label':'short string test', 'singlechar':'a', 'empty':'', 'endoftest':'end' }"; + // LLSD response; + // S32 count = LLSDSerialize::fromNotation( + // response, + // resp, + // resp.str().size()); + // ensure_equals("parse count", count, 5); + // ensure_equals("sd type", response.type(), LLSD::TypeMap); + // ensure_equals("map element count", response.size(), 4); + // ensure_equals("singlechar", response["singlechar"].asString(), "a"); + // ensure_equals("empty", response["empty"].asString(), ""); + // } + } + + TUT_CASE("commonmisc_test::sd_object_test_9") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::sd_object::test<9> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_object::test<9>() + // { + // std::ostringstream resp; + // resp << "{'label':'short binary test', 'singlebinary':b(1)\"A\", 'singlerawstring':s(1)\"A\", 'endoftest':'end' }"; + // std::string str = resp.str(); + // LLSD sd; + // LLMemoryStream mstr((U8*)str.c_str(), static_cast(str.size())); + // S32 count = LLSDSerialize::fromNotation(sd, mstr, str.size()); + // ensure_equals("parse count", count, 5); + // ensure("sd created", sd.isDefined()); + // ensure_equals("sd type", sd.type(), LLSD::TypeMap); + // ensure_equals("map element count", sd.size(), 4); + // ensure_equals( + // "label", + // sd["label"].asString(), + // "short binary test"); + // std::vector bin = sd["singlebinary"].asBinary(); + // std::vector expected; + // expected.resize(1); + // expected[0] = 'A'; + // ensure("single binary", (0 == memcmp(&bin[0], &expected[0], 1))); + // ensure_equals( + // "single string", + // sd["singlerawstring"].asString(), + // std::string("A")); + // ensure_equals("end", sd["endoftest"].asString(), "end"); + // } + } + + TUT_CASE("commonmisc_test::sd_object_test_10") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::sd_object::test<10> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_object::test<10>() + // { + + // std::string message("parcel '' is naughty."); + // std::stringstream str; + // str << "{'message':'" << LLSDNotationFormatter::escapeString(message) + // << "'}"; + // std::string expected_str("{'message':'parcel \\'\\' is naughty.'}"); + // std::string actual_str = str.str(); + // ensure_equals("stream contents", actual_str, expected_str); + // LLSD sd; + // S32 count = LLSDSerialize::fromNotation(sd, str, actual_str.size()); + // ensure_equals("parse count", count, 2); + // ensure("valid parse", sd.isDefined()); + // std::string actual = sd["message"].asString(); + // ensure_equals("message contents", actual, message); + // } + } + + TUT_CASE("commonmisc_test::sd_object_test_11") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::sd_object::test<11> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_object::test<11>() + // { + // std::string expected("\"\"\"\"''''''\""); + // std::stringstream str; + // str << "'" << LLSDNotationFormatter::escapeString(expected) << "'"; + // LLSD sd; + // S32 count = LLSDSerialize::fromNotation(sd, str, str.str().size()); + // ensure_equals("parse count", count, 1); + // ensure_equals("string value", sd.asString(), expected); + // } + } + + TUT_CASE("commonmisc_test::sd_object_test_12") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::sd_object::test<12> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_object::test<12>() + // { + // std::string expected("mytest\\"); + // std::stringstream str; + // str << "'" << LLSDNotationFormatter::escapeString(expected) << "'"; + // LLSD sd; + // S32 count = LLSDSerialize::fromNotation(sd, str, str.str().size()); + // ensure_equals("parse count", count, 1); + // ensure_equals("string value", sd.asString(), expected); + // } + } + + TUT_CASE("commonmisc_test::sd_object_test_13") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::sd_object::test<13> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_object::test<13>() + // { + // for(S32 i = 0; i < 1000; ++i) + // { + // // gen up a starting point + // std::string expected; + // srand(1337 + i); /* Flawfinder: ignore */ + // S32 size = rand() % 30 + 5; + // std::generate_n( + // std::back_insert_iterator(expected), + // size, + // rand); + // std::stringstream str; + // str << "'" << LLSDNotationFormatter::escapeString(expected) << "'"; + // LLSD sd; + // S32 count = LLSDSerialize::fromNotation(sd, str, expected.size()); + // ensure_equals("parse count", count, 1); + // std::string actual = sd.asString(); + // /* + // if(actual != expected) + // { + // LL_WARNS() << "iteration " << i << LL_ENDL; + // std::ostringstream e_str; + // std::string::iterator iter = expected.begin(); + // std::string::iterator end = expected.end(); + // for(; iter != end; ++iter) + // { + // e_str << (S32)((U8)(*iter)) << " "; + // } + // e_str << std::endl; + // llsd_serialize_string(e_str, expected); + // LL_WARNS() << "expected size: " << expected.size() << LL_ENDL; + // LL_WARNS() << "expected: " << e_str.str() << LL_ENDL; + + // std::ostringstream a_str; + // iter = actual.begin(); + // end = actual.end(); + // for(; iter != end; ++iter) + // { + // a_str << (S32)((U8)(*iter)) << " "; + // } + // a_str << std::endl; + // llsd_serialize_string(a_str, actual); + // LL_WARNS() << "actual size: " << actual.size() << LL_ENDL; + // LL_WARNS() << "actual: " << a_str.str() << LL_ENDL; + // } + // */ + // ensure_equals("string value", actual, expected); + // } + // } + } + + TUT_CASE("commonmisc_test::sd_object_test_14") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::sd_object::test<14> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_object::test<14>() + // { + // //#if LL_WINDOWS && _MSC_VER >= 1400 + // // skip_fail("Fails on VS2005 due to broken LLSDSerialize::fromNotation() parser."); + // //#endif + // std::string param = "[{'version':i1},{'data':{'binary_bucket':b(0)\"\"},'from_id':u3c115e51-04f4-523c-9fa6-98aff1034730,'from_name':'Phoenix Linden','id':u004e45e5-5576-277a-fba7-859d6a4cb5c8,'message':'hey','offline':i0,'timestamp':i0,'to_id':u3c5f1bb4-5182-7546-6401-1d329b4ff2f8,'type':i0},{'agent_id':u3c115e51-04f4-523c-9fa6-98aff1034730,'god_level':i0,'limited_to_estate':i1}]"; + // std::istringstream istr; + // istr.str(param); + // LLSD param_sd; + // LLSDSerialize::fromNotation(param_sd, istr, param.size()); + // ensure_equals("parsed type", param_sd.type(), LLSD::TypeArray); + // LLSD version_sd = param_sd[0]; + // ensure_equals("version type", version_sd.type(), LLSD::TypeMap); + // ensure("has version", version_sd.has("version")); + // ensure_equals("version number", version_sd["version"].asInteger(), 1); + // LLSD src_sd = param_sd[1]; + // ensure_equals("src type", src_sd.type(), LLSD::TypeMap); + // LLSD dst_sd = param_sd[2]; + // ensure_equals("dst type", dst_sd.type(), LLSD::TypeMap); + // } + } + + TUT_CASE("commonmisc_test::sd_object_test_15") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::sd_object::test<15> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_object::test<15>() + // { + // std::string val = "[{'failures':!,'successfuls':[u3c115e51-04f4-523c-9fa6-98aff1034730]}]"; + // std::istringstream istr; + // istr.str(val); + // LLSD sd; + // LLSDSerialize::fromNotation(sd, istr, val.size()); + // ensure_equals("parsed type", sd.type(), LLSD::TypeArray); + // ensure_equals("parsed size", sd.size(), 1); + // LLSD failures = sd[0]["failures"]; + // ensure("no failures.", failures.isUndefined()); + // LLSD success = sd[0]["successfuls"]; + // ensure_equals("success type", success.type(), LLSD::TypeArray); + // ensure_equals("success size", success.size(), 1); + // ensure_equals("success instance type", success[0].type(), LLSD::TypeUUID); + // } + } + + TUT_CASE("commonmisc_test::sd_object_test_16") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::sd_object::test<16> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_object::test<16>() + // { + // std::string val = "[f,t,0,1,{'foo':t,'bar':f}]"; + // std::istringstream istr; + // istr.str(val); + // LLSD sd; + // LLSDSerialize::fromNotation(sd, istr, val.size()); + // ensure_equals("parsed type", sd.type(), LLSD::TypeArray); + // ensure_equals("parsed size", sd.size(), 5); + // ensure_equals("element 0 false", sd[0].asBoolean(), false); + // ensure_equals("element 1 true", sd[1].asBoolean(), true); + // ensure_equals("element 2 false", sd[2].asBoolean(), false); + // ensure_equals("element 3 true", sd[3].asBoolean(), true); + // LLSD map = sd[4]; + // ensure_equals("element 4 type", map.type(), LLSD::TypeMap); + // ensure_equals("map foo type", map["foo"].type(), LLSD::TypeBoolean); + // ensure_equals("map foo value", map["foo"].asBoolean(), true); + // ensure_equals("map bar type", map["bar"].type(), LLSD::TypeBoolean); + // ensure_equals("map bar value", map["bar"].asBoolean(), false); + // } + } + + TUT_CASE("commonmisc_test::sd_object_test_16") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::sd_object::test<16> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_object::test<16>() + // { + // } + } + + TUT_CASE("commonmisc_test::mem_object_test_1") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::mem_object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void mem_object::test<1>() + // { + // const char HELLO_WORLD[] = "hello world"; + // LLMemoryStream mem((U8*)&HELLO_WORLD[0], static_cast(strlen(HELLO_WORLD))); /* Flawfinder: ignore */ + // std::string hello; + // std::string world; + // mem >> hello >> world; + // ensure_equals("first word", hello, std::string("hello")); + // ensure_equals("second word", world, std::string("world")); + // } + } + + TUT_CASE("commonmisc_test::U64_object_test_1") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::U64_object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void U64_object::test<1>() + // { + // U64 val; + // std::string val_str; + // char result[256]; + // std::string result_str; + + // val = U64L(18446744073709551610); // slightly less than MAX_U64 + // val_str = "18446744073709551610"; + + // U64_to_str(val, result, sizeof(result)); + // result_str = (const char*) result; + // ensure_equals("U64_to_str converted 1.1", val_str, result_str); + + // val = 0; + // val_str = "0"; + // U64_to_str(val, result, sizeof(result)); + // result_str = (const char*) result; + // ensure_equals("U64_to_str converted 1.2", val_str, result_str); + + // val = U64L(18446744073709551615); // 0xFFFFFFFFFFFFFFFF + // val_str = "18446744073709551615"; + // U64_to_str(val, result, sizeof(result)); + // result_str = (const char*) result; + // ensure_equals("U64_to_str converted 1.3", val_str, result_str); + + // // overflow - will result in warning at compile time + // val = U64L(18446744073709551615) + 1; // overflow 0xFFFFFFFFFFFFFFFF + 1 == 0 + // val_str = "0"; + // U64_to_str(val, result, sizeof(result)); + // result_str = (const char*) result; + // ensure_equals("U64_to_str converted 1.4", val_str, result_str); + + // val = U64L(-1); // 0xFFFFFFFFFFFFFFFF == 18446744073709551615 + // val_str = "18446744073709551615"; + // U64_to_str(val, result, sizeof(result)); + // result_str = (const char*) result; + // ensure_equals("U64_to_str converted 1.5", val_str, result_str); + + // val = U64L(10000000000000000000); // testing preserving of 0s + // val_str = "10000000000000000000"; + // U64_to_str(val, result, sizeof(result)); + // result_str = (const char*) result; + // ensure_equals("U64_to_str converted 1.6", val_str, result_str); + + // val = 1; // testing no leading 0s + // val_str = "1"; + // U64_to_str(val, result, sizeof(result)); + // result_str = (const char*) result; + // ensure_equals("U64_to_str converted 1.7", val_str, result_str); + + // val = U64L(18446744073709551615); // testing exact sized buffer for result + // val_str = "18446744073709551615"; + // memset(result, 'A', sizeof(result)); // initialize buffer with all 'A' + // U64_to_str(val, result, sizeof("18446744073709551615")); //pass in the exact size + // result_str = (const char*) result; + // ensure_equals("U64_to_str converted 1.8", val_str, result_str); + + // val = U64L(18446744073709551615); // testing smaller sized buffer for result + // val_str = "1844"; + // memset(result, 'A', sizeof(result)); // initialize buffer with all 'A' + // U64_to_str(val, result, 5); //pass in a size of 5. should only copy first 4 integers and add a null terminator + // result_str = (const char*) result; + // ensure_equals("U64_to_str converted 1.9", val_str, result_str); + // } + } + + TUT_CASE("commonmisc_test::U64_object_test_2") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::U64_object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void U64_object::test<2>() + // { + // U64 val; + // U64 result; + + // val = U64L(18446744073709551610); // slightly less than MAX_U64 + // result = str_to_U64("18446744073709551610"); + // ensure_equals("str_to_U64 converted 2.1", val, result); + + // val = U64L(0); // empty string + // result = str_to_U64(LLStringUtil::null); + // ensure_equals("str_to_U64 converted 2.2", val, result); + + // val = U64L(0); // 0 + // result = str_to_U64("0"); + // ensure_equals("str_to_U64 converted 2.3", val, result); + + // val = U64L(18446744073709551615); // 0xFFFFFFFFFFFFFFFF + // result = str_to_U64("18446744073709551615"); + // ensure_equals("str_to_U64 converted 2.4", val, result); + + // // overflow - will result in warning at compile time + // val = U64L(18446744073709551615) + 1; // overflow 0xFFFFFFFFFFFFFFFF + 1 == 0 + // result = str_to_U64("18446744073709551616"); + // ensure_equals("str_to_U64 converted 2.5", val, result); + + // val = U64L(1234); // process till first non-integral character + // result = str_to_U64("1234A5678"); + // ensure_equals("str_to_U64 converted 2.6", val, result); + + // val = U64L(5678); // skip all non-integral characters + // result = str_to_U64("ABCD5678"); + // ensure_equals("str_to_U64 converted 2.7", val, result); + + // // should it skip negative sign and process + // // rest of string or return 0 + // val = U64L(1234); // skip initial negative sign + // result = str_to_U64("-1234"); + // ensure_equals("str_to_U64 converted 2.8", val, result); + + // val = U64L(5678); // stop at negative sign in the middle + // result = str_to_U64("5678-1234"); + // ensure_equals("str_to_U64 converted 2.9", val, result); + + // val = U64L(0); // no integers + // result = str_to_U64("AaCD"); + // ensure_equals("str_to_U64 converted 2.10", val, result); + // } + } + + TUT_CASE("commonmisc_test::U64_object_test_3") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::U64_object::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void U64_object::test<3>() + // { + // F64 val; + // F64 result; + + // result = 18446744073709551610.0; + // val = U64_to_F64(U64L(18446744073709551610)); + // ensure_equals("U64_to_F64 converted 3.1", val, result); + + // result = 18446744073709551615.0; // 0xFFFFFFFFFFFFFFFF + // val = U64_to_F64(U64L(18446744073709551615)); + // ensure_equals("U64_to_F64 converted 3.2", val, result); + + // result = 0.0; // overflow 0xFFFFFFFFFFFFFFFF + 1 == 0 + // // overflow - will result in warning at compile time + // val = U64_to_F64(U64L(18446744073709551615)+1); + // ensure_equals("U64_to_F64 converted 3.3", val, result); + + // result = 0.0; // 0 + // val = U64_to_F64(U64L(0)); + // ensure_equals("U64_to_F64 converted 3.4", val, result); + + // result = 1.0; // odd + // val = U64_to_F64(U64L(1)); + // ensure_equals("U64_to_F64 converted 3.5", val, result); + + // result = 2.0; // even + // val = U64_to_F64(U64L(2)); + // ensure_equals("U64_to_F64 converted 3.6", val, result); + + // result = U64L(0x7FFFFFFFFFFFFFFF) * 1.0L; // 0x7FFFFFFFFFFFFFFF + // val = U64_to_F64(U64L(0x7FFFFFFFFFFFFFFF)); + // ensure_equals("U64_to_F64 converted 3.7", val, result); + // } + } + + TUT_CASE("commonmisc_test::hash_object_test_1") + { + DOCTEST_FAIL("TODO: convert commonmisc_test.cpp::hash_object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void hash_object::test<1>() + // { + // const char * str1 = "test string one"; + // const char * same_as_str1 = "test string one"; + + // size_t hash1 = llhash(str1); + // size_t same_as_hash1 = llhash(same_as_str1); + + + // ensure("Hashes from identical strings should be equal", hash1 == same_as_hash1); + + // char str[100]; + // strcpy( str, "Another test" ); + + // size_t hash2 = llhash(str); + + // strcpy( str, "Different string, same pointer" ); + + // size_t hash3 = llhash(str); + + // ensure("Hashes from same pointer but different string should not be equal", hash2 != hash3); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/generated.index b/indra/llcommon/tests_doctest/generated.index new file mode 100644 index 00000000000..eb9493ff198 --- /dev/null +++ b/indra/llcommon/tests_doctest/generated.index @@ -0,0 +1,41 @@ +apply_test.cpp -> apply_test_doctest.cpp +bitpack_test.cpp -> bitpack_test_doctest.cpp +classic_callback_test.cpp -> classic_callback_test_doctest.cpp +commonmisc_test.cpp -> commonmisc_test_doctest.cpp +lazyeventapi_test.cpp -> lazyeventapi_test_doctest.cpp +llallocator_heap_profile_test.cpp -> llallocator_heap_profile_test_doctest.cpp +llallocator_test.cpp -> llallocator_test_doctest.cpp +llbase64_test.cpp -> llbase64_test_doctest.cpp +llcond_test.cpp -> llcond_test_doctest.cpp +lldate_test.cpp -> lldate_test_doctest.cpp +lldeadmantimer_test.cpp -> lldeadmantimer_test_doctest.cpp +lldependencies_test.cpp -> lldependencies_test_doctest.cpp +llerror_test.cpp -> llerror_test_doctest.cpp +lleventcoro_test.cpp -> lleventcoro_test_doctest.cpp +lleventdispatcher_test.cpp -> lleventdispatcher_test_doctest.cpp +lleventfilter_test.cpp -> lleventfilter_test_doctest.cpp +llexception_test.cpp -> llexception_test_doctest.cpp +llframetimer_test.cpp -> llframetimer_test_doctest.cpp +llheteromap_test.cpp -> llheteromap_test_doctest.cpp +llinstancetracker_test.cpp -> llinstancetracker_test_doctest.cpp +lllazy_test.cpp -> lllazy_test_doctest.cpp +llleap_test.cpp -> llleap_test_doctest.cpp +llmainthreadtask_test.cpp -> llmainthreadtask_test_doctest.cpp +llmemtype_test.cpp -> llmemtype_test_doctest.cpp +llpounceable_test.cpp -> llpounceable_test_doctest.cpp +llprocess_test.cpp -> llprocess_test_doctest.cpp +llprocessor_test.cpp -> llprocessor_test_doctest.cpp +llprocinfo_test.cpp -> llprocinfo_test_doctest.cpp +llrand_test.cpp -> llrand_test_doctest.cpp +llsdserialize_test.cpp -> llsdserialize_test_doctest.cpp +llsingleton_test.cpp -> llsingleton_test_doctest.cpp +llstreamqueue_test.cpp -> llstreamqueue_test_doctest.cpp +llstring_test.cpp -> llstring_test_doctest.cpp +lltrace_test.cpp -> lltrace_test_doctest.cpp +lltreeiterators_test.cpp -> lltreeiterators_test_doctest.cpp +llunits_test.cpp -> llunits_test_doctest.cpp +lluri_test.cpp -> lluri_test_doctest.cpp +stringize_test.cpp -> stringize_test_doctest.cpp +threadsafeschedule_test.cpp -> threadsafeschedule_test_doctest.cpp +tuple_test.cpp -> tuple_test_doctest.cpp +workqueue_test.cpp -> workqueue_test_doctest.cpp diff --git a/indra/llcommon/tests_doctest/lazyeventapi_test_doctest.cpp b/indra/llcommon/tests_doctest/lazyeventapi_test_doctest.cpp new file mode 100644 index 00000000000..7168d03dce7 --- /dev/null +++ b/indra/llcommon/tests_doctest/lazyeventapi_test_doctest.cpp @@ -0,0 +1,110 @@ +/** + * @file lazyeventapi_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for lazyeventapi + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from lazyeventapi_test.cpp at 2025-10-16T18:47:16Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "lazyeventapi.h" +#include "llevents.h" +#include "llsdutil.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("lazyeventapi_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert lazyeventapi_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // set_test_name("LazyEventAPI"); + // // this is where the magic (should) happen + // // 'register' still a keyword until C++17 + // MyRegistrar regster; + // LLEventPumps::instance().obtain("Test").post(llsd::map("op", "set", "data", "hey")); + // ensure_equals("failed to set data", data.asString(), "hey"); + // } + } + + TUT_CASE("lazyeventapi_test::object_test_2") + { + DOCTEST_FAIL("TODO: convert lazyeventapi_test.cpp::object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<2>() + // { + // set_test_name("No LazyEventAPI"); + // // Because the MyRegistrar declaration in test<1>() is local, because + // // it has been destroyed, we fully expect NOT to reach a MyListener + // // instance with this post. + // LLEventPumps::instance().obtain("Test").post(llsd::map("op", "set", "data", "moot")); + // ensure("accidentally set data", ! data.isDefined()); + // } + } + + TUT_CASE("lazyeventapi_test::object_test_3") + { + DOCTEST_FAIL("TODO: convert lazyeventapi_test.cpp::object::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<3>() + // { + // set_test_name("LazyEventAPI metadata"); + // MyRegistrar regster; + // // Of course we have 'regster' in hand; we don't need to search for + // // it. But this next test verifies that we can find (all) LazyEventAPI + // // instances using LazyEventAPIBase::instance_snapshot. Normally we + // // wouldn't search; normally we'd just look at each instance in the + // // loop body. + // const MyRegistrar* found = nullptr; + // for (const auto& registrar : LL::LazyEventAPIBase::instance_snapshot()) + // if ((found = dynamic_cast(®istrar))) + // break; + // ensure("Failed to find MyRegistrar via LLInstanceTracker", found); + + // ensure_equals("wrong API name", found->getName(), "Test"); + // ensure_contains("wrong API desc", found->getDesc(), "test LLEventAPI"); + // ensure_equals("wrong API field", found->getDispatchKey(), "op"); + // // Normally we'd just iterate over *found. But for test purposes, + // // actually capture the range of NameDesc pairs in a vector. + // std::vector ops{ found->begin(), found->end() }; + // ensure_equals("failed to find operations", ops.size(), 1); + // ensure_equals("wrong operation name", ops[0].first, "set"); + // ensure_contains("wrong operation desc", ops[0].second, "set operation"); + // LLSD metadata{ found->getMetadata(ops[0].first) }; + // ensure_equals("bad metadata name", metadata["name"].asString(), ops[0].first); + // ensure_equals("bad metadata desc", metadata["desc"].asString(), ops[0].second); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llallocator_heap_profile_test_doctest.cpp b/indra/llcommon/tests_doctest/llallocator_heap_profile_test_doctest.cpp new file mode 100644 index 00000000000..6e5250bc1ff --- /dev/null +++ b/indra/llcommon/tests_doctest/llallocator_heap_profile_test_doctest.cpp @@ -0,0 +1,101 @@ +/** + * @file llallocator_heap_profile_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL allocator heap profile + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llallocator_heap_profile_test.cpp at 2025-10-16T18:47:16Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +// #include "../llallocator_heap_profile.h" // not available on Windows + +TUT_SUITE("llcommon") +{ + TUT_CASE("llallocator_heap_profile_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert llallocator_heap_profile_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // prof.parse(sample_win_profile); + + // ensure_equals("count lines", prof.mLines.size() , 5); + // ensure_equals("alloc counts", prof.mLines[0].mLiveCount, 2131854U); + // ensure_equals("alloc counts", prof.mLines[0].mLiveSize, 2245710106ULL); + // ensure_equals("alloc counts", prof.mLines[0].mTotalCount, 14069198U); + // ensure_equals("alloc counts", prof.mLines[0].mTotalSize, 4295177308ULL); + // ensure_equals("count markers", prof.mLines[0].mTrace.size(), 0); + // ensure_equals("count markers", prof.mLines[1].mTrace.size(), 0); + // ensure_equals("count markers", prof.mLines[2].mTrace.size(), 4); + // ensure_equals("count markers", prof.mLines[3].mTrace.size(), 6); + // ensure_equals("count markers", prof.mLines[4].mTrace.size(), 7); + + // //prof.dump(std::cout); + // } + } + + TUT_CASE("llallocator_heap_profile_test::object_test_2") + { + DOCTEST_FAIL("TODO: convert llallocator_heap_profile_test.cpp::object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<2>() + // { + // prof.parse(crash_testcase); + + // ensure_equals("count lines", prof.mLines.size(), 2); + // ensure_equals("alloc counts", prof.mLines[0].mLiveCount, 3U); + // ensure_equals("alloc counts", prof.mLines[0].mLiveSize, 1049652ULL); + // ensure_equals("alloc counts", prof.mLines[0].mTotalCount, 8U); + // ensure_equals("alloc counts", prof.mLines[0].mTotalSize, 1049748ULL); + // ensure_equals("count markers", prof.mLines[0].mTrace.size(), 0); + // ensure_equals("count markers", prof.mLines[1].mTrace.size(), 0); + + // //prof.dump(std::cout); + // } + } + + TUT_CASE("llallocator_heap_profile_test::object_test_3") + { + DOCTEST_FAIL("TODO: convert llallocator_heap_profile_test.cpp::object::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<3>() + // { + // // test that we don't crash on edge case data + // prof.parse(""); + // ensure("emtpy on error", prof.mLines.empty()); + + // prof.parse("heap profile:"); + // ensure("emtpy on error", prof.mLines.empty()); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llallocator_test_doctest.cpp b/indra/llcommon/tests_doctest/llallocator_test_doctest.cpp new file mode 100644 index 00000000000..ac19fb52d3f --- /dev/null +++ b/indra/llcommon/tests_doctest/llallocator_test_doctest.cpp @@ -0,0 +1,86 @@ +/** + * @file llallocator_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL allocator + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llallocator_test.cpp at 2025-10-16T18:47:16Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +// #include "../llallocator.h" // not available on Windows + +TUT_SUITE("llcommon") +{ + TUT_CASE("llallocator_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert llallocator_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // llallocator.setProfilingEnabled(false); + // ensure("Profiler disable", !llallocator.isProfiling()); + // } + } + + TUT_CASE("llallocator_test::object_test_2") + { + DOCTEST_FAIL("TODO: convert llallocator_test.cpp::object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<2>() + // { + // llallocator.setProfilingEnabled(true); + // ensure("Profiler enable", llallocator.isProfiling()); + // } + } + + TUT_CASE("llallocator_test::object_test_3") + { + DOCTEST_FAIL("TODO: convert llallocator_test.cpp::object::test<3> from TUT to doctest"); + // Original snippet: + // template <> template <> + // void object::test<3>() + // { + // llallocator.setProfilingEnabled(true); + + // char * test_alloc = new char[1024]; + + // llallocator.getProfile(); + + // delete [] test_alloc; + + // llallocator.getProfile(); + + // // *NOTE - this test isn't ensuring anything right now other than no + // // exceptions are thrown. + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llbase64_test_doctest.cpp b/indra/llcommon/tests_doctest/llbase64_test_doctest.cpp new file mode 100644 index 00000000000..f3167487955 --- /dev/null +++ b/indra/llcommon/tests_doctest/llbase64_test_doctest.cpp @@ -0,0 +1,84 @@ +/** + * @file llbase64_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL BASE64 + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llbase64_test.cpp at 2025-10-16T18:47:16Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include +#include "linden_common.h" +#include "../llbase64.h" +#include "../lluuid.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("llbase64_test::base64_object_test_1") + { + DOCTEST_FAIL("TODO: convert llbase64_test.cpp::base64_object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void base64_object::test<1>() + // { + // std::string result; + + // result = LLBase64::encode(NULL, 0); + // ensure("encode nothing", (result == "") ); + + // LLUUID nothing; + // result = LLBase64::encode(¬hing.mData[0], UUID_BYTES); + // ensure("encode blank uuid", + // (result == "AAAAAAAAAAAAAAAAAAAAAA==") ); + + // LLUUID id("526a1e07-a19d-baed-84c4-ff08a488d15e"); + // result = LLBase64::encode(&id.mData[0], UUID_BYTES); + // ensure("encode random uuid", + // (result == "UmoeB6Gduu2ExP8IpIjRXg==") ); + + // } + } + + TUT_CASE("llbase64_test::base64_object_test_2") + { + DOCTEST_FAIL("TODO: convert llbase64_test.cpp::base64_object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void base64_object::test<2>() + // { + // std::string result; + + // U8 blob[40] = { 115, 223, 172, 255, 140, 70, 49, 125, 236, 155, 45, 199, 101, 17, 164, 131, 230, 19, 80, 64, 112, 53, 135, 98, 237, 12, 26, 72, 126, 14, 145, 143, 118, 196, 11, 177, 132, 169, 195, 134 }; + // result = LLBase64::encode(&blob[0], 40); + // ensure("encode 40 bytes", + // (result == "c9+s/4xGMX3smy3HZRGkg+YTUEBwNYdi7QwaSH4OkY92xAuxhKnDhg==") ); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llcond_test_doctest.cpp b/indra/llcommon/tests_doctest/llcond_test_doctest.cpp new file mode 100644 index 00000000000..8a735c98cb4 --- /dev/null +++ b/indra/llcommon/tests_doctest/llcond_test_doctest.cpp @@ -0,0 +1,84 @@ +/** + * @file llcond_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL cond + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llcond_test.cpp at 2025-10-16T18:47:16Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "llcond.h" +#include "llcoros.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("llcond_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert llcond_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // set_test_name("Immediate gratification"); + // cond.set_one(1); + // ensure("wait_for_equal() failed", + // cond.wait_for_equal(F32Milliseconds(1), 1)); + // ensure("wait_for_unequal() should have failed", + // ! cond.wait_for_unequal(F32Milliseconds(1), 1)); + // } + } + + TUT_CASE("llcond_test::object_test_2") + { + DOCTEST_FAIL("TODO: convert llcond_test.cpp::object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<2>() + // { + // set_test_name("Simple two-coroutine test"); + // LLCoros::instance().launch( + // "test<2>", + // [this]() + // { + // // Lambda immediately entered -- control comes here first. + // ensure_equals(cond.get(), 0); + // cond.set_all(1); + // cond.wait_equal(2); + // ensure_equals(cond.get(), 2); + // cond.set_all(3); + // }); + // // Main coroutine is resumed only when the lambda waits. + // ensure_equals(cond.get(), 1); + // cond.set_all(2); + // cond.wait_equal(3); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/lldate_test_doctest.cpp b/indra/llcommon/tests_doctest/lldate_test_doctest.cpp new file mode 100644 index 00000000000..f8164fe9e42 --- /dev/null +++ b/indra/llcommon/tests_doctest/lldate_test_doctest.cpp @@ -0,0 +1,212 @@ +/** + * @file lldate_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL date + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from lldate_test.cpp at 2025-10-16T18:47:16Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "../llstring.h" +#include "../lldate.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("lldate_test::date_test_object_t_test_1") + { + DOCTEST_FAIL("TODO: convert lldate_test.cpp::date_test_object_t::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void date_test_object_t::test<1>() + // { + // LLDate date(VALID_DATE); + // std::string expected_string; + // bool result; + // expected_string = VALID_DATE; + // ensure_equals("Valid Date failed" , expected_string, date.asString()); + + // result = date.fromString(VALID_DATE_LEAP); + // expected_string = VALID_DATE_LEAP; + // ensure_equals("VALID_DATE_LEAP failed" , expected_string, date.asString()); + + // result = date.fromString(VALID_DATE_HOUR_BOUNDARY); + // expected_string = VALID_DATE_HOUR_BOUNDARY; + // ensure_equals("VALID_DATE_HOUR_BOUNDARY failed" , expected_string, date.asString()); + + // result = date.fromString(VALID_DATE_FRACTIONAL_SECS); + // expected_string = VALID_DATE_FRACTIONAL_SECS; + // ensure_equals("VALID_DATE_FRACTIONAL_SECS failed" , expected_string, date.asString()); + + // result = date.fromString(INVALID_DATE_MISSING_YEAR); + // ensure_equals("INVALID_DATE_MISSING_YEAR should have failed" , result, false); + + // result = date.fromString(INVALID_DATE_MISSING_MONTH); + // ensure_equals("INVALID_DATE_MISSING_MONTH should have failed" , result, false); + + // result = date.fromString(INVALID_DATE_MISSING_DATE); + // ensure_equals("INVALID_DATE_MISSING_DATE should have failed" , result, false); + + // result = date.fromString(INVALID_DATE_MISSING_T); + // ensure_equals("INVALID_DATE_MISSING_T should have failed" , result, false); + + // result = date.fromString(INVALID_DATE_MISSING_HOUR); + // ensure_equals("INVALID_DATE_MISSING_HOUR should have failed" , result, false); + + // result = date.fromString(INVALID_DATE_MISSING_MIN); + // ensure_equals("INVALID_DATE_MISSING_MIN should have failed" , result, false); + + // result = date.fromString(INVALID_DATE_MISSING_SEC); + // ensure_equals("INVALID_DATE_MISSING_SEC should have failed" , result, false); + + // result = date.fromString(INVALID_DATE_MISSING_Z); + // ensure_equals("INVALID_DATE_MISSING_Z should have failed" , result, false); + + // result = date.fromString(INVALID_DATE_EMPTY); + // ensure_equals("INVALID_DATE_EMPTY should have failed" , result, false); + // } + } + + TUT_CASE("lldate_test::date_test_object_t_test_2") + { + DOCTEST_FAIL("TODO: convert lldate_test.cpp::date_test_object_t::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void date_test_object_t::test<2>() + // { + // #if LL_DATE_PARSER_CHECKS_BOUNDARY + // LLDate date; + // std::string expected_string; + // bool result; + + // result = date.fromString(INVALID_DATE_24HOUR_BOUNDARY); + // ensure_equals("INVALID_DATE_24HOUR_BOUNDARY should have failed" , result, false); + // ensure_equals("INVALID_DATE_24HOUR_BOUNDARY date still set to old value on failure!" , date.secondsSinceEpoch(), 0); + + // result = date.fromString(INVALID_DATE_LEAP); + // ensure_equals("INVALID_DATE_LEAP should have failed" , result, false); + + // result = date.fromString(INVALID_DATE_HOUR); + // ensure_equals("INVALID_DATE_HOUR should have failed" , result, false); + + // result = date.fromString(INVALID_DATE_MIN); + // ensure_equals("INVALID_DATE_MIN should have failed" , result, false); + + // result = date.fromString(INVALID_DATE_SEC); + // ensure_equals("INVALID_DATE_SEC should have failed" , result, false); + + // result = date.fromString(INVALID_DATE_YEAR); + // ensure_equals("INVALID_DATE_YEAR should have failed" , result, false); + + // result = date.fromString(INVALID_DATE_MONTH); + // ensure_equals("INVALID_DATE_MONTH should have failed" , result, false); + + // result = date.fromString(INVALID_DATE_DAY); + // ensure_equals("INVALID_DATE_DAY should have failed" , result, false); + // #endif + // } + } + + TUT_CASE("lldate_test::date_test_object_t_test_3") + { + DOCTEST_FAIL("TODO: convert lldate_test.cpp::date_test_object_t::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void date_test_object_t::test<3>() + // { + // LLDate date; + // std::istringstream stream(VALID_DATE); + // std::string expected_string = VALID_DATE; + // date.fromStream(stream); + // ensure_equals("fromStream failed", date.asString(), expected_string); + // } + } + + TUT_CASE("lldate_test::date_test_object_t_test_4") + { + DOCTEST_FAIL("TODO: convert lldate_test.cpp::date_test_object_t::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void date_test_object_t::test<4>() + // { + // LLDate date1(VALID_DATE); + // LLDate date2(date1); + // ensure_equals("LLDate(const LLDate& date) constructor failed", date1.asString(), date2.asString()); + // } + } + + TUT_CASE("lldate_test::date_test_object_t_test_5") + { + DOCTEST_FAIL("TODO: convert lldate_test.cpp::date_test_object_t::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void date_test_object_t::test<5>() + // { + // LLDate date1(VALID_DATE); + // LLDate date2(date1.secondsSinceEpoch()); + // ensure_equals("secondsSinceEpoch not equal",date1.secondsSinceEpoch(), date2.secondsSinceEpoch()); + // ensure_equals("LLDate created using secondsSinceEpoch not equal", date1.asString(), date2.asString()); + // } + } + + TUT_CASE("lldate_test::date_test_object_t_test_6") + { + DOCTEST_FAIL("TODO: convert lldate_test.cpp::date_test_object_t::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void date_test_object_t::test<6>() + // { + // LLDate date(VALID_DATE); + // std::ostringstream stream; + // stream << date; + // std::string expected_str = VALID_DATE; + // ensure_equals("ostringstream failed", expected_str, stream.str()); + // } + } + + TUT_CASE("lldate_test::date_test_object_t_test_7") + { + DOCTEST_FAIL("TODO: convert lldate_test.cpp::date_test_object_t::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void date_test_object_t::test<7>() + // { + // LLDate date; + // std::istringstream stream(VALID_DATE); + // stream >> date; + // std::string expected_str = VALID_DATE; + // std::ostringstream out_stream; + // out_stream << date; + + // ensure_equals("<< failed", date.asString(),expected_str); + // ensure_equals("<< to >> failed", stream.str(),out_stream.str()); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/lldeadmantimer_test_doctest.cpp b/indra/llcommon/tests_doctest/lldeadmantimer_test_doctest.cpp new file mode 100644 index 00000000000..e2f2b70e69a --- /dev/null +++ b/indra/llcommon/tests_doctest/lldeadmantimer_test_doctest.cpp @@ -0,0 +1,634 @@ +/** + * @file lldeadmantimer_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL deadmantimer + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from lldeadmantimer_test.cpp at 2025-10-16T18:47:16Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "../lldeadmantimer.h" +#include "../llsd.h" +#include "../lltimer.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("lldeadmantimer_test::deadmantimer_object_t_test_1") + { + DOCTEST_FAIL("TODO: convert lldeadmantimer_test.cpp::deadmantimer_object_t::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void deadmantimer_object_t::test<1>() + // { + // { + // // Without cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)); + // LLDeadmanTimer timer(10.0, false); + + // ensure_equals("WOCM isExpired() returns false after ctor()", timer.isExpired(0, started, stopped, count), false); + // ensure_approximately_equals("WOCM t1 - isExpired() does not modify started", started, F64(42.0), 2); + // ensure_approximately_equals("WOCM t1 - isExpired() does not modify stopped", stopped, F64(97.0), 2); + // ensure_equals("WOCM t1 - isExpired() does not modify count", count, U64L(8)); + // } + + // { + // // With cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)), user_cpu(29000), sys_cpu(57000); + // LLDeadmanTimer timer(10.0, true); + + // ensure_equals("WCM isExpired() returns false after ctor()", timer.isExpired(0, started, stopped, count, user_cpu, sys_cpu), false); + // ensure_approximately_equals("WCM t1 - isExpired() does not modify started", started, F64(42.0), 2); + // ensure_approximately_equals("WCM t1 - isExpired() does not modify stopped", stopped, F64(97.0), 2); + // ensure_equals("WCM t1 - isExpired() does not modify count", count, U64L(8)); + // ensure_equals("WCM t1 - isExpired() does not modify user_cpu", user_cpu, U64L(29000)); + // ensure_equals("WCM t1 - isExpired() does not modify sys_cpu", sys_cpu, U64L(57000)); + // } + // } + } + + TUT_CASE("lldeadmantimer_test::deadmantimer_object_t_test_2") + { + DOCTEST_FAIL("TODO: convert lldeadmantimer_test.cpp::deadmantimer_object_t::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void deadmantimer_object_t::test<2>() + // { + // { + // // Without cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)); + // LLDeadmanTimer timer(0.0, false); // Zero is pre-expired + + // ensure_equals("WOCM isExpired() still returns false with 0.0 time ctor()", + // timer.isExpired(0, started, stopped, count), false); + // } + + // { + // // With cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)), user_cpu(29000), sys_cpu(57000); + // LLDeadmanTimer timer(0.0, true); // Zero is pre-expired + + // ensure_equals("WCM isExpired() still returns false with 0.0 time ctor()", + // timer.isExpired(0, started, stopped, count, user_cpu, sys_cpu), false); + // } + // } + } + + TUT_CASE("lldeadmantimer_test::deadmantimer_object_t_test_3") + { + DOCTEST_FAIL("TODO: convert lldeadmantimer_test.cpp::deadmantimer_object_t::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void deadmantimer_object_t::test<3>() + // { + // { + // // Without cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)); + // LLDeadmanTimer timer(0.0, false); + + // timer.start(0); + // ensure_equals("WOCM isExpired() returns true with 0.0 horizon time", + // timer.isExpired(0, started, stopped, count), true); + // ensure_approximately_equals("WOCM expired timer with no bell ringing has stopped == started", started, stopped, 8); + // } + // { + // // With cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)), user_cpu(29000), sys_cpu(57000); + // LLDeadmanTimer timer(0.0, true); + + // timer.start(0); + // ensure_equals("WCM isExpired() returns true with 0.0 horizon time", + // timer.isExpired(0, started, stopped, count, user_cpu, sys_cpu), true); + // ensure_approximately_equals("WCM expired timer with no bell ringing has stopped == started", started, stopped, 8); + // } + // } + } + + TUT_CASE("lldeadmantimer_test::deadmantimer_object_t_test_4") + { + DOCTEST_FAIL("TODO: convert lldeadmantimer_test.cpp::deadmantimer_object_t::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void deadmantimer_object_t::test<4>() + // { + // { + // // Without cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)); + // LLDeadmanTimer timer(0.0, false); + + // timer.start(0); + // timer.ringBell(LLDeadmanTimer::getNow() + float_time_to_u64(1000.0), 1); + // ensure_equals("WOCM isExpired() returns true with 0.0 horizon time after bell ring", + // timer.isExpired(0, started, stopped, count), true); + // ensure_approximately_equals("WOCM ringBell has no impact on expired timer leaving stopped == started", started, stopped, 8); + // } + // { + // // With cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)), user_cpu(29000), sys_cpu(57000); + // LLDeadmanTimer timer(0.0, true); + + // timer.start(0); + // timer.ringBell(LLDeadmanTimer::getNow() + float_time_to_u64(1000.0), 1); + // ensure_equals("WCM isExpired() returns true with 0.0 horizon time after bell ring", + // timer.isExpired(0, started, stopped, count, user_cpu, sys_cpu), true); + // ensure_approximately_equals("WCM ringBell has no impact on expired timer leaving stopped == started", started, stopped, 8); + // } + // } + } + + TUT_CASE("lldeadmantimer_test::deadmantimer_object_t_test_5") + { + DOCTEST_FAIL("TODO: convert lldeadmantimer_test.cpp::deadmantimer_object_t::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void deadmantimer_object_t::test<5>() + // { + // { + // // Without cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)); + // LLDeadmanTimer timer(10.0, false); + + // timer.start(0); + // ensure_equals("WOCM isExpired() returns false after starting with 10.0 horizon time", + // timer.isExpired(0, started, stopped, count), false); + // ensure_approximately_equals("WOCM t5 - isExpired() does not modify started", started, F64(42.0), 2); + // ensure_approximately_equals("WOCM t5 - isExpired() does not modify stopped", stopped, F64(97.0), 2); + // ensure_equals("WOCM t5 - isExpired() does not modify count", count, U64L(8)); + // } + // { + // // With cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)), user_cpu(29000), sys_cpu(57000); + // LLDeadmanTimer timer(10.0, true); + + // timer.start(0); + // ensure_equals("WCM isExpired() returns false after starting with 10.0 horizon time", + // timer.isExpired(0, started, stopped, count, user_cpu, sys_cpu), false); + // ensure_approximately_equals("WCM t5 - isExpired() does not modify started", started, F64(42.0), 2); + // ensure_approximately_equals("WCM t5 - isExpired() does not modify stopped", stopped, F64(97.0), 2); + // ensure_equals("WCM t5 - isExpired() does not modify count", count, U64L(8)); + // ensure_equals("WCM t5 - isExpired() does not modify user_cpu", user_cpu, U64L(29000)); + // ensure_equals("WCM t5 - isExpired() does not modify sys_cpu", sys_cpu, U64L(57000)); + // } + // } + } + + TUT_CASE("lldeadmantimer_test::deadmantimer_object_t_test_6") + { + DOCTEST_FAIL("TODO: convert lldeadmantimer_test.cpp::deadmantimer_object_t::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void deadmantimer_object_t::test<6>() + // { + // { + // // Without cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)); + // LLDeadmanTimer timer(10.0, false); + + // // Would like to do subtraction on current time but can't because + // // the implementation on Windows is zero-based. We wrap around + // // the backside resulting in a large U64 number. + + // LLDeadmanTimer::time_type the_past(LLDeadmanTimer::getNow()); + // LLDeadmanTimer::time_type now(the_past + float_time_to_u64(5.0)); + // timer.start(the_past); + // ensure_equals("WOCM t6 - isExpired() returns false with 10.0 horizon time starting 5.0 in past", + // timer.isExpired(now, started, stopped, count), false); + // ensure_approximately_equals("WOCM t6 - isExpired() does not modify started", started, F64(42.0), 2); + // ensure_approximately_equals("WOCM t6 - isExpired() does not modify stopped", stopped, F64(97.0), 2); + // ensure_equals("WOCM t6 - isExpired() does not modify count", count, U64L(8)); + // } + // { + // // With cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)), user_cpu(29000), sys_cpu(57000); + // LLDeadmanTimer timer(10.0, true); + + // // Would like to do subtraction on current time but can't because + // // the implementation on Windows is zero-based. We wrap around + // // the backside resulting in a large U64 number. + + // LLDeadmanTimer::time_type the_past(LLDeadmanTimer::getNow()); + // LLDeadmanTimer::time_type now(the_past + float_time_to_u64(5.0)); + // timer.start(the_past); + // ensure_equals("WCM t6 - isExpired() returns false with 10.0 horizon time starting 5.0 in past", + // timer.isExpired(now, started, stopped, count, user_cpu, sys_cpu), false); + // ensure_approximately_equals("WCM t6 - isExpired() does not modify started", started, F64(42.0), 2); + // ensure_approximately_equals("WCM t6 - isExpired() does not modify stopped", stopped, F64(97.0), 2); + // ensure_equals("t6 - isExpired() does not modify count", count, U64L(8)); + // ensure_equals("WCM t6 - isExpired() does not modify user_cpu", user_cpu, U64L(29000)); + // ensure_equals("WCM t6 - isExpired() does not modify sys_cpu", sys_cpu, U64L(57000)); + // } + // } + } + + TUT_CASE("lldeadmantimer_test::deadmantimer_object_t_test_7") + { + DOCTEST_FAIL("TODO: convert lldeadmantimer_test.cpp::deadmantimer_object_t::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void deadmantimer_object_t::test<7>() + // { + // { + // // Without cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)); + // LLDeadmanTimer timer(10.0, false); + + // // Would like to do subtraction on current time but can't because + // // the implementation on Windows is zero-based. We wrap around + // // the backside resulting in a large U64 number. + + // LLDeadmanTimer::time_type the_past(LLDeadmanTimer::getNow()); + // LLDeadmanTimer::time_type now(the_past + float_time_to_u64(20.0)); + // timer.start(the_past); + // ensure_equals("WOCM t7 - isExpired() returns true with 10.0 horizon time starting 20.0 in past", + // timer.isExpired(now,started, stopped, count), true); + // ensure_approximately_equals("WOCM t7 - starting before horizon still gives equal started / stopped", started, stopped, 8); + // } + // { + // // With cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)), user_cpu(29000), sys_cpu(57000); + // LLDeadmanTimer timer(10.0, true); + + // // Would like to do subtraction on current time but can't because + // // the implementation on Windows is zero-based. We wrap around + // // the backside resulting in a large U64 number. + + // LLDeadmanTimer::time_type the_past(LLDeadmanTimer::getNow()); + // LLDeadmanTimer::time_type now(the_past + float_time_to_u64(20.0)); + // timer.start(the_past); + // ensure_equals("WCM t7 - isExpired() returns true with 10.0 horizon time starting 20.0 in past", + // timer.isExpired(now,started, stopped, count, user_cpu, sys_cpu), true); + // ensure_approximately_equals("WOCM t7 - starting before horizon still gives equal started / stopped", started, stopped, 8); + // } + // } + } + + TUT_CASE("lldeadmantimer_test::deadmantimer_object_t_test_8") + { + DOCTEST_FAIL("TODO: convert lldeadmantimer_test.cpp::deadmantimer_object_t::test<8> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void deadmantimer_object_t::test<8>() + // { + // { + // // Without cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)); + // LLDeadmanTimer timer(10.0, false); + + // // Would like to do subtraction on current time but can't because + // // the implementation on Windows is zero-based. We wrap around + // // the backside resulting in a large U64 number. + + // LLDeadmanTimer::time_type the_past(LLDeadmanTimer::getNow()); + // LLDeadmanTimer::time_type now(the_past + float_time_to_u64(20.0)); + // timer.start(the_past); + // ensure_equals("WOCM t8 - isExpired() returns true with 10.0 horizon time starting 20.0 in past", + // timer.isExpired(now, started, stopped, count), true); + + // started = 42.0; + // stopped = 97.0; + // count = U64L(8); + // ensure_equals("WOCM t8 - second isExpired() returns false after true", + // timer.isExpired(now, started, stopped, count), false); + // ensure_approximately_equals("WOCM t8 - 2nd isExpired() does not modify started", started, F64(42.0), 2); + // ensure_approximately_equals("WOCM t8 - 2nd isExpired() does not modify stopped", stopped, F64(97.0), 2); + // ensure_equals("WOCM t8 - 2nd isExpired() does not modify count", count, U64L(8)); + // } + // { + // // With cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)), user_cpu(29000), sys_cpu(57000); + // LLDeadmanTimer timer(10.0, true); + + // // Would like to do subtraction on current time but can't because + // // the implementation on Windows is zero-based. We wrap around + // // the backside resulting in a large U64 number. + + // LLDeadmanTimer::time_type the_past(LLDeadmanTimer::getNow()); + // LLDeadmanTimer::time_type now(the_past + float_time_to_u64(20.0)); + // timer.start(the_past); + // ensure_equals("WCM t8 - isExpired() returns true with 10.0 horizon time starting 20.0 in past", + // timer.isExpired(now, started, stopped, count, user_cpu, sys_cpu), true); + + // started = 42.0; + // stopped = 97.0; + // count = U64L(8); + // user_cpu = 29000; + // sys_cpu = 57000; + // ensure_equals("WCM t8 - second isExpired() returns false after true", + // timer.isExpired(now, started, stopped, count), false); + // ensure_approximately_equals("WCM t8 - 2nd isExpired() does not modify started", started, F64(42.0), 2); + // ensure_approximately_equals("WCM t8 - 2nd isExpired() does not modify stopped", stopped, F64(97.0), 2); + // ensure_equals("WCM t8 - 2nd isExpired() does not modify count", count, U64L(8)); + // ensure_equals("WCM t8 - 2nd isExpired() does not modify user_cpu", user_cpu, U64L(29000)); + // ensure_equals("WCM t8 - 2nd isExpired() does not modify sys_cpu", sys_cpu, U64L(57000)); + // } + // } + } + + TUT_CASE("lldeadmantimer_test::deadmantimer_object_t_test_9") + { + DOCTEST_FAIL("TODO: convert lldeadmantimer_test.cpp::deadmantimer_object_t::test<9> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void deadmantimer_object_t::test<9>() + // { + // { + // // Without cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)); + // LLDeadmanTimer timer(5.0, false); + + // LLDeadmanTimer::time_type now(LLDeadmanTimer::getNow()); + // F64 real_start(u64_time_to_float(now)); + // timer.start(0); + + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // ensure_equals("WOCM t9 - 5.0 horizon timer has not timed out after 10 1-second bell rings", + // timer.isExpired(now, started, stopped, count), false); + // F64 last_good_ring(u64_time_to_float(now)); + + // // Jump forward and expire + // now += float_time_to_u64(10.0); + // ensure_equals("WOCM t9 - 5.0 horizon timer expires on 10-second jump", + // timer.isExpired(now, started, stopped, count), true); + // ensure_approximately_equals("WOCM t9 - started matches start() time", started, real_start, 4); + // ensure_approximately_equals("WOCM t9 - stopped matches last ringBell() time", stopped, last_good_ring, 4); + // ensure_equals("WOCM t9 - 10 good ringBell()s", count, U64L(10)); + // ensure_equals("WOCM t9 - single read only", timer.isExpired(now, started, stopped, count), false); + // } + // { + // // With cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)), user_cpu(29000), sys_cpu(57000); + // LLDeadmanTimer timer(5.0, true); + + // LLDeadmanTimer::time_type now(LLDeadmanTimer::getNow()); + // F64 real_start(u64_time_to_float(now)); + // timer.start(0); + + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // ensure_equals("WCM t9 - 5.0 horizon timer has not timed out after 10 1-second bell rings", + // timer.isExpired(now, started, stopped, count, user_cpu, sys_cpu), false); + // F64 last_good_ring(u64_time_to_float(now)); + + // // Jump forward and expire + // now += float_time_to_u64(10.0); + // ensure_equals("WCM t9 - 5.0 horizon timer expires on 10-second jump", + // timer.isExpired(now, started, stopped, count, user_cpu, sys_cpu), true); + // ensure_approximately_equals("WCM t9 - started matches start() time", started, real_start, 4); + // ensure_approximately_equals("WCM t9 - stopped matches last ringBell() time", stopped, last_good_ring, 4); + // ensure_equals("WCM t9 - 10 good ringBell()s", count, U64L(10)); + // ensure_equals("WCM t9 - single read only", timer.isExpired(now, started, stopped, count, user_cpu, sys_cpu), false); + // } + // } + } + + TUT_CASE("lldeadmantimer_test::deadmantimer_object_t_test_10") + { + DOCTEST_FAIL("TODO: convert lldeadmantimer_test.cpp::deadmantimer_object_t::test<10> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void deadmantimer_object_t::test<10>() + // { + // { + // // Without cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)); + // LLDeadmanTimer timer(5.0, false); + + // LLDeadmanTimer::time_type now(LLDeadmanTimer::getNow()); + // F64 real_start(u64_time_to_float(now)); + // timer.start(0); + + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // ensure_equals("WOCM t10 - 5.0 horizon timer has not timed out after 10 1-second bell rings", + // timer.isExpired(now, started, stopped, count), false); + // F64 last_good_ring(u64_time_to_float(now)); + + // // Jump forward and expire + // now += float_time_to_u64(10.0); + // ensure_equals("WOCM t10 - 5.0 horizon timer expires on 10-second jump", + // timer.isExpired(now, started, stopped, count), true); + // ensure_approximately_equals("WOCM t10 - started matches start() time", started, real_start, 4); + // ensure_approximately_equals("WOCM t10 - stopped matches last ringBell() time", stopped, last_good_ring, 4); + // ensure_equals("WOCM t10 - 10 good ringBell()s", count, U64L(10)); + // ensure_equals("WOCM t10 - single read only", timer.isExpired(now, started, stopped, count), false); + + // // Jump forward and restart + // now += float_time_to_u64(1.0); + // real_start = u64_time_to_float(now); + // timer.start(now); + + // // Run a modified bell ring sequence + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // ensure_equals("WOCM t10 - 5.0 horizon timer has not timed out after 8 1-second bell rings", + // timer.isExpired(now, started, stopped, count), false); + // last_good_ring = u64_time_to_float(now); + + // // Jump forward and expire + // now += float_time_to_u64(10.0); + // ensure_equals("WOCM t10 - 5.0 horizon timer expires on 8-second jump", + // timer.isExpired(now, started, stopped, count), true); + // ensure_approximately_equals("WOCM t10 - 2nd started matches start() time", started, real_start, 4); + // ensure_approximately_equals("WOCM t10 - 2nd stopped matches last ringBell() time", stopped, last_good_ring, 4); + // ensure_equals("WOCM t10 - 8 good ringBell()s", count, U64L(8)); + // ensure_equals("WOCM t10 - single read only - 2nd start", + // timer.isExpired(now, started, stopped, count), false); + // } + // { + // // With cpu metrics + // F64 started(42.0), stopped(97.0); + // U64 count(U64L(8)), user_cpu(29000), sys_cpu(57000); + + // LLDeadmanTimer timer(5.0, true); + + // LLDeadmanTimer::time_type now(LLDeadmanTimer::getNow()); + // F64 real_start(u64_time_to_float(now)); + // timer.start(0); + + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // ensure_equals("WCM t10 - 5.0 horizon timer has not timed out after 10 1-second bell rings", + // timer.isExpired(now, started, stopped, count, user_cpu, sys_cpu), false); + // F64 last_good_ring(u64_time_to_float(now)); + + // // Jump forward and expire + // now += float_time_to_u64(10.0); + // ensure_equals("WCM t10 - 5.0 horizon timer expires on 10-second jump", + // timer.isExpired(now, started, stopped, count, user_cpu, sys_cpu), true); + // ensure_approximately_equals("WCM t10 - started matches start() time", started, real_start, 4); + // ensure_approximately_equals("WCM t10 - stopped matches last ringBell() time", stopped, last_good_ring, 4); + // ensure_equals("WCM t10 - 10 good ringBell()s", count, U64L(10)); + // ensure_equals("WCM t10 - single read only", timer.isExpired(now, started, stopped, count, user_cpu, sys_cpu), false); + + // // Jump forward and restart + // now += float_time_to_u64(1.0); + // real_start = u64_time_to_float(now); + // timer.start(now); + + // // Run a modified bell ring sequence + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // now += float_time_to_u64(1.0); + // timer.ringBell(now, 1); + // ensure_equals("WCM t10 - 5.0 horizon timer has not timed out after 8 1-second bell rings", + // timer.isExpired(now, started, stopped, count, user_cpu, sys_cpu), false); + // last_good_ring = u64_time_to_float(now); + + // // Jump forward and expire + // now += float_time_to_u64(10.0); + // ensure_equals("WCM t10 - 5.0 horizon timer expires on 8-second jump", + // timer.isExpired(now, started, stopped, count, user_cpu, sys_cpu), true); + // ensure_approximately_equals("WCM t10 - 2nd started matches start() time", started, real_start, 4); + // ensure_approximately_equals("WCM t10 - 2nd stopped matches last ringBell() time", stopped, last_good_ring, 4); + // ensure_equals("WCM t10 - 8 good ringBell()s", count, U64L(8)); + // ensure_equals("WCM t10 - single read only - 2nd start", + // timer.isExpired(now, started, stopped, count, user_cpu, sys_cpu), false); + // } + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/lldependencies_test_doctest.cpp b/indra/llcommon/tests_doctest/lldependencies_test_doctest.cpp new file mode 100644 index 00000000000..30246cf9cd9 --- /dev/null +++ b/indra/llcommon/tests_doctest/lldependencies_test_doctest.cpp @@ -0,0 +1,197 @@ +/** + * @file lldependencies_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL dependencies + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from lldependencies_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include +#include +#include +#include "linden_common.h" +#include "../lldependencies.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("lldependencies_test::deps_object_test_1") + { + DOCTEST_FAIL("TODO: convert lldependencies_test.cpp::deps_object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void deps_object::test<1>() + // { + // StringDeps deps; + // StringList empty; + // // The quick brown fox jumps over the lazy yellow dog. + // // (note, "The" and "the" are distinct, else this test wouldn't work) + // deps.add("lazy"); + // ensure_equals(sorted_keys(deps), make(list_of("lazy"))); + // deps.add("jumps"); + // ensure("found lazy", deps.get("lazy")); + // ensure("not found dog.", ! deps.get("dog.")); + // // NOTE: Maybe it's overkill to test each of these intermediate + // // results before all the interdependencies have been specified. My + // // thought is simply that if the order changes, I'd like to know why. + // // A change to the implementation of boost::topological_sort() would + // // be an acceptable reason, and you can simply update the expected + // // test output. + // ensure_equals(sorted_keys(deps), make(list_of("lazy")("jumps"))); + // deps.add("The", 0, empty, list_of("fox")("dog.")); + // // Test key accessors + // ensure("empty before deps for missing key", is_empty(deps.get_before_range("bogus"))); + // ensure("empty before deps for jumps", is_empty(deps.get_before_range("jumps"))); + // ensure_equals(instance_from_range< std::set >(deps.get_before_range("The")), + // make< std::set >(list_of("dog.")("fox"))); + // // resume building dependencies + // ensure_equals(sorted_keys(deps), make(list_of("lazy")("jumps")("The"))); + // deps.add("the", 0, list_of("The")); + // ensure_equals(sorted_keys(deps), make(list_of("lazy")("jumps")("The")("the"))); + // deps.add("fox", 0, list_of("The"), list_of("jumps")); + // ensure_equals(sorted_keys(deps), make(list_of("lazy")("The")("the")("fox")("jumps"))); + // deps.add("the", 0, list_of("The")); // same, see if cache works + // ensure_equals(sorted_keys(deps), make(list_of("lazy")("The")("the")("fox")("jumps"))); + // deps.add("jumps", 0, empty, list_of("over")); // update jumps deps + // ensure_equals(sorted_keys(deps), make(list_of("lazy")("The")("the")("fox")("jumps"))); + // /*==========================================================================*| + // // It drives me nuts that this test doesn't work in the test + // // framework, because -- for reasons unknown -- running the test + // // framework on Mac OS X 10.5 Leopard and Windows XP Pro, the catch + // // clause below doesn't catch the exception. Something about the TUT + // // test framework?!? The identical code works fine in a standalone + // // test program. Commenting out the test for now, in hopes that our + // // real builds will be able to catch Cycle exceptions... + // try + // { + // // We've already specified fox -> jumps and jumps -> over. Try an + // // impossible constraint. + // deps.add("over", 0, empty, list_of("fox")); + // } + // catch (const StringDeps::Cycle& e) + // { + // std::cout << "Cycle detected: " << e.what() << '\n'; + // // It's legal to add() an impossible constraint because we don't + // // detect the cycle until sort(). So sort() can't know the minimum set + // // of nodes to remove to make the StringDeps object valid again. + // // Therefore we must break the cycle by hand. + // deps.remove("over"); + // } + // |*==========================================================================*/ + // deps.add("dog.", 0, list_of("yellow")("lazy")); + // ensure_equals(instance_from_range< std::set >(deps.get_after_range("dog.")), + // make< std::set >(list_of("lazy")("yellow"))); + // ensure_equals(sorted_keys(deps), make(list_of("lazy")("The")("the")("fox")("jumps")("dog."))); + // deps.add("quick", 0, list_of("The"), list_of("fox")("brown")); + // ensure_equals(sorted_keys(deps), make(list_of("lazy")("The")("the")("quick")("fox")("jumps")("dog."))); + // deps.add("over", 0, list_of("jumps"), list_of("yellow")("the")); + // ensure_equals(sorted_keys(deps), make(list_of("lazy")("The")("quick")("fox")("jumps")("over")("the")("dog."))); + // deps.add("yellow", 0, list_of("the"), list_of("lazy")); + // ensure_equals(sorted_keys(deps), make(list_of("The")("quick")("fox")("jumps")("over")("the")("yellow")("lazy")("dog."))); + // deps.add("brown"); + // // By now the dependencies are pretty well in place. A change to THIS + // // order should be viewed with suspicion. + // ensure_equals(sorted_keys(deps), make(list_of("The")("quick")("brown")("fox")("jumps")("over")("the")("yellow")("lazy")("dog."))); + + // StringList keys(make(list_of("The")("brown")("dog.")("fox")("jumps")("lazy")("over")("quick")("the")("yellow"))); + // ensure_equals(instance_from_range(deps.get_key_range()), keys); + // #if (! defined(__GNUC__)) || (__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ > 3) + // // This is the succinct way, works on modern compilers + // ensure_equals(instance_from_range(make_transform_range(deps.get_range(), extract_key)), keys); + // #else // gcc 3.3 + // StringDeps::range got_range(deps.get_range()); + // StringDeps::iterator kni = got_range.begin(), knend = got_range.end(); + // StringList::iterator ki = keys.begin(), kend = keys.end(); + // for ( ; kni != knend && ki != kend; ++kni, ++ki) + // { + // ensure_equals(kni->first, *ki); + // } + // ensure("get_range() returns proper length", kni == knend && ki == kend); + // #endif // gcc 3.3 + // // blow off get_node_range() because they're all LLDependenciesEmpty instances + // } + } + + TUT_CASE("lldependencies_test::deps_object_test_2") + { + DOCTEST_FAIL("TODO: convert lldependencies_test.cpp::deps_object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void deps_object::test<2>() + // { + // typedef LLDependencies NameIndexDeps; + // NameIndexDeps nideps; + // const NameIndexDeps& const_nideps(nideps); + // nideps.add("def", 2, list_of("ghi")); + // nideps.add("ghi", 3); + // nideps.add("abc", 1, list_of("def")); + // NameIndexDeps::range range(nideps.get_range()); + // ensure_equals(range.begin()->first, "abc"); + // ensure_equals(range.begin()->second, 1); + // range.begin()->second = 0; + // range.begin()->second = 1; + // NameIndexDeps::const_range const_range(const_nideps.get_range()); + // NameIndexDeps::const_iterator const_iterator(const_range.begin()); + // ++const_iterator; + // ensure_equals(const_iterator->first, "def"); + // ensure_equals(const_iterator->second, 2); + // // NameIndexDeps::node_range node_range(nideps.get_node_range()); + // // ensure_equals(instance_from_range >(node_range), make< std::vector >(list_of(1)(2)(3))); + // // *node_range.begin() = 0; + // // *node_range.begin() = 1; + // NameIndexDeps::const_node_range const_node_range(const_nideps.get_node_range()); + // ensure_equals(instance_from_range >(const_node_range), make< std::vector >(list_of(1)(2)(3))); + // NameIndexDeps::const_key_range const_key_range(const_nideps.get_key_range()); + // ensure_equals(instance_from_range(const_key_range), make(list_of("abc")("def")("ghi"))); + // NameIndexDeps::sorted_range sorted(const_nideps.sort()); + // NameIndexDeps::sorted_iterator sortiter(sorted.begin()); + // ensure_equals(sortiter->first, "ghi"); + // ensure_equals(sortiter->second, 3); + + // // test all iterator-flavored versions of get_after_range() + // StringList def(make(list_of("def"))); + // ensure("empty abc before list", is_empty(nideps.get_before_range(nideps.get_range().begin()))); + // ensure_equals(instance_from_range(nideps.get_after_range(nideps.get_range().begin())), + // def); + // ensure_equals(instance_from_range(const_nideps.get_after_range(const_nideps.get_range().begin())), + // def); + // // ensure_equals(instance_from_range(nideps.get_after_range(nideps.get_node_range().begin())), + // // def); + // ensure_equals(instance_from_range(const_nideps.get_after_range(const_nideps.get_node_range().begin())), + // def); + // ensure_equals(instance_from_range(nideps.get_after_range(nideps.get_key_range().begin())), + // def); + // // advance from "ghi" to "def", which must come after "ghi" + // ++sortiter; + // ensure_equals(instance_from_range(const_nideps.get_after_range(sortiter)), + // make(list_of("ghi"))); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llerror_test_doctest.cpp b/indra/llcommon/tests_doctest/llerror_test_doctest.cpp new file mode 100644 index 00000000000..8e080fa5283 --- /dev/null +++ b/indra/llcommon/tests_doctest/llerror_test_doctest.cpp @@ -0,0 +1,49 @@ +/** + * @file llerror_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL error + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llerror_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include +#include +#include "linden_common.h" +#include "../llerror.h" +#include "../llerrorcontrol.h" +#include "../llsd.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("llerror_test::no_tests_detected") + { + DOCTEST_FAIL("TODO: no TUT tests discovered in source file"); + } +} + diff --git a/indra/llcommon/tests_doctest/lleventcoro_test_doctest.cpp b/indra/llcommon/tests_doctest/lleventcoro_test_doctest.cpp new file mode 100644 index 00000000000..fe0f1247ca6 --- /dev/null +++ b/indra/llcommon/tests_doctest/lleventcoro_test_doctest.cpp @@ -0,0 +1,174 @@ +/** + * @file lleventcoro_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL eventcoro + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from lleventcoro_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include +#include +#include +#include "linden_common.h" +#include +#include +#include +#include "../test/lltestapp.h" +#include "llsd.h" +#include "llsdutil.h" +#include "llevents.h" +#include "llcoros.h" +#include "lleventfilter.h" +#include "lleventcoro.h" +#include "../test/debug.h" +#include "../test/sync.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("lleventcoro_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert lleventcoro_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // set_test_name("explicit_wait"); + // DEBUG; + + // // Construct the coroutine instance that will run explicit_wait. + // std::shared_ptr> respond; + // LLCoros::instance().launch("test<1>", + // [this, &respond](){ explicit_wait(respond); }); + // mSync.bump(); + // // When the coroutine waits for the future, it returns here. + // debug("about to respond"); + // // Now we're the I/O subsystem delivering a result. This should make + // // the coroutine ready. + // respond->set_value("received"); + // // but give it a chance to wake up + // mSync.yield(); + // // ensure the coroutine ran and woke up again with the intended result + // ensure_equals(stringdata, "received"); + // } + } + + TUT_CASE("lleventcoro_test::object_test_2") + { + DOCTEST_FAIL("TODO: convert lleventcoro_test.cpp::object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<2>() + // { + // set_test_name("waitForEventOn1"); + // DEBUG; + // LLCoros::instance().launch("test<2>", [this](){ waitForEventOn1(); }); + // mSync.bump(); + // debug("about to send"); + // LLEventPumps::instance().obtain("source").post("received"); + // // give waitForEventOn1() a chance to run + // mSync.yield(); + // debug("back from send"); + // ensure_equals(result.asString(), "received"); + // } + } + + TUT_CASE("lleventcoro_test::object_test_3") + { + DOCTEST_FAIL("TODO: convert lleventcoro_test.cpp::object::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<3>() + // { + // set_test_name("coroPump"); + // DEBUG; + // LLCoros::instance().launch("test<3>", [this](){ coroPump(); }); + // mSync.bump(); + // debug("about to send"); + // LLEventPumps::instance().obtain(replyName).post("received"); + // // give coroPump() a chance to run + // mSync.yield(); + // debug("back from send"); + // ensure_equals(result.asString(), "received"); + // } + } + + TUT_CASE("lleventcoro_test::object_test_4") + { + DOCTEST_FAIL("TODO: convert lleventcoro_test.cpp::object::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<4>() + // { + // set_test_name("postAndWait1"); + // DEBUG; + // LLCoros::instance().launch("test<4>", [this](){ postAndWait1(); }); + // ensure_equals(result.asInteger(), 18); + // } + } + + TUT_CASE("lleventcoro_test::object_test_5") + { + DOCTEST_FAIL("TODO: convert lleventcoro_test.cpp::object::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<5>() + // { + // set_test_name("coroPumpPost"); + // DEBUG; + // LLCoros::instance().launch("test<5>", [this](){ coroPumpPost(); }); + // ensure_equals(result.asInteger(), 18); + // } + } + + TUT_CASE("lleventcoro_test::object_test_6") + { + DOCTEST_FAIL("TODO: convert lleventcoro_test.cpp::object::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<6>() + // { + // set_test_name("LLEventMailDrop"); + // tut::test(); + // } + } + + TUT_CASE("lleventcoro_test::object_test_7") + { + DOCTEST_FAIL("TODO: convert lleventcoro_test.cpp::object::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<7>() + // { + // set_test_name("LLEventLogProxyFor"); + // tut::test< LLEventLogProxyFor >(); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/lleventdispatcher_test_doctest.cpp b/indra/llcommon/tests_doctest/lleventdispatcher_test_doctest.cpp new file mode 100644 index 00000000000..2e2fa6fcca7 --- /dev/null +++ b/indra/llcommon/tests_doctest/lleventdispatcher_test_doctest.cpp @@ -0,0 +1,1127 @@ +/** + * @file lleventdispatcher_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL eventdispatcher + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from lleventdispatcher_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "lleventdispatcher.h" +#include "lleventfilter.h" +#include "llsd.h" +#include "llsdutil.h" +#include "llevents.h" +#include "stringize.h" +// #include "StringVec.h" // not available on Windows +#include "tests/wrapllerrs.h" +#include "../test/catch_and_store_what_in.h" +#include "../test/debug.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +TUT_SUITE("llcommon") +{ + TUT_CASE("lleventdispatcher_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // set_test_name("map-style registration with non-array params"); + // // Pass "param names" as scalar or as map + // LLSD attempts(llsd::array(17, LLSDMap("pi", 3.14)("two", 2))); + // for (LLSD ae: inArray(attempts)) + // { + // std::string threw = catch_what([this, &ae](){ + // work.add("freena_err", "freena", freena, ae); + // }); + // ensure_has(threw, "must be an array"); + // } + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_2") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<2>() + // { + // set_test_name("map-style registration with badly-formed defaults"); + // std::string threw = catch_what([this](){ + // work.add("freena_err", "freena", freena, llsd::array("a", "b"), 17); + // }); + // ensure_has(threw, "must be a map or an array"); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_3") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<3>() + // { + // set_test_name("map-style registration with too many array defaults"); + // std::string threw = catch_what([this](){ + // work.add("freena_err", "freena", freena, + // llsd::array("a", "b"), + // llsd::array(17, 0.9, "gack")); + // }); + // ensure_has(threw, "shorter than"); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_4") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<4>() + // { + // set_test_name("map-style registration with too many map defaults"); + // std::string threw = catch_what([this](){ + // work.add("freena_err", "freena", freena, + // llsd::array("a", "b"), + // LLSDMap("b", 17)("foo", 3.14)("bar", "sinister")); + // }); + // ensure_has(threw, "nonexistent params"); + // ensure_has(threw, "foo"); + // ensure_has(threw, "bar"); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_5") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<5>() + // { + // set_test_name("query all"); + // verify_descs(); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_6") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<6>() + // { + // set_test_name("query all with remove()"); + // ensure("remove('bogus') returned true", ! work.remove("bogus")); + // ensure("remove('real') returned false", work.remove("free1")); + // // Of course, remove that from 'descs' too... + // descs.erase("free1"); + // verify_descs(); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_7") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<7>() + // { + // set_test_name("getDispatchKey()"); + // ensure_equals(work.getDispatchKey(), "op"); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_8") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<8> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<8>() + // { + // set_test_name("query Callables with/out required params"); + // LLSD names(llsd::array("free1", "Dmethod1", "Dcmethod1", "method1")); + // for (LLSD nm: inArray(names)) + // { + // LLSD metadata(getMetadata(nm)); + // ensure_equals("name mismatch", metadata["name"], nm); + // ensure_equals(metadata["desc"].asString(), descs[nm]); + // ensure("should not have required structure", metadata["required"].isUndefined()); + // ensure("should not have optional", metadata["optional"].isUndefined()); + + // std::string name_req(nm.asString() + "_req"); + // metadata = getMetadata(name_req); + // ensure_equals(metadata["name"].asString(), name_req); + // ensure_equals(metadata["desc"].asString(), descs[name_req]); + // ensure_equals("required mismatch", required, metadata["required"]); + // ensure("should not have optional", metadata["optional"].isUndefined()); + // } + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_9") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<9> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<9>() + // { + // set_test_name("query array-style functions/methods"); + // // Associate each registered name with expected arity. + // LLSD expected(llsd::array + // (llsd::array + // (0, llsd::array("free0_array", "smethod0_array", "method0_array")), + // llsd::array + // (5, llsd::array("freena_array", "smethodna_array", "methodna_array")), + // llsd::array + // (5, llsd::array("freenb_array", "smethodnb_array", "methodnb_array")))); + // for (LLSD ae: inArray(expected)) + // { + // LLSD::Integer arity(ae[0].asInteger()); + // LLSD names(ae[1]); + // LLSD req(LLSD::emptyArray()); + // if (arity) + // req[arity - 1] = LLSD(); + // for (LLSD nm: inArray(names)) + // { + // LLSD metadata(getMetadata(nm)); + // ensure_equals("name mismatch", metadata["name"], nm); + // ensure_equals(metadata["desc"].asString(), descs[nm]); + // ensure_equals(stringize("mismatched required for ", nm.asString()), + // metadata["required"], req); + // ensure("should not have optional", metadata["optional"].isUndefined()); + // } + // } + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_10") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<10> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<10>() + // { + // set_test_name("query map-style no-params functions/methods"); + // // - (Free function | non-static method), map style, no params (ergo + // // no defaults) + // LLSD names(llsd::array("free0_map", "smethod0_map", "method0_map")); + // for (LLSD nm: inArray(names)) + // { + // LLSD metadata(getMetadata(nm)); + // ensure_equals("name mismatch", metadata["name"], nm); + // ensure_equals(metadata["desc"].asString(), descs[nm]); + // ensure("should not have required", + // (metadata["required"].isUndefined() || metadata["required"].size() == 0)); + // ensure("should not have optional", metadata["optional"].isUndefined()); + // } + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_11") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<11> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<11>() + // { + // set_test_name("query map-style arbitrary-params functions/methods: " + // "full array defaults vs. full map defaults"); + // // With functions registered with no defaults ("_allreq" suffixes), + // // there is of course no difference between array defaults and map + // // defaults. (We don't even bother registering with LLSD::emptyArray() + // // vs. LLSD::emptyMap().) With functions registered with all defaults, + // // there should (!) be no difference beween array defaults and map + // // defaults. Verify, so we can ignore the distinction for all other + // // tests. + // LLSD equivalences(llsd::array + // (llsd::array("freena_map_adft", "freena_map_mdft"), + // llsd::array("freenb_map_adft", "freenb_map_mdft"), + // llsd::array("smethodna_map_adft", "smethodna_map_mdft"), + // llsd::array("smethodnb_map_adft", "smethodnb_map_mdft"), + // llsd::array("methodna_map_adft", "methodna_map_mdft"), + // llsd::array("methodnb_map_adft", "methodnb_map_mdft"))); + // for (LLSD eq: inArray(equivalences)) + // { + // LLSD adft(eq[0]); + // LLSD mdft(eq[1]); + // // We can't just compare the results of the two getMetadata() + // // calls, because they contain ["name"], which are different. So + // // capture them, verify that each ["name"] is as expected, then + // // remove for comparing the rest. + // LLSD ameta(getMetadata(adft)); + // LLSD mmeta(getMetadata(mdft)); + // ensure_equals("adft name", adft, ameta["name"]); + // ensure_equals("mdft name", mdft, mmeta["name"]); + // ameta.erase("name"); + // mmeta.erase("name"); + // ensure_equals(stringize("metadata for ", adft.asString(), + // " vs. ", mdft.asString()), + // ameta, mmeta); + // } + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_12") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<12> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<12>() + // { + // set_test_name("query map-style arbitrary-params functions/methods"); + // // - (Free function | non-static method), map style, arbitrary params, + // // (empty | full | partial (array | map)) defaults + + // // Generate maps containing all parameter names for cases in which all + // // params are required. Also maps containing left requirements for + // // partial defaults arrays. Also defaults maps from defaults arrays. + // LLSD allreq, leftreq, rightdft; + // for (LLSD::String a: ab) + // { + // // The map in which all params are required uses params[a] as + // // keys, with all isUndefined() as values. We can accomplish that + // // by passing zipmap() an empty values array. + // allreq[a] = zipmap(params[a], LLSD::emptyArray()); + // // Same for leftreq, save that we use the subset of the params not + // // supplied by dft_array_partial[a]. + // LLSD::Integer partition(static_cast(params[a].size() - dft_array_partial[a].size())); + // leftreq[a] = zipmap(llsd_copy_array(params[a].beginArray(), + // params[a].beginArray() + partition), + // LLSD::emptyArray()); + // // Generate map pairing dft_array_partial[a] values with their + // // param names. + // rightdft[a] = zipmap(llsd_copy_array(params[a].beginArray() + partition, + // params[a].endArray()), + // dft_array_partial[a]); + // } + // debug("allreq:\n", + // allreq, "\n" + // "leftreq:\n", + // leftreq, "\n" + // "rightdft:\n", + // rightdft); + + // // Generate maps containing parameter names not provided by the + // // dft_map_partial maps. + // LLSD skipreq(allreq); + // for (LLSD::String a: ab) + // { + // for (const MapEntry& me: inMap(dft_map_partial[a])) + // { + // skipreq[a].erase(me.first); + // } + // } + // debug("skipreq:\n", + // skipreq); + + // LLSD groups(llsd::array // array of groups + + // (llsd::array // group + // (llsd::array("freena_map_allreq", "smethodna_map_allreq", "methodna_map_allreq"), + // llsd::array(allreq["a"], LLSD())), // required, optional + + // llsd::array // group + // (llsd::array("freenb_map_allreq", "smethodnb_map_allreq", "methodnb_map_allreq"), + // llsd::array(allreq["b"], LLSD())), // required, optional + + // llsd::array // group + // (llsd::array("freena_map_leftreq", "smethodna_map_leftreq", "methodna_map_leftreq"), + // llsd::array(leftreq["a"], rightdft["a"])), // required, optional + + // llsd::array // group + // (llsd::array("freenb_map_leftreq", "smethodnb_map_leftreq", "methodnb_map_leftreq"), + // llsd::array(leftreq["b"], rightdft["b"])), // required, optional + + // llsd::array // group + // (llsd::array("freena_map_skipreq", "smethodna_map_skipreq", "methodna_map_skipreq"), + // llsd::array(skipreq["a"], dft_map_partial["a"])), // required, optional + + // llsd::array // group + // (llsd::array("freenb_map_skipreq", "smethodnb_map_skipreq", "methodnb_map_skipreq"), + // llsd::array(skipreq["b"], dft_map_partial["b"])), // required, optional + + // // We only need mention the full-map-defaults ("_mdft" suffix) + // // registrations, having established their equivalence with the + // // full-array-defaults ("_adft" suffix) registrations in another test. + // llsd::array // group + // (llsd::array("freena_map_mdft", "smethodna_map_mdft", "methodna_map_mdft"), + // llsd::array(LLSD::emptyMap(), dft_map_full["a"])), // required, optional + + // llsd::array // group + // (llsd::array("freenb_map_mdft", "smethodnb_map_mdft", "methodnb_map_mdft"), + // llsd::array(LLSD::emptyMap(), dft_map_full["b"])))); // required, optional + + // for (LLSD grp: inArray(groups)) + // { + // // Internal structure of each group in 'groups': + // LLSD names(grp[0]); + // LLSD required(grp[1][0]); + // LLSD optional(grp[1][1]); + // debug("For ", names, ",\n", + // "required:\n", + // required, "\n" + // "optional:\n", + // optional); + + // // Loop through 'names' + // for (LLSD nm: inArray(names)) + // { + // LLSD metadata(getMetadata(nm)); + // ensure_equals("name mismatch", metadata["name"], nm); + // ensure_equals(nm.asString(), metadata["desc"].asString(), descs[nm]); + // ensure_equals(stringize(nm, " required mismatch"), + // metadata["required"], required); + // ensure_equals(stringize(nm, " optional mismatch"), + // metadata["optional"], optional); + // } + // } + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_13") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<13> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<13>() + // { + // set_test_name("try_call()"); + // ensure("try_call(bogus name, LLSD()) returned true", ! work.try_call("freek", LLSD())); + // ensure("try_call(bogus name) returned true", ! work.try_call(LLSDMap("op", "freek"))); + // ensure("try_call(real name, LLSD()) returned false", work.try_call("free0_array", LLSD())); + // ensure("try_call(real name) returned false", work.try_call(LLSDMap("op", "free0_map"))); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_14") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<14> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<14>() + // { + // set_test_name("call with bad name"); + // call_exc("freek", LLSD(), "not found"); + // std::string threw = call_exc("", LLSDMap("op", "freek"), "bad"); + // ensure_has(threw, "op"); + // ensure_has(threw, "freek"); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_15") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<15> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<15>() + // { + // set_test_name("call with event key"); + // // We don't need a separate test for operator()(string, LLSD) with + // // valid name, because all the rest of the tests exercise that case. + // // The one we don't exercise elsewhere is operator()(LLSD) with valid + // // name, so here it is. + // work(LLSDMap("op", "free0_map")); + // ensure_equals(g.i, 17); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_16") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<16> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<16>() + // { + // set_test_name("call Callables"); + // CallablesTriple tests[] = + // { + // { "free1", "free1_req", g.llsd }, + // { "Dmethod1", "Dmethod1_req", work.llsd }, + // { "Dcmethod1", "Dcmethod1_req", work.llsd }, + // { "method1", "method1_req", v.llsd } + // }; + // // Arbitrary LLSD value that we should be able to pass to Callables + // // without 'required', but should not be able to pass to Callables + // // with 'required'. + // LLSD answer(42); + // // LLSD value matching 'required' according to llsd_matches() rules. + // LLSD matching(LLSDMap("d", 3.14)("array", llsd::array("answer", true, answer))); + // // Okay, walk through 'tests'. + // for (const CallablesTriple& tr: tests) + // { + // // Should be able to pass 'answer' to Callables registered + // // without 'required'. + // work(tr.name, answer); + // ensure_equals("answer mismatch", tr.llsd, answer); + // // Should NOT be able to pass 'answer' to Callables registered + // // with 'required'. + // call_logerr(tr.name_req, answer, "bad request"); + // // But SHOULD be able to pass 'matching' to Callables registered + // // with 'required'. + // work(tr.name_req, matching); + // ensure_equals("matching mismatch", tr.llsd, matching); + // } + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_17") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<17> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<17>() + // { + // set_test_name("passing wrong args to (map | array)-style registrations"); + + // // Pass scalar/map to array-style functions, scalar/array to map-style + // // functions. It seems pointless to repeat this with every variation: + // // (free function | non-static method), (no | arbitrary) args. We + // // should only need to engage it for one map-style registration and + // // one array-style registration. + // // Now that LLEventDispatcher has been extended to treat an LLSD + // // scalar as a single-entry array, the error we expect in this case is + // // that apply() is trying to pass that non-empty array to a nullary + // // function. + // call_logerr("free0_array", 17, "LL::apply"); + // // similarly, apply() doesn't accept an LLSD Map + // call_logerr("free0_array", LLSDMap("pi", 3.14), "unsupported"); + + // std::string map_exc("needs a map"); + // call_logerr("free0_map", 17, map_exc); + // // Passing an array to a map-style function works now! No longer an + // // error case! + // // call_exc("free0_map", llsd::array("a", "b"), map_exc); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_18") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<18> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<18>() + // { + // set_test_name("call no-args functions"); + // LLSD names(llsd::array + // ("free0_array", "free0_map", + // "smethod0_array", "smethod0_map", + // "method0_array", "method0_map")); + // for (LLSD name: inArray(names)) + // { + // // Look up the Vars instance for this function. + // Vars* vars(varsfor(name)); + // // Both the global and stack Vars instances are automatically + // // cleared at the start of each test method. But since we're + // // calling these things several different times in the same + // // test method, manually reset the Vars between each. + // *vars = Vars(); + // ensure_equals(vars->i, 0); + // // call function with empty array (or LLSD(), should be equivalent) + // work(name, LLSD()); + // ensure_equals(vars->i, 17); + // } + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_19") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<19> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<19>() + // { + // set_test_name("call array-style functions with wrong-length arrays"); + // // Could have different wrong-length arrays for *na and for *nb, but + // // since they both take 5 params... + // LLSD tooshort(llsd::array("this", "array", "too", "short")); + // LLSD toolong (llsd::array("this", "array", "is", "one", "too", "long")); + // LLSD badargs (llsd::array(tooshort, toolong)); + // for (const LLSD& toosomething: inArray(badargs)) + // { + // for (const LLSD& funcsab: inArray(array_funcs)) + // { + // for (const llsd::MapEntry& e: inMap(funcsab)) + // { + // // apply() complains about wrong number of array entries + // call_logerr(e.second, toosomething, "LL::apply"); + // } + // } + // } + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_20") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<20> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<20>() + // { + // set_test_name("call array-style functions with right-size arrays"); + // std::vector binary; + // for (size_t h(0x01), i(0); i < 5; h+= 0x22, ++i) + // { + // binary.push_back((U8)h); + // } + // LLSD args(LLSDMap("a", llsd::array(true, 17, 3.14, 123.456, "char*")) + // ("b", llsd::array("string", + // LLUUID("01234567-89ab-cdef-0123-456789abcdef"), + // LLDate("2011-02-03T15:07:00Z"), + // LLURI("http://secondlife.com"), + // binary))); + // LLSD expect; + // for (LLSD::String a: ab) + // { + // expect[a] = zipmap(params[a], args[a]); + // } + // // Adjust expect["a"]["cp"] for special Vars::cp treatment. + // expect["a"]["cp"] = stringize("'", expect["a"]["cp"].asString(), "'"); + // debug("expect: ", expect); + + // for (const LLSD& funcsab: inArray(array_funcs)) + // { + // for (LLSD::String a: ab) + // { + // // Reset the Vars instance before each call + // Vars* vars(varsfor(funcsab[a])); + // *vars = Vars(); + // work(funcsab[a], args[a]); + // ensure_llsd(stringize(funcsab[a].asString(), ": expect[\"", a, "\"] mismatch"), + // vars->inspect(), expect[a], 7); // 7 bits ~= 2 decimal digits + // } + // } + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_21") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<21> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<21>() + // { + // set_test_name("verify that passing LLSD() to const char* sends NULL"); + + // ensure_equals("Vars::cp init", v.cp, ""); + // work("methodna_map_mdft", LLSDMap("cp", LLSD())); + // ensure_equals("passing LLSD()", v.cp, "NULL"); + // work("methodna_map_mdft", LLSDMap("cp", "")); + // ensure_equals("passing \"\"", v.cp, "''"); + // work("methodna_map_mdft", LLSDMap("cp", "non-NULL")); + // ensure_equals("passing \"non-NULL\"", v.cp, "'non-NULL'"); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_22") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<22> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<22>() + // { + // set_test_name("call map-style functions with (full | oversized) (arrays | maps)"); + // const char binary[] = "\x99\x88\x77\x66\x55"; + // LLSD array_full(LLSDMap + // ("a", llsd::array(false, 255, 98.6, 1024.5, "pointer")) + // ("b", llsd::array("object", LLUUID::generateNewID(), LLDate::now(), LLURI("http://wiki.lindenlab.com/wiki"), LLSD::Binary(boost::begin(binary), boost::end(binary))))); + // LLSD array_overfull(array_full); + // for (LLSD::String a: ab) + // { + // array_overfull[a].append("bogus"); + // } + // debug("array_full: ", array_full, "\n" + // "array_overfull: ", array_overfull); + // // We rather hope that LLDate::now() will generate a timestamp + // // distinct from the one it generated in the constructor, moments ago. + // ensure_not_equals("Timestamps too close", + // array_full["b"][2].asDate(), dft_array_full["b"][2].asDate()); + // // We /insist/ that LLUUID::generateNewID() do so. + // ensure_not_equals("UUID collision", + // array_full["b"][1].asUUID(), dft_array_full["b"][1].asUUID()); + // LLSD map_full, map_overfull; + // for (LLSD::String a: ab) + // { + // map_full[a] = zipmap(params[a], array_full[a]); + // map_overfull[a] = map_full[a]; + // map_overfull[a]["extra"] = "ignore"; + // } + // debug("map_full: ", map_full, "\n" + // "map_overfull: ", map_overfull); + // LLSD expect(map_full); + // // Twiddle the const char* param. + // expect["a"]["cp"] = std::string("'") + expect["a"]["cp"].asString() + "'"; + // // Another adjustment. For each data type, we're trying to distinguish + // // three values: the Vars member's initial value (member wasn't + // // stored; control never reached the set function), the registered + // // default param value from dft_array_full, and the array_full value + // // in this test. But bool can only distinguish two values. In this + // // case, we want to differentiate the local array_full value from the + // // dft_array_full value, so we use 'false'. However, that means + // // Vars::inspect() doesn't differentiate it from the initial value, + // // so won't bother returning it. Predict that behavior to match the + // // LLSD values. + // expect["a"].erase("b"); + // debug("expect: ", expect); + // // For this test, calling functions registered with different sets of + // // parameter defaults should make NO DIFFERENCE WHATSOEVER. Every call + // // should pass all params. + // LLSD names(LLSDMap + // ("a", llsd::array + // ("freena_map_allreq", "smethodna_map_allreq", "methodna_map_allreq", + // "freena_map_leftreq", "smethodna_map_leftreq", "methodna_map_leftreq", + // "freena_map_skipreq", "smethodna_map_skipreq", "methodna_map_skipreq", + // "freena_map_adft", "smethodna_map_adft", "methodna_map_adft", + // "freena_map_mdft", "smethodna_map_mdft", "methodna_map_mdft")) + // ("b", llsd::array + // ("freenb_map_allreq", "smethodnb_map_allreq", "methodnb_map_allreq", + // "freenb_map_leftreq", "smethodnb_map_leftreq", "methodnb_map_leftreq", + // "freenb_map_skipreq", "smethodnb_map_skipreq", "methodnb_map_skipreq", + // "freenb_map_adft", "smethodnb_map_adft", "methodnb_map_adft", + // "freenb_map_mdft", "smethodnb_map_mdft", "methodnb_map_mdft"))); + // // Treat (full | overfull) (array | map) the same. + // LLSD argssets(llsd::array(array_full, array_overfull, map_full, map_overfull)); + // for (const LLSD& args: inArray(argssets)) + // { + // for (LLSD::String a: ab) + // { + // for (LLSD::String name: inArray(names[a])) + // { + // // Reset the Vars instance + // Vars* vars(varsfor(name)); + // *vars = Vars(); + // work(name, args[a]); + // ensure_llsd(stringize(name, ": expect[\"", a, "\"] mismatch"), + // vars->inspect(), expect[a], 7); // 7 bits, 2 decimal digits + // // intercept LL_WARNS for the two overfull cases? + // } + // } + // } + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_23") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<23> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<23>() + // { + // set_test_name("string result"); + // DispatchResult service; + // LLSD result{ service("strfunc", "a string") }; + // ensure_equals("strfunc() mismatch", result.asString(), "got a string"); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_24") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<24> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<24>() + // { + // set_test_name("void result"); + // DispatchResult service; + // LLSD result{ service("voidfunc", LLSD()) }; + // ensure("voidfunc() returned defined", result.isUndefined()); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_25") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<25> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<25>() + // { + // set_test_name("Integer result"); + // DispatchResult service; + // LLSD result{ service("intfunc", -17) }; + // ensure_equals("intfunc() mismatch", result.asInteger(), 17); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_26") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<26> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<26>() + // { + // set_test_name("LLSD echo"); + // DispatchResult service; + // LLSD result{ service("llsdfunc", llsd::map("op", "llsdfunc", "reqid", 17)) }; + // ensure_equals("llsdfunc() mismatch", result, + // llsd::map("op", "llsdfunc", "reqid", 17, "with", "string")); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_27") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<27> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<27>() + // { + // set_test_name("map LLSD result"); + // DispatchResult service; + // LLSD result{ service("mapfunc", llsd::array(-12, "value")) }; + // ensure_equals("mapfunc() mismatch", result, llsd::map("i", 12, "str", "got value")); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_28") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<28> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<28>() + // { + // set_test_name("array LLSD result"); + // DispatchResult service; + // LLSD result{ service("arrayfunc", llsd::array(-8, "word")) }; + // ensure_equals("arrayfunc() mismatch", result, llsd::array(8, "got word")); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_29") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<29> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<29>() + // { + // set_test_name("listener error, no reply"); + // DispatchResult service; + // tut::call_exc( + // [&service]() + // { service.post(llsd::map("op", "nosuchfunc", "reqid", 17)); }, + // "nosuchfunc"); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_30") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<30> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<30>() + // { + // set_test_name("listener error with reply"); + // DispatchResult service; + // LLCaptureListener result; + // service.post(llsd::map("op", "nosuchfunc", "reqid", 17, "reply", result.getName())); + // LLSD reply{ result.get() }; + // ensure("no reply", reply.isDefined()); + // ensure_equals("reqid not echoed", reply["reqid"].asInteger(), 17); + // ensure_has(reply["error"].asString(), "nosuchfunc"); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_31") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<31> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<31>() + // { + // set_test_name("listener call to void function"); + // DispatchResult service; + // LLCaptureListener result; + // result.set("non-empty"); + // for (const auto& func: StringVec{ "voidfunc", "emptyfunc" }) + // { + // service.post(llsd::map( + // "op", func, + // "reqid", 17, + // "reply", result.getName())); + // ensure_equals("reply from " + func, result.get().asString(), "non-empty"); + // } + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_32") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<32> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<32>() + // { + // set_test_name("listener call to string function"); + // DispatchResult service; + // LLCaptureListener result; + // service.post(llsd::map( + // "op", "strfunc", + // "args", llsd::array("a string"), + // "reqid", 17, + // "reply", result.getName())); + // LLSD reply{ result.get() }; + // ensure_equals("reqid not echoed", reply["reqid"].asInteger(), 17); + // ensure_equals("bad reply from strfunc", reply["data"].asString(), "got a string"); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_33") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<33> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<33>() + // { + // set_test_name("listener call to map function"); + // DispatchResult service; + // LLCaptureListener result; + // service.post(llsd::map( + // "op", "mapfunc", + // "args", llsd::array(-7, "value"), + // "reqid", 17, + // "reply", result.getName())); + // LLSD reply{ result.get() }; + // ensure_equals("reqid not echoed", reply["reqid"].asInteger(), 17); + // ensure_equals("bad i from mapfunc", reply["i"].asInteger(), 7); + // ensure_equals("bad str from mapfunc", reply["str"], "got value"); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_34") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<34> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<34>() + // { + // set_test_name("batched map success"); + // DispatchResult service; + // LLCaptureListener result; + // service.post(llsd::map( + // "op", llsd::map( + // "strfunc", "some string", + // "intfunc", 2, + // "voidfunc", LLSD(), + // "arrayfunc", llsd::array(-5, "other string")), + // "reqid", 17, + // "reply", result.getName())); + // LLSD reply{ result.get() }; + // ensure_equals("reqid not echoed", reply["reqid"].asInteger(), 17); + // reply.erase("reqid"); + // ensure_equals( + // "bad map batch", + // reply, + // llsd::map( + // "strfunc", "got some string", + // "intfunc", -2, + // "voidfunc", LLSD(), + // "arrayfunc", llsd::array(5, "got other string"))); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_35") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<35> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<35>() + // { + // set_test_name("batched map error"); + // DispatchResult service; + // LLCaptureListener result; + // service.post(llsd::map( + // "op", llsd::map( + // "badfunc", 34, // ! + // "strfunc", "some string", + // "intfunc", 2, + // "missing", LLSD(), // ! + // "voidfunc", LLSD(), + // "arrayfunc", llsd::array(-5, "other string")), + // "reqid", 17, + // "reply", result.getName())); + // LLSD reply{ result.get() }; + // ensure_equals("reqid not echoed", reply["reqid"].asInteger(), 17); + // reply.erase("reqid"); + // auto error{ reply["error"].asString() }; + // reply.erase("error"); + // ensure_has(error, "badfunc"); + // ensure_has(error, "missing"); + // ensure_equals( + // "bad partial batch", + // reply, + // llsd::map( + // "strfunc", "got some string", + // "intfunc", -2, + // "voidfunc", LLSD(), + // "arrayfunc", llsd::array(5, "got other string"))); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_36") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<36> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<36>() + // { + // set_test_name("batched map exception"); + // DispatchResult service; + // auto error = tut::call_exc( + // [&service]() + // { + // service.post(llsd::map( + // "op", llsd::map( + // "badfunc", 34, // ! + // "strfunc", "some string", + // "intfunc", 2, + // "missing", LLSD(), // ! + // "voidfunc", LLSD(), + // "arrayfunc", llsd::array(-5, "other string")), + // "reqid", 17)); + // // no "reply" + // }, + // "badfunc"); + // ensure_has(error, "missing"); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_37") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<37> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<37>() + // { + // set_test_name("batched array success"); + // DispatchResult service; + // LLCaptureListener result; + // service.post(llsd::map( + // "op", llsd::array( + // llsd::array("strfunc", "some string"), + // llsd::array("intfunc", 2), + // "arrayfunc", + // "voidfunc"), + // "args", llsd::array( + // LLSD(), + // LLSD(), + // llsd::array(-5, "other string")), + // // args array deliberately short, since the default + // // [3] is undefined, which should work for voidfunc + // "reqid", 17, + // "reply", result.getName())); + // LLSD reply{ result.get() }; + // ensure_equals("reqid not echoed", reply["reqid"].asInteger(), 17); + // reply.erase("reqid"); + // ensure_equals( + // "bad array batch", + // reply, + // llsd::map( + // "data", llsd::array( + // "got some string", + // -2, + // llsd::array(5, "got other string"), + // LLSD()))); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_38") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<38> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<38>() + // { + // set_test_name("batched array error"); + // DispatchResult service; + // LLCaptureListener result; + // service.post(llsd::map( + // "op", llsd::array( + // llsd::array("strfunc", "some string"), + // llsd::array("intfunc", 2, "whoops"), // bad form + // "arrayfunc", + // "voidfunc"), + // "args", llsd::array( + // LLSD(), + // LLSD(), + // llsd::array(-5, "other string")), + // // args array deliberately short, since the default + // // [3] is undefined, which should work for voidfunc + // "reqid", 17, + // "reply", result.getName())); + // LLSD reply{ result.get() }; + // ensure_equals("reqid not echoed", reply["reqid"].asInteger(), 17); + // reply.erase("reqid"); + // auto error{ reply["error"] }; + // reply.erase("error"); + // ensure_has(error, "[1]"); + // ensure_has(error, "unsupported"); + // ensure_equals("bad array batch", reply, + // llsd::map("data", llsd::array("got some string"))); + // } + } + + TUT_CASE("lleventdispatcher_test::object_test_39") + { + DOCTEST_FAIL("TODO: convert lleventdispatcher_test.cpp::object::test<39> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<39>() + // { + // set_test_name("batched array exception"); + // DispatchResult service; + // auto error = tut::call_exc( + // [&service]() + // { + // service.post(llsd::map( + // "op", llsd::array( + // llsd::array("strfunc", "some string"), + // llsd::array("intfunc", 2, "whoops"), // bad form + // "arrayfunc", + // "voidfunc"), + // "args", llsd::array( + // LLSD(), + // LLSD(), + // llsd::array(-5, "other string")), + // // args array deliberately short, since the default + // // [3] is undefined, which should work for voidfunc + // "reqid", 17)); + // // no "reply" + // }, + // "[1]"); + // ensure_has(error, "unsupported"); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/lleventfilter_test_doctest.cpp b/indra/llcommon/tests_doctest/lleventfilter_test_doctest.cpp new file mode 100644 index 00000000000..578ddaa4e8a --- /dev/null +++ b/indra/llcommon/tests_doctest/lleventfilter_test_doctest.cpp @@ -0,0 +1,319 @@ +/** + * @file lleventfilter_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL eventfilter + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from lleventfilter_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "lleventfilter.h" +#include "stringize.h" +#include "llsdutil.h" +#include "listener.h" +#include "tests/wrapllerrs.h" +#include +#include "llsdutil.cpp" + +TUT_SUITE("llcommon") +{ + TUT_CASE("lleventfilter_test::filter_object_test_1") + { + DOCTEST_FAIL("TODO: convert lleventfilter_test.cpp::filter_object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void filter_object::test<1>() + // { + // set_test_name("LLEventMatching"); + // LLEventPump& driver(pumps.obtain("driver")); + // listener0.reset(0); + // // Listener isn't derived from LLEventTrackable specifically to test + // // various connection-management mechanisms. But that means we have a + // // couple of transient Listener objects, one of which is listening to + // // a persistent LLEventPump. Capture those connections in local + // // LLTempBoundListener instances so they'll disconnect + // // on destruction. + // LLTempBoundListener temp1( + // listener0.listenTo(driver)); + // // Construct a pattern LLSD: desired Event must have a key "foo" + // // containing string "bar" + // LLSD pattern; + // pattern.insert("foo", "bar"); + // LLEventMatching filter(driver, pattern); + // listener1.reset(0); + // LLTempBoundListener temp2( + // listener1.listenTo(filter)); + // driver.post(1); + // check_listener("direct", listener0, LLSD(1)); + // check_listener("filtered", listener1, LLSD(0)); + // // Okay, construct an LLSD map matching the pattern + // LLSD data; + // data["foo"] = "bar"; + // data["random"] = 17; + // driver.post(data); + // check_listener("direct", listener0, data); + // check_listener("filtered", listener1, data); + // } + } + + TUT_CASE("lleventfilter_test::filter_object_test_2") + { + DOCTEST_FAIL("TODO: convert lleventfilter_test.cpp::filter_object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void filter_object::test<2>() + // { + // set_test_name("LLEventTimeout::actionAfter()"); + // LLEventPump& driver(pumps.obtain("driver")); + // TestEventTimeout filter(driver); + // listener0.reset(0); + // LLTempBoundListener temp1( + // listener0.listenTo(filter)); + // // Use listener1.call() as the Action for actionAfter(), since it + // // already provides a way to sense the call + // listener1.reset(0); + // // driver --> filter --> listener0 + // filter.actionAfter(20, + // boost::bind(&Listener::call, boost::ref(listener1), LLSD("timeout"))); + // // Okay, (fake) timer is ticking. 'filter' can only sense the timer + // // when we pump mainloop. Do that right now to take the logic path + // // before either the anticipated event arrives or the timer expires. + // mainloop.post(17); + // check_listener("no timeout 1", listener1, LLSD(0)); + // // Expected event arrives... + // driver.post(1); + // check_listener("event passed thru", listener0, LLSD(1)); + // // Should have canceled the timer. Verify that by asserting that the + // // time has expired, then pumping mainloop again. + // filter.forceTimeout(); + // mainloop.post(17); + // check_listener("no timeout 2", listener1, LLSD(0)); + // // Verify chained actionAfter() calls, that is, that a second + // // actionAfter() resets the timer established by the first + // // actionAfter(). + // filter.actionAfter(20, + // boost::bind(&Listener::call, boost::ref(listener1), LLSD("timeout"))); + // // Since our TestEventTimeout class isn't actually manipulating time + // // (quantities of seconds), only a bool "elapsed" flag, sense that by + // // forcing the flag between actionAfter() calls. + // filter.forceTimeout(); + // // Pumping mainloop here would result in a timeout (as we'll verify + // // below). This state simulates a ticking timer that has not yet timed + // // out. But now, before a mainloop event lets 'filter' recognize + // // timeout on the previous actionAfter() call, pretend we're pushing + // // that timeout farther into the future. + // filter.actionAfter(20, + // boost::bind(&Listener::call, boost::ref(listener1), LLSD("timeout"))); + // // Look ma, no timeout! + // mainloop.post(17); + // check_listener("no timeout 3", listener1, LLSD(0)); + // // Now let the updated actionAfter() timer expire. + // filter.forceTimeout(); + // // Notice the timeout. + // mainloop.post(17); + // check_listener("timeout", listener1, LLSD("timeout")); + // // Timing out cancels the timer. Verify that. + // listener1.reset(0); + // filter.forceTimeout(); + // mainloop.post(17); + // check_listener("no timeout 4", listener1, LLSD(0)); + // // Reset the timer and then cancel() it. + // filter.actionAfter(20, + // boost::bind(&Listener::call, boost::ref(listener1), LLSD("timeout"))); + // // neither expired nor satisified + // mainloop.post(17); + // check_listener("no timeout 5", listener1, LLSD(0)); + // // cancel + // filter.cancel(); + // // timeout! + // filter.forceTimeout(); + // mainloop.post(17); + // check_listener("no timeout 6", listener1, LLSD(0)); + // } + } + + TUT_CASE("lleventfilter_test::filter_object_test_3") + { + DOCTEST_FAIL("TODO: convert lleventfilter_test.cpp::filter_object::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void filter_object::test<3>() + // { + // set_test_name("LLEventTimeout::eventAfter()"); + // LLEventPump& driver(pumps.obtain("driver")); + // TestEventTimeout filter(driver); + // listener0.reset(0); + // LLTempBoundListener temp1( + // listener0.listenTo(filter)); + // filter.eventAfter(20, LLSD("timeout")); + // // Okay, (fake) timer is ticking. 'filter' can only sense the timer + // // when we pump mainloop. Do that right now to take the logic path + // // before either the anticipated event arrives or the timer expires. + // mainloop.post(17); + // check_listener("no timeout 1", listener0, LLSD(0)); + // // Expected event arrives... + // driver.post(1); + // check_listener("event passed thru", listener0, LLSD(1)); + // // Should have canceled the timer. Verify that by asserting that the + // // time has expired, then pumping mainloop again. + // filter.forceTimeout(); + // mainloop.post(17); + // check_listener("no timeout 2", listener0, LLSD(1)); + // // Set timer again. + // filter.eventAfter(20, LLSD("timeout")); + // // Now let the timer expire. + // filter.forceTimeout(); + // // Notice the timeout. + // mainloop.post(17); + // check_listener("timeout", listener0, LLSD("timeout")); + // // Timing out cancels the timer. Verify that. + // listener0.reset(0); + // filter.forceTimeout(); + // mainloop.post(17); + // check_listener("no timeout 3", listener0, LLSD(0)); + // } + } + + TUT_CASE("lleventfilter_test::filter_object_test_4") + { + DOCTEST_FAIL("TODO: convert lleventfilter_test.cpp::filter_object::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void filter_object::test<4>() + // { + // set_test_name("LLEventTimeout::errorAfter()"); + // WrapLLErrs capture; + // LLEventPump& driver(pumps.obtain("driver")); + // TestEventTimeout filter(driver); + // listener0.reset(0); + // LLTempBoundListener temp1( + // listener0.listenTo(filter)); + // filter.errorAfter(20, "timeout"); + // // Okay, (fake) timer is ticking. 'filter' can only sense the timer + // // when we pump mainloop. Do that right now to take the logic path + // // before either the anticipated event arrives or the timer expires. + // mainloop.post(17); + // check_listener("no timeout 1", listener0, LLSD(0)); + // // Expected event arrives... + // driver.post(1); + // check_listener("event passed thru", listener0, LLSD(1)); + // // Should have canceled the timer. Verify that by asserting that the + // // time has expired, then pumping mainloop again. + // filter.forceTimeout(); + // mainloop.post(17); + // check_listener("no timeout 2", listener0, LLSD(1)); + // // Set timer again. + // filter.errorAfter(20, "timeout"); + // // Now let the timer expire. + // filter.forceTimeout(); + // // Notice the timeout. + // std::string threw = capture.catch_llerrs([this](){ + // mainloop.post(17); + // }); + // ensure_contains("errorAfter() timeout exception", threw, "timeout"); + // // Timing out cancels the timer. Verify that. + // listener0.reset(0); + // filter.forceTimeout(); + // mainloop.post(17); + // check_listener("no timeout 3", listener0, LLSD(0)); + // } + } + + TUT_CASE("lleventfilter_test::filter_object_test_5") + { + DOCTEST_FAIL("TODO: convert lleventfilter_test.cpp::filter_object::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void filter_object::test<5>() + // { + // set_test_name("LLEventThrottle"); + // TestEventThrottle throttle(3); + // Concat cat; + // throttle.listen("concat", boost::ref(cat)); + + // // (sequence taken from LLEventThrottleBase Doxygen comments) + // // 1: post(): event immediately passed to listeners, next no sooner than 4 + // throttle.advance(1); + // throttle.post("1"); + // ensure_equals("1", cat.result, "1"); // delivered immediately + // // 2: post(): deferred: waiting for 3 seconds to elapse + // throttle.advance(1); + // throttle.post("2"); + // ensure_equals("2", cat.result, "1"); // "2" not yet delivered + // // 3: post(): deferred + // throttle.advance(1); + // throttle.post("3"); + // ensure_equals("3", cat.result, "1"); // "3" not yet delivered + // // 4: no post() call, but event delivered to listeners; next no sooner than 7 + // throttle.advance(1); + // ensure_equals("4", cat.result, "13"); // "3" delivered + // // 6: post(): deferred + // throttle.advance(2); + // throttle.post("6"); + // ensure_equals("6", cat.result, "13"); // "6" not yet delivered + // // 7: no post() call, but event delivered; next no sooner than 10 + // throttle.advance(1); + // ensure_equals("7", cat.result, "136"); // "6" delivered + // // 12: post(): immediately passed to listeners, next no sooner than 15 + // throttle.advance(5); + // throttle.post(";12"); + // ensure_equals("12", cat.result, "136;12"); // "12" delivered + // // 17: post(): immediately passed to listeners, next no sooner than 20 + // throttle.advance(5); + // throttle.post(";17"); + // ensure_equals("17", cat.result, "136;12;17"); // "17" delivered + // } + } + + TUT_CASE("lleventfilter_test::filter_object_test_6") + { + DOCTEST_FAIL("TODO: convert lleventfilter_test.cpp::filter_object::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void filter_object::test<6>() + // { + // set_test_name("LLEventMailDrop"); + // tut::test(); + // } + } + + TUT_CASE("lleventfilter_test::filter_object_test_7") + { + DOCTEST_FAIL("TODO: convert lleventfilter_test.cpp::filter_object::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void filter_object::test<7>() + // { + // set_test_name("LLEventLogProxyFor"); + // tut::test< LLEventLogProxyFor >(); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llexception_test_doctest.cpp b/indra/llcommon/tests_doctest/llexception_test_doctest.cpp new file mode 100644 index 00000000000..47d3e0a9a4c --- /dev/null +++ b/indra/llcommon/tests_doctest/llexception_test_doctest.cpp @@ -0,0 +1,100 @@ +/** + * @file llexception_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL exception + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llexception_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "llexception.h" +#include +#include + +TUT_SUITE("llcommon") +{ + TUT_CASE("llexception_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert llexception_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // set_test_name("throwing exceptions"); + + // // For each kind of exception, try both kinds of throw against all + // // three catch sequences + // std::size_t margin = 72; + // std::cout << center("FromStd", '=', margin) << std::endl; + // catch_both_several("FromStd"); + + // std::cout << center("FromBoth", '=', margin) << std::endl; + // catch_both_several("FromBoth"); + + // std::cout << center("FromBoost", '=', margin) << std::endl; + // // can't throw with BOOST_THROW_EXCEPTION(), just use catch_several() + // catch_several(plain_throw, "plain_throw"); + + // std::cout << center("FromNeither", '=', margin) << std::endl; + // // can't throw this with BOOST_THROW_EXCEPTION() either + // catch_several(plain_throw, "plain_throw"); + + // std::cout << center("const char*", '=', margin) << std::endl; + // // We don't expect BOOST_THROW_EXCEPTION() to throw anything so daft + // // as a const char* or an int, so don't bother with + // // catch_both_several() -- just catch_several(). + // catch_several(throw_char_ptr, "throw_char_ptr"); + + // std::cout << center("int", '=', margin) << std::endl; + // catch_several(throw_int, "throw_int"); + // } + } + + TUT_CASE("llexception_test::object_test_2") + { + DOCTEST_FAIL("TODO: convert llexception_test.cpp::object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<2>() + // { + // set_test_name("reporting exceptions"); + + // try + // { + // LLTHROW(LLException("badness")); + // } + // catch (...) + // { + // LOG_UNHANDLED_EXCEPTION("llexception test<2>()"); + // } + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llframetimer_test_doctest.cpp b/indra/llcommon/tests_doctest/llframetimer_test_doctest.cpp new file mode 100644 index 00000000000..645dd7093f6 --- /dev/null +++ b/indra/llcommon/tests_doctest/llframetimer_test_doctest.cpp @@ -0,0 +1,135 @@ +/** + * @file llframetimer_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL frametimer + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llframetimer_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "../llframetimer.h" +#include "../llsd.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("llframetimer_test::frametimer_object_t_test_1") + { + DOCTEST_FAIL("TODO: convert llframetimer_test.cpp::frametimer_object_t::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void frametimer_object_t::test<1>() + // { + // F64 seconds_since_epoch = LLFrameTimer::getTotalSeconds(); + // LLFrameTimer timer; + // timer.setExpiryAt(seconds_since_epoch); + // F64 expires_at = timer.expiresAt(); + // ensure_distance( + // "set expiry matches get expiry", + // expires_at, + // seconds_since_epoch, + // 0.001); + // } + } + + TUT_CASE("llframetimer_test::frametimer_object_t_test_2") + { + DOCTEST_FAIL("TODO: convert llframetimer_test.cpp::frametimer_object_t::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void frametimer_object_t::test<2>() + // { + // F64 seconds_since_epoch = LLFrameTimer::getTotalSeconds(); + // seconds_since_epoch += 10.0; + // LLFrameTimer timer; + // timer.setExpiryAt(seconds_since_epoch); + // F64 expires_at = timer.expiresAt(); + // ensure_distance( + // "set expiry matches get expiry 1", + // expires_at, + // seconds_since_epoch, + // 0.001); + // seconds_since_epoch += 10.0; + // timer.setExpiryAt(seconds_since_epoch); + // expires_at = timer.expiresAt(); + // ensure_distance( + // "set expiry matches get expiry 2", + // expires_at, + // seconds_since_epoch, + // 0.001); + // } + } + + TUT_CASE("llframetimer_test::frametimer_object_t_test_3") + { + DOCTEST_FAIL("TODO: convert llframetimer_test.cpp::frametimer_object_t::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void frametimer_object_t::test<3>() + // { + // clock_t t1 = clock(); + // ms_sleep(200); + // clock_t t2 = clock(); + // clock_t elapsed = t2 - t1 + 1; + // std::cout << "Note: using clock(), ms_sleep() actually took " << (long)elapsed << "ms" << std::endl; + + // F64 seconds_since_epoch = LLFrameTimer::getTotalSeconds(); + // seconds_since_epoch += 2.0; + // LLFrameTimer timer; + // timer.setExpiryAt(seconds_since_epoch); + // /* + // * Note that the ms_sleep(200) below is only guaranteed to return + // * in 200ms _or_more_, so it should be true that by the 10th + // * iteration we've gotten to the 2 seconds requested above + // * and the timer should expire, but it can expire in fewer iterations + // * if one or more of the ms_sleep calls takes longer. + // * (as it did when we moved to Mac OS X 10.10) + // */ + // int iterations_until_expiration = 0; + // while ( !timer.hasExpired() ) + // { + // ms_sleep(200); + // LLFrameTimer::updateFrameTime(); + // iterations_until_expiration++; + // } + // ensure("timer took too long to expire", iterations_until_expiration <= 10); + // } + } + + TUT_CASE("llframetimer_test::frametimer_object_t_test_4") + { + DOCTEST_FAIL("TODO: convert llframetimer_test.cpp::frametimer_object_t::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void frametimer_object_t::test<4>() + // { + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llheteromap_test_doctest.cpp b/indra/llcommon/tests_doctest/llheteromap_test_doctest.cpp new file mode 100644 index 00000000000..49638a71e99 --- /dev/null +++ b/indra/llcommon/tests_doctest/llheteromap_test_doctest.cpp @@ -0,0 +1,91 @@ +/** + * @file llheteromap_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL heteromap + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llheteromap_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "llheteromap.h" +#include + +TUT_SUITE("llcommon") +{ + TUT_CASE("llheteromap_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert llheteromap_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // set_test_name("create, get, delete"); + + // { + // LLHeteroMap map; + + // { + // // create each instance + // Chalk& chalk = map.obtain(); + // chalk.name = "Chalk"; + + // Cheese& cheese = map.obtain(); + // cheese.name = "Cheese"; + + // Chowdah& chowdah = map.obtain(); + // chowdah.name = "Chowdah"; + // } // refs go out of scope + + // { + // // verify each instance + // Chalk& chalk = map.obtain(); + // ensure_equals(chalk.name, "Chalk"); + + // Cheese& cheese = map.obtain(); + // ensure_equals(cheese.name, "Cheese"); + + // Chowdah& chowdah = map.obtain(); + // ensure_equals(chowdah.name, "Chowdah"); + // } + // } // destroy map + + // // Chalk, Cheese and Chowdah should have been created in specific order + // ensure_equals(clog, "aeo"); + + // // We don't care what order they're destroyed in, as long as each is + // // appropriately destroyed. + // std::set dtorset; + // for (const char* cp = "aeo"; *cp; ++cp) + // dtorset.insert(std::string(1, *cp)); + // ensure_equals(dlog, dtorset); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llinstancetracker_test_doctest.cpp b/indra/llcommon/tests_doctest/llinstancetracker_test_doctest.cpp new file mode 100644 index 00000000000..171d6d298ff --- /dev/null +++ b/indra/llcommon/tests_doctest/llinstancetracker_test_doctest.cpp @@ -0,0 +1,274 @@ +/** + * @file llinstancetracker_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL instancetracker + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llinstancetracker_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "llinstancetracker.h" +#include +#include +#include +#include + +TUT_SUITE("llcommon") +{ + TUT_CASE("llinstancetracker_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert llinstancetracker_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // ensure_equals(Keyed::instanceCount(), 0); + // { + // Keyed one("one"); + // ensure_equals(Keyed::instanceCount(), 1); + // auto found = Keyed::getInstance("one"); + // ensure("couldn't find stack Keyed", bool(found)); + // ensure_equals("found wrong Keyed instance", found.get(), &one); + // { + // std::unique_ptr two(new Keyed("two")); + // ensure_equals(Keyed::instanceCount(), 2); + // auto found = Keyed::getInstance("two"); + // ensure("couldn't find heap Keyed", bool(found)); + // ensure_equals("found wrong Keyed instance", found.get(), two.get()); + // } + // ensure_equals(Keyed::instanceCount(), 1); + // } + // auto found = Keyed::getInstance("one"); + // ensure("Keyed key lives too long", ! found); + // ensure_equals(Keyed::instanceCount(), 0); + // } + } + + TUT_CASE("llinstancetracker_test::object_test_2") + { + DOCTEST_FAIL("TODO: convert llinstancetracker_test.cpp::object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<2>() + // { + // ensure_equals(Unkeyed::instanceCount(), 0); + // std::weak_ptr dangling; + // { + // Unkeyed one; + // ensure_equals(Unkeyed::instanceCount(), 1); + // std::weak_ptr found = one.getWeak(); + // ensure(! found.expired()); + // { + // std::unique_ptr two(new Unkeyed); + // ensure_equals(Unkeyed::instanceCount(), 2); + // } + // ensure_equals(Unkeyed::instanceCount(), 1); + // // store a weak pointer to a temp Unkeyed instance + // dangling = found; + // } // make that instance vanish + // // check the now-invalid pointer to the destroyed instance + // ensure("weak_ptr failed to track destruction", dangling.expired()); + // ensure_equals(Unkeyed::instanceCount(), 0); + // } + } + + TUT_CASE("llinstancetracker_test::object_test_3") + { + DOCTEST_FAIL("TODO: convert llinstancetracker_test.cpp::object::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<3>() + // { + // Keyed one("one"), two("two"), three("three"); + // // We don't want to rely on the underlying container delivering keys + // // in any particular order. That allows us the flexibility to + // // reimplement LLInstanceTracker using, say, a hash map instead of a + // // std::map. We DO insist that every key appear exactly once. + // typedef std::vector StringVector; + // auto snap = Keyed::key_snapshot(); + // StringVector keys(snap.begin(), snap.end()); + // std::sort(keys.begin(), keys.end()); + // StringVector::const_iterator ki(keys.begin()); + // ensure_equals(*ki++, "one"); + // ensure_equals(*ki++, "three"); + // ensure_equals(*ki++, "two"); + // // Use ensure() here because ensure_equals would want to display + // // mismatched values, and frankly that wouldn't help much. + // ensure("didn't reach end", ki == keys.end()); + + // // Use a somewhat different approach to order independence with + // // instance_snapshot(): explicitly capture the instances we know in a + // // set, and delete them as we iterate through. + // typedef std::set InstanceSet; + // InstanceSet instances; + // instances.insert(&one); + // instances.insert(&two); + // instances.insert(&three); + // for (auto& ref : Keyed::instance_snapshot()) + // { + // ensure_equals("spurious instance", instances.erase(&ref), 1); + // } + // ensure_equals("unreported instance", instances.size(), 0); + // } + } + + TUT_CASE("llinstancetracker_test::object_test_4") + { + DOCTEST_FAIL("TODO: convert llinstancetracker_test.cpp::object::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<4>() + // { + // Unkeyed one, two, three; + // typedef std::set KeySet; + + // KeySet instances; + // instances.insert(&one); + // instances.insert(&two); + // instances.insert(&three); + + // for (auto& ref : Unkeyed::instance_snapshot()) + // { + // ensure_equals("spurious instance", instances.erase(&ref), 1); + // } + + // ensure_equals("unreported instance", instances.size(), 0); + // } + } + + TUT_CASE("llinstancetracker_test::object_test_5") + { + DOCTEST_FAIL("TODO: convert llinstancetracker_test.cpp::object::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<5>() + // { + // std::string desc("delete Keyed with outstanding instance_snapshot"); + // set_test_name(desc); + // Keyed* keyed = new Keyed(desc); + // // capture a snapshot but do not yet traverse it + // auto snapshot = Keyed::instance_snapshot(); + // // delete the one instance + // delete keyed; + // // traversing the snapshot should reflect the deletion + // // avoid ensure_equals() because it requires the ability to stream the + // // two values to std::ostream + // ensure(snapshot.begin() == snapshot.end()); + // } + } + + TUT_CASE("llinstancetracker_test::object_test_6") + { + DOCTEST_FAIL("TODO: convert llinstancetracker_test.cpp::object::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<6>() + // { + // std::string desc("delete Keyed with outstanding key_snapshot"); + // set_test_name(desc); + // Keyed* keyed = new Keyed(desc); + // // capture a snapshot but do not yet traverse it + // auto snapshot = Keyed::key_snapshot(); + // // delete the one instance + // delete keyed; + // // traversing the snapshot should reflect the deletion + // // avoid ensure_equals() because it requires the ability to stream the + // // two values to std::ostream + // ensure(snapshot.begin() == snapshot.end()); + // } + } + + TUT_CASE("llinstancetracker_test::object_test_7") + { + DOCTEST_FAIL("TODO: convert llinstancetracker_test.cpp::object::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<7>() + // { + // set_test_name("delete Unkeyed with outstanding instance_snapshot"); + // std::string what; + // Unkeyed* unkeyed = new Unkeyed; + // // capture a snapshot but do not yet traverse it + // auto snapshot = Unkeyed::instance_snapshot(); + // // delete the one instance + // delete unkeyed; + // // traversing the snapshot should reflect the deletion + // // avoid ensure_equals() because it requires the ability to stream the + // // two values to std::ostream + // ensure(snapshot.begin() == snapshot.end()); + // } + } + + TUT_CASE("llinstancetracker_test::object_test_8") + { + DOCTEST_FAIL("TODO: convert llinstancetracker_test.cpp::object::test<8> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<8>() + // { + // set_test_name("exception in subclass ctor"); + // typedef std::set InstanceSet; + // InstanceSet existing; + // // We can't use the iterator-range InstanceSet constructor because + // // beginInstances() returns an iterator that dereferences to an + // // Unkeyed&, not an Unkeyed*. + // for (auto& ref : Unkeyed::instance_snapshot()) + // { + // existing.insert(&ref); + // } + // try + // { + // // We don't expect the assignment to take place because we expect + // // Unkeyed to respond to the non-empty string param by throwing. + // // We know the LLInstanceTracker base-class constructor will have + // // run before Unkeyed's constructor, therefore the new instance + // // will have added itself to the underlying set. The whole + // // question is, when Unkeyed's constructor throws, will + // // LLInstanceTracker's destructor remove it from the set? I + // // realize we're testing the C++ implementation more than + // // Unkeyed's implementation, but this seems an important point to + // // nail down. + // new Unkeyed("throw"); + // } + // catch (const Badness&) + // { + // } + // // Ensure that every member of the new, updated set of Unkeyed + // // instances was also present in the original set. If that's not true, + // // it's because our new Unkeyed ended up in the updated set despite + // // its constructor exception. + // for (auto& ref : Unkeyed::instance_snapshot()) + // { + // ensure("failed to remove instance", existing.find(&ref) != existing.end()); + // } + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/lllazy_test_doctest.cpp b/indra/llcommon/tests_doctest/lllazy_test_doctest.cpp new file mode 100644 index 00000000000..d015ab79776 --- /dev/null +++ b/indra/llcommon/tests_doctest/lllazy_test_doctest.cpp @@ -0,0 +1,119 @@ +/** + * @file lllazy_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL lazy + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from lllazy_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +// #include "lllazy.h" // not available on Windows +#include +#include +#include +#include "../test/catch_and_store_what_in.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("lllazy_test::lllazy_object_test_1") + { + DOCTEST_FAIL("TODO: convert lllazy_test.cpp::lllazy_object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void lllazy_object::test<1>() + // { + // // Instantiate an official one, just because we can + // NeedsTesting nt; + // // and a test one + // TestNeedsTesting tnt; + // // std::cout << nt.describe() << '\n'; + // ensure_equals(nt.describe(), "NeedsTesting(YuckyFoo, YuckyBar(RealYuckyBar))"); + // // std::cout << tnt.describe() << '\n'; + // ensure_equals(tnt.describe(), + // "TestNeedsTesting(NeedsTesting(TestFoo, TestBar(YuckyBar(TestYuckyBar))))"); + // } + } + + TUT_CASE("lllazy_test::lllazy_object_test_2") + { + DOCTEST_FAIL("TODO: convert lllazy_test.cpp::lllazy_object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void lllazy_object::test<2>() + // { + // TestNeedsTesting tnt; + // std::string threw = catch_what([&tnt](){ + // tnt.toolate(); + // }); + // ensure_contains("InstanceChange exception", threw, "replace LLLazy instance"); + // } + } + + TUT_CASE("lllazy_test::lllazy_object_test_3") + { + DOCTEST_FAIL("TODO: convert lllazy_test.cpp::lllazy_object::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void lllazy_object::test<3>() + // { + // { + // LazyMember lm; + // // operator*() on-demand instantiation + // ensure_equals(lm.getYuckyFoo().whoami(), "YuckyFoo"); + // } + // { + // LazyMember lm; + // // operator->() on-demand instantiation + // ensure_equals(lm.whoisit(), "YuckyFoo"); + // } + // } + } + + TUT_CASE("lllazy_test::lllazy_object_test_4") + { + DOCTEST_FAIL("TODO: convert lllazy_test.cpp::lllazy_object::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void lllazy_object::test<4>() + // { + // { + // // factory setter + // TestLazyMember tlm; + // ensure_equals(tlm.whoisit(), "TestFoo"); + // } + // { + // // instance setter + // TestLazyMember tlm(new TestFoo()); + // ensure_equals(tlm.whoisit(), "TestFoo"); + // } + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llleap_test_doctest.cpp b/indra/llcommon/tests_doctest/llleap_test_doctest.cpp new file mode 100644 index 00000000000..241e861b8d7 --- /dev/null +++ b/indra/llcommon/tests_doctest/llleap_test_doctest.cpp @@ -0,0 +1,279 @@ +/** + * @file llleap_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL leap + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llleap_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "llleap.h" +#include +#include "../test/namedtempfile.h" +#include "../test/catch_and_store_what_in.h" +#include "llevents.h" +#include "llprocess.h" +#include "llstring.h" +#include "stringize.h" +// #include "StringVec.h" // not available on Windows + +TUT_SUITE("llcommon") +{ + TUT_CASE("llleap_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert llleap_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // set_test_name("multiple LLLeap instances"); + // NamedExtTempFile script("py", + // "import time\n" + // "time.sleep(1)\n"); + // LLLeapVector instances; + // instances.push_back(LLLeap::create(get_test_name(), + // StringVec{PYTHON, script.getName()})->getWeak()); + // instances.push_back(LLLeap::create(get_test_name(), + // StringVec{PYTHON, script.getName()})->getWeak()); + // // In this case we're simply establishing that two LLLeap instances + // // can coexist without throwing exceptions or bombing in any other + // // way. Wait for them to terminate. + // waitfor(instances); + // } + } + + TUT_CASE("llleap_test::object_test_2") + { + DOCTEST_FAIL("TODO: convert llleap_test.cpp::object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<2>() + // { + // set_test_name("stderr to log"); + // NamedExtTempFile script("py", + // "import sys\n" + // "sys.stderr.write('''Hello from Python!\n" + // "note partial line''')\n"); + // StringVec vcommand{ PYTHON, script.getName() }; + // CaptureLog log(LLError::LEVEL_INFO); + // waitfor(LLLeap::create(get_test_name(), vcommand)); + // log.messageWith("Hello from Python!"); + // log.messageWith("note partial line"); + // } + } + + TUT_CASE("llleap_test::object_test_3") + { + DOCTEST_FAIL("TODO: convert llleap_test.cpp::object::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<3>() + // { + // set_test_name("bad stdout protocol"); + // NamedExtTempFile script("py", + // "print('Hello from Python!')\n"); + // CaptureLog log(LLError::LEVEL_WARN); + // waitfor(LLLeap::create(get_test_name(), + // StringVec{PYTHON, script.getName()})); + // ensure_contains("error log line", + // log.messageWith("invalid protocol"), "Hello from Python!"); + // } + } + + TUT_CASE("llleap_test::object_test_4") + { + DOCTEST_FAIL("TODO: convert llleap_test.cpp::object::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<4>() + // { + // set_test_name("leftover stdout"); + // NamedExtTempFile script("py", + // "import sys\n" + // // note lack of newline + // "sys.stdout.write('Hello from Python!')\n"); + // CaptureLog log(LLError::LEVEL_WARN); + // waitfor(LLLeap::create(get_test_name(), + // StringVec{PYTHON, script.getName()})); + // ensure_contains("error log line", + // log.messageWith("Discarding"), "Hello from Python!"); + // } + } + + TUT_CASE("llleap_test::object_test_5") + { + DOCTEST_FAIL("TODO: convert llleap_test.cpp::object::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<5>() + // { + // set_test_name("bad stdout len prefix"); + // NamedExtTempFile script("py", + // "import sys\n" + // "sys.stdout.write('5a2:something')\n"); + // CaptureLog log(LLError::LEVEL_WARN); + // waitfor(LLLeap::create(get_test_name(), + // StringVec{PYTHON, script.getName()})); + // ensure_contains("error log line", + // log.messageWith("invalid protocol"), "5a2:"); + // } + } + + TUT_CASE("llleap_test::object_test_6") + { + DOCTEST_FAIL("TODO: convert llleap_test.cpp::object::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<6>() + // { + // set_test_name("empty plugin vector"); + // std::string threw = catch_what([](){ + // LLLeap::create("empty", StringVec()); + // }); + // ensure_contains("LLLeap::Error", threw, "no plugin"); + // // try the suppress-exception variant + // ensure("bad launch returned non-NULL", ! LLLeap::create("empty", StringVec(), false)); + // } + } + + TUT_CASE("llleap_test::object_test_7") + { + DOCTEST_FAIL("TODO: convert llleap_test.cpp::object::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<7>() + // { + // set_test_name("bad launch"); + // // Synthesize bogus executable name + // std::string BADPYTHON(PYTHON.substr(0, PYTHON.length()-1) + "x"); + // CaptureLog log; + // std::string threw = catch_what([&BADPYTHON](){ + // LLLeap::create("bad exe", BADPYTHON); + // }); + // ensure_contains("LLLeap::create() didn't throw", threw, "failed"); + // log.messageWith("failed"); + // log.messageWith(BADPYTHON); + // // try the suppress-exception variant + // ensure("bad launch returned non-NULL", ! LLLeap::create("bad exe", BADPYTHON, false)); + // } + } + + TUT_CASE("llleap_test::object_test_8") + { + DOCTEST_FAIL("TODO: convert llleap_test.cpp::object::test<8> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<8>() + // { + // set_test_name("round trip"); + // AckAPI api; + // Result result; + // NamedExtTempFile script("py", + // [&](std::ostream& out){ out << + // "from " << reader_module << " import *\n" + // // make a request on our little API + // "request(pump='" << api.getName() << "', data={})\n" + // // wait for its response + // "resp = get()\n" + // "result = '' if resp == dict(pump=replypump(), data='ack')\\\n" + // " else 'bad: ' + str(resp)\n" + // "send(pump='" << result.getName() << "', data=result)\n";}); + // waitfor(LLLeap::create(get_test_name(), + // StringVec{PYTHON, script.getName()})); + // result.ensure(); + // } + } + + TUT_CASE("llleap_test::object_test_9") + { + DOCTEST_FAIL("TODO: convert llleap_test.cpp::object::test<9> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<9>() + // { + // set_test_name("many small messages"); + // // It's not clear to me whether there's value in iterating many times + // // over a send/receive loop -- I don't think that will exercise any + // // interesting corner cases. This test first sends a large number of + // // messages, then receives all the responses. The intent is to ensure + // // that some of that data stream crosses buffer boundaries, loop + // // iterations etc. in OS pipes and the LLLeap/LLProcess implementation. + // ReqIDAPI api; + // Result result; + // NamedExtTempFile script("py", + // [&](std::ostream& out){ out << + // "import sys\n" + // "from " << reader_module << " import *\n" + // // Note that since reader imports llsd, this + // // 'import *' gets us llsd too. + // "sample = llsd.format_notation(dict(pump='" << + // api.getName() << "', data=dict(reqid=999999, reply=replypump())))\n" + // // The whole packet has length prefix too: "len:data" + // "samplen = len(str(len(sample))) + 1 + len(sample)\n" + // // guess how many messages it will take to + // // accumulate BUFFERED_LENGTH + // "count = int(" << BUFFERED_LENGTH << "/samplen)\n" + // "print('Sending %s requests' % count, file=sys.stderr)\n" + // "for i in range(count):\n" + // " request('" << api.getName() << "', dict(reqid=i))\n" + // // The assumption in this specific test that + // // replies will arrive in the same order as + // // requests is ONLY valid because the API we're + // // invoking sends replies instantly. If the API + // // had to wait for some external event before + // // sending its reply, replies could arrive in + // // arbitrary order, and we'd have to tick them + // // off from a set. + // "result = ''\n" + // "for i in range(count):\n" + // " resp = get()\n" + // " if resp['data']['reqid'] != i:\n" + // " result = 'expected reqid=%s in %s' % (i, resp)\n" + // " break\n" + // "send(pump='" << result.getName() << "', data=result)\n";}); + // waitfor(LLLeap::create(get_test_name(), StringVec{PYTHON, script.getName()}), + // 300); // needs more realtime than most tests + // result.ensure(); + // } + } + + TUT_CASE("llleap_test::object_test_10") + { + DOCTEST_FAIL("TODO: convert llleap_test.cpp::object::test<10> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<10>() + // { + // set_test_name("very large message"); + // test_or_split(PYTHON, reader_module, get_test_name(), BUFFERED_LENGTH); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llmainthreadtask_test_doctest.cpp b/indra/llcommon/tests_doctest/llmainthreadtask_test_doctest.cpp new file mode 100644 index 00000000000..9c6ecc515e3 --- /dev/null +++ b/indra/llcommon/tests_doctest/llmainthreadtask_test_doctest.cpp @@ -0,0 +1,138 @@ +/** + * @file llmainthreadtask_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL mainthreadtask + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llmainthreadtask_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "llmainthreadtask.h" +#include +#include "../test/sync.h" +#include "lleventtimer.h" +#include "lockstatic.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("llmainthreadtask_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert llmainthreadtask_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // set_test_name("inline"); + // bool ran = false; + // bool result = LLMainThreadTask::dispatch( + // [&ran]()->bool{ + // ran = true; + // return true; + // }); + // ensure("didn't run lambda", ran); + // ensure("didn't return result", result); + // } + } + + TUT_CASE("llmainthreadtask_test::object_test_2") + { + DOCTEST_FAIL("TODO: convert llmainthreadtask_test.cpp::object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<2>() + // { + // set_test_name("cross-thread"); + // skip("This test is prone to build-time hangs"); + // std::atomic_bool result(false); + // // wrapping our thread lambda in a packaged_task will catch any + // // exceptions it might throw and deliver them via future + // std::packaged_task thread_work( + // [this, &result](){ + // // unblock test<2>()'s yield_until(1) + // mSync.set(1); + // // dispatch work to main thread -- should block here + // bool on_main( + // LLMainThreadTask::dispatch( + // []()->bool{ + // // have to lock static mutex to set static data + // LockStatic()->ran = true; + // // indicate whether task was run on the main thread + // return on_main_thread(); + // })); + // // wait for test<2>() to unblock us again + // mSync.yield_until(3); + // result = on_main; + // }); + // auto thread_result = thread_work.get_future(); + // std::thread thread; + // try + // { + // // run thread_work + // thread = std::thread(std::move(thread_work)); + // // wait for thread to set(1) + // mSync.yield_until(1); + // // try to acquire the lock, should block because thread has it + // LockStatic lk; + // // wake up when dispatch() unlocks the static mutex + // ensure("shouldn't have run yet", !lk->ran); + // ensure("shouldn't have returned yet", !result); + // // unlock so the task can acquire the lock + // lk.unlock(); + // // run the task -- should unblock thread, which will immediately block + // // on mSync + // LLEventTimer::updateClass(); + // // 'lk', having unlocked, can no longer be used to access; relock with + // // a new LockStatic instance + // ensure("should now have run", LockStatic()->ran); + // ensure("returned too early", !result); + // // okay, let thread perform the assignment + // mSync.set(3); + // } + // catch (...) + // { + // // A test failure exception anywhere in the try block can cause + // // the test program to terminate without explanation when + // // ~thread() finds that 'thread' is still joinable. We could + // // either join() or detach() it -- but since it might be blocked + // // waiting for something from the main thread that now can never + // // happen, it's safer to detach it. + // thread.detach(); + // throw; + // } + // // 'thread' should be all done now + // thread.join(); + // // deliver any exception thrown by thread_work + // thread_result.get(); + // ensure("ran changed", LockStatic()->ran); + // ensure("didn't run on main thread", result); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llmemtype_test_doctest.cpp b/indra/llcommon/tests_doctest/llmemtype_test_doctest.cpp new file mode 100644 index 00000000000..12e5cd7da3e --- /dev/null +++ b/indra/llcommon/tests_doctest/llmemtype_test_doctest.cpp @@ -0,0 +1,110 @@ +/** + * @file llmemtype_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL memtype + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llmemtype_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +// #include "../llmemtype.h" // not available on Windows +// #include "../llallocator.h" // not available on Windows +#include + +TUT_SUITE("llcommon") +{ + TUT_CASE("llmemtype_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert llmemtype_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // ensure("Simplest test ever", true); + // } + } + + TUT_CASE("llmemtype_test::object_test_2") + { + DOCTEST_FAIL("TODO: convert llmemtype_test.cpp::object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<2>() + // { + // { + // LLMemType m1(LLMemType::MTYPE_INIT); + // } + // ensure("Test that you can construct and destruct the mem type"); + // } + } + + TUT_CASE("llmemtype_test::object_test_3") + { + DOCTEST_FAIL("TODO: convert llmemtype_test.cpp::object::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<3>() + // { + // { + // ensure("Test that creation and destruction properly inc/dec the stack"); + // ensure_equals(memTypeStack.size(), 0); + // { + // LLMemType m1(LLMemType::MTYPE_INIT); + // ensure_equals(memTypeStack.size(), 1); + // LLMemType m2(LLMemType::MTYPE_STARTUP); + // ensure_equals(memTypeStack.size(), 2); + // } + // ensure_equals(memTypeStack.size(), 0); + // } + // } + } + + TUT_CASE("llmemtype_test::object_test_4") + { + DOCTEST_FAIL("TODO: convert llmemtype_test.cpp::object::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<4>() + // { + // // catch the begining and end + // std::string test_name = LLMemType::getNameFromID(LLMemType::MTYPE_INIT.mID); + // ensure_equals("Init name", test_name, "Init"); + + // std::string test_name2 = LLMemType::getNameFromID(LLMemType::MTYPE_VOLUME.mID); + // ensure_equals("Volume name", test_name2, "Volume"); + + // std::string test_name3 = LLMemType::getNameFromID(LLMemType::MTYPE_OTHER.mID); + // ensure_equals("Other name", test_name3, "Other"); + + // std::string test_name4 = LLMemType::getNameFromID(-1); + // ensure_equals("Invalid name", test_name4, "INVALID"); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llpounceable_test_doctest.cpp b/indra/llcommon/tests_doctest/llpounceable_test_doctest.cpp new file mode 100644 index 00000000000..0aacc9731d7 --- /dev/null +++ b/indra/llcommon/tests_doctest/llpounceable_test_doctest.cpp @@ -0,0 +1,227 @@ +/** + * @file llpounceable_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL pounceable + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llpounceable_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "llpounceable.h" +#include + +TUT_SUITE("llcommon") +{ + TUT_CASE("llpounceable_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert llpounceable_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // set_test_name("LLPounceableStatic out-of-order test"); + // // LLPounceable::callWhenReady() must work even + // // before LLPounceable's constructor runs. That's the whole point of + // // implementing it with an LLSingleton queue. This models (say) + // // LLPounceableStatic. + // ensure("static_check should still be null", ! static_check); + // Data myData("test<1>"); + // gForward = &myData; // should run setter + // ensure_equals("static_check should be &myData", static_check, &myData); + // } + } + + TUT_CASE("llpounceable_test::object_test_2") + { + DOCTEST_FAIL("TODO: convert llpounceable_test.cpp::object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<2>() + // { + // set_test_name("LLPounceableQueue different queues"); + // // We expect that LLPounceable should have + // // different queues because that specialization stores the queue + // // directly in the LLPounceable instance. + // Data *aptr = 0, *bptr = 0; + // LLPounceable a, b; + // a.callWhenReady(boost::bind(setter, &aptr, _1)); + // b.callWhenReady(boost::bind(setter, &bptr, _1)); + // ensure("aptr should be null", ! aptr); + // ensure("bptr should be null", ! bptr); + // Data adata("a"), bdata("b"); + // a = &adata; + // ensure_equals("aptr should be &adata", aptr, &adata); + // // but we haven't yet set b + // ensure("bptr should still be null", !bptr); + // b = &bdata; + // ensure_equals("bptr should be &bdata", bptr, &bdata); + // } + } + + TUT_CASE("llpounceable_test::object_test_3") + { + DOCTEST_FAIL("TODO: convert llpounceable_test.cpp::object::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<3>() + // { + // set_test_name("LLPounceableStatic different queues"); + // // LLPounceable should also have a distinct + // // queue for each instance, but that engages an additional map lookup + // // because there's only one LLSingleton for each T. + // Data *aptr = 0, *bptr = 0; + // LLPounceable a, b; + // a.callWhenReady(boost::bind(setter, &aptr, _1)); + // b.callWhenReady(boost::bind(setter, &bptr, _1)); + // ensure("aptr should be null", ! aptr); + // ensure("bptr should be null", ! bptr); + // Data adata("a"), bdata("b"); + // a = &adata; + // ensure_equals("aptr should be &adata", aptr, &adata); + // // but we haven't yet set b + // ensure("bptr should still be null", !bptr); + // b = &bdata; + // ensure_equals("bptr should be &bdata", bptr, &bdata); + // } + } + + TUT_CASE("llpounceable_test::object_test_4") + { + DOCTEST_FAIL("TODO: convert llpounceable_test.cpp::object::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<4>() + // { + // set_test_name("LLPounceable looks like T"); + // // We want LLPounceable to be drop-in replaceable for a plain + // // T for read constructs. In particular, it should behave like a dumb + // // pointer -- and with zero abstraction cost for such usage. + // Data* aptr = 0; + // Data a("a"); + // // should be able to initialize a pounceable (when its constructor + // // runs) + // LLPounceable pounceable(&a); + // // should be able to pass LLPounceable to function accepting T + // setter(&aptr, pounceable); + // ensure_equals("aptr should be &a", aptr, &a); + // // should be able to dereference with * + // ensure_equals("deref with *", (*pounceable).mData, "a"); + // // should be able to dereference with -> + // ensure_equals("deref with ->", pounceable->mData, "a"); + // // bool operations + // ensure("test with operator bool()", pounceable); + // ensure("test with operator !()", ! (! pounceable)); + // } + } + + TUT_CASE("llpounceable_test::object_test_5") + { + DOCTEST_FAIL("TODO: convert llpounceable_test.cpp::object::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<5>() + // { + // set_test_name("Multiple callWhenReady() queue items"); + // Data *p1 = 0, *p2 = 0, *p3 = 0; + // Data a("a"); + // LLPounceable pounceable; + // // queue up a couple setter() calls for later + // pounceable.callWhenReady(boost::bind(setter, &p1, _1)); + // pounceable.callWhenReady(boost::bind(setter, &p2, _1)); + // // should still be pending + // ensure("p1 should be null", !p1); + // ensure("p2 should be null", !p2); + // ensure("p3 should be null", !p3); + // pounceable = 0; + // // assigning a new empty value shouldn't flush the queue + // ensure("p1 should still be null", !p1); + // ensure("p2 should still be null", !p2); + // ensure("p3 should still be null", !p3); + // // using whichever syntax + // pounceable.reset(0); + // // try to make ensure messages distinct... tough to pin down which + // // ensure() failed if multiple ensure() calls in the same test have + // // the same message! + // ensure("p1 should again be null", !p1); + // ensure("p2 should again be null", !p2); + // ensure("p3 should again be null", !p3); + // pounceable.reset(&a); // should flush queue + // ensure_equals("p1 should be &a", p1, &a); + // ensure_equals("p2 should be &a", p2, &a); + // ensure("p3 still not set", !p3); + // // immediate call + // pounceable.callWhenReady(boost::bind(setter, &p3, _1)); + // ensure_equals("p3 should be &a", p3, &a); + // } + } + + TUT_CASE("llpounceable_test::object_test_6") + { + DOCTEST_FAIL("TODO: convert llpounceable_test.cpp::object::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<6>() + // { + // set_test_name("queue order"); + // std::string data; + // LLPounceable pounceable; + // pounceable.callWhenReady(boost::bind(append, _1, "a")); + // pounceable.callWhenReady(boost::bind(append, _1, "b")); + // pounceable.callWhenReady(boost::bind(append, _1, "c")); + // pounceable = &data; + // ensure_equals("callWhenReady() must preserve chronological order", + // data, "abc"); + + // std::string data2; + // pounceable = NULL; + // pounceable.callWhenReady(boost::bind(append, _1, "d")); + // pounceable.callWhenReady(boost::bind(append, _1, "e")); + // pounceable.callWhenReady(boost::bind(append, _1, "f")); + // pounceable = &data2; + // ensure_equals("LLPounceable must reset queue when fired", + // data2, "def"); + // } + } + + TUT_CASE("llpounceable_test::object_test_7") + { + DOCTEST_FAIL("TODO: convert llpounceable_test.cpp::object::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<7>() + // { + // set_test_name("compile-fail test, uncomment to check"); + // // The following declaration should fail: only LLPounceableQueue and + // // LLPounceableStatic should work as tags. + // // LLPounceable pounceable; + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llprocess_test_doctest.cpp b/indra/llcommon/tests_doctest/llprocess_test_doctest.cpp new file mode 100644 index 00000000000..4022356877b --- /dev/null +++ b/indra/llcommon/tests_doctest/llprocess_test_doctest.cpp @@ -0,0 +1,1092 @@ +/** + * @file llprocess_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL process + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llprocess_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "llprocess.h" +#include +#include +#include +#include "llapr.h" +#include "apr_thread_proc.h" +#include +#include +#include +#include "../test/namedtempfile.h" +#include "../test/catch_and_store_what_in.h" +#include "stringize.h" +#include "llsdutil.h" +#include "llevents.h" +#include "llstring.h" +// #include // not available on Windows + +TUT_SUITE("llcommon") +{ + TUT_CASE("llprocess_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // set_test_name("raw APR nonblocking I/O"); + + // // Create a script file in a temporary place. + // NamedExtTempFile script("py", + // "from __future__ import print_function" EOL + // "import sys" EOL + // "import time" EOL + // EOL + // "time.sleep(2)" EOL + // "print('stdout after wait',file=sys.stdout)" EOL + // "sys.stdout.flush()" EOL + // "time.sleep(2)" EOL + // "print('stderr after wait',file=sys.stderr)" EOL + // "sys.stderr.flush()" EOL + // ); + + // // Arrange to track the history of our interaction with child: what we + // // fetched, which pipe it came from, how many tries it took before we + // // got it. + // std::vector history; + // history.push_back(Item()); + + // // Run the child process. + // apr_procattr_t *procattr = NULL; + // aprchk(apr_procattr_create(&procattr, pool.getAPRPool())); + // aprchk(apr_procattr_io_set(procattr, APR_CHILD_BLOCK, APR_CHILD_BLOCK, APR_CHILD_BLOCK)); + // aprchk(apr_procattr_cmdtype_set(procattr, APR_PROGRAM_PATH)); + + // std::vector argv; + // apr_proc_t child; + // #if defined(LL_WINDOWS) + // argv.push_back("python"); + // #else + // argv.push_back("python3"); + // #endif + // // Have to have a named copy of this std::string so its c_str() value + // // will persist. + // std::string scriptname(script.getName()); + // argv.push_back(scriptname.c_str()); + // argv.push_back(NULL); + + // aprchk(apr_proc_create(&child, argv[0], + // &argv[0], + // NULL, // if we wanted to pass explicit environment + // procattr, + // pool.getAPRPool())); + + // // We do not want this child process to outlive our APR pool. On + // // destruction of the pool, forcibly kill the process. Tell APR to try + // // SIGTERM and wait 3 seconds. If that didn't work, use SIGKILL. + // apr_pool_note_subprocess(pool.getAPRPool(), &child, APR_KILL_AFTER_TIMEOUT); + + // // arrange to call child_status_callback() + // WaitInfo wi(&child); + // apr_proc_other_child_register(&child, child_status_callback, &wi, child.in, pool.getAPRPool()); + + // // TODO: + // // Stuff child.in until it (would) block to verify EWOULDBLOCK/EAGAIN. + // // Have child script clear it later, then write one more line to prove + // // that it gets through. + + // // Monitor two different output pipes. Because one will be closed + // // before the other, keep them in a list so we can drop whichever of + // // them is closed first. + // typedef std::pair DescFile; + // typedef std::list DescFileList; + // DescFileList outfiles; + // outfiles.push_back(DescFile("out", child.out)); + // outfiles.push_back(DescFile("err", child.err)); + + // while (! outfiles.empty()) + // { + // // This peculiar for loop is designed to let us erase(dfli). With + // // a list, that invalidates only dfli itself -- but even so, we + // // lose the ability to increment it for the next item. So at the + // // top of every loop, while dfli is still valid, increment + // // dflnext. Then before the next iteration, set dfli to dflnext. + // for (DescFileList::iterator + // dfli(outfiles.begin()), dflnext(outfiles.begin()), dflend(outfiles.end()); + // dfli != dflend; dfli = dflnext) + // { + // // Only valid to increment dflnext once we're sure it's not + // // already at dflend. + // ++dflnext; + + // char buf[4096]; + + // apr_status_t rv = apr_file_gets(buf, sizeof(buf), dfli->second); + // if (APR_STATUS_IS_EOF(rv)) + // { + // // std::cout << "(EOF on " << dfli->first << ")\n"; + // // history.back().which = dfli->first; + // // history.back().what = "*eof*"; + // // history.push_back(Item()); + // outfiles.erase(dfli); + // continue; + // } + // if (rv == EWOULDBLOCK || rv == EAGAIN) + // { + // // std::cout << "(waiting; apr_file_gets(" << dfli->first << ") => " << rv << ": " << manager.strerror(rv) << ")\n"; + // ++history.back().tries; + // continue; + // } + // aprchk_("apr_file_gets(buf, sizeof(buf), dfli->second)", rv); + // // Is it even possible to get APR_SUCCESS but read 0 bytes? + // // Hope not, but defend against that anyway. + // if (buf[0]) + // { + // // std::cout << dfli->first << ": " << buf; + // history.back().which = dfli->first; + // history.back().what.append(buf); + // if (buf[strlen(buf) - 1] == '\n') + // history.push_back(Item()); + // else + // { + // // Just for pretty output... if we only read a partial + // // line, terminate it. + // // std::cout << "...\n"; + // } + // } + // } + // // Do this once per tick, as we expect the viewer will + // apr_proc_other_child_refresh_all(APR_OC_REASON_RUNNING); + // sleep(1); + // } + // apr_file_close(child.in); + // apr_file_close(child.out); + // apr_file_close(child.err); + + // // Okay, we've broken the loop because our pipes are all closed. If we + // // haven't yet called wait, give the callback one more chance. This + // // models the fact that unlike this small test program, the viewer + // // will still be running. + // if (wi.rv == -1) + // { + // std::cout << "last gasp apr_proc_other_child_refresh_all()\n"; + // apr_proc_other_child_refresh_all(APR_OC_REASON_RUNNING); + // } + + // if (wi.rv == -1) + // { + // std::cout << "child_status_callback(APR_OC_REASON_DEATH) wasn't called" << std::endl; + // wi.rv = apr_proc_wait(wi.child, &wi.rc, &wi.why, APR_NOWAIT); + // } + // // std::cout << "child done: rv = " << rv << " (" << manager.strerror(rv) << "), why = " << why << ", rc = " << rc << '\n'; + // aprchk_("apr_proc_wait(wi->child, &wi->rc, &wi->why, APR_NOWAIT)", wi.rv, APR_CHILD_DONE); + + // // Beyond merely executing all the above successfully, verify that we + // // obtained expected output -- and that we duly got control while + // // waiting, proving the non-blocking nature of these pipes. + // try + // { + // // Perform these ensure_equals_() within this try/catch so that if + // // we don't get expected results, we'll dump whatever we did get + // // to help diagnose. + // ensure_equals_(wi.why, APR_PROC_EXIT); + // ensure_equals_(wi.rc, 0); + + // unsigned i = 0; + // ensure("blocking I/O on child pipe (0)", history[i].tries); + // ensure_equals_(history[i].which, "out"); + // ensure_equals_(history[i].what, "stdout after wait" EOL); + // // ++i; + // // ensure_equals_(history[i].which, "out"); + // // ensure_equals_(history[i].what, "*eof*"); + // ++i; + // ensure("blocking I/O on child pipe (1)", history[i].tries); + // ensure_equals_(history[i].which, "err"); + // ensure_equals_(history[i].what, "stderr after wait" EOL); + // // ++i; + // // ensure_equals_(history[i].which, "err"); + // // ensure_equals_(history[i].what, "*eof*"); + // } + // catch (const failure&) + // { + // std::cout << "History:\n"; + // for (const Item& item : history) + // { + // std::string what(item.what); + // if ((! what.empty()) && what[what.length() - 1] == '\n') + // { + // what.erase(what.length() - 1); + // if ((! what.empty()) && what[what.length() - 1] == '\r') + // { + // what.erase(what.length() - 1); + // what.append("\\r"); + // } + // what.append("\\n"); + // } + // std::cout << " " << item.which << ": '" << what << "' (" + // << item.tries << " tries)\n"; + // } + // std::cout << std::flush; + // // re-raise same error; just want to enrich the output + // throw; + // } + // } + } + + TUT_CASE("llprocess_test::object_test_2") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<2>() + // { + // set_test_name("setWorkingDirectory()"); + // // We want to test setWorkingDirectory(). But what directory is + // // guaranteed to exist on every machine, under every OS? Have to + // // create one. Naturally, ensure we clean it up when done. + // NamedTempDir tempdir; + // PythonProcessLauncher py(get_test_name(), + // "from __future__ import with_statement\n" + // "import os, sys\n" + // "with open(sys.argv[1], 'w') as f:\n" + // " f.write(os.path.normcase(os.path.normpath(os.getcwd())))\n"); + // // Before running, call setWorkingDirectory() + // py.mParams.cwd = tempdir.getName(); + // std::string expected{ tempdir.getName() }; + // #if LL_WINDOWS + // // SIGH, don't get tripped up by "C:" != "c:" -- + // // but on the Mac, using tolower() fails because "/users" != "/Users"! + // expected = utf8str_tolower(expected); + // #endif + // ensure_equals("os.getcwd()", py.run_read(), expected); + // } + } + + TUT_CASE("llprocess_test::object_test_3") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<3>() + // { + // set_test_name("arguments"); + // PythonProcessLauncher py(get_test_name(), + // "from __future__ import with_statement, print_function\n" + // "import sys\n" + // // note nonstandard output-file arg! + // "with open(sys.argv[3], 'w') as f:\n" + // " for arg in sys.argv[1:]:\n" + // " print(arg,file=f)\n"); + // // We expect that PythonProcessLauncher has already appended + // // its own NamedTempFile to mParams.args (sys.argv[0]). + // py.mParams.args.add("first arg"); // sys.argv[1] + // py.mParams.args.add("second arg"); // sys.argv[2] + // // run_read() appends() one more argument, hence [3] + // std::string output(py.run_read()); + // boost::split_iterator + // li(output, boost::first_finder("\n")), lend; + // ensure("didn't get first arg", li != lend); + // std::string arg(li->begin(), li->end()); + // ensure_equals(arg, "first arg"); + // ++li; + // ensure("didn't get second arg", li != lend); + // arg.assign(li->begin(), li->end()); + // ensure_equals(arg, "second arg"); + // ++li; + // ensure("didn't get output filename?!", li != lend); + // arg.assign(li->begin(), li->end()); + // ensure("output filename empty?!", ! arg.empty()); + // ++li; + // ensure("too many args", li == lend); + // } + } + + TUT_CASE("llprocess_test::object_test_4") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<4>() + // { + // set_test_name("exit(0)"); + // PythonProcessLauncher py(get_test_name(), + // "import sys\n" + // "sys.exit(0)\n"); + // py.run(); + // ensure_equals("Status.mState", py.mPy->getStatus().mState, LLProcess::EXITED); + // ensure_equals("Status.mData", py.mPy->getStatus().mData, 0); + // } + } + + TUT_CASE("llprocess_test::object_test_5") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<5>() + // { + // set_test_name("exit(2)"); + // PythonProcessLauncher py(get_test_name(), + // "import sys\n" + // "sys.exit(2)\n"); + // py.run(); + // ensure_equals("Status.mState", py.mPy->getStatus().mState, LLProcess::EXITED); + // ensure_equals("Status.mData", py.mPy->getStatus().mData, 2); + // } + } + + TUT_CASE("llprocess_test::object_test_6") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<6>() + // { + // set_test_name("syntax_error"); + // PythonProcessLauncher py(get_test_name(), + // "syntax_error:\n"); + // py.mParams.files.add(LLProcess::FileParam()); // inherit stdin + // py.mParams.files.add(LLProcess::FileParam()); // inherit stdout + // py.mParams.files.add(LLProcess::FileParam().type("pipe")); // pipe for stderr + // py.run(); + // ensure_equals("Status.mState", py.mPy->getStatus().mState, LLProcess::EXITED); + // ensure_equals("Status.mData", py.mPy->getStatus().mData, 1); + // std::istream& rpipe(py.mPy->getReadPipe(LLProcess::STDERR).get_istream()); + // std::vector buffer(4096); + // rpipe.read(&buffer[0], buffer.size()); + // std::streamsize got(rpipe.gcount()); + // ensure("Nothing read from stderr pipe", got); + // std::string data(&buffer[0], got); + // ensure("Didn't find 'SyntaxError:'", data.find("\nSyntaxError:") != std::string::npos); + // } + } + + TUT_CASE("llprocess_test::object_test_7") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<7>() + // { + // set_test_name("explicit kill()"); + // PythonProcessLauncher py(get_test_name(), + // "from __future__ import with_statement\n" + // "import sys, time\n" + // "with open(sys.argv[1], 'w') as f:\n" + // " f.write('ok')\n" + // "# now sleep; expect caller to kill\n" + // "time.sleep(120)\n" + // "# if caller hasn't managed to kill by now, bad\n" + // "with open(sys.argv[1], 'w') as f:\n" + // " f.write('bad')\n"); + // NamedTempFile out("out", "not started"); + // py.mParams.args.add(out.getName()); + // py.launch(); + // // Wait for the script to wake up and do its first write + // int i = 0, timeout = 60; + // for ( ; i < timeout; ++i) + // { + // yield(); + // if (readfile(out.getName(), "from kill() script") == "ok") + // break; + // } + // // If we broke this loop because of the counter, something's wrong + // ensure("script never started", i < timeout); + // // script has performed its first write and should now be sleeping. + // py.mPy->kill(); + // // wait for the script to terminate... one way or another. + // waitfor(*py.mPy); + // #if LL_WINDOWS + // ensure_equals("Status.mState", py.mPy->getStatus().mState, LLProcess::EXITED); + // ensure_equals("Status.mData", py.mPy->getStatus().mData, -1); + // #else + // ensure_equals("Status.mState", py.mPy->getStatus().mState, LLProcess::KILLED); + // ensure_equals("Status.mData", py.mPy->getStatus().mData, SIGTERM); + // #endif + // // If kill() failed, the script would have woken up on its own and + // // overwritten the file with 'bad'. But if kill() succeeded, it should + // // not have had that chance. + // ensure_equals(get_test_name() + " script output", readfile(out.getName()), "ok"); + // } + } + + TUT_CASE("llprocess_test::object_test_8") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<8> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<8>() + // { + // set_test_name("implicit kill()"); + // NamedTempFile out("out", "not started"); + // LLProcess::handle phandle(0); + // { + // PythonProcessLauncher py(get_test_name(), + // "from __future__ import with_statement\n" + // "import sys, time\n" + // "with open(sys.argv[1], 'w') as f:\n" + // " f.write('ok')\n" + // "# now sleep; expect caller to kill\n" + // "time.sleep(120)\n" + // "# if caller hasn't managed to kill by now, bad\n" + // "with open(sys.argv[1], 'w') as f:\n" + // " f.write('bad')\n"); + // py.mParams.args.add(out.getName()); + // py.launch(); + // // Capture handle for later + // phandle = py.mPy->getProcessHandle(); + // // Wait for the script to wake up and do its first write + // int i = 0, timeout = 60; + // for ( ; i < timeout; ++i) + // { + // yield(); + // if (readfile(out.getName(), "from kill() script") == "ok") + // break; + // } + // // If we broke this loop because of the counter, something's wrong + // ensure("script never started", i < timeout); + // // Script has performed its first write and should now be sleeping. + // // Destroy the LLProcess, which should kill the child. + // } + // // wait for the script to terminate... one way or another. + // waitfor(phandle, "kill() script"); + // // If kill() failed, the script would have woken up on its own and + // // overwritten the file with 'bad'. But if kill() succeeded, it should + // // not have had that chance. + // ensure_equals(get_test_name() + " script output", readfile(out.getName()), "ok"); + // } + } + + TUT_CASE("llprocess_test::object_test_9") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<9> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<9>() + // { + // set_test_name("autokill=false"); + // NamedTempFile from("from", "not started"); + // NamedTempFile to("to", ""); + // LLProcess::handle phandle(0); + // { + // PythonProcessLauncher py(get_test_name(), + // "from __future__ import with_statement\n" + // "import sys, time\n" + // "with open(sys.argv[1], 'w') as f:\n" + // " f.write('ok')\n" + // "# wait for 'go' from test program\n" + // "for i in range(60):\n" + // " time.sleep(1)\n" + // " with open(sys.argv[2]) as f:\n" + // " go = f.read()\n" + // " if go == 'go':\n" + // " break\n" + // "else:\n" + // " with open(sys.argv[1], 'w') as f:\n" + // " f.write('never saw go')\n" + // " sys.exit(1)\n" + // "# okay, saw 'go', write 'ack'\n" + // "with open(sys.argv[1], 'w') as f:\n" + // " f.write('ack')\n"); + // py.mParams.args.add(from.getName()); + // py.mParams.args.add(to.getName()); + // py.mParams.autokill = false; + // py.launch(); + // // Capture handle for later + // phandle = py.mPy->getProcessHandle(); + // // Wait for the script to wake up and do its first write + // int i = 0, timeout = 60; + // for ( ; i < timeout; ++i) + // { + // yield(); + // if (readfile(from.getName(), "from autokill script") == "ok") + // break; + // } + // // If we broke this loop because of the counter, something's wrong + // ensure("script never started", i < timeout); + // // Now destroy the LLProcess, which should NOT kill the child! + // } + // // If the destructor killed the child anyway, give it time to die + // yield(2); + // // How do we know it's not terminated? By making it respond to + // // a specific stimulus in a specific way. + // { + // std::ofstream outf(to.getName().c_str()); + // outf << "go"; + // } // flush and close. + // // now wait for the script to terminate... one way or another. + // waitfor(phandle, "autokill script"); + // // If the LLProcess destructor implicitly called kill(), the + // // script could not have written 'ack' as we expect. + // ensure_equals(get_test_name() + " script output", readfile(from.getName()), "ack"); + // } + } + + TUT_CASE("llprocess_test::object_test_10") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<10> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<10>() + // { + // set_test_name("attached=false"); + // // almost just like autokill=false, except set autokill=true with + // // attached=false. + // NamedTempFile from("from", "not started"); + // NamedTempFile to("to", ""); + // LLProcess::handle phandle(0); + // { + // PythonProcessLauncher py(get_test_name(), + // "from __future__ import with_statement\n" + // "import sys, time\n" + // "with open(sys.argv[1], 'w') as f:\n" + // " f.write('ok')\n" + // "# wait for 'go' from test program\n" + // "for i in range(60):\n" + // " time.sleep(1)\n" + // " with open(sys.argv[2]) as f:\n" + // " go = f.read()\n" + // " if go == 'go':\n" + // " break\n" + // "else:\n" + // " with open(sys.argv[1], 'w') as f:\n" + // " f.write('never saw go')\n" + // " sys.exit(1)\n" + // "# okay, saw 'go', write 'ack'\n" + // "with open(sys.argv[1], 'w') as f:\n" + // " f.write('ack')\n"); + // py.mParams.args.add(from.getName()); + // py.mParams.args.add(to.getName()); + // py.mParams.autokill = true; + // py.mParams.attached = false; + // py.launch(); + // // Capture handle for later + // phandle = py.mPy->getProcessHandle(); + // // Wait for the script to wake up and do its first write + // int i = 0, timeout = 60; + // for ( ; i < timeout; ++i) + // { + // yield(); + // if (readfile(from.getName(), "from autokill script") == "ok") + // break; + // } + // // If we broke this loop because of the counter, something's wrong + // ensure("script never started", i < timeout); + // // Now destroy the LLProcess, which should NOT kill the child! + // } + // // If the destructor killed the child anyway, give it time to die + // yield(2); + // // How do we know it's not terminated? By making it respond to + // // a specific stimulus in a specific way. + // { + // std::ofstream outf(to.getName().c_str()); + // outf << "go"; + // } // flush and close. + // // now wait for the script to terminate... one way or another. + // waitfor(phandle, "autokill script"); + // // If the LLProcess destructor implicitly called kill(), the + // // script could not have written 'ack' as we expect. + // ensure_equals(get_test_name() + " script output", readfile(from.getName()), "ack"); + // } + } + + TUT_CASE("llprocess_test::object_test_11") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<11> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<11>() + // { + // set_test_name("'bogus' test"); + // CaptureLog recorder; + // PythonProcessLauncher py(get_test_name(), + // "from __future__ import print_function\n" + // "print('Hello world')\n"); + // py.mParams.files.add(LLProcess::FileParam("bogus")); + // py.mPy = LLProcess::create(py.mParams); + // ensure("should have rejected 'bogus'", ! py.mPy); + // std::string message(recorder.messageWith("bogus")); + // ensure_contains("did not name 'stdin'", message, "stdin"); + // } + } + + TUT_CASE("llprocess_test::object_test_12") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<12> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<12>() + // { + // set_test_name("'file' test"); + // // Replace this test with one or more real 'file' tests when we + // // implement 'file' support + // PythonProcessLauncher py(get_test_name(), + // "from __future__ import print_function\n" + // "print('Hello world')\n"); + // py.mParams.files.add(LLProcess::FileParam()); + // py.mParams.files.add(LLProcess::FileParam("file")); + // py.mPy = LLProcess::create(py.mParams); + // ensure("should have rejected 'file'", ! py.mPy); + // } + } + + TUT_CASE("llprocess_test::object_test_13") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<13> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<13>() + // { + // set_test_name("'tpipe' test"); + // // Replace this test with one or more real 'tpipe' tests when we + // // implement 'tpipe' support + // CaptureLog recorder; + // PythonProcessLauncher py(get_test_name(), + // "from __future__ import print_function\n" + // "print('Hello world')\n"); + // py.mParams.files.add(LLProcess::FileParam()); + // py.mParams.files.add(LLProcess::FileParam("tpipe")); + // py.mPy = LLProcess::create(py.mParams); + // ensure("should have rejected 'tpipe'", ! py.mPy); + // std::string message(recorder.messageWith("tpipe")); + // ensure_contains("did not name 'stdout'", message, "stdout"); + // } + } + + TUT_CASE("llprocess_test::object_test_14") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<14> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<14>() + // { + // set_test_name("'npipe' test"); + // // Replace this test with one or more real 'npipe' tests when we + // // implement 'npipe' support + // CaptureLog recorder; + // PythonProcessLauncher py(get_test_name(), + // "from __future__ import print_function\n" + // "print('Hello world')\n"); + // py.mParams.files.add(LLProcess::FileParam()); + // py.mParams.files.add(LLProcess::FileParam()); + // py.mParams.files.add(LLProcess::FileParam("npipe")); + // py.mPy = LLProcess::create(py.mParams); + // ensure("should have rejected 'npipe'", ! py.mPy); + // std::string message(recorder.messageWith("npipe")); + // ensure_contains("did not name 'stderr'", message, "stderr"); + // } + } + + TUT_CASE("llprocess_test::object_test_15") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<15> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<15>() + // { + // set_test_name("internal pipe name warning"); + // CaptureLog recorder; + // PythonProcessLauncher py(get_test_name(), + // "import sys\n" + // "sys.exit(7)\n"); + // py.mParams.files.add(LLProcess::FileParam("pipe", "somename")); + // py.run(); // verify that it did launch anyway + // ensure_equals("Status.mState", py.mPy->getStatus().mState, LLProcess::EXITED); + // ensure_equals("Status.mData", py.mPy->getStatus().mData, 7); + // std::string message(recorder.messageWith("not yet supported")); + // ensure_contains("log message did not mention internal pipe name", + // message, "somename"); + // } + } + + TUT_CASE("llprocess_test::object_test_16") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<16> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<16>() + // { + // set_test_name("get*Pipe() validation"); + // PythonProcessLauncher py(get_test_name(), + // "from __future__ import print_function\n" + // "print('this output is expected')\n"); + // py.mParams.files.add(LLProcess::FileParam("pipe")); // pipe for stdin + // py.mParams.files.add(LLProcess::FileParam()); // inherit stdout + // py.mParams.files.add(LLProcess::FileParam("pipe")); // pipe for stderr + // py.run(); + // TEST_getPipe(*py.mPy, getWritePipe, getOptWritePipe, + // LLProcess::STDIN, // VALID + // LLProcess::STDOUT, // NOPIPE + // LLProcess::STDERR); // BADPIPE + // TEST_getPipe(*py.mPy, getReadPipe, getOptReadPipe, + // LLProcess::STDERR, // VALID + // LLProcess::STDOUT, // NOPIPE + // LLProcess::STDIN); // BADPIPE + // } + } + + TUT_CASE("llprocess_test::object_test_17") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<17> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<17>() + // { + // set_test_name("talk to stdin/stdout"); + // PythonProcessLauncher py(get_test_name(), + // "from __future__ import print_function\n" + // "import sys, time\n" + // "print('ok')\n" + // "sys.stdout.flush()\n" + // "# wait for 'go' from test program\n" + // "go = sys.stdin.readline()\n" + // "if go != 'go\\n':\n" + // " sys.exit('expected \"go\", saw %r' % go)\n" + // "print('ack')\n"); + // py.mParams.files.add(LLProcess::FileParam("pipe")); // stdin + // py.mParams.files.add(LLProcess::FileParam("pipe")); // stdout + // py.launch(); + // LLProcess::ReadPipe& childout(py.mPy->getReadPipe(LLProcess::STDOUT)); + // int i, timeout = 60; + // for (i = 0; i < timeout && py.mPy->isRunning() && childout.size() < 3; ++i) + // { + // yield(); + // } + // ensure("script never started", i < timeout); + // ensure_equals("bad wakeup from stdin/stdout script", + // childout.getline(), "ok"); + // // important to get the implicit flush from std::endl + // py.mPy->getWritePipe().get_ostream() << "go" << std::endl; + // waitfor(*py.mPy); + // ensure("script never replied", childout.contains("\n")); + // ensure_equals("child didn't ack", childout.getline(), "ack"); + // ensure_equals("bad child termination", py.mPy->getStatus().mState, LLProcess::EXITED); + // ensure_equals("bad child exit code", py.mPy->getStatus().mData, 0); + // } + } + + TUT_CASE("llprocess_test::object_test_18") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<18> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<18>() + // { + // set_test_name("listen for ReadPipe events"); + // PythonProcessLauncher py(get_test_name(), + // "import sys\n" + // "sys.stdout.write('abc')\n" + // "sys.stdout.flush()\n" + // "sys.stdin.readline()\n" + // "sys.stdout.write('def')\n" + // "sys.stdout.flush()\n" + // "sys.stdin.readline()\n" + // "sys.stdout.write('ghi\\n')\n" + // "sys.stdout.flush()\n" + // "sys.stdin.readline()\n" + // "sys.stdout.write('second line\\n')\n"); + // py.mParams.files.add(LLProcess::FileParam("pipe")); // stdin + // py.mParams.files.add(LLProcess::FileParam("pipe")); // stdout + // py.launch(); + // std::ostream& childin(py.mPy->getWritePipe(LLProcess::STDIN).get_ostream()); + // LLProcess::ReadPipe& childout(py.mPy->getReadPipe(LLProcess::STDOUT)); + // // lift the default limit; allow event to carry (some of) the actual data + // childout.setLimit(20); + // // listen for incoming data on childout + // EventListener listener(childout.getPump()); + // // also listen with a function that prompts the child to continue + // // every time we see output + // LLTempBoundListener connection( + // childout.getPump().listen("ack", boost::bind(ack, boost::ref(childin), _1))); + // int i, timeout = 60; + // // wait through stuttering first line + // for (i = 0; i < timeout && py.mPy->isRunning() && ! childout.contains("\n"); ++i) + // { + // yield(); + // } + // ensure("couldn't get first line", i < timeout); + // // disconnect from listener + // listener.mConnection.disconnect(); + // // finish out the run + // waitfor(*py.mPy); + // // now verify history + // listener.checkHistory( + // [](const EventListener::Listory& history) + // { + // auto li(history.begin()), lend(history.end()); + // ensure("no events", li != lend); + // ensure_equals("history[0]", (*li)["data"].asString(), "abc"); + // ensure_equals("history[0] len", (*li)["len"].asInteger(), 3); + // ++li; + // ensure("only 1 event", li != lend); + // ensure_equals("history[1]", (*li)["data"].asString(), "abcdef"); + // ensure_equals("history[0] len", (*li)["len"].asInteger(), 6); + // ++li; + // ensure("only 2 events", li != lend); + // ensure_equals("history[2]", (*li)["data"].asString(), "abcdefghi" EOL); + // ensure_equals("history[0] len", (*li)["len"].asInteger(), 9 + sizeof(EOL) - 1); + // ++li; + // // We DO NOT expect a whole new event for the second line because we + // // disconnected. + // ensure("more than 3 events", li == lend); + // }); + // } + } + + TUT_CASE("llprocess_test::object_test_19") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<19> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<19>() + // { + // set_test_name("ReadPipe \"eof\" event"); + // PythonProcessLauncher py(get_test_name(), + // "from __future__ import print_function\n" + // "print('Hello from Python!')\n"); + // py.mParams.files.add(LLProcess::FileParam()); // stdin + // py.mParams.files.add(LLProcess::FileParam("pipe")); // stdout + // py.launch(); + // LLProcess::ReadPipe& childout(py.mPy->getReadPipe(LLProcess::STDOUT)); + // EventListener listener(childout.getPump()); + // waitfor(*py.mPy); + // // We can't be positive there will only be a single event, if the OS + // // (or any other intervening layer) does crazy buffering. What we want + // // to ensure is that there was exactly ONE event with "eof" true, and + // // that it was the LAST event. + // listener.checkHistory( + // [](const EventListener::Listory& history) + // { + // auto rli(history.rbegin()), rlend(history.rend()); + // ensure("no events", rli != rlend); + // ensure("last event not \"eof\"", (*rli)["eof"].asBoolean()); + // while (++rli != rlend) + // { + // ensure("\"eof\" event not last", ! (*rli)["eof"].asBoolean()); + // } + // }); + // } + } + + TUT_CASE("llprocess_test::object_test_20") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<20> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<20>() + // { + // set_test_name("setLimit()"); + // PythonProcessLauncher py(get_test_name(), + // "import sys\n" + // "sys.stdout.write(sys.argv[1])\n"); + // std::string abc("abcdefghijklmnopqrstuvwxyz"); + // py.mParams.args.add(abc); + // py.mParams.files.add(LLProcess::FileParam()); // stdin + // py.mParams.files.add(LLProcess::FileParam("pipe")); // stdout + // py.launch(); + // LLProcess::ReadPipe& childout(py.mPy->getReadPipe(LLProcess::STDOUT)); + // // listen for incoming data on childout + // EventListener listener(childout.getPump()); + // // but set limit + // childout.setLimit(10); + // ensure_equals("getLimit() after setlimit(10)", childout.getLimit(), 10); + // // okay, pump I/O to pick up output from child + // waitfor(*py.mPy); + // listener.checkHistory( + // [abc](const EventListener::Listory& history) + // { + // ensure("no events", ! history.empty()); + // // For all we know, that data could have arrived in several different + // // bursts... probably not, but anyway, only check the last one. + // ensure_equals("event[\"len\"]", + // history.back()["len"].asInteger(), abc.length()); + // ensure_equals("length of setLimit(10) data", + // history.back()["data"].asString().length(), 10); + // }); + // } + } + + TUT_CASE("llprocess_test::object_test_21") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<21> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<21>() + // { + // set_test_name("peek() ReadPipe data"); + // PythonProcessLauncher py(get_test_name(), + // "import sys\n" + // "sys.stdout.write(sys.argv[1])\n"); + // std::string abc("abcdefghijklmnopqrstuvwxyz"); + // py.mParams.args.add(abc); + // py.mParams.files.add(LLProcess::FileParam()); // stdin + // py.mParams.files.add(LLProcess::FileParam("pipe")); // stdout + // py.launch(); + // LLProcess::ReadPipe& childout(py.mPy->getReadPipe(LLProcess::STDOUT)); + // // okay, pump I/O to pick up output from child + // waitfor(*py.mPy); + // // peek() with substr args + // ensure_equals("peek()", childout.peek(), abc); + // ensure_equals("peek(23)", childout.peek(23), abc.substr(23)); + // ensure_equals("peek(5, 3)", childout.peek(5, 3), abc.substr(5, 3)); + // ensure_equals("peek(27, 2)", childout.peek(27, 2), ""); + // ensure_equals("peek(23, 5)", childout.peek(23, 5), "xyz"); + // // contains() -- we don't exercise as thoroughly as find() because the + // // contains() implementation is trivially (and visibly) based on find() + // ensure("contains(\":\")", ! childout.contains(":")); + // ensure("contains(':')", ! childout.contains(':')); + // ensure("contains(\"d\")", childout.contains("d")); + // ensure("contains('d')", childout.contains('d')); + // ensure("contains(\"klm\")", childout.contains("klm")); + // ensure("contains(\"klx\")", ! childout.contains("klx")); + // // find() + // ensure("find(\":\")", childout.find(":") == LLProcess::ReadPipe::npos); + // ensure("find(':')", childout.find(':') == LLProcess::ReadPipe::npos); + // ensure_equals("find(\"d\")", childout.find("d"), 3); + // ensure_equals("find('d')", childout.find('d'), 3); + // ensure_equals("find(\"d\", 3)", childout.find("d", 3), 3); + // ensure_equals("find('d', 3)", childout.find('d', 3), 3); + // ensure("find(\"d\", 4)", childout.find("d", 4) == LLProcess::ReadPipe::npos); + // ensure("find('d', 4)", childout.find('d', 4) == LLProcess::ReadPipe::npos); + // // The case of offset == end and offset > end are different. In the + // // first case, we can form a valid (albeit empty) iterator range and + // // search that. In the second, guard logic in the implementation must + // // realize we can't form a valid iterator range. + // ensure("find(\"d\", 26)", childout.find("d", 26) == LLProcess::ReadPipe::npos); + // ensure("find('d', 26)", childout.find('d', 26) == LLProcess::ReadPipe::npos); + // ensure("find(\"d\", 27)", childout.find("d", 27) == LLProcess::ReadPipe::npos); + // ensure("find('d', 27)", childout.find('d', 27) == LLProcess::ReadPipe::npos); + // ensure_equals("find(\"ghi\")", childout.find("ghi"), 6); + // ensure_equals("find(\"ghi\", 6)", childout.find("ghi"), 6); + // ensure("find(\"ghi\", 7)", childout.find("ghi", 7) == LLProcess::ReadPipe::npos); + // ensure("find(\"ghi\", 26)", childout.find("ghi", 26) == LLProcess::ReadPipe::npos); + // ensure("find(\"ghi\", 27)", childout.find("ghi", 27) == LLProcess::ReadPipe::npos); + // } + } + + TUT_CASE("llprocess_test::object_test_22") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<22> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<22>() + // { + // set_test_name("bad postend"); + // std::string pumpname("postend"); + // EventListener listener(LLEventPumps::instance().obtain(pumpname)); + // LLProcess::Params params; + // params.desc = get_test_name(); + // params.postend = pumpname; + // LLProcessPtr child = LLProcess::create(params); + // ensure("shouldn't have launched", ! child); + // listener.checkHistory( + // [¶ms](const EventListener::Listory& history) + // { + // ensure_equals("number of postend events", history.size(), 1); + // LLSD postend(history.front()); + // ensure("has id", ! postend.has("id")); + // ensure_equals("desc", postend["desc"].asString(), std::string(params.desc)); + // ensure_equals("state", postend["state"].asInteger(), LLProcess::UNSTARTED); + // ensure("has data", ! postend.has("data")); + // std::string error(postend["string"]); + // // All we get from canned parameter validation is a bool, so the + // // "validation failed" message we ourselves generate can't mention + // // "executable" by name. Just check that it's nonempty. + // //ensure_contains("error", error, "executable"); + // ensure("string", ! error.empty()); + // }); + // } + } + + TUT_CASE("llprocess_test::object_test_23") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<23> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<23>() + // { + // set_test_name("good postend"); + // PythonProcessLauncher py(get_test_name(), + // "import sys\n" + // "sys.exit(35)\n"); + // std::string pumpname("postend"); + // EventListener listener(LLEventPumps::instance().obtain(pumpname)); + // py.mParams.postend = pumpname; + // py.launch(); + // LLProcess::id childid(py.mPy->getProcessID()); + // // Don't use waitfor(), which calls isRunning(); instead wait for an + // // event on pumpname. + // int i, timeout = 60; + // for (i = 0; i < timeout && listener.mHistory.empty(); ++i) + // { + // yield(); + // } + // listener.checkHistory( + // [i, timeout, childid](const EventListener::Listory& history) + // { + // ensure("no postend event", i < timeout); + // ensure_equals("number of postend events", history.size(), 1); + // LLSD postend(history.front()); + // ensure_equals("id", postend["id"].asInteger(), childid); + // ensure("desc empty", ! postend["desc"].asString().empty()); + // ensure_equals("state", postend["state"].asInteger(), LLProcess::EXITED); + // ensure_equals("data", postend["data"].asInteger(), 35); + // std::string str(postend["string"]); + // ensure_contains("string", str, "exited"); + // ensure_contains("string", str, "35"); + // }); + // } + } + + TUT_CASE("llprocess_test::object_test_24") + { + DOCTEST_FAIL("TODO: convert llprocess_test.cpp::object::test<24> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<24>() + // { + // set_test_name("all data visible at postend"); + // PythonProcessLauncher py(get_test_name(), + // "import sys\n" + // // note, no '\n' in written data + // "sys.stdout.write('partial line')\n"); + // std::string pumpname("postend"); + // py.mParams.files.add(LLProcess::FileParam()); // stdin + // py.mParams.files.add(LLProcess::FileParam("pipe")); // stdout + // py.mParams.postend = pumpname; + // py.launch(); + // PostendListener listener(py.mPy->getReadPipe(LLProcess::STDOUT), + // pumpname, + // "partial line"); + // waitfor(*py.mPy); + // ensure("postend never triggered", listener.mTriggered); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llprocessor_test_doctest.cpp b/indra/llcommon/tests_doctest/llprocessor_test_doctest.cpp new file mode 100644 index 00000000000..d5c7b5d679d --- /dev/null +++ b/indra/llcommon/tests_doctest/llprocessor_test_doctest.cpp @@ -0,0 +1,65 @@ +/** + * @file llprocessor_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL processor + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llprocessor_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "../llprocessor.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("llprocessor_test::processor_object_t_test_1") + { + DOCTEST_FAIL("TODO: convert llprocessor_test.cpp::processor_object_t::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void processor_object_t::test<1>() + // { + // set_test_name("LLProcessorInfo regression test"); + + // LLProcessorInfo pi; + // F64 freq = pi.getCPUFrequency(); + // //bool sse = pi.hasSSE(); + // //bool sse2 = pi.hasSSE2(); + // //bool alitvec = pi.hasAltivec(); + // std::string family = pi.getCPUFamilyName(); + // std::string brand = pi.getCPUBrandName(); + // //std::string steam = pi.getCPUFeatureDescription(); + + // ensure_not_equals("Unknown Brand name", brand, "Unknown"); + // ensure_not_equals("Unknown Family name", family, "Unknown"); + // ensure("Reasonable CPU Frequency > 100 && < 10000", freq > 100 && freq < 10000); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llprocinfo_test_doctest.cpp b/indra/llcommon/tests_doctest/llprocinfo_test_doctest.cpp new file mode 100644 index 00000000000..27419d7bf9e --- /dev/null +++ b/indra/llcommon/tests_doctest/llprocinfo_test_doctest.cpp @@ -0,0 +1,86 @@ +/** + * @file llprocinfo_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL procinfo + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llprocinfo_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "../llprocinfo.h" +#include "../lltimer.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("llprocinfo_test::procinfo_object_t_test_1") + { + DOCTEST_FAIL("TODO: convert llprocinfo_test.cpp::procinfo_object_t::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void procinfo_object_t::test<1>() + // { + // LLProcInfo::time_type user(bad_user), system(bad_system); + + // set_test_name("getCPUUsage() basic function"); + + // LLProcInfo::getCPUUsage(user, system); + + // ensure_not_equals("getCPUUsage() writes to its user argument", user, bad_user); + // ensure_not_equals("getCPUUsage() writes to its system argument", system, bad_system); + // } + } + + TUT_CASE("llprocinfo_test::procinfo_object_t_test_2") + { + DOCTEST_FAIL("TODO: convert llprocinfo_test.cpp::procinfo_object_t::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void procinfo_object_t::test<2>() + // { + // LLProcInfo::time_type user(bad_user), system(bad_system); + // LLProcInfo::time_type user2(bad_user), system2(bad_system); + + // set_test_name("getCPUUsage() increases over time"); + + // LLProcInfo::getCPUUsage(user, system); + + // for (int i(0); i < 100000; ++i) + // { + // ms_sleep(0); + // } + + // LLProcInfo::getCPUUsage(user2, system2); + + // ensure_equals("getCPUUsage() user value doesn't decrease over time", user2 >= user, true); + // ensure_equals("getCPUUsage() system value doesn't decrease over time", system2 >= system, true); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llrand_test_doctest.cpp b/indra/llcommon/tests_doctest/llrand_test_doctest.cpp new file mode 100644 index 00000000000..4ae2dade468 --- /dev/null +++ b/indra/llcommon/tests_doctest/llrand_test_doctest.cpp @@ -0,0 +1,142 @@ +/** + * @file llrand_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL rand + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llrand_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "../llrand.h" +#include "stringize.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("llrand_test::random_object_t_test_1") + { + DOCTEST_FAIL("TODO: convert llrand_test.cpp::random_object_t::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void random_object_t::test<1>() + // { + // for(S32 ii = 0; ii < 100000; ++ii) + // { + // ensure_in_range("frand", ll_frand(), 0.0f, 1.0f); + // } + // } + } + + TUT_CASE("llrand_test::random_object_t_test_2") + { + DOCTEST_FAIL("TODO: convert llrand_test.cpp::random_object_t::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void random_object_t::test<2>() + // { + // for(S32 ii = 0; ii < 100000; ++ii) + // { + // ensure_in_range("drand", ll_drand(), 0.0, 1.0); + // } + // } + } + + TUT_CASE("llrand_test::random_object_t_test_3") + { + DOCTEST_FAIL("TODO: convert llrand_test.cpp::random_object_t::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void random_object_t::test<3>() + // { + // for(S32 ii = 0; ii < 100000; ++ii) + // { + // ensure_in_range("frand(2.0f)", ll_frand(2.0f) - 1.0f, -1.0f, 1.0f); + // } + // } + } + + TUT_CASE("llrand_test::random_object_t_test_4") + { + DOCTEST_FAIL("TODO: convert llrand_test.cpp::random_object_t::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void random_object_t::test<4>() + // { + // for(S32 ii = 0; ii < 100000; ++ii) + // { + // // Negate the result so we don't have to allow a templated low-end + // // comparison as well. + // ensure_in_range("-frand(-7.0)", -ll_frand(-7.0), 0.0f, 7.0f); + // } + // } + } + + TUT_CASE("llrand_test::random_object_t_test_5") + { + DOCTEST_FAIL("TODO: convert llrand_test.cpp::random_object_t::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void random_object_t::test<5>() + // { + // for(S32 ii = 0; ii < 100000; ++ii) + // { + // ensure_in_range("-drand(-2.0)", -ll_drand(-2.0), 0.0, 2.0); + // } + // } + } + + TUT_CASE("llrand_test::random_object_t_test_6") + { + DOCTEST_FAIL("TODO: convert llrand_test.cpp::random_object_t::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void random_object_t::test<6>() + // { + // for(S32 ii = 0; ii < 100000; ++ii) + // { + // ensure_in_range("rand(100)", ll_rand(100), 0, 100); + // } + // } + } + + TUT_CASE("llrand_test::random_object_t_test_7") + { + DOCTEST_FAIL("TODO: convert llrand_test.cpp::random_object_t::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void random_object_t::test<7>() + // { + // for(S32 ii = 0; ii < 100000; ++ii) + // { + // ensure_in_range("-rand(-127)", -ll_rand(-127), 0, 127); + // } + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llsdserialize_test_doctest.cpp b/indra/llcommon/tests_doctest/llsdserialize_test_doctest.cpp new file mode 100644 index 00000000000..08d9aba90ad --- /dev/null +++ b/indra/llcommon/tests_doctest/llsdserialize_test_doctest.cpp @@ -0,0 +1,2906 @@ +/** + * @file llsdserialize_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL sdserialize + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llsdserialize_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include +#include +#include +// #include // not available on Windows +// #include // not available on Windows +#include +#include +#include +// #include // not available on Windows +#include "llprocess.h" +#include "llstring.h" +#include "boost/range.hpp" +#include "llsd.h" +#include "llsdserialize.h" +#include "llsdutil.h" +#include "llformat.h" +#include "llmemorystream.h" +#include "../test/hexdump.h" +#include "../test/namedtempfile.h" +#include "stringize.h" +// #include "StringVec.h" // not available on Windows +#include + +TUT_SUITE("llcommon") +{ + TUT_CASE("llsdserialize_test::sd_xml_object_test_1") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::sd_xml_object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_xml_object::test<1>() + // { + // // random atomic tests + // std::string expected; + + // expected = "\n"; + // xml_test("undef", expected); + + // mSD = 3463; + // expected = "3463\n"; + // xml_test("integer", expected); + + // mSD = ""; + // expected = "\n"; + // xml_test("empty string", expected); + + // mSD = "foobar"; + // expected = "foobar\n"; + // xml_test("string", expected); + + // mSD = LLUUID::null; + // expected = "\n"; + // xml_test("null uuid", expected); + + // mSD = LLUUID("c96f9b1e-f589-4100-9774-d98643ce0bed"); + // expected = "c96f9b1e-f589-4100-9774-d98643ce0bed\n"; + // xml_test("uuid", expected); + + // mSD = LLURI("https://secondlife.com/login"); + // expected = "https://secondlife.com/login\n"; + // xml_test("uri", expected); + + // mSD = LLDate("2006-04-24T16:11:33Z"); + // expected = "2006-04-24T16:11:33Z\n"; + // xml_test("date", expected); + + // // Generated by: echo -n 'hello' | openssl enc -e -base64 + // std::vector hello; + // hello.push_back('h'); + // hello.push_back('e'); + // hello.push_back('l'); + // hello.push_back('l'); + // hello.push_back('o'); + // mSD = hello; + // expected = "aGVsbG8=\n"; + // xml_test("binary", expected); + // } + } + + TUT_CASE("llsdserialize_test::sd_xml_object_test_2") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::sd_xml_object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_xml_object::test<2>() + // { + // // tests with boolean values. + // std::string expected; + + // mFormatter->boolalpha(true); + // mSD = true; + // expected = "true\n"; + // xml_test("bool alpha true", expected); + // mSD = false; + // expected = "false\n"; + // xml_test("bool alpha false", expected); + + // mFormatter->boolalpha(false); + // mSD = true; + // expected = "1\n"; + // xml_test("bool true", expected); + // mSD = false; + // expected = "0\n"; + // xml_test("bool false", expected); + // } + } + + TUT_CASE("llsdserialize_test::sd_xml_object_test_3") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::sd_xml_object::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_xml_object::test<3>() + // { + // // tests with real values. + // std::string expected; + + // mFormatter->realFormat("%.2f"); + // mSD = 1.0; + // expected = "1.00\n"; + // xml_test("real 1", expected); + + // mSD = -34379.0438; + // expected = "-34379.04\n"; + // xml_test("real reduced precision", expected); + // mFormatter->realFormat("%.4f"); + // expected = "-34379.0438\n"; + // xml_test("higher precision", expected); + + // mFormatter->realFormat("%.0f"); + // mSD = 0.0; + // expected = "0\n"; + // xml_test("no decimal 0", expected); + // mSD = 3287.4387; + // expected = "3287\n"; + // xml_test("no decimal real number", expected); + // } + } + + TUT_CASE("llsdserialize_test::sd_xml_object_test_4") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::sd_xml_object::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_xml_object::test<4>() + // { + // // tests with arrays + // std::string expected; + + // mSD = LLSD::emptyArray(); + // expected = "\n"; + // xml_test("empty array", expected); + + // mSD.append(LLSD()); + // expected = "\n"; + // xml_test("1 element array", expected); + + // mSD.append(1); + // expected = "1\n"; + // xml_test("2 element array", expected); + // } + } + + TUT_CASE("llsdserialize_test::sd_xml_object_test_5") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::sd_xml_object::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_xml_object::test<5>() + // { + // // tests with arrays + // std::string expected; + + // mSD = LLSD::emptyMap(); + // expected = "\n"; + // xml_test("empty map", expected); + + // mSD["foo"] = "bar"; + // expected = "foobar\n"; + // xml_test("1 element map", expected); + + // mSD["baz"] = LLSD(); + // expected = "bazfoobar\n"; + // xml_test("2 element map", expected); + // } + } + + TUT_CASE("llsdserialize_test::sd_xml_object_test_6") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::sd_xml_object::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void sd_xml_object::test<6>() + // { + // // tests with binary + // std::string expected; + + // // Generated by: echo -n 'hello' | openssl enc -e -base64 + // mSD = string_to_vector("hello"); + // expected = "aGVsbG8=\n"; + // xml_test("binary", expected); + + // mSD = string_to_vector("6|6|asdfhappybox|60e44ec5-305c-43c2-9a19-b4b89b1ae2a6|60e44ec5-305c-43c2-9a19-b4b89b1ae2a6|60e44ec5-305c-43c2-9a19-b4b89b1ae2a6|00000000-0000-0000-0000-000000000000|7fffffff|7fffffff|0|0|82000|450fe394-2904-c9ad-214c-a07eb7feec29|(No Description)|0|10|0"); + // expected = "Nnw2fGFzZGZoYXBweWJveHw2MGU0NGVjNS0zMDVjLTQzYzItOWExOS1iNGI4OWIxYWUyYTZ8NjBlNDRlYzUtMzA1Yy00M2MyLTlhMTktYjRiODliMWFlMmE2fDYwZTQ0ZWM1LTMwNWMtNDNjMi05YTE5LWI0Yjg5YjFhZTJhNnwwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDB8N2ZmZmZmZmZ8N2ZmZmZmZmZ8MHwwfDgyMDAwfDQ1MGZlMzk0LTI5MDQtYzlhZC0yMTRjLWEwN2ViN2ZlZWMyOXwoTm8gRGVzY3JpcHRpb24pfDB8MTB8MA==\n"; + // xml_test("binary", expected); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDSerializeObject_test_1") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDSerializeObject::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDSerializeObject::test<1>() + // { + // setFormatterParser(new LLSDNotationFormatter(false, "", LLSDFormatter::OPTIONS_PRETTY_BINARY), + // new LLSDNotationParser()); + // doRoundTripTests("pretty binary notation serialization"); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDSerializeObject_test_2") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDSerializeObject::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDSerializeObject::test<2>() + // { + // setFormatterParser(new LLSDNotationFormatter(false, "", LLSDFormatter::OPTIONS_NONE), + // new LLSDNotationParser()); + // doRoundTripTests("raw binary notation serialization"); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDSerializeObject_test_3") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDSerializeObject::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDSerializeObject::test<3>() + // { + // setFormatterParser(new LLSDXMLFormatter(), new LLSDXMLParser()); + // doRoundTripTests("xml serialization"); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDSerializeObject_test_4") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDSerializeObject::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDSerializeObject::test<4>() + // { + // setFormatterParser(new LLSDBinaryFormatter(), new LLSDBinaryParser()); + // doRoundTripTests("binary serialization"); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDSerializeObject_test_5") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDSerializeObject::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDSerializeObject::test<5>() + // { + // mFormatter = [](const LLSD& sd, std::ostream& str) + // { + // LLSDSerialize::serialize(sd, str, LLSDSerialize::LLSD_BINARY); + // }; + // setParser(LLSDSerialize::deserialize); + // doRoundTripTests("serialize(LLSD_BINARY)"); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDSerializeObject_test_6") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDSerializeObject::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDSerializeObject::test<6>() + // { + // mFormatter = [](const LLSD& sd, std::ostream& str) + // { + // LLSDSerialize::serialize(sd, str, LLSDSerialize::LLSD_XML); + // }; + // setParser(LLSDSerialize::deserialize); + // doRoundTripTests("serialize(LLSD_XML)"); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDSerializeObject_test_7") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDSerializeObject::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDSerializeObject::test<7>() + // { + // mFormatter = [](const LLSD& sd, std::ostream& str) + // { + // LLSDSerialize::serialize(sd, str, LLSDSerialize::LLSD_NOTATION); + // }; + // setParser(LLSDSerialize::deserialize); + // // In this test, serialize(LLSD_NOTATION) emits a header recognized by + // // deserialize(). + // doRoundTripTests("serialize(LLSD_NOTATION)"); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDSerializeObject_test_8") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDSerializeObject::test<8> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDSerializeObject::test<8>() + // { + // setFormatterParser(new LLSDNotationFormatter(false, "", LLSDFormatter::OPTIONS_NONE), + // new LLSDNotationParser()); + // setParser(LLSDSerialize::deserialize); + // // This is an interesting test because LLSDNotationFormatter does not + // // emit an llsd/notation header. + // doRoundTripTests("LLSDNotationFormatter -> deserialize"); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDSerializeObject_test_9") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDSerializeObject::test<9> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDSerializeObject::test<9>() + // { + // setFormatterParser(new LLSDXMLFormatter(false, "", LLSDFormatter::OPTIONS_NONE), + // new LLSDXMLParser()); + // setParser(LLSDSerialize::deserialize); + // // This is an interesting test because LLSDXMLFormatter does not + // // emit an LLSD/XML header. + // doRoundTripTests("LLSDXMLFormatter -> deserialize"); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDSerializeObject_test_10") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDSerializeObject::test<10> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDSerializeObject::test<10>() + // { + // setFormatterParser(new LLSDBinaryFormatter(false, "", LLSDFormatter::OPTIONS_NONE), + // new LLSDBinaryParser()); + // setParser(LLSDSerialize::deserialize); + // // This is an interesting test because LLSDBinaryFormatter does not + // // emit an LLSD/Binary header. + // doRoundTripTests("LLSDBinaryFormatter -> deserialize"); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDXMLParsingObject_test_1") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDXMLParsingObject::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDXMLParsingObject::test<1>() + // { + // // test handling of xml not recognized as llsd results in an + // // LLSD Undefined + // ensureParse( + // "malformed xml", + // "ha ha", + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // ensureParse( + // "not llsd", + // "

ha ha

", + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // ensureParse( + // "value without llsd", + // "ha ha", + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // ensureParse( + // "key without llsd", + // "ha ha", + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDXMLParsingObject_test_2") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDXMLParsingObject::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDXMLParsingObject::test<2>() + // { + // // test handling of unrecognized or unparseable llsd values + // LLSD v; + // v["amy"] = 23; + // v["bob"] = LLSD(); + // v["cam"] = 1.23; + + // ensureParse( + // "unknown data type", + // "" + // "amy23" + // "bob99999999999999999" + // "cam1.23" + // "", + // v, + // static_cast(v.size()) + 1); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDXMLParsingObject_test_3") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDXMLParsingObject::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDXMLParsingObject::test<3>() + // { + // // test handling of nested bad data + + // LLSD v; + // v["amy"] = 23; + // v["cam"] = 1.23; + + // ensureParse( + // "map with html", + // "" + // "amy23" + // "ha ha" + // "cam1.23" + // "", + // v, + // static_cast(v.size()) + 1); + + // v.clear(); + // v["amy"] = 23; + // v["cam"] = 1.23; + // ensureParse( + // "map with value for key", + // "" + // "amy23" + // "ha ha" + // "cam1.23" + // "", + // v, + // static_cast(v.size()) + 1); + + // v.clear(); + // v["amy"] = 23; + // v["bob"] = LLSD::emptyMap(); + // v["cam"] = 1.23; + // ensureParse( + // "map with map of html", + // "" + // "amy23" + // "bob" + // "" + // "ha ha" + // "" + // "cam1.23" + // "", + // v, + // static_cast(v.size()) + 1); + + // v.clear(); + // v[0] = 23; + // v[1] = LLSD(); + // v[2] = 1.23; + + // ensureParse( + // "array value of html", + // "" + // "23" + // "ha ha" + // "1.23" + // "", + // v, + // static_cast(v.size()) + 1); + + // v.clear(); + // v[0] = 23; + // v[1] = LLSD::emptyMap(); + // v[2] = 1.23; + // ensureParse( + // "array with map of html", + // "" + // "23" + // "" + // "ha ha" + // "" + // "1.23" + // "", + // v, + // static_cast(v.size()) + 1); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDXMLParsingObject_test_4") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDXMLParsingObject::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDXMLParsingObject::test<4>() + // { + // // test handling of binary object in XML + // std::string xml; + // LLSD expected; + + // // Generated by: echo -n 'hello' | openssl enc -e -base64 + // expected = string_to_vector("hello"); + // xml = "aGVsbG8=\n"; + // ensureParse( + // "the word 'hello' packed in binary encoded base64", + // xml, + // expected, + // 1); + + // expected = string_to_vector("6|6|asdfhappybox|60e44ec5-305c-43c2-9a19-b4b89b1ae2a6|60e44ec5-305c-43c2-9a19-b4b89b1ae2a6|60e44ec5-305c-43c2-9a19-b4b89b1ae2a6|00000000-0000-0000-0000-000000000000|7fffffff|7fffffff|0|0|82000|450fe394-2904-c9ad-214c-a07eb7feec29|(No Description)|0|10|0"); + // xml = "Nnw2fGFzZGZoYXBweWJveHw2MGU0NGVjNS0zMDVjLTQzYzItOWExOS1iNGI4OWIxYWUyYTZ8NjBlNDRlYzUtMzA1Yy00M2MyLTlhMTktYjRiODliMWFlMmE2fDYwZTQ0ZWM1LTMwNWMtNDNjMi05YTE5LWI0Yjg5YjFhZTJhNnwwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDB8N2ZmZmZmZmZ8N2ZmZmZmZmZ8MHwwfDgyMDAwfDQ1MGZlMzk0LTI5MDQtYzlhZC0yMTRjLWEwN2ViN2ZlZWMyOXwoTm8gRGVzY3JpcHRpb24pfDB8MTB8MA==\n"; + // ensureParse( + // "a common binary blob for object -> agent offline inv transfer", + // xml, + // expected, + // 1); + + // expected = string_to_vector("6|6|asdfhappybox|60e44ec5-305c-43c2-9a19-b4b89b1ae2a6|60e44ec5-305c-43c2-9a19-b4b89b1ae2a6|60e44ec5-305c-43c2-9a19-b4b89b1ae2a6|00000000-0000-0000-0000-000000000000|7fffffff|7fffffff|0|0|82000|450fe394-2904-c9ad-214c-a07eb7feec29|(No Description)|0|10|0"); + // xml = "Nnw2fGFzZGZoYXBweWJveHw2MGU0NGVjNS0zMDVjLTQzYzItOWExOS1iNGI4OWIxYWUyYTZ8NjBl\n"; + // xml += "NDRlYzUtMzA1Yy00M2MyLTlhMTktYjRiODliMWFlMmE2fDYwZTQ0ZWM1LTMwNWMtNDNjMi05YTE5\n"; + // xml += "LWI0Yjg5YjFhZTJhNnwwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDB8N2ZmZmZm\n"; + // xml += "ZmZ8N2ZmZmZmZmZ8MHwwfDgyMDAwfDQ1MGZlMzk0LTI5MDQtYzlhZC0yMTRjLWEwN2ViN2ZlZWMy\n"; + // xml += "OXwoTm8gRGVzY3JpcHRpb24pfDB8MTB8MA==\n"; + // ensureParse( + // "a common binary blob for object -> agent offline inv transfer", + // xml, + // expected, + // 1); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDXMLParsingObject_test_5") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDXMLParsingObject::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDXMLParsingObject::test<5>() + // { + // // test deeper nested levels + // LLSD level_5 = LLSD::emptyMap(); level_5["level_5"] = 42.f; + // LLSD level_4 = LLSD::emptyMap(); level_4["level_4"] = level_5; + // LLSD level_3 = LLSD::emptyMap(); level_3["level_3"] = level_4; + // LLSD level_2 = LLSD::emptyMap(); level_2["level_2"] = level_3; + // LLSD level_1 = LLSD::emptyMap(); level_1["level_1"] = level_2; + // LLSD level_0 = LLSD::emptyMap(); level_0["level_0"] = level_1; + + // LLSD v; + // v["deep"] = level_0; + + // ensureParse( + // "deep llsd xml map", + // "" + // "deep" + // "level_0" + // "level_1" + // "level_2" + // "level_3" + // "level_4" + // "level_542.0" + // "" + // "" + // "" + // "" + // "" + // "" + // "", + // v, + // 8); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_1") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<1>() + // { + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_2") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<2>() + // { + // ensureParse("valid undef", "!", LLSD(), 1); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_3") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<3>() + // { + // LLSD val = false; + // ensureParse("valid boolean false 0", "false", val, 1); + // ensureParse("valid boolean false 1", "f", val, 1); + // ensureParse("valid boolean false 2", "0", val, 1); + // ensureParse("valid boolean false 3", "F", val, 1); + // ensureParse("valid boolean false 4", "FALSE", val, 1); + // val = true; + // ensureParse("valid boolean true 0", "true", val, 1); + // ensureParse("valid boolean true 1", "t", val, 1); + // ensureParse("valid boolean true 2", "1", val, 1); + // ensureParse("valid boolean true 3", "T", val, 1); + // ensureParse("valid boolean true 4", "TRUE", val, 1); + + // val.clear(); + // ensureParse("invalid true", "TR", val, LLSDParser::PARSE_FAILURE); + // ensureParse("invalid false", "FAL", val, LLSDParser::PARSE_FAILURE); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_4") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<4>() + // { + // LLSD val = 123; + // ensureParse("valid integer", "i123", val, 1); + // val.clear(); + // ensureParse("invalid integer", "421", val, LLSDParser::PARSE_FAILURE); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_5") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<5>() + // { + // LLSD val = 456.7; + // ensureParse("valid real", "r456.7", val, 1); + // val.clear(); + // ensureParse("invalid real", "456.7", val, LLSDParser::PARSE_FAILURE); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_6") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<6>() + // { + // LLUUID id; + // LLSD val = id; + // ensureParse( + // "unparseable uuid", + // "u123", + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // id.generate(); + // val = id; + // std::string uuid_str("u"); + // uuid_str += id.asString(); + // ensureParse("valid uuid", uuid_str.c_str(), val, 1); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_7") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<7>() + // { + // LLSD val = std::string("foolish"); + // ensureParse("valid string 1", "\"foolish\"", val, 1); + // val = std::string("g'day"); + // ensureParse("valid string 2", "\"g'day\"", val, 1); + // val = std::string("have a \"nice\" day"); + // ensureParse("valid string 3", "'have a \"nice\" day'", val, 1); + // val = std::string("whatever"); + // ensureParse("valid string 4", "s(8)\"whatever\"", val, 1); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_8") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<8> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<8>() + // { + // ensureParse( + // "invalid string 1", + // "s(7)\"whatever\"", + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // ensureParse( + // "invalid string 2", + // "s(9)\"whatever\"", + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_9") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<9> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<9>() + // { + // LLSD val = LLURI("http://www.google.com"); + // ensureParse("valid uri", "l\"http://www.google.com\"", val, 1); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_10") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<10> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<10>() + // { + // LLSD val = LLDate("2007-12-28T09:22:53.10Z"); + // ensureParse("valid date", "d\"2007-12-28T09:22:53.10Z\"", val, 1); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_11") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<11> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<11>() + // { + // std::vector vec; + // vec.push_back((U8)'a'); vec.push_back((U8)'b'); vec.push_back((U8)'c'); + // vec.push_back((U8)'3'); vec.push_back((U8)'2'); vec.push_back((U8)'1'); + // LLSD val = vec; + // ensureParse("valid binary b64", "b64\"YWJjMzIx\"", val, 1); + // ensureParse("valid bainry b16", "b16\"616263333231\"", val, 1); + // ensureParse("valid bainry raw", "b(6)\"abc321\"", val, 1); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_12") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<12> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<12>() + // { + // ensureParse( + // "invalid -- binary length specified too long", + // "b(7)\"abc321\"", + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // ensureParse( + // "invalid -- binary length specified way too long", + // "b(1000000)\"abc321\"", + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_13") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<13> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<13>() + // { + // LLSD val; + // val["amy"] = 23; + // val["bob"] = LLSD(); + // val["cam"] = 1.23; + // ensureParse("simple map", "{'amy':i23,'bob':!,'cam':r1.23}", val, 4); + + // val["bob"] = LLSD::emptyMap(); + // val["bob"]["vehicle"] = std::string("bicycle"); + // ensureParse( + // "nested map", + // "{'amy':i23,'bob':{'vehicle':'bicycle'},'cam':r1.23}", + // val, + // 5); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_14") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<14> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<14>() + // { + // LLSD val; + // val.append(23); + // val.append(LLSD()); + // val.append(1.23); + // ensureParse("simple array", "[i23,!,r1.23]", val, 4); + // val[1] = LLSD::emptyArray(); + // val[1].append("bicycle"); + // ensureParse("nested array", "[i23,['bicycle'],r1.23]", val, 5); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_15") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<15> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<15>() + // { + // LLSD val; + // val["amy"] = 23; + // val["bob"]["dogs"] = LLSD::emptyArray(); + // val["bob"]["dogs"].append(LLSD::emptyMap()); + // val["bob"]["dogs"][0]["name"] = std::string("groove"); + // val["bob"]["dogs"][0]["breed"] = std::string("samoyed"); + // val["bob"]["dogs"].append(LLSD::emptyMap()); + // val["bob"]["dogs"][1]["name"] = std::string("greyley"); + // val["bob"]["dogs"][1]["breed"] = std::string("chow/husky"); + // val["cam"] = 1.23; + // ensureParse( + // "nested notation", + // "{'amy':i23," + // " 'bob':{'dogs':[" + // "{'name':'groove', 'breed':'samoyed'}," + // "{'name':'greyley', 'breed':'chow/husky'}]}," + // " 'cam':r1.23}", + // val, + // 11); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_16") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<16> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<16>() + // { + // // text to make sure that incorrect sizes bail because + // std::string bad_str("s(5)\"hi\""); + // ensureParse( + // "size longer than bytes left", + // bad_str, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_17") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<17> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<17>() + // { + // // text to make sure that incorrect sizes bail because + // std::string bad_bin("b(5)\"hi\""); + // ensureParse( + // "size longer than bytes left", + // bad_bin, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_18") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<18> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<18>() + // { + // LLSD level_1 = LLSD::emptyMap(); level_1["level_2"] = 99; + // LLSD level_0 = LLSD::emptyMap(); level_0["level_1"] = level_1; + + // LLSD deep = LLSD::emptyMap(); + // deep["level_0"] = level_0; + + // LLSD root = LLSD::emptyMap(); + // root["deep"] = deep; + + // ensureParse( + // "nested notation 3 deep", + // "{'deep' : {'level_0':{'level_1':{'level_2': i99} } } }", + // root, + // 5, + // 5); // 4 '{' plus i99 also counts as llsd, so real depth is 5 + // } + + // template<> template<> + // void TestLLSDNotationParsingObject::test<19>() + // { + // LLSD level_9 = LLSD::emptyMap(); level_9["level_9"] = (S32)99; + // LLSD level_8 = LLSD::emptyMap(); level_8["level_8"] = level_9; + // LLSD level_7 = LLSD::emptyMap(); level_7["level_7"] = level_8; + // LLSD level_6 = LLSD::emptyMap(); level_6["level_6"] = level_7; + // LLSD level_5 = LLSD::emptyMap(); level_5["level_5"] = level_6; + // LLSD level_4 = LLSD::emptyMap(); level_4["level_4"] = level_5; + // LLSD level_3 = LLSD::emptyMap(); level_3["level_3"] = level_4; + // LLSD level_2 = LLSD::emptyMap(); level_2["level_2"] = level_3; + // LLSD level_1 = LLSD::emptyMap(); level_1["level_1"] = level_2; + // LLSD level_0 = LLSD::emptyMap(); level_0["level_0"] = level_1; + + // LLSD deep = LLSD::emptyMap(); + // deep["deep"] = level_0; + + // ensureParse( + // "nested notation 10 deep", + // "{'deep' : {'level_0':{'level_1':{'level_2':{'level_3':{'level_4':{'level_5':{'level_6':{'level_7':{'level_8':{'level_9':i99}" + // "} } } } } } } } } }", + // deep, + // 12, + // 15); + // } + + // template<> template<> + // void TestLLSDNotationParsingObject::test<20>() + // { + // LLSD end = LLSD::emptyMap(); end["end"] = (S32)99; + + // LLSD level_49 = LLSD::emptyMap(); level_49["level_49"] = end; + // LLSD level_48 = LLSD::emptyMap(); level_48["level_48"] = level_49; + // LLSD level_47 = LLSD::emptyMap(); level_47["level_47"] = level_48; + // LLSD level_46 = LLSD::emptyMap(); level_46["level_46"] = level_47; + // LLSD level_45 = LLSD::emptyMap(); level_45["level_45"] = level_46; + // LLSD level_44 = LLSD::emptyMap(); level_44["level_44"] = level_45; + // LLSD level_43 = LLSD::emptyMap(); level_43["level_43"] = level_44; + // LLSD level_42 = LLSD::emptyMap(); level_42["level_42"] = level_43; + // LLSD level_41 = LLSD::emptyMap(); level_41["level_41"] = level_42; + // LLSD level_40 = LLSD::emptyMap(); level_40["level_40"] = level_41; + + // LLSD level_39 = LLSD::emptyMap(); level_39["level_39"] = level_40; + // LLSD level_38 = LLSD::emptyMap(); level_38["level_38"] = level_39; + // LLSD level_37 = LLSD::emptyMap(); level_37["level_37"] = level_38; + // LLSD level_36 = LLSD::emptyMap(); level_36["level_36"] = level_37; + // LLSD level_35 = LLSD::emptyMap(); level_35["level_35"] = level_36; + // LLSD level_34 = LLSD::emptyMap(); level_34["level_34"] = level_35; + // LLSD level_33 = LLSD::emptyMap(); level_33["level_33"] = level_34; + // LLSD level_32 = LLSD::emptyMap(); level_32["level_32"] = level_33; + // LLSD level_31 = LLSD::emptyMap(); level_31["level_31"] = level_32; + // LLSD level_30 = LLSD::emptyMap(); level_30["level_30"] = level_31; + + // LLSD level_29 = LLSD::emptyMap(); level_29["level_29"] = level_30; + // LLSD level_28 = LLSD::emptyMap(); level_28["level_28"] = level_29; + // LLSD level_27 = LLSD::emptyMap(); level_27["level_27"] = level_28; + // LLSD level_26 = LLSD::emptyMap(); level_26["level_26"] = level_27; + // LLSD level_25 = LLSD::emptyMap(); level_25["level_25"] = level_26; + // LLSD level_24 = LLSD::emptyMap(); level_24["level_24"] = level_25; + // LLSD level_23 = LLSD::emptyMap(); level_23["level_23"] = level_24; + // LLSD level_22 = LLSD::emptyMap(); level_22["level_22"] = level_23; + // LLSD level_21 = LLSD::emptyMap(); level_21["level_21"] = level_22; + // LLSD level_20 = LLSD::emptyMap(); level_20["level_20"] = level_21; + + // LLSD level_19 = LLSD::emptyMap(); level_19["level_19"] = level_20; + // LLSD level_18 = LLSD::emptyMap(); level_18["level_18"] = level_19; + // LLSD level_17 = LLSD::emptyMap(); level_17["level_17"] = level_18; + // LLSD level_16 = LLSD::emptyMap(); level_16["level_16"] = level_17; + // LLSD level_15 = LLSD::emptyMap(); level_15["level_15"] = level_16; + // LLSD level_14 = LLSD::emptyMap(); level_14["level_14"] = level_15; + // LLSD level_13 = LLSD::emptyMap(); level_13["level_13"] = level_14; + // LLSD level_12 = LLSD::emptyMap(); level_12["level_12"] = level_13; + // LLSD level_11 = LLSD::emptyMap(); level_11["level_11"] = level_12; + // LLSD level_10 = LLSD::emptyMap(); level_10["level_10"] = level_11; + + // LLSD level_9 = LLSD::emptyMap(); level_9["level_9"] = level_10; + // LLSD level_8 = LLSD::emptyMap(); level_8["level_8"] = level_9; + // LLSD level_7 = LLSD::emptyMap(); level_7["level_7"] = level_8; + // LLSD level_6 = LLSD::emptyMap(); level_6["level_6"] = level_7; + // LLSD level_5 = LLSD::emptyMap(); level_5["level_5"] = level_6; + // LLSD level_4 = LLSD::emptyMap(); level_4["level_4"] = level_5; + // LLSD level_3 = LLSD::emptyMap(); level_3["level_3"] = level_4; + // LLSD level_2 = LLSD::emptyMap(); level_2["level_2"] = level_3; + // LLSD level_1 = LLSD::emptyMap(); level_1["level_1"] = level_2; + // LLSD level_0 = LLSD::emptyMap(); level_0["level_0"] = level_1; + + // LLSD deep = LLSD::emptyMap(); + // deep["deep"] = level_0; + + // ensureParse( + // "nested notation deep", + // "{'deep':" + // "{'level_0' :{'level_1' :{'level_2' :{'level_3' :{'level_4' :{'level_5' :{'level_6' :{'level_7' :{'level_8' :{'level_9' :" + // "{'level_10':{'level_11':{'level_12':{'level_13':{'level_14':{'level_15':{'level_16':{'level_17':{'level_18':{'level_19':" + // "{'level_20':{'level_21':{'level_22':{'level_23':{'level_24':{'level_25':{'level_26':{'level_27':{'level_28':{'level_29':" + // "{'level_30':{'level_31':{'level_32':{'level_33':{'level_34':{'level_35':{'level_36':{'level_37':{'level_38':{'level_39':" + // "{'level_40':{'level_41':{'level_42':{'level_43':{'level_44':{'level_45':{'level_46':{'level_47':{'level_48':{'level_49':" + // "{'end':i99}" + // "} } } } } } } } } }" + // "} } } } } } } } } }" + // "} } } } } } } } } }" + // "} } } } } } } } } }" + // "} } } } } } } } } }" + // "}", + // deep, + // 53); + // } + + // template<> template<> + // void TestLLSDNotationParsingObject::test<21>() + // { + // ensureParse( + // "nested notation 10 deep", + // "{'deep' : {'level_0':{'level_1':{'level_2':{'level_3':{'level_4':{'level_5':{'level_6':{'level_7':{'level_8':{'level_9':i99}" + // "} } } } } } } } } }", + // LLSD(), + // LLSDParser::PARSE_FAILURE, + // 9); + // } + + // /** + // * @class TestLLSDBinaryParsing + // * @brief Concrete instance of a parse tester. + // */ + // class TestLLSDBinaryParsing : public TestLLSDParsing + // { + // public: + // TestLLSDBinaryParsing() {} + // }; + + // typedef tut::test_group TestLLSDBinaryParsingGroup; + // typedef TestLLSDBinaryParsingGroup::object TestLLSDBinaryParsingObject; + // TestLLSDBinaryParsingGroup gTestLLSDBinaryParsingGroup( + // "llsd binary parsing"); + + // template<> template<> + // void TestLLSDBinaryParsingObject::test<1>() + // { + // std::vector vec; + // vec.resize(6); + // vec[0] = 'a'; vec[1] = 'b'; vec[2] = 'c'; + // vec[3] = '3'; vec[4] = '2'; vec[5] = '1'; + // std::string string_expected((char*)&vec[0], vec.size()); + // LLSD value = string_expected; + + // vec.resize(11); + // vec[0] = 's'; // for string + // vec[5] = 'a'; vec[6] = 'b'; vec[7] = 'c'; + // vec[8] = '3'; vec[9] = '2'; vec[10] = '1'; + + // uint32_t size = htonl(6); + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_good((char*)&vec[0], vec.size()); + // ensureParse("correct string parse", str_good, value, 1); + + // size = htonl(7); + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_bad_1((char*)&vec[0], vec.size()); + // ensureParse( + // "incorrect size string parse", + // str_bad_1, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + + // size = htonl(100000); + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_bad_2((char*)&vec[0], vec.size()); + // ensureParse( + // "incorrect size string parse", + // str_bad_2, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // } + + // template<> template<> + // void TestLLSDBinaryParsingObject::test<2>() + // { + // std::vector vec; + // vec.resize(6); + // vec[0] = 'a'; vec[1] = 'b'; vec[2] = 'c'; + // vec[3] = '3'; vec[4] = '2'; vec[5] = '1'; + // LLSD value = vec; + + // vec.resize(11); + // vec[0] = 'b'; // for binary + // vec[5] = 'a'; vec[6] = 'b'; vec[7] = 'c'; + // vec[8] = '3'; vec[9] = '2'; vec[10] = '1'; + + // uint32_t size = htonl(6); + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_good((char*)&vec[0], vec.size()); + // ensureParse("correct binary parse", str_good, value, 1); + + // size = htonl(7); + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_bad_1((char*)&vec[0], vec.size()); + // ensureParse( + // "incorrect size binary parse 1", + // str_bad_1, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + + // size = htonl(100000); + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_bad_2((char*)&vec[0], vec.size()); + // ensureParse( + // "incorrect size binary parse 2", + // str_bad_2, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // } + + // template<> template<> + // void TestLLSDBinaryParsingObject::test<3>() + // { + // // test handling of xml not recognized as llsd results in an + // // LLSD Undefined + // ensureParse( + // "malformed binary map", + // "{'ha ha'", + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // ensureParse( + // "malformed binary array", + // "['ha ha'", + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // ensureParse( + // "malformed binary string", + // "'ha ha", + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // ensureParse( + // "bad noise", + // "g48ejlnfr", + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // } + // template<> template<> + // void TestLLSDBinaryParsingObject::test<4>() + // { + // ensureParse("valid undef", "!", LLSD(), 1); + // } + + // template<> template<> + // void TestLLSDBinaryParsingObject::test<5>() + // { + // LLSD val = false; + // ensureParse("valid boolean false 2", "0", val, 1); + // val = true; + // ensureParse("valid boolean true 2", "1", val, 1); + + // val.clear(); + // ensureParse("invalid true", "t", val, LLSDParser::PARSE_FAILURE); + // ensureParse("invalid false", "f", val, LLSDParser::PARSE_FAILURE); + // } + + // template<> template<> + // void TestLLSDBinaryParsingObject::test<6>() + // { + // std::vector vec; + // vec.push_back('{'); + // vec.resize(vec.size() + 4); + // uint32_t size = htonl(1); + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // vec.push_back('k'); + // auto key_size_loc = vec.size(); + // size = htonl(1); // 1 too short + // vec.resize(vec.size() + 4); + // memcpy(&vec[key_size_loc], &size, sizeof(uint32_t)); + // vec.push_back('a'); vec.push_back('m'); vec.push_back('y'); + // vec.push_back('i'); + // auto integer_loc = vec.size(); + // vec.resize(vec.size() + 4); + // uint32_t val_int = htonl(23); + // memcpy(&vec[integer_loc], &val_int, sizeof(uint32_t)); + // std::string str_bad_1((char*)&vec[0], vec.size()); + // ensureParse( + // "invalid key size", + // str_bad_1, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + + // // check with correct size, but unterminated map (missing '}') + // size = htonl(3); // correct size + // memcpy(&vec[key_size_loc], &size, sizeof(uint32_t)); + // std::string str_bad_2((char*)&vec[0], vec.size()); + // ensureParse( + // "valid key size, unterminated map", + // str_bad_2, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + + // // check w/ correct size and correct map termination + // LLSD val; + // val["amy"] = 23; + // vec.push_back('}'); + // std::string str_good((char*)&vec[0], vec.size()); + // ensureParse( + // "valid map", + // str_good, + // val, + // 2); + + // // check w/ incorrect sizes and correct map termination + // size = htonl(0); // 1 too few (for the map entry) + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_bad_3((char*)&vec[0], vec.size()); + // ensureParse( + // "invalid map too long", + // str_bad_3, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + + // size = htonl(2); // 1 too many + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_bad_4((char*)&vec[0], vec.size()); + // ensureParse( + // "invalid map too short", + // str_bad_4, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // } + + // template<> template<> + // void TestLLSDBinaryParsingObject::test<7>() + // { + // std::vector vec; + // vec.push_back('['); + // vec.resize(vec.size() + 4); + // uint32_t size = htonl(1); // 1 too short + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // vec.push_back('"'); vec.push_back('a'); vec.push_back('m'); + // vec.push_back('y'); vec.push_back('"'); vec.push_back('i'); + // auto integer_loc = vec.size(); + // vec.resize(vec.size() + 4); + // uint32_t val_int = htonl(23); + // memcpy(&vec[integer_loc], &val_int, sizeof(uint32_t)); + + // std::string str_bad_1((char*)&vec[0], vec.size()); + // ensureParse( + // "invalid array size", + // str_bad_1, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + + // // check with correct size, but unterminated map (missing ']') + // size = htonl(2); // correct size + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_bad_2((char*)&vec[0], vec.size()); + // ensureParse( + // "unterminated array", + // str_bad_2, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + + // // check w/ correct size and correct map termination + // LLSD val; + // val.append("amy"); + // val.append(23); + // vec.push_back(']'); + // std::string str_good((char*)&vec[0], vec.size()); + // ensureParse( + // "valid array", + // str_good, + // val, + // 3); + + // // check with too many elements + // size = htonl(3); // 1 too long + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_bad_3((char*)&vec[0], vec.size()); + // ensureParse( + // "array too short", + // str_bad_3, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // } + + // template<> template<> + // void TestLLSDBinaryParsingObject::test<8>() + // { + // std::vector vec; + // vec.push_back('{'); + // vec.resize(vec.size() + 4); + // memset(&vec[1], 0, 4); + // vec.push_back('}'); + // std::string str_good((char*)&vec[0], vec.size()); + // LLSD val = LLSD::emptyMap(); + // ensureParse( + // "empty map", + // str_good, + // val, + // 1); + // } + + // template<> template<> + // void TestLLSDBinaryParsingObject::test<9>() + // { + // std::vector vec; + // vec.push_back('['); + // vec.resize(vec.size() + 4); + // memset(&vec[1], 0, 4); + // vec.push_back(']'); + // std::string str_good((char*)&vec[0], vec.size()); + // LLSD val = LLSD::emptyArray(); + // ensureParse( + // "empty array", + // str_good, + // val, + // 1); + // } + + // template<> template<> + // void TestLLSDBinaryParsingObject::test<10>() + // { + // std::vector vec; + // vec.push_back('l'); + // vec.resize(vec.size() + 4); + // uint32_t size = htonl(14); // 1 too long + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // vec.push_back('h'); vec.push_back('t'); vec.push_back('t'); + // vec.push_back('p'); vec.push_back(':'); vec.push_back('/'); + // vec.push_back('/'); vec.push_back('s'); vec.push_back('l'); + // vec.push_back('.'); vec.push_back('c'); vec.push_back('o'); + // vec.push_back('m'); + // std::string str_bad((char*)&vec[0], vec.size()); + // ensureParse( + // "invalid uri length size", + // str_bad, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + + // LLSD val; + // val = LLURI("http://sl.com"); + // size = htonl(13); // correct length + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_good((char*)&vec[0], vec.size()); + // ensureParse( + // "valid key size", + // str_good, + // val, + // 1); + // } + + // /* + // template<> template<> + // void TestLLSDBinaryParsingObject::test<11>() + // { + // } + // */ + + // /** + // * @class TestLLSDCrossCompatible + // * @brief Miscellaneous serialization and parsing tests + // */ + // class TestLLSDCrossCompatible + // { + // public: + // TestLLSDCrossCompatible() {} + + // void ensureBinaryAndNotation( + // const std::string& msg, + // const LLSD& input) + // { + // // to binary, and back again + // std::stringstream str1; + // S32 count1 = LLSDSerialize::toBinary(input, str1); + // LLSD actual_value_bin; + // S32 count2 = LLSDSerialize::fromBinary( + // actual_value_bin, + // str1, + // LLSDSerialize::SIZE_UNLIMITED); + // ensure_equals( + // "ensureBinaryAndNotation binary count", + // count2, + // count1); + + // // to notation and back again + // std::stringstream str2; + // S32 count3 = LLSDSerialize::toNotation(actual_value_bin, str2); + // ensure_equals( + // "ensureBinaryAndNotation notation count1", + // count3, + // count2); + // LLSD actual_value_notation; + // S32 count4 = LLSDSerialize::fromNotation( + // actual_value_notation, + // str2, + // LLSDSerialize::SIZE_UNLIMITED); + // ensure_equals( + // "ensureBinaryAndNotation notation count2", + // count4, + // count3); + // ensure_equals( + // (msg + " (binaryandnotation)").c_str(), + // actual_value_notation, + // input); + // } + + // void ensureBinaryAndXML( + // const std::string& msg, + // const LLSD& input) + // { + // // to binary, and back again + // std::stringstream str1; + // S32 count1 = LLSDSerialize::toBinary(input, str1); + // LLSD actual_value_bin; + // S32 count2 = LLSDSerialize::fromBinary( + // actual_value_bin, + // str1, + // LLSDSerialize::SIZE_UNLIMITED); + // ensure_equals( + // "ensureBinaryAndXML binary count", + // count2, + // count1); + + // // to xml and back again + // std::stringstream str2; + // S32 count3 = LLSDSerialize::toXML(actual_value_bin, str2); + // ensure_equals( + // "ensureBinaryAndXML xml count1", + // count3, + // count2); + // LLSD actual_value_xml; + // S32 count4 = LLSDSerialize::fromXML(actual_value_xml, str2); + // ensure_equals( + // "ensureBinaryAndXML xml count2", + // count4, + // count3); + // ensure_equals((msg + " (binaryandxml)").c_str(), actual_value_xml, input); + // } + // }; + + // typedef tut::test_group TestLLSDCompatibleGroup; + // typedef TestLLSDCompatibleGroup::object TestLLSDCompatibleObject; + // TestLLSDCompatibleGroup gTestLLSDCompatibleGroup( + // "llsd serialize compatible"); + + // template<> template<> + // void TestLLSDCompatibleObject::test<1>() + // { + // LLSD test; + // ensureBinaryAndNotation("undef", test); + // ensureBinaryAndXML("undef", test); + // test = true; + // ensureBinaryAndNotation("boolean true", test); + // ensureBinaryAndXML("boolean true", test); + // test = false; + // ensureBinaryAndNotation("boolean false", test); + // ensureBinaryAndXML("boolean false", test); + // test = 0; + // ensureBinaryAndNotation("integer zero", test); + // ensureBinaryAndXML("integer zero", test); + // test = 1; + // ensureBinaryAndNotation("integer positive", test); + // ensureBinaryAndXML("integer positive", test); + // test = -234567; + // ensureBinaryAndNotation("integer negative", test); + // ensureBinaryAndXML("integer negative", test); + // test = 0.0; + // ensureBinaryAndNotation("real zero", test); + // ensureBinaryAndXML("real zero", test); + // test = 1.0; + // ensureBinaryAndNotation("real positive", test); + // ensureBinaryAndXML("real positive", test); + // test = -1.0; + // ensureBinaryAndNotation("real negative", test); + // ensureBinaryAndXML("real negative", test); + // } + + // template<> template<> + // void TestLLSDCompatibleObject::test<2>() + // { + // LLSD test; + // test = "foobar"; + // ensureBinaryAndNotation("string", test); + // ensureBinaryAndXML("string", test); + // } + + // template<> template<> + // void TestLLSDCompatibleObject::test<3>() + // { + // LLSD test; + // LLUUID id; + // id.generate(); + // test = id; + // ensureBinaryAndNotation("uuid", test); + // ensureBinaryAndXML("uuid", test); + // } + + // template<> template<> + // void TestLLSDCompatibleObject::test<4>() + // { + // LLSD test; + // test = LLDate(12345.0); + // ensureBinaryAndNotation("date", test); + // ensureBinaryAndXML("date", test); + // } + + // template<> template<> + // void TestLLSDCompatibleObject::test<5>() + // { + // LLSD test; + // test = LLURI("http://www.secondlife.com/"); + // ensureBinaryAndNotation("uri", test); + // ensureBinaryAndXML("uri", test); + // } + + // template<> template<> + // void TestLLSDCompatibleObject::test<6>() + // { + // LLSD test; + // typedef std::vector buf_t; + // buf_t val; + // for(int ii = 0; ii < 100; ++ii) + // { + // srand(ii); /* Flawfinder: ignore */ + // S32 size = rand() % 100 + 10; + // std::generate_n( + // std::back_insert_iterator(val), + // size, + // rand); + // } + // test = val; + // ensureBinaryAndNotation("binary", test); + // ensureBinaryAndXML("binary", test); + // } + + // template<> template<> + // void TestLLSDCompatibleObject::test<7>() + // { + // LLSD test; + // test = LLSD::emptyArray(); + // test.append(1); + // test.append("hello"); + // ensureBinaryAndNotation("array", test); + // ensureBinaryAndXML("array", test); + // } + + // template<> template<> + // void TestLLSDCompatibleObject::test<8>() + // { + // LLSD test; + // test = LLSD::emptyArray(); + // test["foo"] = "bar"; + // test["baz"] = 100; + // ensureBinaryAndNotation("map", test); + // ensureBinaryAndXML("map", test); + // } + + // // helper for TestPythonCompatible + // static std::string import_llsd("import os.path\n" + // "import sys\n" + // "import llsd\n"); + + // // helper for TestPythonCompatible + // template + // void python_expect(const std::string& desc, const CONTENT& script, int expect=0, + // ARGS&&... args) + // { + // auto PYTHON(LLStringUtil::getenv("PYTHON")); + // ensure("Set $PYTHON to the Python interpreter", !PYTHON.empty()); + + // NamedTempFile scriptfile("py", script); + + // #if LL_WINDOWS + // std::string q("\""); + // std::string qPYTHON(q + PYTHON + q); + // std::string qscript(q + scriptfile.getName() + q); + // int rc = (int)_spawnl(_P_WAIT, PYTHON.c_str(), qPYTHON.c_str(), qscript.c_str(), + // std::forward(args)..., NULL); + // if (rc == -1) + // { + // char buffer[256]; + // strerror_s(buffer, errno); // C++ can infer the buffer size! :-O + // ensure(STRINGIZE("Couldn't run Python " << desc << "script: " << buffer), false); + // } + // else + // { + // ensure_equals(STRINGIZE(desc << " script terminated with rc " << rc), rc, expect); + // } + + // #else // LL_DARWIN, LL_LINUX + // LLProcess::Params params; + // params.executable = PYTHON; + // params.args.add(scriptfile.getName()); + // for (const std::string& arg : StringVec{ std::forward(args)... }) + // { + // params.args.add(arg); + // } + // LLProcessPtr py(LLProcess::create(params)); + // ensure(STRINGIZE("Couldn't launch " << desc << " script"), bool(py)); + // // Implementing timeout would mean messing with alarm() and + // // catching SIGALRM... later maybe... + // int status(0); + // if (waitpid(py->getProcessID(), &status, 0) == -1) + // { + // int waitpid_errno(errno); + // ensure_equals(STRINGIZE("Couldn't retrieve rc from " << desc << " script: " + // "waitpid() errno " << waitpid_errno), + // waitpid_errno, ECHILD); + // } + // else + // { + // if (WIFEXITED(status)) + // { + // int rc(WEXITSTATUS(status)); + // ensure_equals(STRINGIZE(desc << " script terminated with rc " << rc), + // rc, expect); + // } + // else if (WIFSIGNALED(status)) + // { + // ensure(STRINGIZE(desc << " script terminated by signal " << WTERMSIG(status)), + // false); + // } + // else + // { + // ensure(STRINGIZE(desc << " script produced impossible status " << status), + // false); + // } + // } + // #endif + // } + + // // helper for TestPythonCompatible + // template + // void python(const std::string& desc, const CONTENT& script, ARGS&&... args) + // { + // // plain python() expects rc 0 + // python_expect(desc, script, 0, std::forward(args)...); + // } + + // struct TestPythonCompatible + // { + // TestPythonCompatible() {} + // ~TestPythonCompatible() {} + // }; + + // typedef tut::test_group TestPythonCompatibleGroup; + // typedef TestPythonCompatibleGroup::object TestPythonCompatibleObject; + // TestPythonCompatibleGroup pycompat("LLSD serialize Python compatibility"); + + // template<> template<> + // void TestPythonCompatibleObject::test<1>() + // { + // set_test_name("verify python()"); + // python_expect("hello", + // "import sys\n" + // "sys.exit(17)\n", + // 17); // expect nonzero rc + // } + + // template<> template<> + // void TestPythonCompatibleObject::test<2>() + // { + // set_test_name("verify NamedTempFile"); + // python("platform", + // "import sys\n" + // "print('Running on', sys.platform)\n"); + // } + + // // helper for test<3> - test<7> + // static void writeLLSDArray(const FormatterFunction& serialize, + // std::ostream& out, const LLSD& array) + // { + // for (const LLSD& item: llsd::inArray(array)) + // { + // // It's important to delimit the entries in this file somehow + // // because, although Python's llsd.parse() can accept a file + // // stream, the XML parser expects EOF after a single outer element + // // -- it doesn't just stop. So we must extract a sequence of bytes + // // strings from the file. But since one of the serialization + // // formats we want to test is binary, we can't pick any single + // // byte value as a delimiter! Use a binary integer length prefix + // // instead. + // std::ostringstream buffer; + // serialize(item, buffer); + // auto buffstr{ buffer.str() }; + // int bufflen{ static_cast(buffstr.length()) }; + // out.write(reinterpret_cast(&bufflen), sizeof(bufflen)); + // LL_DEBUGS() << "Wrote length: " + // << hexdump(reinterpret_cast(&bufflen), + // sizeof(bufflen)) + // << LL_ENDL; + // out.write(buffstr.c_str(), buffstr.length()); + // LL_DEBUGS() << "Wrote data: " + // << hexmix(buffstr.c_str(), buffstr.length()) + // << LL_ENDL; + // } + // } + + // // helper for test<3> - test<7> + // static void toPythonUsing(const std::string& desc, + // const FormatterFunction& serialize) + // { + // LLSD cdata(llsd::array(17, 3.14, + // "This string\n" + // "has several\n" + // "lines.")); + + // const char pydata[] = + // "def verify(iterable):\n" + // " it = iter(iterable)\n" + // " assert next(it) == 17\n" + // " assert abs(next(it) - 3.14) < 0.01\n" + // " assert next(it) == '''\\\n" + // "This string\n" + // "has several\n" + // "lines.'''\n" + // " try:\n" + // " next(it)\n" + // " except StopIteration:\n" + // " pass\n" + // " else:\n" + // " raise AssertionError('Too many data items')\n"; + + // // Create an llsdXXXXXX file containing 'data' serialized per + // // FormatterFunction. + // NamedTempFile file("llsd", + // // NamedTempFile's function constructor + // // takes a callable. To this callable it passes the + // // std::ostream with which it's writing the + // // NamedTempFile. + // [serialize, cdata] + // (std::ostream& out) + // { writeLLSDArray(serialize, out, cdata); }); + + // // 'debug' starts empty because it's intended as an output file + // NamedTempFile debug("debug", ""); + + // try + // { + // python("read C++ " + desc, + // [&](std::ostream& out){ out << + // import_llsd << + // "from functools import partial\n" + // "import io\n" + // "import struct\n" + // "lenformat = struct.Struct('i')\n" + // "def parse_each(inf):\n" + // " for rawlen in iter(partial(inf.read, lenformat.size), b''):\n" + // " print('Read length:', ''.join(('%02x' % b) for b in rawlen),\n" + // " file=debug)\n" + // " len = lenformat.unpack(rawlen)[0]\n" + // // Since llsd.parse() has no max_bytes argument, instead of + // // passing the input stream directly to parse(), read the item + // // into a distinct bytes object and parse that. + // " data = inf.read(len)\n" + // " print('Read data: ', repr(data), file=debug)\n" + // " try:\n" + // " frombytes = llsd.parse(data)\n" + // " except llsd.LLSDParseError as err:\n" + // " print(f'*** {err}')\n" + // " print(f'Bad content:\\n{data!r}')\n" + // " raise\n" + // // Also try parsing from a distinct stream. + // " stream = io.BytesIO(data)\n" + // " fromstream = llsd.parse(stream)\n" + // " assert frombytes == fromstream\n" + // " yield frombytes\n" + // << pydata << + // // Don't forget raw-string syntax for Windows pathnames. + // "debug = open(r'" << debug.getName() << "', 'w')\n" + // "verify(parse_each(open(r'" << file.getName() << "', 'rb')))\n";}); + // } + // catch (const failure&) + // { + // LL_DEBUGS() << "Script debug output:" << LL_ENDL; + // debug.peep_log(); + // throw; + // } + // } + + // template<> template<> + // void TestPythonCompatibleObject::test<3>() + // { + // set_test_name("to Python using LLSDSerialize::serialize(LLSD_XML)"); + // toPythonUsing("LLSD_XML", + // [](const LLSD& sd, std::ostream& out) + // { LLSDSerialize::serialize(sd, out, LLSDSerialize::LLSD_XML); }); + // } + + // template<> template<> + // void TestPythonCompatibleObject::test<4>() + // { + // set_test_name("to Python using LLSDSerialize::serialize(LLSD_NOTATION)"); + // toPythonUsing("LLSD_NOTATION", + // [](const LLSD& sd, std::ostream& out) + // { LLSDSerialize::serialize(sd, out, LLSDSerialize::LLSD_NOTATION); }); + // } + + // template<> template<> + // void TestPythonCompatibleObject::test<5>() + // { + // set_test_name("to Python using LLSDSerialize::serialize(LLSD_BINARY)"); + // toPythonUsing("LLSD_BINARY", + // [](const LLSD& sd, std::ostream& out) + // { LLSDSerialize::serialize(sd, out, LLSDSerialize::LLSD_BINARY); }); + // } + + // template<> template<> + // void TestPythonCompatibleObject::test<6>() + // { + // set_test_name("to Python using LLSDSerialize::toXML()"); + // toPythonUsing("toXML()", LLSDSerialize::toXML); + // } + + // template<> template<> + // void TestPythonCompatibleObject::test<7>() + // { + // set_test_name("to Python using LLSDSerialize::toNotation()"); + // toPythonUsing("toNotation()", LLSDSerialize::toNotation); + // } + + // /*==========================================================================*| + // template<> template<> + // void TestPythonCompatibleObject::test<8>() + // { + // set_test_name("to Python using LLSDSerialize::toBinary()"); + // // We don't expect this to work because, without a header, + // // llsd.parse() will assume notation rather than binary. + // toPythonUsing("toBinary()", LLSDSerialize::toBinary); + // } + // |*==========================================================================*/ + + // // helper for test<8> - test<12> + // bool itemFromStream(std::istream& istr, LLSD& item, const ParserFunction& parse) + // { + // // reset the output value for debugging clarity + // item.clear(); + // // We use an int length prefix as a foolproof delimiter even for + // // binary serialized streams. + // int length{ 0 }; + // istr.read(reinterpret_cast(&length), sizeof(length)); + // // return parse(istr, item, length); + // // Sadly, as of 2022-12-01 it seems we can't really trust our LLSD + // // parsers to honor max_bytes: this test works better when we read + // // each item into its own distinct LLMemoryStream, instead of passing + // // the original istr with a max_bytes constraint. + // std::vector buffer(length); + // istr.read(reinterpret_cast(buffer.data()), length); + // LLMemoryStream stream(buffer.data(), length); + // return parse(stream, item, length); + // } + + // // helper for test<8> - test<12> + // void fromPythonUsing(const std::string& pyformatter, + // const ParserFunction& parse= + // [](std::istream& istr, LLSD& data, llssize max_bytes) + // { return LLSDSerialize::deserialize(data, istr, max_bytes); }) + // { + // // Create an empty data file. This is just a placeholder for our + // // script to write into. Create it to establish a unique name that + // // we know. + // NamedTempFile file("llsd", ""); + + // python("Python " + pyformatter, + // [&](std::ostream& out){ out << + // import_llsd << + // "import struct\n" + // "lenformat = struct.Struct('i')\n" + // "DATA = [\n" + // " 17,\n" + // " 3.14,\n" + // " '''\\\n" + // "This string\n" + // "has several\n" + // "lines.''',\n" + // "]\n" + // // Don't forget raw-string syntax for Windows pathnames. + // // N.B. Using 'print' implicitly adds newlines. + // "with open(r'" << file.getName() << "', 'wb') as f:\n" + // " for item in DATA:\n" + // " serialized = llsd." << pyformatter << "(item)\n" + // " f.write(lenformat.pack(len(serialized)))\n" + // " f.write(serialized)\n";}); + + // std::ifstream inf(file.getName().c_str()); + // LLSD item; + // try + // { + // ensure("Failed to read LLSD::Integer from Python", + // itemFromStream(inf, item, parse)); + // ensure_equals(item.asInteger(), 17); + // ensure("Failed to read LLSD::Real from Python", + // itemFromStream(inf, item, parse)); + // ensure_approximately_equals("Bad LLSD::Real value from Python", + // item.asReal(), 3.14, 7); // 7 bits ~= 0.01 + // ensure("Failed to read LLSD::String from Python", + // itemFromStream(inf, item, parse)); + // ensure_equals(item.asString(), + // "This string\n" + // "has several\n" + // "lines."); + // } + // catch (const tut::failure& err) + // { + // std::cout << "for " << err.what() << ", item = " << item << std::endl; + // throw; + // } + // } + + // template<> template<> + // void TestPythonCompatibleObject::test<8>() + // { + // set_test_name("from Python XML using LLSDSerialize::deserialize()"); + // fromPythonUsing("format_xml"); + // } + + // template<> template<> + // void TestPythonCompatibleObject::test<9>() + // { + // set_test_name("from Python notation using LLSDSerialize::deserialize()"); + // fromPythonUsing("format_notation"); + // } + + // template<> template<> + // void TestPythonCompatibleObject::test<10>() + // { + // set_test_name("from Python binary using LLSDSerialize::deserialize()"); + // fromPythonUsing("format_binary"); + // } + + // template<> template<> + // void TestPythonCompatibleObject::test<11>() + // { + // set_test_name("from Python XML using fromXML()"); + // // fromXML()'s optional 3rd param isn't max_bytes, it's emit_errors + // fromPythonUsing("format_xml", + // [](std::istream& istr, LLSD& data, llssize) + // { return LLSDSerialize::fromXML(data, istr) > 0; }); + // } + + // template<> template<> + // void TestPythonCompatibleObject::test<12>() + // { + // set_test_name("from Python notation using fromNotation()"); + // fromPythonUsing("format_notation", + // [](std::istream& istr, LLSD& data, llssize max_bytes) + // { return LLSDSerialize::fromNotation(data, istr, max_bytes) > 0; }); + // } + + // /*==========================================================================*| + // template<> template<> + // void TestPythonCompatibleObject::test<13>() + // { + // set_test_name("from Python binary using fromBinary()"); + // // We don't expect this to work because format_binary() emits a + // // header, but fromBinary() won't recognize a header. + // fromPythonUsing("format_binary", + // [](std::istream& istr, LLSD& data, llssize max_bytes) + // { return LLSDSerialize::fromBinary(data, istr, max_bytes) > 0; }); + // } + // |*==========================================================================*/ + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_19") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<19> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<19>() + // { + // LLSD level_9 = LLSD::emptyMap(); level_9["level_9"] = (S32)99; + // LLSD level_8 = LLSD::emptyMap(); level_8["level_8"] = level_9; + // LLSD level_7 = LLSD::emptyMap(); level_7["level_7"] = level_8; + // LLSD level_6 = LLSD::emptyMap(); level_6["level_6"] = level_7; + // LLSD level_5 = LLSD::emptyMap(); level_5["level_5"] = level_6; + // LLSD level_4 = LLSD::emptyMap(); level_4["level_4"] = level_5; + // LLSD level_3 = LLSD::emptyMap(); level_3["level_3"] = level_4; + // LLSD level_2 = LLSD::emptyMap(); level_2["level_2"] = level_3; + // LLSD level_1 = LLSD::emptyMap(); level_1["level_1"] = level_2; + // LLSD level_0 = LLSD::emptyMap(); level_0["level_0"] = level_1; + + // LLSD deep = LLSD::emptyMap(); + // deep["deep"] = level_0; + + // ensureParse( + // "nested notation 10 deep", + // "{'deep' : {'level_0':{'level_1':{'level_2':{'level_3':{'level_4':{'level_5':{'level_6':{'level_7':{'level_8':{'level_9':i99}" + // "} } } } } } } } } }", + // deep, + // 12, + // 15); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_20") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<20> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<20>() + // { + // LLSD end = LLSD::emptyMap(); end["end"] = (S32)99; + + // LLSD level_49 = LLSD::emptyMap(); level_49["level_49"] = end; + // LLSD level_48 = LLSD::emptyMap(); level_48["level_48"] = level_49; + // LLSD level_47 = LLSD::emptyMap(); level_47["level_47"] = level_48; + // LLSD level_46 = LLSD::emptyMap(); level_46["level_46"] = level_47; + // LLSD level_45 = LLSD::emptyMap(); level_45["level_45"] = level_46; + // LLSD level_44 = LLSD::emptyMap(); level_44["level_44"] = level_45; + // LLSD level_43 = LLSD::emptyMap(); level_43["level_43"] = level_44; + // LLSD level_42 = LLSD::emptyMap(); level_42["level_42"] = level_43; + // LLSD level_41 = LLSD::emptyMap(); level_41["level_41"] = level_42; + // LLSD level_40 = LLSD::emptyMap(); level_40["level_40"] = level_41; + + // LLSD level_39 = LLSD::emptyMap(); level_39["level_39"] = level_40; + // LLSD level_38 = LLSD::emptyMap(); level_38["level_38"] = level_39; + // LLSD level_37 = LLSD::emptyMap(); level_37["level_37"] = level_38; + // LLSD level_36 = LLSD::emptyMap(); level_36["level_36"] = level_37; + // LLSD level_35 = LLSD::emptyMap(); level_35["level_35"] = level_36; + // LLSD level_34 = LLSD::emptyMap(); level_34["level_34"] = level_35; + // LLSD level_33 = LLSD::emptyMap(); level_33["level_33"] = level_34; + // LLSD level_32 = LLSD::emptyMap(); level_32["level_32"] = level_33; + // LLSD level_31 = LLSD::emptyMap(); level_31["level_31"] = level_32; + // LLSD level_30 = LLSD::emptyMap(); level_30["level_30"] = level_31; + + // LLSD level_29 = LLSD::emptyMap(); level_29["level_29"] = level_30; + // LLSD level_28 = LLSD::emptyMap(); level_28["level_28"] = level_29; + // LLSD level_27 = LLSD::emptyMap(); level_27["level_27"] = level_28; + // LLSD level_26 = LLSD::emptyMap(); level_26["level_26"] = level_27; + // LLSD level_25 = LLSD::emptyMap(); level_25["level_25"] = level_26; + // LLSD level_24 = LLSD::emptyMap(); level_24["level_24"] = level_25; + // LLSD level_23 = LLSD::emptyMap(); level_23["level_23"] = level_24; + // LLSD level_22 = LLSD::emptyMap(); level_22["level_22"] = level_23; + // LLSD level_21 = LLSD::emptyMap(); level_21["level_21"] = level_22; + // LLSD level_20 = LLSD::emptyMap(); level_20["level_20"] = level_21; + + // LLSD level_19 = LLSD::emptyMap(); level_19["level_19"] = level_20; + // LLSD level_18 = LLSD::emptyMap(); level_18["level_18"] = level_19; + // LLSD level_17 = LLSD::emptyMap(); level_17["level_17"] = level_18; + // LLSD level_16 = LLSD::emptyMap(); level_16["level_16"] = level_17; + // LLSD level_15 = LLSD::emptyMap(); level_15["level_15"] = level_16; + // LLSD level_14 = LLSD::emptyMap(); level_14["level_14"] = level_15; + // LLSD level_13 = LLSD::emptyMap(); level_13["level_13"] = level_14; + // LLSD level_12 = LLSD::emptyMap(); level_12["level_12"] = level_13; + // LLSD level_11 = LLSD::emptyMap(); level_11["level_11"] = level_12; + // LLSD level_10 = LLSD::emptyMap(); level_10["level_10"] = level_11; + + // LLSD level_9 = LLSD::emptyMap(); level_9["level_9"] = level_10; + // LLSD level_8 = LLSD::emptyMap(); level_8["level_8"] = level_9; + // LLSD level_7 = LLSD::emptyMap(); level_7["level_7"] = level_8; + // LLSD level_6 = LLSD::emptyMap(); level_6["level_6"] = level_7; + // LLSD level_5 = LLSD::emptyMap(); level_5["level_5"] = level_6; + // LLSD level_4 = LLSD::emptyMap(); level_4["level_4"] = level_5; + // LLSD level_3 = LLSD::emptyMap(); level_3["level_3"] = level_4; + // LLSD level_2 = LLSD::emptyMap(); level_2["level_2"] = level_3; + // LLSD level_1 = LLSD::emptyMap(); level_1["level_1"] = level_2; + // LLSD level_0 = LLSD::emptyMap(); level_0["level_0"] = level_1; + + // LLSD deep = LLSD::emptyMap(); + // deep["deep"] = level_0; + + // ensureParse( + // "nested notation deep", + // "{'deep':" + // "{'level_0' :{'level_1' :{'level_2' :{'level_3' :{'level_4' :{'level_5' :{'level_6' :{'level_7' :{'level_8' :{'level_9' :" + // "{'level_10':{'level_11':{'level_12':{'level_13':{'level_14':{'level_15':{'level_16':{'level_17':{'level_18':{'level_19':" + // "{'level_20':{'level_21':{'level_22':{'level_23':{'level_24':{'level_25':{'level_26':{'level_27':{'level_28':{'level_29':" + // "{'level_30':{'level_31':{'level_32':{'level_33':{'level_34':{'level_35':{'level_36':{'level_37':{'level_38':{'level_39':" + // "{'level_40':{'level_41':{'level_42':{'level_43':{'level_44':{'level_45':{'level_46':{'level_47':{'level_48':{'level_49':" + // "{'end':i99}" + // "} } } } } } } } } }" + // "} } } } } } } } } }" + // "} } } } } } } } } }" + // "} } } } } } } } } }" + // "} } } } } } } } } }" + // "}", + // deep, + // 53); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDNotationParsingObject_test_21") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDNotationParsingObject::test<21> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDNotationParsingObject::test<21>() + // { + // ensureParse( + // "nested notation 10 deep", + // "{'deep' : {'level_0':{'level_1':{'level_2':{'level_3':{'level_4':{'level_5':{'level_6':{'level_7':{'level_8':{'level_9':i99}" + // "} } } } } } } } } }", + // LLSD(), + // LLSDParser::PARSE_FAILURE, + // 9); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDBinaryParsingObject_test_1") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDBinaryParsingObject::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDBinaryParsingObject::test<1>() + // { + // std::vector vec; + // vec.resize(6); + // vec[0] = 'a'; vec[1] = 'b'; vec[2] = 'c'; + // vec[3] = '3'; vec[4] = '2'; vec[5] = '1'; + // std::string string_expected((char*)&vec[0], vec.size()); + // LLSD value = string_expected; + + // vec.resize(11); + // vec[0] = 's'; // for string + // vec[5] = 'a'; vec[6] = 'b'; vec[7] = 'c'; + // vec[8] = '3'; vec[9] = '2'; vec[10] = '1'; + + // uint32_t size = htonl(6); + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_good((char*)&vec[0], vec.size()); + // ensureParse("correct string parse", str_good, value, 1); + + // size = htonl(7); + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_bad_1((char*)&vec[0], vec.size()); + // ensureParse( + // "incorrect size string parse", + // str_bad_1, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + + // size = htonl(100000); + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_bad_2((char*)&vec[0], vec.size()); + // ensureParse( + // "incorrect size string parse", + // str_bad_2, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDBinaryParsingObject_test_2") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDBinaryParsingObject::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDBinaryParsingObject::test<2>() + // { + // std::vector vec; + // vec.resize(6); + // vec[0] = 'a'; vec[1] = 'b'; vec[2] = 'c'; + // vec[3] = '3'; vec[4] = '2'; vec[5] = '1'; + // LLSD value = vec; + + // vec.resize(11); + // vec[0] = 'b'; // for binary + // vec[5] = 'a'; vec[6] = 'b'; vec[7] = 'c'; + // vec[8] = '3'; vec[9] = '2'; vec[10] = '1'; + + // uint32_t size = htonl(6); + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_good((char*)&vec[0], vec.size()); + // ensureParse("correct binary parse", str_good, value, 1); + + // size = htonl(7); + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_bad_1((char*)&vec[0], vec.size()); + // ensureParse( + // "incorrect size binary parse 1", + // str_bad_1, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + + // size = htonl(100000); + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_bad_2((char*)&vec[0], vec.size()); + // ensureParse( + // "incorrect size binary parse 2", + // str_bad_2, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDBinaryParsingObject_test_3") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDBinaryParsingObject::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDBinaryParsingObject::test<3>() + // { + // // test handling of xml not recognized as llsd results in an + // // LLSD Undefined + // ensureParse( + // "malformed binary map", + // "{'ha ha'", + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // ensureParse( + // "malformed binary array", + // "['ha ha'", + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // ensureParse( + // "malformed binary string", + // "'ha ha", + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // ensureParse( + // "bad noise", + // "g48ejlnfr", + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // } + // template<> template<> + // void TestLLSDBinaryParsingObject::test<4>() + // { + // ensureParse("valid undef", "!", LLSD(), 1); + // } + + // template<> template<> + // void TestLLSDBinaryParsingObject::test<5>() + // { + // LLSD val = false; + // ensureParse("valid boolean false 2", "0", val, 1); + // val = true; + // ensureParse("valid boolean true 2", "1", val, 1); + + // val.clear(); + // ensureParse("invalid true", "t", val, LLSDParser::PARSE_FAILURE); + // ensureParse("invalid false", "f", val, LLSDParser::PARSE_FAILURE); + // } + + // template<> template<> + // void TestLLSDBinaryParsingObject::test<6>() + // { + // std::vector vec; + // vec.push_back('{'); + // vec.resize(vec.size() + 4); + // uint32_t size = htonl(1); + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // vec.push_back('k'); + // auto key_size_loc = vec.size(); + // size = htonl(1); // 1 too short + // vec.resize(vec.size() + 4); + // memcpy(&vec[key_size_loc], &size, sizeof(uint32_t)); + // vec.push_back('a'); vec.push_back('m'); vec.push_back('y'); + // vec.push_back('i'); + // auto integer_loc = vec.size(); + // vec.resize(vec.size() + 4); + // uint32_t val_int = htonl(23); + // memcpy(&vec[integer_loc], &val_int, sizeof(uint32_t)); + // std::string str_bad_1((char*)&vec[0], vec.size()); + // ensureParse( + // "invalid key size", + // str_bad_1, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + + // // check with correct size, but unterminated map (missing '}') + // size = htonl(3); // correct size + // memcpy(&vec[key_size_loc], &size, sizeof(uint32_t)); + // std::string str_bad_2((char*)&vec[0], vec.size()); + // ensureParse( + // "valid key size, unterminated map", + // str_bad_2, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + + // // check w/ correct size and correct map termination + // LLSD val; + // val["amy"] = 23; + // vec.push_back('}'); + // std::string str_good((char*)&vec[0], vec.size()); + // ensureParse( + // "valid map", + // str_good, + // val, + // 2); + + // // check w/ incorrect sizes and correct map termination + // size = htonl(0); // 1 too few (for the map entry) + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_bad_3((char*)&vec[0], vec.size()); + // ensureParse( + // "invalid map too long", + // str_bad_3, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + + // size = htonl(2); // 1 too many + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_bad_4((char*)&vec[0], vec.size()); + // ensureParse( + // "invalid map too short", + // str_bad_4, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDBinaryParsingObject_test_4") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDBinaryParsingObject::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDBinaryParsingObject::test<4>() + // { + // ensureParse("valid undef", "!", LLSD(), 1); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDBinaryParsingObject_test_5") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDBinaryParsingObject::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDBinaryParsingObject::test<5>() + // { + // LLSD val = false; + // ensureParse("valid boolean false 2", "0", val, 1); + // val = true; + // ensureParse("valid boolean true 2", "1", val, 1); + + // val.clear(); + // ensureParse("invalid true", "t", val, LLSDParser::PARSE_FAILURE); + // ensureParse("invalid false", "f", val, LLSDParser::PARSE_FAILURE); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDBinaryParsingObject_test_6") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDBinaryParsingObject::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDBinaryParsingObject::test<6>() + // { + // std::vector vec; + // vec.push_back('{'); + // vec.resize(vec.size() + 4); + // uint32_t size = htonl(1); + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // vec.push_back('k'); + // auto key_size_loc = vec.size(); + // size = htonl(1); // 1 too short + // vec.resize(vec.size() + 4); + // memcpy(&vec[key_size_loc], &size, sizeof(uint32_t)); + // vec.push_back('a'); vec.push_back('m'); vec.push_back('y'); + // vec.push_back('i'); + // auto integer_loc = vec.size(); + // vec.resize(vec.size() + 4); + // uint32_t val_int = htonl(23); + // memcpy(&vec[integer_loc], &val_int, sizeof(uint32_t)); + // std::string str_bad_1((char*)&vec[0], vec.size()); + // ensureParse( + // "invalid key size", + // str_bad_1, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + + // // check with correct size, but unterminated map (missing '}') + // size = htonl(3); // correct size + // memcpy(&vec[key_size_loc], &size, sizeof(uint32_t)); + // std::string str_bad_2((char*)&vec[0], vec.size()); + // ensureParse( + // "valid key size, unterminated map", + // str_bad_2, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + + // // check w/ correct size and correct map termination + // LLSD val; + // val["amy"] = 23; + // vec.push_back('} + } + + TUT_CASE("llsdserialize_test::TestLLSDBinaryParsingObject_test_7") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDBinaryParsingObject::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDBinaryParsingObject::test<7>() + // { + // std::vector vec; + // vec.push_back('['); + // vec.resize(vec.size() + 4); + // uint32_t size = htonl(1); // 1 too short + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // vec.push_back('"'); vec.push_back('a'); vec.push_back('m'); + // vec.push_back('y'); vec.push_back('"'); vec.push_back('i'); + // auto integer_loc = vec.size(); + // vec.resize(vec.size() + 4); + // uint32_t val_int = htonl(23); + // memcpy(&vec[integer_loc], &val_int, sizeof(uint32_t)); + + // std::string str_bad_1((char*)&vec[0], vec.size()); + // ensureParse( + // "invalid array size", + // str_bad_1, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + + // // check with correct size, but unterminated map (missing ']') + // size = htonl(2); // correct size + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_bad_2((char*)&vec[0], vec.size()); + // ensureParse( + // "unterminated array", + // str_bad_2, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + + // // check w/ correct size and correct map termination + // LLSD val; + // val.append("amy"); + // val.append(23); + // vec.push_back(']'); + // std::string str_good((char*)&vec[0], vec.size()); + // ensureParse( + // "valid array", + // str_good, + // val, + // 3); + + // // check with too many elements + // size = htonl(3); // 1 too long + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_bad_3((char*)&vec[0], vec.size()); + // ensureParse( + // "array too short", + // str_bad_3, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDBinaryParsingObject_test_8") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDBinaryParsingObject::test<8> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDBinaryParsingObject::test<8>() + // { + // std::vector vec; + // vec.push_back('{'); + // vec.resize(vec.size() + 4); + // memset(&vec[1], 0, 4); + // vec.push_back('}'); + // std::string str_good((char*)&vec[0], vec.size()); + // LLSD val = LLSD::emptyMap(); + // ensureParse( + // "empty map", + // str_good, + // val, + // 1); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDBinaryParsingObject_test_9") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDBinaryParsingObject::test<9> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDBinaryParsingObject::test<9>() + // { + // std::vector vec; + // vec.push_back('['); + // vec.resize(vec.size() + 4); + // memset(&vec[1], 0, 4); + // vec.push_back(']'); + // std::string str_good((char*)&vec[0], vec.size()); + // LLSD val = LLSD::emptyArray(); + // ensureParse( + // "empty array", + // str_good, + // val, + // 1); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDBinaryParsingObject_test_10") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDBinaryParsingObject::test<10> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDBinaryParsingObject::test<10>() + // { + // std::vector vec; + // vec.push_back('l'); + // vec.resize(vec.size() + 4); + // uint32_t size = htonl(14); // 1 too long + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // vec.push_back('h'); vec.push_back('t'); vec.push_back('t'); + // vec.push_back('p'); vec.push_back(':'); vec.push_back('/'); + // vec.push_back('/'); vec.push_back('s'); vec.push_back('l'); + // vec.push_back('.'); vec.push_back('c'); vec.push_back('o'); + // vec.push_back('m'); + // std::string str_bad((char*)&vec[0], vec.size()); + // ensureParse( + // "invalid uri length size", + // str_bad, + // LLSD(), + // LLSDParser::PARSE_FAILURE); + + // LLSD val; + // val = LLURI("http://sl.com"); + // size = htonl(13); // correct length + // memcpy(&vec[1], &size, sizeof(uint32_t)); + // std::string str_good((char*)&vec[0], vec.size()); + // ensureParse( + // "valid key size", + // str_good, + // val, + // 1); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDBinaryParsingObject_test_11") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDBinaryParsingObject::test<11> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDBinaryParsingObject::test<11>() + // { + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDCompatibleObject_test_1") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDCompatibleObject::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDCompatibleObject::test<1>() + // { + // LLSD test; + // ensureBinaryAndNotation("undef", test); + // ensureBinaryAndXML("undef", test); + // test = true; + // ensureBinaryAndNotation("boolean true", test); + // ensureBinaryAndXML("boolean true", test); + // test = false; + // ensureBinaryAndNotation("boolean false", test); + // ensureBinaryAndXML("boolean false", test); + // test = 0; + // ensureBinaryAndNotation("integer zero", test); + // ensureBinaryAndXML("integer zero", test); + // test = 1; + // ensureBinaryAndNotation("integer positive", test); + // ensureBinaryAndXML("integer positive", test); + // test = -234567; + // ensureBinaryAndNotation("integer negative", test); + // ensureBinaryAndXML("integer negative", test); + // test = 0.0; + // ensureBinaryAndNotation("real zero", test); + // ensureBinaryAndXML("real zero", test); + // test = 1.0; + // ensureBinaryAndNotation("real positive", test); + // ensureBinaryAndXML("real positive", test); + // test = -1.0; + // ensureBinaryAndNotation("real negative", test); + // ensureBinaryAndXML("real negative", test); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDCompatibleObject_test_2") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDCompatibleObject::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDCompatibleObject::test<2>() + // { + // LLSD test; + // test = "foobar"; + // ensureBinaryAndNotation("string", test); + // ensureBinaryAndXML("string", test); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDCompatibleObject_test_3") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDCompatibleObject::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDCompatibleObject::test<3>() + // { + // LLSD test; + // LLUUID id; + // id.generate(); + // test = id; + // ensureBinaryAndNotation("uuid", test); + // ensureBinaryAndXML("uuid", test); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDCompatibleObject_test_4") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDCompatibleObject::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDCompatibleObject::test<4>() + // { + // LLSD test; + // test = LLDate(12345.0); + // ensureBinaryAndNotation("date", test); + // ensureBinaryAndXML("date", test); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDCompatibleObject_test_5") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDCompatibleObject::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDCompatibleObject::test<5>() + // { + // LLSD test; + // test = LLURI("http://www.secondlife.com/"); + // ensureBinaryAndNotation("uri", test); + // ensureBinaryAndXML("uri", test); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDCompatibleObject_test_6") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDCompatibleObject::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDCompatibleObject::test<6>() + // { + // LLSD test; + // typedef std::vector buf_t; + // buf_t val; + // for(int ii = 0; ii < 100; ++ii) + // { + // srand(ii); /* Flawfinder: ignore */ + // S32 size = rand() % 100 + 10; + // std::generate_n( + // std::back_insert_iterator(val), + // size, + // rand); + // } + // test = val; + // ensureBinaryAndNotation("binary", test); + // ensureBinaryAndXML("binary", test); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDCompatibleObject_test_7") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDCompatibleObject::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDCompatibleObject::test<7>() + // { + // LLSD test; + // test = LLSD::emptyArray(); + // test.append(1); + // test.append("hello"); + // ensureBinaryAndNotation("array", test); + // ensureBinaryAndXML("array", test); + // } + } + + TUT_CASE("llsdserialize_test::TestLLSDCompatibleObject_test_8") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestLLSDCompatibleObject::test<8> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestLLSDCompatibleObject::test<8>() + // { + // LLSD test; + // test = LLSD::emptyArray(); + // test["foo"] = "bar"; + // test["baz"] = 100; + // ensureBinaryAndNotation("map", test); + // ensureBinaryAndXML("map", test); + // } + } + + TUT_CASE("llsdserialize_test::TestPythonCompatibleObject_test_1") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestPythonCompatibleObject::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestPythonCompatibleObject::test<1>() + // { + // set_test_name("verify python()"); + // python_expect("hello", + // "import sys\n" + // "sys.exit(17)\n", + // 17); // expect nonzero rc + // } + } + + TUT_CASE("llsdserialize_test::TestPythonCompatibleObject_test_2") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestPythonCompatibleObject::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestPythonCompatibleObject::test<2>() + // { + // set_test_name("verify NamedTempFile"); + // python("platform", + // "import sys\n" + // "print('Running on', sys.platform)\n"); + // } + } + + TUT_CASE("llsdserialize_test::TestPythonCompatibleObject_test_3") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestPythonCompatibleObject::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestPythonCompatibleObject::test<3>() + // { + // set_test_name("to Python using LLSDSerialize::serialize(LLSD_XML)"); + // toPythonUsing("LLSD_XML", + // [](const LLSD& sd, std::ostream& out) + // { LLSDSerialize::serialize(sd, out, LLSDSerialize::LLSD_XML); }); + // } + } + + TUT_CASE("llsdserialize_test::TestPythonCompatibleObject_test_4") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestPythonCompatibleObject::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestPythonCompatibleObject::test<4>() + // { + // set_test_name("to Python using LLSDSerialize::serialize(LLSD_NOTATION)"); + // toPythonUsing("LLSD_NOTATION", + // [](const LLSD& sd, std::ostream& out) + // { LLSDSerialize::serialize(sd, out, LLSDSerialize::LLSD_NOTATION); }); + // } + } + + TUT_CASE("llsdserialize_test::TestPythonCompatibleObject_test_5") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestPythonCompatibleObject::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestPythonCompatibleObject::test<5>() + // { + // set_test_name("to Python using LLSDSerialize::serialize(LLSD_BINARY)"); + // toPythonUsing("LLSD_BINARY", + // [](const LLSD& sd, std::ostream& out) + // { LLSDSerialize::serialize(sd, out, LLSDSerialize::LLSD_BINARY); }); + // } + } + + TUT_CASE("llsdserialize_test::TestPythonCompatibleObject_test_6") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestPythonCompatibleObject::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestPythonCompatibleObject::test<6>() + // { + // set_test_name("to Python using LLSDSerialize::toXML()"); + // toPythonUsing("toXML()", LLSDSerialize::toXML); + // } + } + + TUT_CASE("llsdserialize_test::TestPythonCompatibleObject_test_7") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestPythonCompatibleObject::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestPythonCompatibleObject::test<7>() + // { + // set_test_name("to Python using LLSDSerialize::toNotation()"); + // toPythonUsing("toNotation()", LLSDSerialize::toNotation); + // } + } + + TUT_CASE("llsdserialize_test::TestPythonCompatibleObject_test_8") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestPythonCompatibleObject::test<8> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestPythonCompatibleObject::test<8>() + // { + // set_test_name("to Python using LLSDSerialize::toBinary()"); + // // We don't expect this to work because, without a header, + // // llsd.parse() will assume notation rather than binary. + // toPythonUsing("toBinary()", LLSDSerialize::toBinary); + // } + } + + TUT_CASE("llsdserialize_test::TestPythonCompatibleObject_test_8") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestPythonCompatibleObject::test<8> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestPythonCompatibleObject::test<8>() + // { + // set_test_name("from Python XML using LLSDSerialize::deserialize()"); + // fromPythonUsing("format_xml"); + // } + } + + TUT_CASE("llsdserialize_test::TestPythonCompatibleObject_test_9") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestPythonCompatibleObject::test<9> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestPythonCompatibleObject::test<9>() + // { + // set_test_name("from Python notation using LLSDSerialize::deserialize()"); + // fromPythonUsing("format_notation"); + // } + } + + TUT_CASE("llsdserialize_test::TestPythonCompatibleObject_test_10") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestPythonCompatibleObject::test<10> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestPythonCompatibleObject::test<10>() + // { + // set_test_name("from Python binary using LLSDSerialize::deserialize()"); + // fromPythonUsing("format_binary"); + // } + } + + TUT_CASE("llsdserialize_test::TestPythonCompatibleObject_test_11") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestPythonCompatibleObject::test<11> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestPythonCompatibleObject::test<11>() + // { + // set_test_name("from Python XML using fromXML()"); + // // fromXML()'s optional 3rd param isn't max_bytes, it's emit_errors + // fromPythonUsing("format_xml", + // [](std::istream& istr, LLSD& data, llssize) + // { return LLSDSerialize::fromXML(data, istr) > 0; }); + // } + } + + TUT_CASE("llsdserialize_test::TestPythonCompatibleObject_test_12") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestPythonCompatibleObject::test<12> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestPythonCompatibleObject::test<12>() + // { + // set_test_name("from Python notation using fromNotation()"); + // fromPythonUsing("format_notation", + // [](std::istream& istr, LLSD& data, llssize max_bytes) + // { return LLSDSerialize::fromNotation(data, istr, max_bytes) > 0; }); + // } + } + + TUT_CASE("llsdserialize_test::TestPythonCompatibleObject_test_13") + { + DOCTEST_FAIL("TODO: convert llsdserialize_test.cpp::TestPythonCompatibleObject::test<13> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void TestPythonCompatibleObject::test<13>() + // { + // set_test_name("from Python binary using fromBinary()"); + // // We don't expect this to work because format_binary() emits a + // // header, but fromBinary() won't recognize a header. + // fromPythonUsing("format_binary", + // [](std::istream& istr, LLSD& data, llssize max_bytes) + // { return LLSDSerialize::fromBinary(data, istr, max_bytes) > 0; }); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llsingleton_test_doctest.cpp b/indra/llcommon/tests_doctest/llsingleton_test_doctest.cpp new file mode 100644 index 00000000000..42d8d60ed32 --- /dev/null +++ b/indra/llcommon/tests_doctest/llsingleton_test_doctest.cpp @@ -0,0 +1,194 @@ +/** + * @file llsingleton_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL singleton + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llsingleton_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "llsingleton.h" +#include "wrapllerrs.h" +#include "llsd.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("llsingleton_test::singleton_object_t_test_1") + { + DOCTEST_FAIL("TODO: convert llsingleton_test.cpp::singleton_object_t::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void singleton_object_t::test<1>() + // { + + // } + } + + TUT_CASE("llsingleton_test::singleton_object_t_test_2") + { + DOCTEST_FAIL("TODO: convert llsingleton_test.cpp::singleton_object_t::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void singleton_object_t::test<2>() + // { + // LLSingletonTest* singleton_test = LLSingletonTest::getInstance(); + // ensure(singleton_test); + // } + } + + TUT_CASE("llsingleton_test::singleton_object_t_test_3") + { + DOCTEST_FAIL("TODO: convert llsingleton_test.cpp::singleton_object_t::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void singleton_object_t::test<3>() + // { + // //Construct the instance + // LLSingletonTest::getInstance(); + // ensure(LLSingletonTest::instanceExists()); + + // //Delete the instance + // LLSingletonTest::deleteSingleton(); + // ensure(!LLSingletonTest::instanceExists()); + + // //Construct it again. + // LLSingletonTest* singleton_test = LLSingletonTest::getInstance(); + // ensure(singleton_test); + // ensure(LLSingletonTest::instanceExists()); + // } + } + + TUT_CASE("llsingleton_test::singleton_object_t_test_12") + { + DOCTEST_FAIL("TODO: convert llsingleton_test.cpp::singleton_object_t::test<12> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void singleton_object_t::test<12>() + // { + // set_test_name("LLParamSingleton"); + + // WrapLLErrs catcherr; + // // query methods + // ensure("false positive on instanceExists()", ! PSing1::instanceExists()); + // ensure("false positive on wasDeleted()", ! PSing1::wasDeleted()); + // // try to reference before initializing + // std::string threw = catcherr.catch_llerrs([](){ + // (void)PSing1::instance(); + // }); + // ensure_contains("too-early instance() didn't throw", threw, "Uninitialized"); + // // getInstance() behaves the same as instance() + // threw = catcherr.catch_llerrs([](){ + // (void)PSing1::getInstance(); + // }); + // ensure_contains("too-early getInstance() didn't throw", threw, "Uninitialized"); + // // initialize using LLSD::String constructor + // PSing1::initParamSingleton("string"); + // ensure_equals(PSing1::instance().desc(), "string"); + // ensure("false negative on instanceExists()", PSing1::instanceExists()); + // // try to initialize again + // threw = catcherr.catch_llerrs([](){ + // PSing1::initParamSingleton("again"); + // }); + // ensure_contains("second ctor(string) didn't throw", threw, "twice"); + // // try to initialize using the other constructor -- should be + // // well-formed, but illegal at runtime + // threw = catcherr.catch_llerrs([](){ + // PSing1::initParamSingleton(17); + // }); + // ensure_contains("other ctor(int) didn't throw", threw, "twice"); + // PSing1::deleteSingleton(); + // ensure("false negative on wasDeleted()", PSing1::wasDeleted()); + // threw = catcherr.catch_llerrs([](){ + // (void)PSing1::instance(); + // }); + // ensure_contains("accessed deleted LLParamSingleton", threw, "deleted"); + // } + } + + TUT_CASE("llsingleton_test::singleton_object_t_test_13") + { + DOCTEST_FAIL("TODO: convert llsingleton_test.cpp::singleton_object_t::test<13> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void singleton_object_t::test<13>() + // { + // set_test_name("LLParamSingleton alternate ctor"); + + // WrapLLErrs catcherr; + // // We don't have to restate all the tests for PSing1. Only test validly + // // using the other constructor. + // PSing2::initParamSingleton(17); + // ensure_equals(PSing2::instance().desc(), "17"); + // // can't do it twice + // std::string threw = catcherr.catch_llerrs([](){ + // PSing2::initParamSingleton(34); + // }); + // ensure_contains("second ctor(int) didn't throw", threw, "twice"); + // // can't use the other constructor either + // threw = catcherr.catch_llerrs([](){ + // PSing2::initParamSingleton("string"); + // }); + // ensure_contains("other ctor(string) didn't throw", threw, "twice"); + // } + } + + TUT_CASE("llsingleton_test::singleton_object_t_test_14") + { + DOCTEST_FAIL("TODO: convert llsingleton_test.cpp::singleton_object_t::test<14> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void singleton_object_t::test<14>() + // { + // set_test_name("Circular LLParamSingleton constructor"); + // WrapLLErrs catcherr; + // std::string threw = catcherr.catch_llerrs([](){ + // CircularPCtor::initParamSingleton(); + // }); + // ensure_contains("constructor circularity didn't throw", threw, "constructor"); + // } + } + + TUT_CASE("llsingleton_test::singleton_object_t_test_15") + { + DOCTEST_FAIL("TODO: convert llsingleton_test.cpp::singleton_object_t::test<15> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void singleton_object_t::test<15>() + // { + // set_test_name("Circular LLParamSingleton initSingleton()"); + // WrapLLErrs catcherr; + // std::string threw = catcherr.catch_llerrs([](){ + // CircularPInit::initParamSingleton(); + // }); + // ensure("initSingleton() circularity threw", threw.empty()); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llstreamqueue_test_doctest.cpp b/indra/llcommon/tests_doctest/llstreamqueue_test_doctest.cpp new file mode 100644 index 00000000000..dfe9d91c9c2 --- /dev/null +++ b/indra/llcommon/tests_doctest/llstreamqueue_test_doctest.cpp @@ -0,0 +1,223 @@ +/** + * @file llstreamqueue_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL streamqueue + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llstreamqueue_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "llstreamqueue.h" +#include +#include "stringize.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("llstreamqueue_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert llstreamqueue_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // set_test_name("empty LLStreamQueue"); + // ensure_equals("brand-new LLStreamQueue isn't empty", + // strq.size(), 0); + // ensure_equals("brand-new LLStreamQueue returns data", + // strq.asSource().read(&buffer[0], buffer.size()), 0); + // strq.asSink().close(); + // ensure_equals("closed empty LLStreamQueue not at EOF", + // strq.asSource().read(&buffer[0], buffer.size()), -1); + // } + } + + TUT_CASE("llstreamqueue_test::object_test_2") + { + DOCTEST_FAIL("TODO: convert llstreamqueue_test.cpp::object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<2>() + // { + // set_test_name("one internal block, one buffer"); + // LLStreamQueue::Sink sink(strq.asSink()); + // ensure_equals("write(\"\")", sink.write("", 0), 0); + // ensure_equals("0 write should leave LLStreamQueue empty (size())", + // strq.size(), 0); + // ensure_equals("0 write should leave LLStreamQueue empty (peek())", + // strq.peek(&buffer[0], buffer.size()), 0); + // // The meaning of "atomic" is that it must be smaller than our buffer. + // std::string atomic("atomic"); + // ensure("test data exceeds buffer", atomic.length() < buffer.size()); + // ensure_equals(STRINGIZE("write(\"" << atomic << "\")"), + // sink.write(&atomic[0], atomic.length()), atomic.length()); + // ensure_equals("size() after write()", strq.size(), atomic.length()); + // size_t peeklen(strq.peek(&buffer[0], buffer.size())); + // ensure_equals(STRINGIZE("peek(\"" << atomic << "\")"), + // peeklen, atomic.length()); + // ensure_equals(STRINGIZE("peek(\"" << atomic << "\") result"), + // std::string(buffer.begin(), buffer.begin() + peeklen), atomic); + // ensure_equals("size() after peek()", strq.size(), atomic.length()); + // // peek() should not consume. Use a different buffer to prove it isn't + // // just leftover data from the first peek(). + // std::vector again(buffer.size()); + // peeklen = size_t(strq.peek(&again[0], again.size())); + // ensure_equals(STRINGIZE("peek(\"" << atomic << "\") again"), + // peeklen, atomic.length()); + // ensure_equals(STRINGIZE("peek(\"" << atomic << "\") again result"), + // std::string(again.begin(), again.begin() + peeklen), atomic); + // // now consume. + // std::vector third(buffer.size()); + // size_t readlen(strq.read(&third[0], third.size())); + // ensure_equals(STRINGIZE("read(\"" << atomic << "\")"), + // readlen, atomic.length()); + // ensure_equals(STRINGIZE("read(\"" << atomic << "\") result"), + // std::string(third.begin(), third.begin() + readlen), atomic); + // ensure_equals("peek() after read()", strq.peek(&buffer[0], buffer.size()), 0); + // ensure_equals("size() after read()", strq.size(), 0); + // } + } + + TUT_CASE("llstreamqueue_test::object_test_3") + { + DOCTEST_FAIL("TODO: convert llstreamqueue_test.cpp::object::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<3>() + // { + // set_test_name("basic skip()"); + // std::string lovecraft("lovecraft"); + // ensure("test data exceeds buffer", lovecraft.length() < buffer.size()); + // ensure_equals(STRINGIZE("write(\"" << lovecraft << "\")"), + // strq.write(&lovecraft[0], lovecraft.length()), lovecraft.length()); + // size_t peeklen(strq.peek(&buffer[0], buffer.size())); + // ensure_equals(STRINGIZE("peek(\"" << lovecraft << "\")"), + // peeklen, lovecraft.length()); + // ensure_equals(STRINGIZE("peek(\"" << lovecraft << "\") result"), + // std::string(buffer.begin(), buffer.begin() + peeklen), lovecraft); + // std::streamsize skip1(4); + // ensure_equals(STRINGIZE("skip(" << skip1 << ")"), strq.skip(skip1), skip1); + // ensure_equals("size() after skip()", strq.size(), lovecraft.length() - skip1); + // size_t readlen(strq.read(&buffer[0], buffer.size())); + // ensure_equals(STRINGIZE("read(\"" << lovecraft.substr(skip1) << "\")"), + // readlen, lovecraft.length() - skip1); + // ensure_equals(STRINGIZE("read(\"" << lovecraft.substr(skip1) << "\") result"), + // std::string(buffer.begin(), buffer.begin() + readlen), + // lovecraft.substr(skip1)); + // ensure_equals("unconsumed", strq.read(&buffer[0], buffer.size()), 0); + // } + } + + TUT_CASE("llstreamqueue_test::object_test_4") + { + DOCTEST_FAIL("TODO: convert llstreamqueue_test.cpp::object::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<4>() + // { + // set_test_name("skip() multiple blocks"); + // std::string blocks[] = { "books of ", "H.P. ", "Lovecraft" }; + // std::streamsize total(blocks[0].length() + blocks[1].length() + blocks[2].length()); + // std::streamsize leave(5); // len("craft") above + // std::streamsize skip(total - leave); + // std::streamsize written(0); + // for (const std::string& block : blocks) + // { + // written += strq.write(&block[0], block.length()); + // ensure_equals("size() after write()", strq.size(), written); + // } + // std::streamsize skiplen(strq.skip(skip)); + // ensure_equals(STRINGIZE("skip(" << skip << ")"), skiplen, skip); + // ensure_equals("size() after skip()", strq.size(), leave); + // size_t readlen(strq.read(&buffer[0], buffer.size())); + // ensure_equals("read(\"craft\")", readlen, leave); + // ensure_equals("read(\"craft\") result", + // std::string(buffer.begin(), buffer.begin() + readlen), "craft"); + // } + } + + TUT_CASE("llstreamqueue_test::object_test_5") + { + DOCTEST_FAIL("TODO: convert llstreamqueue_test.cpp::object::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<5>() + // { + // set_test_name("concatenate blocks"); + // std::string blocks[] = { "abcd", "efghij", "klmnopqrs" }; + // for (const std::string& block : blocks) + // { + // strq.write(&block[0], block.length()); + // } + // std::vector longbuffer(30); + // std::streamsize readlen(strq.read(&longbuffer[0], longbuffer.size())); + // ensure_equals("read() multiple blocks", + // readlen, blocks[0].length() + blocks[1].length() + blocks[2].length()); + // ensure_equals("read() multiple blocks result", + // std::string(longbuffer.begin(), longbuffer.begin() + readlen), + // blocks[0] + blocks[1] + blocks[2]); + // } + } + + TUT_CASE("llstreamqueue_test::object_test_6") + { + DOCTEST_FAIL("TODO: convert llstreamqueue_test.cpp::object::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<6>() + // { + // set_test_name("split blocks"); + // std::string blocks[] = { "abcdefghijklm", "nopqrstuvwxyz" }; + // for (const std::string& block : blocks) + // { + // strq.write(&block[0], block.length()); + // } + // strq.close(); + // // We've already verified what strq.size() should be at this point; + // // see above test named "skip() multiple blocks" + // std::streamsize chksize(strq.size()); + // std::streamsize readlen(strq.read(&buffer[0], buffer.size())); + // ensure_equals("read() 0", readlen, buffer.size()); + // ensure_equals("read() 0 result", std::string(buffer.begin(), buffer.end()), "abcdefghij"); + // chksize -= readlen; + // ensure_equals("size() after read() 0", strq.size(), chksize); + // readlen = strq.read(&buffer[0], buffer.size()); + // ensure_equals("read() 1", readlen, buffer.size()); + // ensure_equals("read() 1 result", std::string(buffer.begin(), buffer.end()), "klmnopqrst"); + // chksize -= readlen; + // ensure_equals("size() after read() 1", strq.size(), chksize); + // readlen = strq.read(&buffer[0], buffer.size()); + // ensure_equals("read() 2", readlen, chksize); + // ensure_equals("read() 2 result", + // std::string(buffer.begin(), buffer.begin() + readlen), "uvwxyz"); + // ensure_equals("read() 3", strq.read(&buffer[0], buffer.size()), -1); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llstring_test_doctest.cpp b/indra/llcommon/tests_doctest/llstring_test_doctest.cpp new file mode 100644 index 00000000000..99cc7ef3781 --- /dev/null +++ b/indra/llcommon/tests_doctest/llstring_test_doctest.cpp @@ -0,0 +1,1040 @@ +/** + * @file llstring_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL string + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llstring_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include +#include "../llstring.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("llstring_test::string_index_object_t_test_1") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<1>() + // { + // std::string llstr1; + // ensure("Empty std::string", (llstr1.size() == 0) && llstr1.empty()); + + // std::string llstr2("Hello"); + // ensure("std::string = Hello", (!strcmp(llstr2.c_str(), "Hello")) && (llstr2.size() == 5) && !llstr2.empty()); + + // std::string llstr3(llstr2); + // ensure("std::string = std::string(std::string)", (!strcmp(llstr3.c_str(), "Hello")) && (llstr3.size() == 5) && !llstr3.empty()); + + // std::string str("Hello World"); + // std::string llstr4(str, 6); + // ensure("std::string = std::string(s, size_type pos, size_type n = npos)", (!strcmp(llstr4.c_str(), "World")) && (llstr4.size() == 5) && !llstr4.empty()); + + // std::string llstr5(str, str.size()); + // ensure("std::string = std::string(s, size_type pos, size_type n = npos)", (llstr5.size() == 0) && llstr5.empty()); + + // std::string llstr6(5, 'A'); + // ensure("std::string = std::string(count, c)", (!strcmp(llstr6.c_str(), "AAAAA")) && (llstr6.size() == 5) && !llstr6.empty()); + + // std::string llstr7("Hello World", 5); + // ensure("std::string(s, n)", (!strcmp(llstr7.c_str(), "Hello")) && (llstr7.size() == 5) && !llstr7.empty()); + + // std::string llstr8("Hello World", 6, 5); + // ensure("std::string(s, n, count)", (!strcmp(llstr8.c_str(), "World")) && (llstr8.size() == 5) && !llstr8.empty()); + + // std::string llstr9("Hello World", sizeof("Hello World")-1, 5); // go past end + // ensure("std::string(s, n, count) goes past end", (llstr9.size() == 0) && llstr9.empty()); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_3") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<3>() + // { + // std::string str("Len=5"); + // ensure("isValidIndex failed", LLStringUtil::isValidIndex(str, 0) == true && + // LLStringUtil::isValidIndex(str, 5) == true && + // LLStringUtil::isValidIndex(str, 6) == false); + + // std::string str1; + // ensure("isValidIndex failed fo rempty string", LLStringUtil::isValidIndex(str1, 0) == false); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_4") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<4>() + // { + // std::string str_val(" Testing the extra whitespaces "); + // LLStringUtil::trimHead(str_val); + // ensure_equals("1: trimHead failed", str_val, "Testing the extra whitespaces "); + + // std::string str_val1("\n\t\r\n Testing the extra whitespaces "); + // LLStringUtil::trimHead(str_val1); + // ensure_equals("2: trimHead failed", str_val1, "Testing the extra whitespaces "); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_5") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<5>() + // { + // std::string str_val(" Testing the extra whitespaces "); + // LLStringUtil::trimTail(str_val); + // ensure_equals("1: trimTail failed", str_val, " Testing the extra whitespaces"); + + // std::string str_val1("\n Testing the extra whitespaces \n\t\r\n "); + // LLStringUtil::trimTail(str_val1); + // ensure_equals("2: trimTail failed", str_val1, "\n Testing the extra whitespaces"); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_6") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<6>() + // { + // std::string str_val(" \t \r Testing the extra \r\n whitespaces \n \t "); + // LLStringUtil::trim(str_val); + // ensure_equals("1: trim failed", str_val, "Testing the extra \r\n whitespaces"); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_7") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<7>() + // { + // std::string str("Second LindenLabs"); + // LLStringUtil::truncate(str, 6); + // ensure_equals("1: truncate", str, "Second"); + + // // further truncate more than the length + // LLStringUtil::truncate(str, 0); + // ensure_equals("2: truncate", str, ""); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_8") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<8> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<8>() + // { + // std::string str_val("SecondLife Source"); + // LLStringUtil::toUpper(str_val); + // ensure_equals("toUpper failed", str_val, "SECONDLIFE SOURCE"); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_9") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<9> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<9>() + // { + // std::string str_val("SecondLife Source"); + // LLStringUtil::toLower(str_val); + // ensure_equals("toLower failed", str_val, "secondlife source"); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_10") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<10> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<10>() + // { + // std::string str_val("Second"); + // ensure("1. isHead failed", LLStringUtil::isHead(str_val, "SecondLife Source") == true); + // ensure("2. isHead failed", LLStringUtil::isHead(str_val, " SecondLife Source") == false); + // std::string str_val2(""); + // ensure("3. isHead failed", LLStringUtil::isHead(str_val2, "") == false); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_11") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<11> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<11>() + // { + // std::string str_val("Hello.\n\n Lindenlabs. \n This is \na simple test.\n"); + // std::string orig_str_val(str_val); + // LLStringUtil::addCRLF(str_val); + // ensure_equals("addCRLF failed", str_val, "Hello.\r\n\r\n Lindenlabs. \r\n This is \r\na simple test.\r\n"); + // LLStringUtil::removeCRLF(str_val); + // ensure_equals("removeCRLF failed", str_val, orig_str_val); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_12") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<12> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<12>() + // { + // std::string str_val("Hello.\n\n\t \t Lindenlabs. \t\t"); + // std::string orig_str_val(str_val); + // LLStringUtil::replaceTabsWithSpaces(str_val, 1); + // ensure_equals("replaceTabsWithSpaces failed", str_val, "Hello.\n\n Lindenlabs. "); + // LLStringUtil::replaceTabsWithSpaces(orig_str_val, 0); + // ensure_equals("replaceTabsWithSpaces failed for 0", orig_str_val, "Hello.\n\n Lindenlabs. "); + + // str_val = "\t\t\t\t"; + // LLStringUtil::replaceTabsWithSpaces(str_val, 0); + // ensure_equals("replaceTabsWithSpaces failed for all tabs", str_val, ""); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_13") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<13> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<13>() + // { + // std::string str_val("Hello.\n\n\t\t\r\nLindenlabsX."); + // LLStringUtil::replaceNonstandardASCII(str_val, 'X'); + // ensure_equals("replaceNonstandardASCII failed", str_val, "Hello.\n\nXXX\nLindenlabsX."); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_14") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<14> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<14>() + // { + // std::string str_val("Hello.\n\t\r\nABCDEFGHIABABAB"); + // LLStringUtil::replaceChar(str_val, 'A', 'X'); + // ensure_equals("1: replaceChar failed", str_val, "Hello.\n\t\r\nXBCDEFGHIXBXBXB"); + // std::string str_val1("Hello.\n\t\r\nABCDEFGHIABABAB"); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_15") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<15> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<15>() + // { + // std::string str_val("Hello.\n\r\t"); + // ensure("containsNonprintable failed", LLStringUtil::containsNonprintable(str_val) == true); + + // str_val = "ABC "; + // ensure("containsNonprintable failed", LLStringUtil::containsNonprintable(str_val) == false); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_16") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<16> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<16>() + // { + // std::string str_val("Hello.\n\r\t Again!"); + // LLStringUtil::stripNonprintable(str_val); + // ensure_equals("stripNonprintable failed", str_val, "Hello. Again!"); + + // str_val = "\r\n\t\t"; + // LLStringUtil::stripNonprintable(str_val); + // ensure_equals("stripNonprintable resulting in empty string failed", str_val, ""); + + // str_val = ""; + // LLStringUtil::stripNonprintable(str_val); + // ensure_equals("stripNonprintable of empty string resulting in empty string failed", str_val, ""); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_17") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<17> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<17>() + // { + // bool value; + // std::string str_val("1"); + // ensure("convertToBOOL 1 failed", LLStringUtil::convertToBOOL(str_val, value) && value); + // str_val = "T"; + // ensure("convertToBOOL T failed", LLStringUtil::convertToBOOL(str_val, value) && value); + // str_val = "t"; + // ensure("convertToBOOL t failed", LLStringUtil::convertToBOOL(str_val, value) && value); + // str_val = "TRUE"; + // ensure("convertToBOOL TRUE failed", LLStringUtil::convertToBOOL(str_val, value) && value); + // str_val = "True"; + // ensure("convertToBOOL True failed", LLStringUtil::convertToBOOL(str_val, value) && value); + // str_val = "true"; + // ensure("convertToBOOL true failed", LLStringUtil::convertToBOOL(str_val, value) && value); + + // str_val = "0"; + // ensure("convertToBOOL 0 failed", LLStringUtil::convertToBOOL(str_val, value) && !value); + // str_val = "F"; + // ensure("convertToBOOL F failed", LLStringUtil::convertToBOOL(str_val, value) && !value); + // str_val = "f"; + // ensure("convertToBOOL f failed", LLStringUtil::convertToBOOL(str_val, value) && !value); + // str_val = "FALSE"; + // ensure("convertToBOOL FASLE failed", LLStringUtil::convertToBOOL(str_val, value) && !value); + // str_val = "False"; + // ensure("convertToBOOL False failed", LLStringUtil::convertToBOOL(str_val, value) && !value); + // str_val = "false"; + // ensure("convertToBOOL false failed", LLStringUtil::convertToBOOL(str_val, value) && !value); + + // str_val = "Tblah"; + // ensure("convertToBOOL false failed", !LLStringUtil::convertToBOOL(str_val, value)); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_18") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<18> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<18>() + // { + // U8 value; + // std::string str_val("255"); + // ensure("1: convertToU8 failed", LLStringUtil::convertToU8(str_val, value) && value == 255); + + // str_val = "0"; + // ensure("2: convertToU8 failed", LLStringUtil::convertToU8(str_val, value) && value == 0); + + // str_val = "-1"; + // ensure("3: convertToU8 failed", !LLStringUtil::convertToU8(str_val, value)); + + // str_val = "256"; // bigger than MAX_U8 + // ensure("4: convertToU8 failed", !LLStringUtil::convertToU8(str_val, value)); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_19") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<19> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<19>() + // { + // S8 value; + // std::string str_val("127"); + // ensure("1: convertToS8 failed", LLStringUtil::convertToS8(str_val, value) && value == 127); + + // str_val = "0"; + // ensure("2: convertToS8 failed", LLStringUtil::convertToS8(str_val, value) && value == 0); + + // str_val = "-128"; + // ensure("3: convertToS8 failed", LLStringUtil::convertToS8(str_val, value) && value == -128); + + // str_val = "128"; // bigger than MAX_S8 + // ensure("4: convertToS8 failed", !LLStringUtil::convertToS8(str_val, value)); + + // str_val = "-129"; + // ensure("5: convertToS8 failed", !LLStringUtil::convertToS8(str_val, value)); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_20") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<20> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<20>() + // { + // S16 value; + // std::string str_val("32767"); + // ensure("1: convertToS16 failed", LLStringUtil::convertToS16(str_val, value) && value == 32767); + + // str_val = "0"; + // ensure("2: convertToS16 failed", LLStringUtil::convertToS16(str_val, value) && value == 0); + + // str_val = "-32768"; + // ensure("3: convertToS16 failed", LLStringUtil::convertToS16(str_val, value) && value == -32768); + + // str_val = "32768"; + // ensure("4: convertToS16 failed", !LLStringUtil::convertToS16(str_val, value)); + + // str_val = "-32769"; + // ensure("5: convertToS16 failed", !LLStringUtil::convertToS16(str_val, value)); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_21") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<21> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<21>() + // { + // U16 value; + // std::string str_val("65535"); //0xFFFF + // ensure("1: convertToU16 failed", LLStringUtil::convertToU16(str_val, value) && value == 65535); + + // str_val = "0"; + // ensure("2: convertToU16 failed", LLStringUtil::convertToU16(str_val, value) && value == 0); + + // str_val = "-1"; + // ensure("3: convertToU16 failed", !LLStringUtil::convertToU16(str_val, value)); + + // str_val = "65536"; + // ensure("4: convertToU16 failed", !LLStringUtil::convertToU16(str_val, value)); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_22") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<22> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<22>() + // { + // U32 value; + // std::string str_val("4294967295"); //0xFFFFFFFF + // ensure("1: convertToU32 failed", LLStringUtil::convertToU32(str_val, value) && value == 4294967295UL); + + // str_val = "0"; + // ensure("2: convertToU32 failed", LLStringUtil::convertToU32(str_val, value) && value == 0); + + // str_val = "4294967296"; + // ensure("3: convertToU32 failed", !LLStringUtil::convertToU32(str_val, value)); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_23") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<23> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<23>() + // { + // S32 value; + // std::string str_val("2147483647"); //0x7FFFFFFF + // ensure("1: convertToS32 failed", LLStringUtil::convertToS32(str_val, value) && value == 2147483647); + + // str_val = "0"; + // ensure("2: convertToS32 failed", LLStringUtil::convertToS32(str_val, value) && value == 0); + + // // Avoid "unary minus operator applied to unsigned type" warning on VC++. JC + // S32 min_val = -2147483647 - 1; + // str_val = "-2147483648"; + // ensure("3: convertToS32 failed", LLStringUtil::convertToS32(str_val, value) && value == min_val); + + // str_val = "2147483648"; + // ensure("4: convertToS32 failed", !LLStringUtil::convertToS32(str_val, value)); + + // str_val = "-2147483649"; + // ensure("5: convertToS32 failed", !LLStringUtil::convertToS32(str_val, value)); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_24") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<24> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<24>() + // { + // F32 value; + // std::string str_val("2147483647"); //0x7FFFFFFF + // ensure("1: convertToF32 failed", LLStringUtil::convertToF32(str_val, value) && value == 2147483647); + + // str_val = "0"; + // ensure("2: convertToF32 failed", LLStringUtil::convertToF32(str_val, value) && value == 0); + + // /* Need to find max/min F32 values + // str_val = "-2147483648"; + // ensure("3: convertToF32 failed", LLStringUtil::convertToF32(str_val, value) && value == -2147483648); + + // str_val = "2147483648"; + // ensure("4: convertToF32 failed", !LLStringUtil::convertToF32(str_val, value)); + + // str_val = "-2147483649"; + // ensure("5: convertToF32 failed", !LLStringUtil::convertToF32(str_val, value)); + // */ + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_25") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<25> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<25>() + // { + // F64 value; + // std::string str_val("9223372036854775807"); //0x7FFFFFFFFFFFFFFF + // ensure("1: convertToF64 failed", LLStringUtil::convertToF64(str_val, value) && value == 9223372036854775807LL); + + // str_val = "0"; + // ensure("2: convertToF64 failed", LLStringUtil::convertToF64(str_val, value) && value == 0.0F); + + // /* Need to find max/min F64 values + // str_val = "-2147483648"; + // ensure("3: convertToF32 failed", LLStringUtil::convertToF32(str_val, value) && value == -2147483648); + + // str_val = "2147483648"; + // ensure("4: convertToF32 failed", !LLStringUtil::convertToF32(str_val, value)); + + // str_val = "-2147483649"; + // ensure("5: convertToF32 failed", !LLStringUtil::convertToF32(str_val, value)); + // */ + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_26") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<26> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<26>() + // { + // const char* str1 = NULL; + // const char* str2 = NULL; + + // ensure("1: compareStrings failed", LLStringUtil::compareStrings(str1, str2) == 0); + // str2 = "A"; + // ensure("2: compareStrings failed", LLStringUtil::compareStrings(str1, str2) > 0); + // ensure("3: compareStrings failed", LLStringUtil::compareStrings(str2, str1) < 0); + + // str1 = "A is smaller than B"; + // str2 = "B is greater than A"; + // ensure("4: compareStrings failed", LLStringUtil::compareStrings(str1, str2) < 0); + + // str2 = "A is smaller than B"; + // ensure("5: compareStrings failed", LLStringUtil::compareStrings(str1, str2) == 0); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_27") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<27> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<27>() + // { + // const char* str1 = NULL; + // const char* str2 = NULL; + + // ensure("1: compareInsensitive failed", LLStringUtil::compareInsensitive(str1, str2) == 0); + // str2 = "A"; + // ensure("2: compareInsensitive failed", LLStringUtil::compareInsensitive(str1, str2) > 0); + // ensure("3: compareInsensitive failed", LLStringUtil::compareInsensitive(str2, str1) < 0); + + // str1 = "A is equal to a"; + // str2 = "a is EQUAL to A"; + // ensure("4: compareInsensitive failed", LLStringUtil::compareInsensitive(str1, str2) == 0); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_28") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<28> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<28>() + // { + // std::string lhs_str("PROgraM12files"); + // std::string rhs_str("PROgram12Files"); + // ensure("compareDict 1 failed", LLStringUtil::compareDict(lhs_str, rhs_str) < 0); + // ensure("precedesDict 1 failed", LLStringUtil::precedesDict(lhs_str, rhs_str) == true); + + // lhs_str = "PROgram12Files"; + // rhs_str = "PROgram12Files"; + // ensure("compareDict 2 failed", LLStringUtil::compareDict(lhs_str, rhs_str) == 0); + // ensure("precedesDict 2 failed", LLStringUtil::precedesDict(lhs_str, rhs_str) == false); + + // lhs_str = "PROgram12Files"; + // rhs_str = "PROgRAM12FILES"; + // ensure("compareDict 3 failed", LLStringUtil::compareDict(lhs_str, rhs_str) > 0); + // ensure("precedesDict 3 failed", LLStringUtil::precedesDict(lhs_str, rhs_str) == false); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_29") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<29> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<29>() + // { + // char str1[] = "First String..."; + // char str2[100]; + + // LLStringUtil::copy(str2, str1, 100); + // ensure("LLStringUtil::copy with enough dest length failed", strcmp(str2, str1) == 0); + // LLStringUtil::copy(str2, str1, sizeof("First")); + // ensure("LLStringUtil::copy with less dest length failed", strcmp(str2, "First") == 0); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_30") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<30> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<30>() + // { + // std::string str1 = "This is the sentence..."; + // std::string str2 = "This is the "; + // std::string str3 = "first "; + // std::string str4 = "This is the first sentence..."; + // std::string str5 = "This is the sentence...first "; + // std::string dest; + + // dest = str1; + // LLStringUtil::copyInto(dest, str3, str2.length()); + // ensure("LLStringUtil::copyInto insert failed", dest == str4); + + // dest = str1; + // LLStringUtil::copyInto(dest, str3, dest.length()); + // ensure("LLStringUtil::copyInto append failed", dest == str5); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_31") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<31> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<31>() + // { + // std::string stripped; + + // // Plain US ASCII text, including spaces and punctuation, + // // should not be altered. + // std::string simple_text = "Hello, world!"; + // stripped = LLStringFn::strip_invalid_xml(simple_text); + // ensure("Simple text passed unchanged", stripped == simple_text); + + // // Control characters should be removed + // // except for 0x09, 0x0a, 0x0d + // std::string control_chars; + // for (char c = 0x01; c < 0x20; c++) + // { + // control_chars.push_back(c); + // } + // std::string allowed_control_chars; + // allowed_control_chars.push_back( (char)0x09 ); + // allowed_control_chars.push_back( (char)0x0a ); + // allowed_control_chars.push_back( (char)0x0d ); + + // stripped = LLStringFn::strip_invalid_xml(control_chars); + // ensure("Only tab, LF, CR control characters allowed", + // stripped == allowed_control_chars); + + // // UTF-8 should be passed intact, including high byte + // // characters. Try Francais (with C squiggle cedilla) + // std::string french = "Fran"; + // french.push_back( (char)0xC3 ); + // french.push_back( (char)0xA7 ); + // french += "ais"; + // stripped = LLStringFn::strip_invalid_xml( french ); + // ensure("UTF-8 high byte text is allowed", french == stripped ); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_32") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<32> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<32>() + // { + // // Test LLStringUtil::format() string interpolation + // LLStringUtil::format_map_t fmt_map; + // std::string s; + // int subcount; + + // fmt_map["[TRICK1]"] = "[A]"; + // fmt_map["[A]"] = "a"; + // fmt_map["[B]"] = "b"; + // fmt_map["[AAA]"] = "aaa"; + // fmt_map["[BBB]"] = "bbb"; + // fmt_map["[TRICK2]"] = "[A]"; + // fmt_map["[EXPLOIT]"] = "!!!!!!!!!!!![EXPLOIT]!!!!!!!!!!!!"; + // fmt_map["[KEYLONGER]"] = "short"; + // fmt_map["[KEYSHORTER]"] = "Am I not a long string?"; + // fmt_map["?"] = "?"; + // fmt_map["[DELETE]"] = ""; + // fmt_map["[]"] = "[]"; // doesn't do a substitution, but shouldn't crash either + + // for (LLStringUtil::format_map_t::const_iterator iter = fmt_map.begin(); iter != fmt_map.end(); ++iter) + // { + // // Test when source string is entirely one key + // std::string s1 = (std::string)iter->first; + // std::string s2 = (std::string)iter->second; + // subcount = LLStringUtil::format(s1, fmt_map); + // ensure_equals("LLStringUtil::format: Raw interpolation result", s1, s2); + // if (s1 == "?" || s1 == "[]") // no interp expected + // { + // ensure_equals("LLStringUtil::format: Raw interpolation result count", 0, subcount); + // } + // else + // { + // ensure_equals("LLStringUtil::format: Raw interpolation result count", 1, subcount); + // } + // } + + // for (LLStringUtil::format_map_t::const_iterator iter = fmt_map.begin(); iter != fmt_map.end(); ++iter) + // { + // // Test when source string is one key, duplicated + // std::string s1 = (std::string)iter->first; + // std::string s2 = (std::string)iter->second; + // s = s1 + s1 + s1 + s1; + // subcount = LLStringUtil::format(s, fmt_map); + // ensure_equals("LLStringUtil::format: Rawx4 interpolation result", s, s2 + s2 + s2 + s2); + // if (s1 == "?" || s1 == "[]") // no interp expected + // { + // ensure_equals("LLStringUtil::format: Rawx4 interpolation result count", 0, subcount); + // } + // else + // { + // ensure_equals("LLStringUtil::format: Rawx4 interpolation result count", 4, subcount); + // } + // } + + // // Test when source string has no keys + // std::string srcs = "!!!!!!!!!!!!!!!!"; + // s = srcs; + // subcount = LLStringUtil::format(s, fmt_map); + // ensure_equals("LLStringUtil::format: No key test result", s, srcs); + // ensure_equals("LLStringUtil::format: No key test result count", 0, subcount); + + // // Test when source string has no keys and is empty + // std::string srcs3; + // s = srcs3; + // subcount = LLStringUtil::format(s, fmt_map); + // ensure("LLStringUtil::format: No key test3 result", s.empty()); + // ensure_equals("LLStringUtil::format: No key test3 result count", 0, subcount); + + // // Test a substitution where a key is substituted with blankness + // std::string srcs2 = "[DELETE]"; + // s = srcs2; + // subcount = LLStringUtil::format(s, fmt_map); + // ensure("LLStringUtil::format: Delete key test2 result", s.empty()); + // ensure_equals("LLStringUtil::format: Delete key test2 result count", 1, subcount); + + // // Test an assorted substitution + // std::string srcs4 = "[TRICK1][A][B][AAA][BBB][TRICK2][KEYLONGER][KEYSHORTER]?[DELETE]"; + // s = srcs4; + // subcount = LLStringUtil::format(s, fmt_map); + // ensure_equals("LLStringUtil::format: Assorted Test1 result", s, "[A]abaaabbb[A]shortAm I not a long string??"); + // ensure_equals("LLStringUtil::format: Assorted Test1 result count", 9, subcount); + + // // Test an assorted substitution + // std::string srcs5 = "[DELETE]?[KEYSHORTER][KEYLONGER][TRICK2][BBB][AAA][B][A][TRICK1]"; + // s = srcs5; + // subcount = LLStringUtil::format(s, fmt_map); + // ensure_equals("LLStringUtil::format: Assorted Test2 result", s, "?Am I not a long string?short[A]bbbaaaba[A]"); + // ensure_equals("LLStringUtil::format: Assorted Test2 result count", 9, subcount); + + // // Test on nested brackets + // std::string srcs6 = "[[TRICK1]][[A]][[B]][[AAA]][[BBB]][[TRICK2]][[KEYLONGER]][[KEYSHORTER]]?[[DELETE]]"; + // s = srcs6; + // subcount = LLStringUtil::format(s, fmt_map); + // ensure_equals("LLStringUtil::format: Assorted Test2 result", s, "[[A]][a][b][aaa][bbb][[A]][short][Am I not a long string?]?[]"); + // ensure_equals("LLStringUtil::format: Assorted Test2 result count", 9, subcount); + + + // // Test an assorted substitution + // std::string srcs8 = "foo[DELETE]bar?"; + // s = srcs8; + // subcount = LLStringUtil::format(s, fmt_map); + // ensure_equals("LLStringUtil::format: Assorted Test3 result", s, "foobar?"); + // ensure_equals("LLStringUtil::format: Assorted Test3 result count", 1, subcount); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_33") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<33> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<33>() + // { + // // Test LLStringUtil::format() string interpolation + // LLStringUtil::format_map_t blank_fmt_map; + // std::string s; + // int subcount; + + // // Test substituting out of a blank format_map + // std::string srcs6 = "12345"; + // s = srcs6; + // subcount = LLStringUtil::format(s, blank_fmt_map); + // ensure_equals("LLStringUtil::format: Blankfmt Test1 result", s, "12345"); + // ensure_equals("LLStringUtil::format: Blankfmt Test1 result count", 0, subcount); + + // // Test substituting a blank string out of a blank format_map + // std::string srcs7; + // s = srcs7; + // subcount = LLStringUtil::format(s, blank_fmt_map); + // ensure("LLStringUtil::format: Blankfmt Test2 result", s.empty()); + // ensure_equals("LLStringUtil::format: Blankfmt Test2 result count", 0, subcount); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_34") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<34> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<34>() + // { + // // Test that incorrect LLStringUtil::format() use does not explode. + // LLStringUtil::format_map_t nasty_fmt_map; + // std::string s; + // int subcount; + + // nasty_fmt_map[""] = "never used"; // see, this is nasty. + + // // Test substituting out of a nasty format_map + // std::string srcs6 = "12345"; + // s = srcs6; + // subcount = LLStringUtil::format(s, nasty_fmt_map); + // ensure_equals("LLStringUtil::format: Nastyfmt Test1 result", s, "12345"); + // ensure_equals("LLStringUtil::format: Nastyfmt Test1 result count", 0, subcount); + + // // Test substituting a blank string out of a nasty format_map + // std::string srcs7; + // s = srcs7; + // subcount = LLStringUtil::format(s, nasty_fmt_map); + // ensure("LLStringUtil::format: Nastyfmt Test2 result", s.empty()); + // ensure_equals("LLStringUtil::format: Nastyfmt Test2 result count", 0, subcount); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_35") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<35> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<35>() + // { + // // Make sure startsWith works + // std::string string("anybody in there?"); + // std::string substr("anybody"); + // ensure("startsWith works.", LLStringUtil::startsWith(string, substr)); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_36") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<36> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<36>() + // { + // // Make sure startsWith correctly fails + // std::string string("anybody in there?"); + // std::string substr("there"); + // ensure("startsWith fails.", !LLStringUtil::startsWith(string, substr)); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_37") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<37> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<37>() + // { + // // startsWith fails on empty strings + // std::string value("anybody in there?"); + // std::string empty; + // ensure("empty string.", !LLStringUtil::startsWith(value, empty)); + // ensure("empty substr.", !LLStringUtil::startsWith(empty, value)); + // ensure("empty everything.", !LLStringUtil::startsWith(empty, empty)); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_38") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<38> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<38>() + // { + // // Make sure endsWith works correctly + // std::string string("anybody in there?"); + // std::string substr("there?"); + // ensure("endsWith works.", LLStringUtil::endsWith(string, substr)); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_39") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<39> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<39>() + // { + // // Make sure endsWith correctly fails + // std::string string("anybody in there?"); + // std::string substr("anybody"); + // ensure("endsWith fails.", !LLStringUtil::endsWith(string, substr)); + // substr = "there"; + // ensure("endsWith fails.", !LLStringUtil::endsWith(string, substr)); + // substr = "ther?"; + // ensure("endsWith fails.", !LLStringUtil::endsWith(string, substr)); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_40") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<40> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<40>() + // { + // // endsWith fails on empty strings + // std::string value("anybody in there?"); + // std::string empty; + // ensure("empty string.", !LLStringUtil::endsWith(value, empty)); + // ensure("empty substr.", !LLStringUtil::endsWith(empty, value)); + // ensure("empty everything.", !LLStringUtil::endsWith(empty, empty)); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_41") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<41> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<41>() + // { + // set_test_name("getTokens(\"delims\")"); + // ensure_equals("empty string", LLStringUtil::getTokens("", " "), StringVec()); + // ensure_equals("only delims", + // LLStringUtil::getTokens(" \r\n ", " \r\n"), StringVec()); + // ensure_equals("sequence of delims", + // LLStringUtil::getTokens(",,, one ,,,", ","), list_of("one")); + // // nat considers this a dubious implementation side effect, but I'd + // // hate to change it now... + // ensure_equals("noncontiguous tokens", + // LLStringUtil::getTokens(", ,, , one ,,,", ","), list_of("")("")("one")); + // ensure_equals("space-padded tokens", + // LLStringUtil::getTokens(", one , two ,", ","), list_of("one")("two")); + // ensure_equals("no delims", LLStringUtil::getTokens("one", ","), list_of("one")); + // } + } + + TUT_CASE("llstring_test::string_index_object_t_test_42") + { + DOCTEST_FAIL("TODO: convert llstring_test.cpp::string_index_object_t::test<42> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void string_index_object_t::test<42>() + // { + // set_test_name("getTokens(\"delims\", etc.)"); + // // Signatures to test in this method: + // // getTokens(string, drop_delims, keep_delims [, quotes [, escapes]]) + // // If you omit keep_delims, you get the older function (test above). + + // // cases like the getTokens(string, delims) tests above + // ensure_getTokens("empty string", "", " ", "", StringVec()); + // ensure_getTokens("only delims", + // " \r\n ", " \r\n", "", StringVec()); + // ensure_getTokens("sequence of delims", + // ",,, one ,,,", ", ", "", list_of("one")); + // // Note contrast with the case in the previous method + // ensure_getTokens("noncontiguous tokens", + // ", ,, , one ,,,", ", ", "", list_of("one")); + // ensure_getTokens("space-padded tokens", + // ", one , two ,", ", ", "", + // list_of("one")("two")); + // ensure_getTokens("no delims", "one", ",", "", list_of("one")); + + // // drop_delims vs. keep_delims + // ensure_getTokens("arithmetic", + // " ab+def / xx* yy ", " ", "+-*/", + // list_of("ab")("+")("def")("/")("xx")("*")("yy")); + + // // quotes + // ensure_getTokens("no quotes", + // "She said, \"Don't go.\"", " ", ",", "", + // list_of("She")("said")(",")("\"Don't")("go.\"")); + // ensure_getTokens("quotes", + // "She said, \"Don't go.\"", " ", ",", "\"", + // list_of("She")("said")(",")("Don't go.")); + // ensure_getTokens("quotes and delims", + // "run c:/'Documents and Settings'/someone", " ", "", "'", + // list_of("run")("c:/Documents and Settings/someone")); + // ensure_getTokens("unmatched quote", + // "baby don't leave", " ", "", "'", + // list_of("baby")("don't")("leave")); + // ensure_getTokens("adjacent quoted", + // "abc'def \"ghi'\"jkl' mno\"pqr", " ", "", "\"'", + // list_of("abcdef \"ghijkl' mnopqr")); + // ensure_getTokens("quoted empty string", + // "--set SomeVar ''", " ", "", "'", + // list_of("--set")("SomeVar")("")); + + // // escapes + // // Don't use backslash as an escape for these tests -- you'll go nuts + // // between the C++ string scanner and getTokens() escapes. Test with + // // something else! + // ensure_equals("escaped delims", + // LLStringUtil::getTokens("^ a - dog^-gone^ phrase", " ", "-", "", "^"), + // list_of(" a")("-")("dog-gone phrase")); + // ensure_equals("escaped quotes", + // LLStringUtil::getTokens("say: 'this isn^'t w^orking'.", " ", "", "'", "^"), + // list_of("say:")("this isn't working.")); + // ensure_equals("escaped escape", + // LLStringUtil::getTokens("want x^^2", " ", "", "", "^"), + // list_of("want")("x^2")); + // ensure_equals("escape at end", + // LLStringUtil::getTokens("it's^ up there^", " ", "", "'", "^"), + // list_of("it's up")("there^")); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/lltrace_test_doctest.cpp b/indra/llcommon/tests_doctest/lltrace_test_doctest.cpp new file mode 100644 index 00000000000..b49ec41b918 --- /dev/null +++ b/indra/llcommon/tests_doctest/lltrace_test_doctest.cpp @@ -0,0 +1,103 @@ +/** + * @file lltrace_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL trace + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from lltrace_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "lltrace.h" +#include "lltracethreadrecorder.h" +#include "lltracerecording.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("lltrace_test::trace_object_t_test_1") + { + DOCTEST_FAIL("TODO: convert lltrace_test.cpp::trace_object_t::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void trace_object_t::test<1>() + // { + // sample(sCaffeineLevelStat, sCaffeineLevel); + + // Recording all_day; + // Recording at_work; + // Recording after_3pm; + + // all_day.start(); + // { + // // warm up with one grande cup + // drink_coffee(1, S32TallCup(1)); + + // // go to work + // at_work.start(); + // { + // // drink 3 tall cups, 1 after 3 pm + // drink_coffee(2, S32GrandeCup(1)); + // after_3pm.start(); + // drink_coffee(1, S32GrandeCup(1)); + // } + // at_work.stop(); + // drink_coffee(1, S32VentiCup(1)); + // } + // // don't need to stop recordings to get accurate values out of them + // //after_3pm.stop(); + // //all_day.stop(); + + // ensure("count stats are counted when recording is active", + // at_work.getSum(sCupsOfCoffeeConsumed) == 3 + // && all_day.getSum(sCupsOfCoffeeConsumed) == 5 + // && after_3pm.getSum(sCupsOfCoffeeConsumed) == 2); + // ensure("measurement sums are counted when recording is active", + // at_work.getSum(sOuncesPerCup) == S32Ounces(48) + // && all_day.getSum(sOuncesPerCup) == S32Ounces(80) + // && after_3pm.getSum(sOuncesPerCup) == S32Ounces(36)); + // ensure("measurement min is specific to when recording is active", + // at_work.getMin(sOuncesPerCup) == S32GrandeCup(1) + // && all_day.getMin(sOuncesPerCup) == S32TallCup(1) + // && after_3pm.getMin(sOuncesPerCup) == S32GrandeCup(1)); + // ensure("measurement max is specific to when recording is active", + // at_work.getMax(sOuncesPerCup) == S32GrandeCup(1) + // && all_day.getMax(sOuncesPerCup) == S32VentiCup(1) + // && after_3pm.getMax(sOuncesPerCup) == S32VentiCup(1)); + // ensure("sample min is specific to when recording is active", + // at_work.getMin(sCaffeineLevelStat) == sCaffeinePerOz * ((S32Ounces)S32TallCup(1)).value() + // && all_day.getMin(sCaffeineLevelStat) == F32Milligrams(0.f) + // && after_3pm.getMin(sCaffeineLevelStat) == sCaffeinePerOz * ((S32Ounces)S32TallCup(1) + (S32Ounces)S32GrandeCup(2)).value()); + // ensure("sample max is specific to when recording is active", + // at_work.getMax(sCaffeineLevelStat) == sCaffeinePerOz * ((S32Ounces)S32TallCup(1) + (S32Ounces)S32GrandeCup(3)).value() + // && all_day.getMax(sCaffeineLevelStat) == sCaffeinePerOz * ((S32Ounces)S32TallCup(1) + (S32Ounces)S32GrandeCup(3) + (S32Ounces)S32VentiCup(1)).value() + // && after_3pm.getMax(sCaffeineLevelStat) == sCaffeinePerOz * ((S32Ounces)S32TallCup(1) + (S32Ounces)S32GrandeCup(3) + (S32Ounces)S32VentiCup(1)).value()); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/lltreeiterators_test_doctest.cpp b/indra/llcommon/tests_doctest/lltreeiterators_test_doctest.cpp new file mode 100644 index 00000000000..b0ff1381ecf --- /dev/null +++ b/indra/llcommon/tests_doctest/lltreeiterators_test_doctest.cpp @@ -0,0 +1,280 @@ +/** + * @file lltreeiterators_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL treeiterators + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from lltreeiterators_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include +#include +#include +#include +#include +#include "../lltreeiterators.h" +#include "../llpointer.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("lltreeiterators_test::iter_object_test_1") + { + DOCTEST_FAIL("TODO: convert lltreeiterators_test.cpp::iter_object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void iter_object::test<1>() + // { + // // set_test_name("LLLinkedIter -- non-refcounted class"); + // PlainNode* last(new PlainNode("c")); + // PlainNode* second(new PlainNode("b", last)); + // PlainNode* first(new PlainNode("a", second)); + // Cleanup cleanup(first); + // static const char* cseq[] = { "a", "b", "c" }; + // Expected seq(boost::begin(cseq), boost::end(cseq)); + // std::string desc1("Iterate by public link member"); + // // std::cout << desc1 << ":\n"; + // // Try instantiating an iterator with NULL. This test is less about + // // "did we iterate once?" than "did we avoid blowing up?" + // for (LLLinkedIter pni(NULL, boost::bind(&PlainNode::mNext, _1)), end; + // pni != end; ++pni) + // { + // // std::cout << (*pni)->name() << '\n'; + // ensure("LLLinkedIter(NULL)", false); + // } + // ensure(desc1, + // verify(desc1, + // boost::make_iterator_range(LLLinkedIter(first, + // boost::bind(&PlainNode::mNext, _1)), + // LLLinkedIter()), + // seq)); + // std::string desc2("Iterate by next() method"); + // // std::cout << desc2 << ":\n"; + // // for (LLLinkedIter pni(first, boost::bind(&PlainNode::next, _1)); ! (pni == end); ++pni) + // // std::cout << (**pni).name() << '\n'; + // ensure(desc2, + // verify(desc2, + // boost::make_iterator_range(LLLinkedIter(first, + // boost::bind(&PlainNode::next, _1)), + // LLLinkedIter()), + // seq)); + // { + // // LLLinkedIter pni(first, boost::bind(&PlainNode::next, _1)); + // // std::cout << "First is " << (*pni++)->name() << '\n'; + // // std::cout << "Second is " << (*pni )->name() << '\n'; + // } + // { + // LLLinkedIter pni(first, boost::bind(&PlainNode::next, _1)); + // ensure_equals("first", (*pni++)->name(), "a"); + // ensure_equals("second", (*pni )->name(), "b"); + // } + // } + } + + TUT_CASE("lltreeiterators_test::iter_object_test_2") + { + DOCTEST_FAIL("TODO: convert lltreeiterators_test.cpp::iter_object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void iter_object::test<2>() + // { + // // set_test_name("LLLinkedIter -- refcounted class"); + // LLLinkedIter rcni, end2; + // { + // // ScopeLabel label("inner scope"); + // RCNodePtr head(new RCNode("x", new RCNode("y", new RCNode("z")))); + // // for (rcni = LLLinkedIter(head, boost::bind(&RCNode::mNext, _1)); rcni != end2; ++rcni) + // // std::cout << **rcni << '\n'; + // rcni = LLLinkedIter(head, boost::bind(&RCNode::next, _1)); + // } + // // std::cout << "Now the LLLinkedIter is the only remaining reference to RCNode chain\n"; + // ensure_equals(last_RCNode_destroyed, ""); + // ensure(rcni != end2); + // ensure_equals((*rcni)->name(), "x"); + // ++rcni; + // ensure_equals(last_RCNode_destroyed, "x"); + // ensure(rcni != end2); + // ensure_equals((*rcni)->name(), "y"); + // ++rcni; + // ensure_equals(last_RCNode_destroyed, "y"); + // ensure(rcni != end2); + // ensure_equals((*rcni)->name(), "z"); + // ++rcni; + // ensure_equals(last_RCNode_destroyed, "z"); + // ensure(rcni == end2); + // } + } + + TUT_CASE("lltreeiterators_test::iter_object_test_3") + { + DOCTEST_FAIL("TODO: convert lltreeiterators_test.cpp::iter_object::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void iter_object::test<3>() + // { + // // set_test_name("LLTreeIter tests"); + // ensure(LLTreeIter_tests + // ("TreeNode", + // boost::bind(&TreeNode::getParent, _1), + // boost::bind(&TreeNode::child_begin, _1), + // boost::bind(&TreeNode::child_end, _1))); + // ensure(LLTreeIter_tests > + // ("PlainTree", + // boost::bind(&PlainTree::mParent, _1), + // PlainTree_child_begin, + // PlainTree_child_end)); + // } + } + + TUT_CASE("lltreeiterators_test::iter_object_test_4") + { + DOCTEST_FAIL("TODO: convert lltreeiterators_test.cpp::iter_object::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void iter_object::test<4>() + // { + // // set_test_name("getRootRange() tests"); + // // This test function illustrates the looping techniques described in the + // // comments for the getRootRange() free function, the + // // EnhancedTreeNode::root_range template and the + // // EnhancedTreeNode::getRootRange() method. Obviously the for() + // // forms are more succinct. + // TreeNodePtr tnroot(example_tree()); + // TreeNodePtr tnB2b(get_B2b + // (tnroot, boost::bind(&TreeNode::child_begin, _1))); + + // std::string desc1("for (TreeNodePr : getRootRange(tnB2b))"); + // // std::cout << desc1 << "\n"; + // // Although we've commented out the output statement, ensure that the + // // loop construct is still valid, as promised by the getRootRange() + // // documentation. + // for (TreeNodePtr node : getRootRange(tnB2b)) + // { + // // std::cout << node->name() << '\n'; + // } + // ensure(desc1, + // verify(desc1, getRootRange(tnB2b), RootExpected())); + + // EnhancedTreeNodePtr etnroot(example_tree()); + // EnhancedTreeNodePtr etnB2b(get_B2b + // (etnroot, boost::bind(&EnhancedTreeNode::child_begin, _1))); + + // // std::cout << "EnhancedTreeNode::root_range::type range =\n" + // // << " etnB2b->getRootRange();\n" + // // << "for (EnhancedTreeNode::root_range::type::iterator ri = range.begin();\n" + // // << " ri != range.end(); ++ri)\n"; + // EnhancedTreeNode::root_range::type range = + // etnB2b->getRootRange(); + // for (EnhancedTreeNode::root_range::type::iterator ri = range.begin(); + // ri != range.end(); ++ri) + // { + // // std::cout << (*ri)->name() << '\n'; + // } + + // std::string desc2("for (EnhancedTreeNodePtr node : etnB2b->getRootRange())"); + // // std::cout << desc2 << '\n'; + // for (EnhancedTreeNodePtr node : etnB2b->getRootRange()) + // { + // // std::cout << node->name() << '\n'; + // } + // ensure(desc2, + // verify(desc2, etnB2b->getRootRange(), RootExpected())); + // } + } + + TUT_CASE("lltreeiterators_test::iter_object_test_5") + { + DOCTEST_FAIL("TODO: convert lltreeiterators_test.cpp::iter_object::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void iter_object::test<5>() + // { + // // set_test_name("getWalkRange() tests"); + // // This test function doesn't illustrate the looping permutations for + // // getWalkRange(); see getRootRange_tests() for such examples. This + // // function simply verifies that they all work. + + // // TreeNode, using helper function + // TreeNodePtr tnroot(example_tree()); + // std::string desc_tnpre("getWalkRange(tnroot)"); + // ensure(desc_tnpre, + // verify(desc_tnpre, + // getWalkRange(tnroot), + // WalkExpected())); + // std::string desc_tnpost("getWalkRange(tnroot)"); + // ensure(desc_tnpost, + // verify(desc_tnpost, + // getWalkRange(tnroot), + // WalkExpected())); + // std::string desc_tnb("getWalkRange(tnroot)"); + // ensure(desc_tnb, + // verify(desc_tnb, + // getWalkRange(tnroot), + // WalkExpected())); + + // // EnhancedTreeNode, using method + // EnhancedTreeNodePtr etnroot(example_tree()); + // std::string desc_etnpre("etnroot->getWalkRange()"); + // ensure(desc_etnpre, + // verify(desc_etnpre, + // etnroot->getWalkRange(), + // WalkExpected())); + // std::string desc_etnpost("etnroot->getWalkRange()"); + // ensure(desc_etnpost, + // verify(desc_etnpost, + // etnroot->getWalkRange(), + // WalkExpected())); + // std::string desc_etnb("etnroot->getWalkRange()"); + // ensure(desc_etnb, + // verify(desc_etnb, + // etnroot->getWalkRange(), + // WalkExpected())); + + // // PlainTree, using helper function + // PlainTree* ptroot(example_tree()); + // Cleanup cleanup(ptroot); + // std::string desc_ptpre("getWalkRange(ptroot)"); + // ensure(desc_ptpre, + // verify(desc_ptpre, + // getWalkRange(ptroot), + // WalkExpected())); + // std::string desc_ptpost("getWalkRange(ptroot)"); + // ensure(desc_ptpost, + // verify(desc_ptpost, + // getWalkRange(ptroot), + // WalkExpected())); + // std::string desc_ptb("getWalkRange(ptroot)"); + // ensure(desc_ptb, + // verify(desc_ptb, + // getWalkRange(ptroot), + // WalkExpected())); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/llunits_test_doctest.cpp b/indra/llcommon/tests_doctest/llunits_test_doctest.cpp new file mode 100644 index 00000000000..c005cfe3a77 --- /dev/null +++ b/indra/llcommon/tests_doctest/llunits_test_doctest.cpp @@ -0,0 +1,387 @@ +/** + * @file llunits_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL units + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from llunits_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "llunits.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("llunits_test::units_object_t_test_1") + { + DOCTEST_FAIL("TODO: convert llunits_test.cpp::units_object_t::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void units_object_t::test<1>() + // { + // LLUnit float_quatloos; + // ensure("default float unit is zero", float_quatloos == F32Quatloos(0.f)); + + // LLUnit float_initialize_quatloos(1); + // ensure("non-zero initialized unit", float_initialize_quatloos == F32Quatloos(1.f)); + + // LLUnit int_quatloos; + // ensure("default int unit is zero", int_quatloos == S32Quatloos(0)); + + // int_quatloos = S32Quatloos(42); + // ensure("int assignment is preserved", int_quatloos == S32Quatloos(42)); + // float_quatloos = int_quatloos; + // ensure("float assignment from int preserves value", float_quatloos == F32Quatloos(42.f)); + + // int_quatloos = float_quatloos; + // ensure("int assignment from float preserves value", int_quatloos == S32Quatloos(42)); + + // float_quatloos = F32Quatloos(42.1f); + // int_quatloos = float_quatloos; + // ensure("int units truncate float units on assignment", int_quatloos == S32Quatloos(42)); + + // LLUnit unsigned_int_quatloos(float_quatloos); + // ensure("unsigned int can be initialized from signed int", unsigned_int_quatloos == S32Quatloos(42)); + + // S32Solari int_solari(1); + + // float_quatloos = int_solari; + // ensure("fractional units are preserved in conversion from integer to float type", float_quatloos == F32Quatloos(0.25f)); + + // int_quatloos = S32Quatloos(1); + // F32Solari float_solari = int_quatloos; + // ensure("can convert with fractional intermediates from integer to float type", float_solari == F32Solari(4.f)); + // } + } + + TUT_CASE("llunits_test::units_object_t_test_2") + { + DOCTEST_FAIL("TODO: convert llunits_test.cpp::units_object_t::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void units_object_t::test<2>() + // { + // LLUnit quatloos(1.f); + // LLUnit latinum_bars(quatloos); + // ensure("conversion between units is automatic via initialization", latinum_bars == F32Latinum(1.f / 4.f)); + + // latinum_bars = S32Latinum(256); + // quatloos = latinum_bars; + // ensure("conversion between units is automatic via assignment, and bidirectional", quatloos == S32Quatloos(1024)); + + // LLUnit single_quatloo(1); + // LLUnit quarter_latinum = single_quatloo; + // ensure("division of integer unit preserves fractional values when converted to float unit", quarter_latinum == F32Latinum(0.25f)); + // } + } + + TUT_CASE("llunits_test::units_object_t_test_3") + { + DOCTEST_FAIL("TODO: convert llunits_test.cpp::units_object_t::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void units_object_t::test<3>() + // { + // LLUnit quatloos(1024); + // LLUnit solari(quatloos); + // ensure("conversions can work between indirectly related units: Quatloos -> Latinum -> Solari", solari == S32Solari(4096)); + + // LLUnit latinum_bars = solari; + // ensure("Non base units can be converted between each other", latinum_bars == S32Latinum(256)); + // } + } + + TUT_CASE("llunits_test::units_object_t_test_4") + { + DOCTEST_FAIL("TODO: convert llunits_test.cpp::units_object_t::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void units_object_t::test<4>() + // { + // // exercise math operations + // LLUnit quatloos(1.f); + // quatloos *= 4.f; + // ensure(quatloos == S32Quatloos(4)); + // quatloos = quatloos * 2; + // ensure(quatloos == S32Quatloos(8)); + // quatloos = 2.f * quatloos; + // ensure(quatloos == S32Quatloos(16)); + + // quatloos += F32Quatloos(4.f); + // ensure(quatloos == S32Quatloos(20)); + // quatloos += S32Quatloos(4); + // ensure(quatloos == S32Quatloos(24)); + // quatloos = quatloos + S32Quatloos(4); + // ensure(quatloos == S32Quatloos(28)); + // quatloos = S32Quatloos(4) + quatloos; + // ensure(quatloos == S32Quatloos(32)); + // quatloos += quatloos * 3; + // ensure(quatloos == S32Quatloos(128)); + + // quatloos -= quatloos / 4 * 3; + // ensure(quatloos == S32Quatloos(32)); + // quatloos = quatloos - S32Quatloos(8); + // ensure(quatloos == S32Quatloos(24)); + // quatloos -= S32Quatloos(4); + // ensure(quatloos == S32Quatloos(20)); + // quatloos -= F32Quatloos(4.f); + // ensure(quatloos == S32Quatloos(16)); + + // quatloos /= 2.f; + // ensure(quatloos == S32Quatloos(8)); + // quatloos = quatloos / 4; + // ensure(quatloos == S32Quatloos(2)); + + // F32 ratio = quatloos / LLUnit(2.f); + // ensure(ratio == 1); + // ratio = quatloos / LLUnit(8.f); + // ensure(ratio == 1); + + // quatloos += LLUnit(8.f); + // ensure(quatloos == S32Quatloos(4)); + // quatloos -= LLUnit(1.f); + // ensure(quatloos == S32Quatloos(0)); + // } + } + + TUT_CASE("llunits_test::units_object_t_test_5") + { + DOCTEST_FAIL("TODO: convert llunits_test.cpp::units_object_t::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void units_object_t::test<5>() + // { + // LLUnit quatloos(1); + // ensure("can perform less than comparison against same type", quatloos < S32Quatloos(2)); + // ensure("can perform less than comparison against different storage type", quatloos < F32Quatloos(2.f)); + // ensure("can perform less than comparison against different units", quatloos < S32Latinum(5)); + // ensure("can perform less than comparison against different storage type and units", quatloos < F32Latinum(5.f)); + + // ensure("can perform greater than comparison against same type", quatloos > S32Quatloos(0)); + // ensure("can perform greater than comparison against different storage type", quatloos > F32Quatloos(0.f)); + // ensure("can perform greater than comparison against different units", quatloos > S32Latinum(0)); + // ensure("can perform greater than comparison against different storage type and units", quatloos > F32Latinum(0.f)); + + // } + } + + TUT_CASE("llunits_test::units_object_t_test_6") + { + DOCTEST_FAIL("TODO: convert llunits_test.cpp::units_object_t::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void units_object_t::test<6>() + // { + // S32Quatloos quatloos(1); + // ensure("can pass unit values as argument", accept_explicit_quatloos(S32Quatloos(1))); + // ensure("can pass unit values as argument", accept_explicit_quatloos(quatloos)); + // } + } + + TUT_CASE("llunits_test::units_object_t_test_7") + { + DOCTEST_FAIL("TODO: convert llunits_test.cpp::units_object_t::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void units_object_t::test<7>() + // { + // LLUnit quatloos; + // LLUnitImplicit quatloos_implicit = quatloos + S32Quatloos(1); + // ensure("can initialize implicit unit from explicit", quatloos_implicit == 1); + + // quatloos = quatloos_implicit; + // ensure("can assign implicit unit to explicit unit", quatloos == S32Quatloos(1)); + // quatloos += quatloos_implicit; + // ensure("can perform math operation using mixture of implicit and explicit units", quatloos == S32Quatloos(2)); + + // // math operations on implicits + // quatloos_implicit = 1; + // ensure(quatloos_implicit == 1); + + // quatloos_implicit += 2; + // ensure(quatloos_implicit == 3); + + // quatloos_implicit *= 2; + // ensure(quatloos_implicit == 6); + + // quatloos_implicit -= 1; + // ensure(quatloos_implicit == 5); + + // quatloos_implicit /= 5; + // ensure(quatloos_implicit == 1); + + // quatloos_implicit = quatloos_implicit + 3 + quatloos_implicit; + // ensure(quatloos_implicit == 5); + + // quatloos_implicit = 10 - quatloos_implicit - 1; + // ensure(quatloos_implicit == 4); + + // quatloos_implicit = 2 * quatloos_implicit * 2; + // ensure(quatloos_implicit == 16); + + // F32 one_half = quatloos_implicit / (quatloos_implicit * 2); + // ensure(one_half == 0.5f); + + // // implicit conversion to POD + // F32 float_val = quatloos_implicit; + // ensure("implicit units convert implicitly to regular values", float_val == 16); + + // S32 int_val = (S32)quatloos_implicit; + // ensure("implicit units convert implicitly to regular values", int_val == 16); + + // // conversion of implicits + // LLUnitImplicit latinum_implicit(2); + // ensure("implicit units of different types are comparable", latinum_implicit * 2 == quatloos_implicit); + + // quatloos_implicit += F32Quatloos(10); + // ensure("can add-assign explicit units", quatloos_implicit == 26); + + // quatloos_implicit -= F32Quatloos(10); + // ensure("can subtract-assign explicit units", quatloos_implicit == 16); + + // // comparisons + // ensure("can compare greater than implicit unit", quatloos_implicit > F32QuatloosImplicit(0.f)); + // ensure("can compare greater than non-implicit unit", quatloos_implicit > F32Quatloos(0.f)); + // ensure("can compare greater than or equal to implicit unit", quatloos_implicit >= F32QuatloosImplicit(0.f)); + // ensure("can compare greater than or equal to non-implicit unit", quatloos_implicit >= F32Quatloos(0.f)); + // ensure("can compare less than implicit unit", quatloos_implicit < F32QuatloosImplicit(20.f)); + // ensure("can compare less than non-implicit unit", quatloos_implicit < F32Quatloos(20.f)); + // ensure("can compare less than or equal to implicit unit", quatloos_implicit <= F32QuatloosImplicit(20.f)); + // ensure("can compare less than or equal to non-implicit unit", quatloos_implicit <= F32Quatloos(20.f)); + // } + } + + TUT_CASE("llunits_test::units_object_t_test_8") + { + DOCTEST_FAIL("TODO: convert llunits_test.cpp::units_object_t::test<8> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void units_object_t::test<8>() + // { + // U32Bytes max_bytes(U32_MAX); + // S32Megabytes mega_bytes = max_bytes; + // ensure("max available precision is used when converting units", mega_bytes == (S32Megabytes)4095); + + // mega_bytes = (S32Megabytes)-5 + (U32Megabytes)1; + // ensure("can mix signed and unsigned in units addition", mega_bytes == (S32Megabytes)-4); + + // mega_bytes = (U32Megabytes)5 + (S32Megabytes)-1; + // ensure("can mix unsigned and signed in units addition", mega_bytes == (S32Megabytes)4); + // } + } + + TUT_CASE("llunits_test::units_object_t_test_9") + { + DOCTEST_FAIL("TODO: convert llunits_test.cpp::units_object_t::test<9> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void units_object_t::test<9>() + // { + // U32Gigabytes GB(1); + // U32Megabytes MB(GB); + // U32Kilobytes KB(GB); + // U32Bytes B(GB); + + // ensure("GB -> MB conversion", MB.value() == 1024); + // ensure("GB -> KB conversion", KB.value() == 1024 * 1024); + // ensure("GB -> B conversion", B.value() == 1024 * 1024 * 1024); + + // KB = U32Kilobytes(1); + // U32Kilobits Kb(KB); + // U32Bits b(KB); + // ensure("KB -> Kb conversion", Kb.value() == 8); + // ensure("KB -> b conversion", b.value() == 8 * 1024); + + // U32Days days(1); + // U32Hours hours(days); + // U32Minutes minutes(days); + // U32Seconds seconds(days); + // U32Milliseconds ms(days); + + // ensure("days -> hours conversion", hours.value() == 24); + // ensure("days -> minutes conversion", minutes.value() == 24 * 60); + // ensure("days -> seconds conversion", seconds.value() == 24 * 60 * 60); + // ensure("days -> ms conversion", ms.value() == 24 * 60 * 60 * 1000); + + // U32Kilometers km(1); + // U32Meters m(km); + // U32Centimeters cm(km); + // U32Millimeters mm(km); + + // ensure("km -> m conversion", m.value() == 1000); + // ensure("km -> cm conversion", cm.value() == 1000 * 100); + // ensure("km -> mm conversion", mm.value() == 1000 * 1000); + + // U32Gigahertz GHz(1); + // U32Megahertz MHz(GHz); + // U32Kilohertz KHz(GHz); + // U32Hertz Hz(GHz); + + // ensure("GHz -> MHz conversion", MHz.value() == 1000); + // ensure("GHz -> KHz conversion", KHz.value() == 1000 * 1000); + // ensure("GHz -> Hz conversion", Hz.value() == 1000 * 1000 * 1000); + + // F32Radians rad(6.2831853071795f); + // S32Degrees deg(rad); + // ensure("radians -> degrees conversion", deg.value() == 360); + + // F32Percent percent(50); + // F32Ratio ratio(percent); + // ensure("percent -> ratio conversion", ratio.value() == 0.5f); + + // U32Kilotriangles ktris(1); + // U32Triangles tris(ktris); + // ensure("kilotriangles -> triangles conversion", tris.value() == 1000); + // } + } + + TUT_CASE("llunits_test::units_object_t_test_10") + { + DOCTEST_FAIL("TODO: convert llunits_test.cpp::units_object_t::test<10> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void units_object_t::test<10>() + // { + // F32Celcius float_celcius(100); + // F32Fahrenheit float_fahrenheit(float_celcius); + // ensure("floating point celcius -> fahrenheit conversion using linear transform", value_near(float_fahrenheit.value(), 212, 0.1f) ); + + // float_celcius = float_fahrenheit; + // ensure("floating point fahrenheit -> celcius conversion using linear transform (round trip)", value_near(float_celcius.value(), 100.f, 0.1f) ); + + // S32Celcius int_celcius(100); + // S32Fahrenheit int_fahrenheit(int_celcius); + // ensure("integer celcius -> fahrenheit conversion using linear transform", int_fahrenheit.value() == 212); + + // int_celcius = int_fahrenheit; + // ensure("integer fahrenheit -> celcius conversion using linear transform (round trip)", int_celcius.value() == 100); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/lluri_test_doctest.cpp b/indra/llcommon/tests_doctest/lluri_test_doctest.cpp new file mode 100644 index 00000000000..5d4d4ee5797 --- /dev/null +++ b/indra/llcommon/tests_doctest/lluri_test_doctest.cpp @@ -0,0 +1,492 @@ +/** + * @file lluri_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for LL uri + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from lluri_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "../llsd.h" +#include "../lluri.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("lluri_test::URITestObject_test_1") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<1>() + // { + // LLURI u("http://abc.com/def/ghi?x=37&y=hello"); + + // ensure_equals("scheme", u.scheme(), "http"); + // ensure_equals("authority", u.authority(), "abc.com"); + // ensure_equals("path", u.path(), "/def/ghi"); + // ensure_equals("query", u.query(), "x=37&y=hello"); + + // ensure_equals("host name", u.hostName(), "abc.com"); + // ensure_equals("host port", u.hostPort(), 80); + + // LLSD query = u.queryMap(); + // ensure_equals("query x", query["x"].asInteger(), 37); + // ensure_equals("query y", query["y"].asString(), "hello"); + + // query = LLURI::queryMap("x=22.23&y=https://lindenlab.com/"); + // ensure_equals("query x", query["x"].asReal(), 22.23); + // ensure_equals("query y", query["y"].asURI().asString(), "https://lindenlab.com/"); + // } + } + + TUT_CASE("lluri_test::URITestObject_test_2") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<2>() + // { + // set_test_name("empty string"); + // checkParts(LLURI(""), "", "", "", ""); + // } + } + + TUT_CASE("lluri_test::URITestObject_test_3") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<3>() + // { + // set_test_name("no scheme"); + // checkParts(LLURI("foo"), "", "foo", "", ""); + // checkParts(LLURI("foo%3A"), "", "foo:", "", ""); + // } + } + + TUT_CASE("lluri_test::URITestObject_test_4") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<4>() + // { + // set_test_name("scheme w/o paths"); + // checkParts(LLURI("mailto:zero@ll.com"), + // "mailto", "zero@ll.com", "", ""); + // checkParts(LLURI("silly://abc/def?foo"), + // "silly", "//abc/def?foo", "", ""); + // } + } + + TUT_CASE("lluri_test::URITestObject_test_5") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<5>() + // { + // set_test_name("authority section"); + // checkParts(LLURI("http:///"), + // "http", "///", "", "/"); + + // checkParts(LLURI("http://abc"), + // "http", "//abc", "abc", ""); + + // checkParts(LLURI("http://a%2Fb/cd"), + // "http", "//a/b/cd", "a/b", "/cd"); + + // checkParts(LLURI("http://host?"), + // "http", "//host?", "host", ""); + // } + } + + TUT_CASE("lluri_test::URITestObject_test_6") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<6>() + // { + // set_test_name("path section"); + // checkParts(LLURI("http://host/a/b/"), + // "http", "//host/a/b/", "host", "/a/b/"); + + // checkParts(LLURI("http://host/a%3Fb/"), + // "http", "//host/a?b/", "host", "/a?b/"); + + // checkParts(LLURI("http://host/a:b/"), + // "http", "//host/a:b/", "host", "/a:b/"); + // } + } + + TUT_CASE("lluri_test::URITestObject_test_7") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<7> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<7>() + // { + // set_test_name("query string"); + // checkParts(LLURI("http://host/?"), + // "http", "//host/?", "host", "/", ""); + + // checkParts(LLURI("http://host/?x"), + // "http", "//host/?x", "host", "/", "x"); + + // checkParts(LLURI("http://host/??"), + // "http", "//host/??", "host", "/", "?"); + + // checkParts(LLURI("http://host/?%3F"), + // "http", "//host/??", "host", "/", "?"); + // } + } + + TUT_CASE("lluri_test::URITestObject_test_8") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<8> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<8>() + // { + // LLSD path; + // path.append("x"); + // path.append("123"); + // checkParts(LLURI::buildHTTP("host", path), + // "http", "//host/x/123", "host", "/x/123"); + + // LLSD query; + // query["123"] = "12"; + // query["abcd"] = "abc"; + // checkParts(LLURI::buildHTTP("host", path, query), + // "http", "//host/x/123?123=12&abcd=abc", + // "host", "/x/123", "123=12&abcd=abc"); + + // ensure_equals(LLURI::buildHTTP("host", "").asString(), + // "http://host"); + // ensure_equals(LLURI::buildHTTP("host", "/").asString(), + // "http://host/"); + // ensure_equals(LLURI::buildHTTP("host", "//").asString(), + // "http://host/"); + // ensure_equals(LLURI::buildHTTP("host", "dir name").asString(), + // "http://host/dir%20name"); + // ensure_equals(LLURI::buildHTTP("host", "dir name/").asString(), + // "http://host/dir%20name/"); + // ensure_equals(LLURI::buildHTTP("host", "/dir name").asString(), + // "http://host/dir%20name"); + // ensure_equals(LLURI::buildHTTP("host", "/dir name/").asString(), + // "http://host/dir%20name/"); + // ensure_equals(LLURI::buildHTTP("host", "dir name/subdir name").asString(), + // "http://host/dir%20name/subdir%20name"); + // ensure_equals(LLURI::buildHTTP("host", "dir name/subdir name/").asString(), + // "http://host/dir%20name/subdir%20name/"); + // ensure_equals(LLURI::buildHTTP("host", "/dir name/subdir name").asString(), + // "http://host/dir%20name/subdir%20name"); + // ensure_equals(LLURI::buildHTTP("host", "/dir name/subdir name/").asString(), + // "http://host/dir%20name/subdir%20name/"); + // ensure_equals(LLURI::buildHTTP("host", "//dir name//subdir name//").asString(), + // "http://host/dir%20name/subdir%20name/"); + // } + } + + TUT_CASE("lluri_test::URITestObject_test_9") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<9> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<9>() + // { + // set_test_name("test unescaped path components"); + // LLSD path; + // path.append("x@*//*$&^"); + // path.append("123"); + // checkParts(LLURI::buildHTTP("host", path), + // "http", "//host/x@*//*$&^/123", "host", "/x@*//*$&^/123"); + // } + } + + TUT_CASE("lluri_test::URITestObject_test_10") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<10> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<10>() + // { + // set_test_name("test unescaped query components"); + // LLSD path; + // path.append("x"); + // path.append("123"); + // LLSD query; + // query["123"] = "?&*#//"; + // query["**@&?//"] = "abc"; + // checkParts(LLURI::buildHTTP("host", path, query), + // "http", "//host/x/123?**@&?//=abc&123=?&*#//", + // "host", "/x/123", "**@&?//=abc&123=?&*#//"); + // } + } + + TUT_CASE("lluri_test::URITestObject_test_11") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<11> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<11>() + // { + // set_test_name("test unescaped host components"); + // LLSD path; + // path.append("x"); + // path.append("123"); + // LLSD query; + // query["123"] = "12"; + // query["abcd"] = "abc"; + // checkParts(LLURI::buildHTTP("hi123*33--} + } + + TUT_CASE("lluri_test::URITestObject_test_12") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<12> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<12>() + // { + // set_test_name("test funky host_port values that are actually prefixes"); + + // checkParts(LLURI::buildHTTP("http://example.com:8080", LLSD()), + // "http", "//example.com:8080", + // "example.com:8080", ""); + + // checkParts(LLURI::buildHTTP("http://example.com:8080/", LLSD()), + // "http", "//example.com:8080/", + // "example.com:8080", "/"); + + // checkParts(LLURI::buildHTTP("http://example.com:8080/a/b", LLSD()), + // "http", "//example.com:8080/a/b", + // "example.com:8080", "/a/b"); + // } + } + + TUT_CASE("lluri_test::URITestObject_test_13") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<13> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<13>() + // { + // const std::string unreserved = + // "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + // "0123456789" + // "-._~"; + // set_test_name("test escape"); + // ensure_equals("escaping", LLURI::escape("abcdefg", "abcdef"), "abcdef%67"); + // ensure_equals("escaping", LLURI::escape("|/&\\+-_!@", ""), "%7C%2F%26%5C%2B%2D%5F%21%40"); + // ensure_equals("escaping as query variable", + // LLURI::escape("http://10.0.1.4:12032/agent/god/agent-id/map/layer/?resume=http://station3.ll.com:12032/agent/203ad6df-b522-491d-ba48-4e24eb57aeff/send-postcard", unreserved + ":@!$'()*+,="), + // "http:%2F%2F10.0.1.4:12032%2Fagent%2Fgod%2Fagent-id%2Fmap%2Flayer%2F%3Fresume=http:%2F%2Fstation3.ll.com:12032%2Fagent%2F203ad6df-b522-491d-ba48-4e24eb57aeff%2Fsend-postcard"); + // // French cedilla (C with squiggle, like in the word Francais) is UTF-8 C3 A7 + + // #if LL_WINDOWS + // #pragma warning(disable: 4309) + // #endif + + // std::string cedilla; + // cedilla.push_back( (char)0xC3 ); + // cedilla.push_back( (char)0xA7 ); + // ensure_equals("escape UTF8", LLURI::escape( cedilla, unreserved), "%C3%A7"); + // } + } + + TUT_CASE("lluri_test::URITestObject_test_14") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<14> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<14>() + // { + // set_test_name("make sure escape and unescape of empty strings return empty strings."); + // std::string uri_esc(LLURI::escape("")); + // ensure("escape string empty", uri_esc.empty()); + // std::string uri_raw(LLURI::unescape("")); + // ensure("unescape string empty", uri_raw.empty()); + // } + } + + TUT_CASE("lluri_test::URITestObject_test_15") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<15> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<15>() + // { + // set_test_name("do some round-trip tests"); + // escapeRoundTrip("http://secondlife.com"); + // escapeRoundTrip("http://secondlife.com/url with spaces"); + // escapeRoundTrip("http://bad[domain]name.com/"); + // escapeRoundTrip("ftp://bill.gates@ms/micro$oft.com/c:\\autoexec.bat"); + // escapeRoundTrip(""); + // } + } + + TUT_CASE("lluri_test::URITestObject_test_16") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<16> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<16>() + // { + // set_test_name("Test the default escaping"); + // // yes -- this mangles the url. This is expected behavior + // std::string simple("http://secondlife.com"); + // ensure_equals( + // "simple http", + // LLURI::escape(simple), + // "http%3A%2F%2Fsecondlife.com"); + // ensure_equals( + // "needs escape", + // LLURI::escape("http://get.secondlife.com/windows viewer"), + // "http%3A%2F%2Fget.secondlife.com%2Fwindows%20viewer"); + // } + } + + TUT_CASE("lluri_test::URITestObject_test_17") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<17> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<17>() + // { + // set_test_name("do some round-trip tests with very long strings."); + // escapeRoundTrip("Welcome to Second Life.We hope you'll have a richly rewarding experience, filled with creativity, self expression and fun.The goals of the Community Standards are simple: treat each other with respect and without harassment, adhere to local standards as indicated by simulator ratings, and refrain from any hate activity which slurs a real-world individual or real-world community. Behavioral Guidelines - The Big Six"); + // escapeRoundTrip( + // "'asset_data':b(12100){'task_id':ucc706f2d-0b68-68f8-11a4-f1043ff35ca0}\n{\n\tname\tObject|\n\tpermissions 0\n\t{\n\t\tbase_mask\t7fffffff\n\t\towner_mask\t7fffffff\n\t\tgroup_mask\t00000000\n\t\teveryone_mask\t00000000\n\t\tnext_owner_mask\t7fffffff\n\t\tcreator_id\t13fd9595-a47b-4d64-a5fb-6da645f038e0\n\t\towner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tlast_owner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tgroup_id\t00000000-0000-0000-0000-000000000000\n\t}\n\tlocal_id\t217444921\n\ttotal_crc\t323\n\ttype\t2\n\ttask_valid\t2\n\ttravel_access\t13\n\tdisplayopts\t2\n\tdisplaytype\tv\n\tpos\t-0.368634403\t0.00781063363\t-0.569040775\n\toldpos\t150.117996\t25.8658009\t8.19664001\n\trotation\t-0.06293071806430816650390625\t-0.6995697021484375\t-0.7002241611480712890625\t0.1277817934751510620117188\n\tchildpos\t-0.00499999989\t-0.0359999985\t0.307999998\n\tchildrot\t-0.515492737293243408203125\t-0.46601200103759765625\t0.529055416584014892578125\t0.4870323240756988525390625\n\tscale" + // "\t0.074629\t0.289956\t0.01\n\tsit_offset\t0\t0\t0\n\tcamera_eye_offset\t0\t0\t0\n\tcamera_at_offset\t0\t0\t0\n\tsit_quat\t0\t0\t0\t1\n\tsit_hint\t0\n\tstate\t160\n\tmaterial\t3\n\tsoundid\t00000000-0000-0000-0000-000000000000\n\tsoundgain\t0\n\tsoundradius\t0\n\tsoundflags\t0\n\ttextcolor\t0 0 0 1\n\tselected\t0\n\tselector\t00000000-0000-0000-0000-000000000000\n\tusephysics\t0\n\trotate_x\t1\n\trotate_y\t1\n\trotate_z\t1\n\tphantom\t0\n\tremote_script_access_pin\t0\n\tvolume_detect\t0\n\tblock_grabs\t0\n\tdie_at_edge\t0\n\treturn_at_edge\t0\n\ttemporary\t0\n\tsandbox\t0\n\tsandboxhome\t0\t0\t0\n\tshape 0\n\t{\n\t\tpath 0\n\t\t{\n\t\t\tcurve\t16\n\t\t\tbegin\t0\n\t\t\tend\t1\n\t\t\tscale_x\t1\n\t\t\tscale_y\t1\n\t\t\tshear_x\t0\n\t\t\tshear_y\t0\n\t\t\ttwist\t0\n\t\t\ttwist_begin\t0\n\t\t\tradius_offset\t0\n\t\t\ttaper_x\t0\n\t\t\ttaper_y\t0\n\t\t\trevolutions\t1\n\t\t\tskew\t0\n\t\t}\n\t\tprofile 0\n\t\t{\n\t\t\tcurve\t1\n\t\t\tbegin\t0\n\t\t\tend\t1\n\t\t\thollow\t0\n\t\t}\n\t}\n\tf" + // "aces\t6\n\t{\n\t\timageid\tddde1ffc-678b-3cda-1748-513086bdf01b\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204" + // "\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tddde1ffc-678b-3cda-1748-513086bdf01b\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t-1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\tps_next_crc\t1\n\tgpw_bias\t1\n\tip\t0\n\tcomplete\tTRUE\n\tdelay\t50000\n\tnextstart\t0\n\tbirthtime\t1061088050622956\n\treztime\t1094866329019785\n\tparceltime\t1133568981980596\n\ttax_rate\t1.00084\n\tscratchpad\t0\n\t{\n\t\n\t}\n\tsale_info\t0\n\t{\n\t\tsale_type\tnot\n\t\tsale_price\t10\n\t}\n\tcorrect_family_id\t00000000-0000-0000-0000-000000000000\n\thas_rezzed\t0\n\tpre_link_base_mask\t7fffffff\n\tlinked \tchild\n\tdefault_pay_price\t-2\t1\t5\t10\t20\n}\n{'task_id':u61fa7364-e151-0597-774c-523312dae31b}\n{\n\tname\tObject|\n\tpermissions 0\n\t{\n\t\tbase_mask\t7fffff" + // "ff\n\t\towner_mask\t7fffffff\n\t\tgroup_mask\t00000000\n\t\teveryone_mask\t00000000\n\t\tnext_owner_mask\t7fffffff\n\t\tcreator_id\t13fd9595-a47b-4d64-a5fb-6da645f038e0\n\t\towner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tlast_owner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tgroup_id\t00000000-0000-0000-0000-000000000000\n\t}\n\tlocal_id\t217444922\n\ttotal_crc\t324\n\ttype\t2\n\ttask_valid\t2\n\ttravel_access\t13\n\tdisplayopts\t2\n\tdisplaytype\tv\n\tpos\t-0.367110789\t0.00780026987\t-0.566269755\n\toldpos\t150.115005\t25.8479004\t8.18669987\n\trotation\t0.47332942485809326171875\t-0.380102097988128662109375\t-0.5734078884124755859375\t0.550168216228485107421875\n\tchildpos\t-0.00499999989\t-0.0370000005\t0.305000007\n\tchildrot\t-0.736649334430694580078125\t-0.03042060509324073791503906\t-0.02784589119255542755126953\t0.67501628398895263671875\n\tscale\t0.074629\t0.289956\t0.01\n\tsit_offset\t0\t0\t0\n\tcamera_eye_offset\t0\t0\t0\n\tcamera_at_offset\t0\t0\t0\n\tsit_quat\t0\t" + // "0\t0\t1\n\tsit_hint\t0\n\tstate\t160\n\tmaterial\t3\n\tsoundid\t00000000-0000-0000-0000-000000000000\n\tsoundgain\t0\n\tsoundradius\t0\n\tsoundflags\t0\n\ttextcolor\t0 0 0 1\n\tselected\t0\n\tselector\t00000000-0000-0000-0000-000000000000\n\tusephysics\t0\n\trotate_x\t1\n\trotate_y\t1\n\trotate_z\t1\n\tphantom\t0\n\tremote_script_access_pin\t0\n\tvolume_detect\t0\n\tblock_grabs\t0\n\tdie_at_edge\t0\n\treturn_at_edge\t0\n\ttemporary\t0\n\tsandbox\t0\n\tsandboxhome\t0\t0\t0\n\tshape 0\n\t{\n\t\tpath 0\n\t\t{\n\t\t\tcurve\t16\n\t\t\tbegin\t0\n\t\t\tend\t1\n\t\t\tscale_x\t1\n\t\t\tscale_y\t1\n\t\t\tshear_x\t0\n\t\t\tshear_y\t0\n\t\t\ttwist\t0\n\t\t\ttwist_begin\t0\n\t\t\tradius_offset\t0\n\t\t\ttaper_x\t0\n\t\t\ttaper_y\t0\n\t\t\trevolutions\t1\n\t\t\tskew\t0\n\t\t}\n\t\tprofile 0\n\t\t{\n\t\t\tcurve\t1\n\t\t\tbegin\t0\n\t\t\tend\t1\n\t\t\thollow\t0\n\t\t}\n\t}\n\tfaces\t6\n\t{\n\t\timageid\tddde1ffc-678b-3cda-1748-513086bdf01b\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t" + // "\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t" + // "\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tddde1ffc-678b-3cda-1748-513086bdf01b\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t-1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\tps_next_crc\t1\n\tgpw_bias\t1\n\tip\t0\n\tcomplete\tTRUE\n\tdelay\t50000\n\tnextstart\t0\n\tbirthtime\t1061087839248891\n\treztime\t1094866329020800\n\tparceltime\t1133568981981983\n\ttax_rate\t1.00084\n\tscratchpad\t0\n\t{\n\t\n\t}\n\tsale_info\t0\n\t{\n\t\tsale_type\tnot\n\t\tsale_price\t10\n\t}\n\tcorrect_family_id\t00000000-0000-0000-0000-000000000000\n\thas_rezzed\t0\n\tpre_link_base_mask\t7fffffff\n\tlinked \tchild\n\tdefault_pay_price\t-2\t1\t5\t10\t20\n}\n{'task_id':ub8d68643-7dd8-57af-0d24-8790032aed0c}\n{\n\tname\tObject|\n\tpermissions 0\n\t{\n\t\tbase_mask\t7fffffff\n\t\towner_mask\t7fffffff\n\t\tgroup_mask\t00000000\n\t\teveryone_mask\t00000000\n\t\tnext_owner_mask\t7fffffff\n\t\tcreat" + // "or_id\t13fd9595-a47b-4d64-a5fb-6da645f038e0\n\t\towner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tlast_owner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tgroup_id\t00000000-0000-0000-0000-000000000000\n\t}\n\tlocal_id\t217444923\n\ttotal_crc\t235\n\ttype\t2\n\ttask_valid\t2\n\ttravel_access\t13\n\tdisplayopts\t2\n\tdisplaytype\tv\n\tpos\t-0.120029509\t-0.00284469454\t-0.0302077383\n\toldpos\t150.710999\t25.8584995\t8.19172001\n\trotation\t0.145459949970245361328125\t-0.1646589934825897216796875\t0.659558117389678955078125\t-0.718826770782470703125\n\tchildpos\t0\t-0.182999998\t-0.26699999\n\tchildrot\t0.991444766521453857421875\t3.271923924330621957778931e-05\t-0.0002416197530692443251609802\t0.1305266767740249633789062\n\tscale\t0.0382982\t0.205957\t0.368276\n\tsit_offset\t0\t0\t0\n\tcamera_eye_offset\t0\t0\t0\n\tcamera_at_offset\t0\t0\t0\n\tsit_quat\t0\t0\t0\t1\n\tsit_hint\t0\n\tstate\t160\n\tmaterial\t3\n\tsoundid\t00000000-0000-0000-0000-000000000000\n\tsoundgain\t0\n\tsoundra" + // "dius\t0\n\tsoundflags\t0\n\ttextcolor\t0 0 0 1\n\tselected\t0\n\tselector\t00000000-0000-0000-0000-000000000000\n\tusephysics\t0\n\trotate_x\t1\n\trotate_y\t1\n\trotate_z\t1\n\tphantom\t0\n\tremote_script_access_pin\t0\n\tvolume_detect\t0\n\tblock_grabs\t0\n\tdie_at_edge\t0\n\treturn_at_edge\t0\n\ttemporary\t0\n\tsandbox\t0\n\tsandboxhome\t0\t0\t0\n\tshape 0\n\t{\n\t\tpath 0\n\t\t{\n\t\t\tcurve\t32\n\t\t\tbegin\t0.3\n\t\t\tend\t0.65\n\t\t\tscale_x\t1\n\t\t\tscale_y\t0.05\n\t\t\tshear_x\t0\n\t\t\tshear_y\t0\n\t\t\ttwist\t0\n\t\t\ttwist_begin\t0\n\t\t\tradius_offset\t0\n\t\t\ttaper_x\t0\n\t\t\ttaper_y\t0\n\t\t\trevolutions\t1\n\t\t\tskew\t0\n\t\t}\n\t\tprofile 0\n\t\t{\n\t\t\tcurve\t0\n\t\t\tbegin\t0\n\t\t\tend\t1\n\t\t\thollow\t0\n\t\t}\n\t}\n\tfaces\t3\n\t{\n\t\timageid\te7150bed-3e3e-c698-eb15-d17b178148af\n\t\tcolors\t0.843137 0.156863 0.156863 1\n\t\tscales\t15\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t-1.57084\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0" + // "\n\t}\n\t{\n\t\timageid\te7150bed-3e3e-c698-eb15-d17b178148af\n\t\tcolors\t0.843137 0.156863 0.156863 1\n\t\tscales\t15\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t-1.57084\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\te7150bed-3e3e-c698-eb15-d17b178148af\n\t\tcolors\t0.843137 0.156863 0.156863 1\n\t\tscales\t15\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t-1.57084\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\tps_next_crc\t1\n\tgpw_bias\t1\n\tip\t0\n\tcomplete\tTRUE\n\tdelay\t50000\n\tnextstart\t0\n\tbirthtime\t1061087534454174\n\treztime\t1094866329021741\n\tparceltime\t1133568981982889\n\ttax_rate\t1.00326\n\tscratchpad\t0\n\t{\n\t\n\t}\n\tsale_info\t0\n\t{\n\t\tsale_type\tnot\n\t\tsale_price\t10\n\t}\n\tcorrect_family_id\t00000000-0000-0000-0000-000000000000\n\thas_rezzed\t0\n\tpre_link_base_mask\t7fffffff\n\tlinked \tchild\n\tdefault_pay_price\t-2\t1\t5\t10\t20\n}\n{'task_id':ue4b19200-9d33-962f-c8c5-6f" + // "25be3a3fd0}\n{\n\tname\tApotheosis_Immolaine_tail|\n\tpermissions 0\n\t{\n\t\tbase_mask\t7fffffff\n\t\towner_mask\t7fffffff\n\t\tgroup_mask\t00000000\n\t\teveryone_mask\t00000000\n\t\tnext_owner_mask\t7fffffff\n\t\tcreator_id\t13fd9595-a47b-4d64-a5fb-6da645f038e0\n\t\towner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tlast_owner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tgroup_id\t00000000-0000-0000-0000-000000000000\n\t}\n\tlocal_id\t217444924\n\ttotal_crc\t675\n\ttype\t1\n\ttask_valid\t2\n\ttravel_access\t13\n\tdisplayopts\t2\n\tdisplaytype\tv\n\tpos\t-0.34780401\t-0.00968400016\t-0.260098994\n\toldpos\t0\t0\t0\n\trotation\t0.73164522647857666015625\t-0.67541944980621337890625\t-0.07733880728483200073242188\t0.05022468417882919311523438\n\tvelocity\t0\t0\t0\n\tangvel\t0\t0\t0\n\tscale\t0.0382982\t0.32228\t0.383834\n\tsit_offset\t0\t0\t0\n\tcamera_eye_offset\t0\t0\t0\n\tcamera_at_offset\t0\t0\t0\n\tsit_quat\t0\t0\t0\t1\n\tsit_hint\t0\n\tstate\t160\n\tmaterial\t3\n\tsoundid\t00000" + // "000-0000-0000-0000-000000000000\n\tsoundgain\t0\n\tsoundradius\t0\n\tsoundflags\t0\n\ttextcolor\t0 0 0 1\n\tselected\t0\n\tselector\t00000000-0000-0000-0000-000000000000\n\tusephysics\t0\n\trotate_x\t1\n\trotate_y\t1\n\trotate_z\t1\n\tphantom\t0\n\tremote_script_access_pin\t0\n\tvolume_detect\t0\n\tblock_grabs\t0\n\tdie_at_edge\t0\n\treturn_at_edge\t0\n\ttemporary\t0\n\tsandbox\t0\n\tsandboxhome\t0\t0\t0\n\tshape 0\n\t{\n\t\tpath 0\n\t\t{\n\t\t\tcurve\t32\n\t\t\tbegin\t0.3\n\t\t\tend\t0.65\n\t\t\tscale_x\t1\n\t\t\tscale_y\t0.05\n\t\t\tshear_x\t0\n\t\t\tshear_y\t0\n\t\t\ttwist\t0\n\t\t\ttwist_begin\t0\n\t\t\tradius_offset\t0\n\t\t\ttaper_x\t0\n\t\t\ttaper_y\t0\n\t\t\trevolutions\t1\n\t\t\tskew\t0\n\t\t}\n\t\tprofile 0\n\t\t{\n\t\t\tcurve\t0\n\t\t\tbegin\t0\n\t\t\tend\t1\n\t\t\thollow\t0\n\t\t}\n\t}\n\tfaces\t3\n\t{\n\t\timageid\te7150bed-3e3e-c698-eb15-d17b178148af\n\t\tcolors\t0.843137 0.156863 0.156863 1\n\t\tscales\t15\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t-1" + // ".57084\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\te7150bed-3e3e-c698-eb15-d17b178148af\n\t\tcolors\t0.843137 0.156863 0.156863 1\n\t\tscales\t15\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t-1.57084\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\te7150bed-3e3e-c698-eb15-d17b178148af\n\t\tcolors\t0.843137 0.156863 0.156863 1\n\t\tscales\t15\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t-1.57084\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\tps_next_crc\t1\n\tgpw_bias\t1\n\tip\t0\n\tcomplete\tTRUE\n\tdelay\t50000\n\tnextstart\t0\n\tbirthtime\t1061087463950186\n\treztime\t1094866329022555\n\tparceltime\t1133568981984359\n\tdescription\t(No Description)|\n\ttax_rate\t1.01736\n\tnamevalue\tAttachPt U32 RW S 10\n\tnamevalue\tAttachmentOrientation VEC3 RW DS -3.110088, -0.182018, 1.493795\n\tnamevalue\tAttachmentOffset VEC3 RW DS -0.347804, -0.009684, -0.260099\n\tnamevalue\tAttachItemI" + // "D STRING RW SV 20f36c3a-b44b-9bc7-87f3-018bfdfc8cda\n\tscratchpad\t0\n\t{\n\t\n\t}\n\tsale_info\t0\n\t{\n\t\tsale_type\tnot\n\t\tsale_price\t10\n\t}\n\torig_asset_id\t8747acbc-d391-1e59-69f1-41d06830e6c0\n\torig_item_id\t20f36c3a-b44b-9bc7-87f3-018bfdfc8cda\n\tfrom_task_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\tcorrect_family_id\t00000000-0000-0000-0000-000000000000\n\thas_rezzed\t0\n\tpre_link_base_mask\t7fffffff\n\tlinked \tlinked\n\tdefault_pay_price\t-2\t1\t5\t10\t20\n}\n"); + // } + } + + TUT_CASE("lluri_test::URITestObject_test_18") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<18> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<18>() + // { + // LLURI u("secondlife:///app/login?first_name=Testert4&last_name=Tester&web_login_key=test"); + // // if secondlife is the scheme, LLURI should parse /app/login as path, with no authority + // ensure_equals("scheme", u.scheme(), "secondlife"); + // ensure_equals("authority", u.authority(), ""); + // ensure_equals("path", u.path(), "/app/login"); + // ensure_equals("pathmap", u.pathArray()[0].asString(), "app"); + // ensure_equals("pathmap", u.pathArray()[1].asString(), "login"); + // ensure_equals("query", u.query(), "first_name=Testert4&last_name=Tester&web_login_key=test"); + // ensure_equals("query map element", u.queryMap()["last_name"].asString(), "Tester"); + + // u = LLURI("secondlife://Da Boom/128/128/128"); + // // if secondlife is the scheme, LLURI should parse /128/128/128 as path, with Da Boom as authority + // ensure_equals("scheme", u.scheme(), "secondlife"); + // ensure_equals("authority", u.authority(), "Da Boom"); + // ensure_equals("path", u.path(), "/128/128/128"); + // ensure_equals("pathmap", u.pathArray()[0].asString(), "128"); + // ensure_equals("pathmap", u.pathArray()[1].asString(), "128"); + // ensure_equals("pathmap", u.pathArray()[2].asString(), "128"); + // ensure_equals("query", u.query(), ""); + // } + } + + TUT_CASE("lluri_test::URITestObject_test_19") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<19> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<19>() + // { + // set_test_name("Parse about: schemes"); + // LLURI u("about:blank?redirect-http-hack=secondlife%3A%2F%2F%2Fapp%2Flogin%3Ffirst_name%3DCallum%26last_name%3DLinden%26location%3Dspecify%26grid%3Dvaak%26region%3D%2FMorris%2F128%2F128%26web_login_key%3Defaa4795-c2aa-4c58-8966-763c27931e78"); + // ensure_equals("scheme", u.scheme(), "about"); + // ensure_equals("authority", u.authority(), ""); + // ensure_equals("path", u.path(), "blank"); + // ensure_equals("pathmap", u.pathArray()[0].asString(), "blank"); + // ensure_equals("query", u.query(), "redirect-http-hack=secondlife:///app/login?first_name=Callum&last_name=Linden&location=specify&grid=vaak®ion=/Morris/128/128&web_login_key=efaa4795-c2aa-4c58-8966-763c27931e78"); + // ensure_equals("query map element", u.queryMap()["redirect-http-hack"].asString(), "secondlife:///app/login?first_name=Callum&last_name=Linden&location=specify&grid=vaak®ion=/Morris/128/128&web_login_key=efaa4795-c2aa-4c58-8966-763c27931e78"); + // } + } + + TUT_CASE("lluri_test::URITestObject_test_20") + { + DOCTEST_FAIL("TODO: convert lluri_test.cpp::URITestObject::test<20> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void URITestObject::test<20>() + // { + // set_test_name("escapePathAndData uri test"); + + // // Basics scheme:[//authority]path[?query][#fragment] + // ensure_equals(LLURI::escapePathAndData("dirname?query"), + // "dirname?query"); + // ensure_equals(LLURI::escapePathAndData("dirname?query=data"), + // "dirname?query=data"); + // ensure_equals(LLURI::escapePathAndData("host://dirname/subdir name?query#fragment"), + // "host://dirname/subdir%20name?query#fragment"); + // ensure_equals(LLURI::escapePathAndData("host://dirname/subdir name?query=some@>data#fragment"), + // "host://dirname/subdir%20name?query=some@%3Edata#fragment"); + // ensure_equals(LLURI::escapePathAndData("host://dir[name/subdir name?query=some[data#fra[gment"), + // "host://dir[name/subdir%20name?query=some%5Bdata#fra[gment"); + // ensure_equals(LLURI::escapePathAndData("mailto:zero@ll.com"), + // "mailto:zero@ll.com"); + // // pre-escaped + // ensure_equals(LLURI::escapePathAndData("host://dirname/subdir%20name"), + // "host://dirname/subdir%20name"); + + // // data:[][;base64], + // ensure_equals(LLURI::escapePathAndData("data:,Hello, World!"), + // "data:,Hello%2C%20World%21"); + // ensure_equals(LLURI::escapePathAndData("data:text/html,

Hello, World!

"), + // "data:text/html,%3Ch1%3EHello%2C%20World%21%3C%2Fh1%3E"); + // // pre-escaped + // ensure_equals(LLURI::escapePathAndData("data:text/html,%3Ch1%3EHello%2C%20World!"), + // "data:text/html,%3Ch1%3EHello%2C%20World%21%3C%2Fh1%3E"); + // // assume that base64 does not need escaping + // ensure_equals(LLURI::escapePathAndData("data:image;base64,SGVs/bG8sIFd/vcmxkIQ%3D%3D!-&*?="), + // "data:image;base64,SGVs/bG8sIFd/vcmxkIQ%3D%3D!-&*?="); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/stringize_test_doctest.cpp b/indra/llcommon/tests_doctest/stringize_test_doctest.cpp new file mode 100644 index 00000000000..6409041a5e1 --- /dev/null +++ b/indra/llcommon/tests_doctest/stringize_test_doctest.cpp @@ -0,0 +1,95 @@ +/** + * @file stringize_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for stringize + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from stringize_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include +#include "linden_common.h" +#include "../stringize.h" +#include "../llsd.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("stringize_test::stringize_object_test_1") + { + DOCTEST_FAIL("TODO: convert stringize_test.cpp::stringize_object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void stringize_object::test<1>() + // { + // ensure_equals(stringize(c), "c"); + // ensure_equals(stringize(s), "17"); + // ensure_equals(stringize(i), "34"); + // ensure_equals(stringize(l), "68"); + // ensure_equals(stringize(f), "3.14159"); + // ensure_equals(stringize(d), "3.14159"); + // ensure_equals(stringize(abc), "abc def"); + // ensure_equals(stringize(def), "def ghi"); //Will generate LL_WARNS() due to narrowing. + // ensure_equals(stringize(llsd), "{'abc':'abc def','d':r3.14159,'i':i34}"); + // } + } + + TUT_CASE("stringize_test::stringize_object_test_2") + { + DOCTEST_FAIL("TODO: convert stringize_test.cpp::stringize_object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void stringize_object::test<2>() + // { + // ensure_equals(STRINGIZE("c is " << c), "c is c"); + // ensure_equals(STRINGIZE(std::setprecision(4) << d), "3.142"); + // } + } + + TUT_CASE("stringize_test::stringize_object_test_3") + { + DOCTEST_FAIL("TODO: convert stringize_test.cpp::stringize_object::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void stringize_object::test<3>() + // { + // //Tests rely on validity of wstring_to_utf8str() + // ensure_equals(wstring_to_utf8str(wstringize(c)), wstring_to_utf8str(L"c")); + // ensure_equals(wstring_to_utf8str(wstringize(s)), wstring_to_utf8str(L"17")); + // ensure_equals(wstring_to_utf8str(wstringize(i)), wstring_to_utf8str(L"34")); + // ensure_equals(wstring_to_utf8str(wstringize(l)), wstring_to_utf8str(L"68")); + // ensure_equals(wstring_to_utf8str(wstringize(f)), wstring_to_utf8str(L"3.14159")); + // ensure_equals(wstring_to_utf8str(wstringize(d)), wstring_to_utf8str(L"3.14159")); + // ensure_equals(wstring_to_utf8str(wstringize(abc)), wstring_to_utf8str(L"abc def")); + // ensure_equals(wstring_to_utf8str(wstringize(abc)), wstring_to_utf8str(wstringize(abc.c_str()))); + // ensure_equals(wstring_to_utf8str(wstringize(def)), wstring_to_utf8str(L"def ghi")); + // // ensure_equals(wstring_to_utf8str(wstringize(llsd)), wstring_to_utf8str(L"{'abc':'abc def','d':r3.14159,'i':i34}")); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/threadsafeschedule_test_doctest.cpp b/indra/llcommon/tests_doctest/threadsafeschedule_test_doctest.cpp new file mode 100644 index 00000000000..889acb8c74d --- /dev/null +++ b/indra/llcommon/tests_doctest/threadsafeschedule_test_doctest.cpp @@ -0,0 +1,78 @@ +/** + * @file threadsafeschedule_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for threadsafeschedule + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from threadsafeschedule_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "threadsafeschedule.h" +#include + +TUT_SUITE("llcommon") +{ + TUT_CASE("threadsafeschedule_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert threadsafeschedule_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // set_test_name("push"); + // // Simply calling push() a few times might result in indeterminate + // // delivery order if the resolution of steady_clock is coarser than + // // the real time required for each push() call. Explicitly increment + // // the timestamp for each one -- but since we're passing explicit + // // timestamps, make the queue reorder them. + // auto now{ Queue::Clock::now() }; + // queue.push(Queue::TimeTuple(now + 200ms, "ghi"s)); + // // Given the various push() overloads, you have to match the type + // // exactly: conversions are ambiguous. + // queue.push(now, "abc"s); + // queue.push(now + 100ms, "def"s); + // queue.close(); + // auto entry = queue.pop(); + // ensure_equals("failed to pop first", std::get<0>(entry), "abc"s); + // entry = queue.pop(); + // ensure_equals("failed to pop second", std::get<0>(entry), "def"s); + // ensure("queue not closed", queue.isClosed()); + // ensure("queue prematurely done", ! queue.done()); + // std::string s; + // bool popped = queue.tryPopFor(1s, s); + // ensure("failed to pop third", popped); + // ensure_equals("third is wrong", s, "ghi"s); + // popped = queue.tryPop(s); + // ensure("queue not empty", ! popped); + // ensure("queue not done", queue.done()); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/tuple_test_doctest.cpp b/indra/llcommon/tests_doctest/tuple_test_doctest.cpp new file mode 100644 index 00000000000..a1118531dae --- /dev/null +++ b/indra/llcommon/tests_doctest/tuple_test_doctest.cpp @@ -0,0 +1,60 @@ +/** + * @file tuple_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for tuple + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from tuple_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "tuple.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("tuple_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert tuple_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // set_test_name("tuple"); + // std::tuple tup{ "abc", 17 }; + // std::tuple ptup{ tuple_cons(34, tup) }; + // std::tuple tup2; + // int i; + // std::tie(i, tup2) = tuple_split(ptup); + // ensure_equals("tuple_car() fail", i, 34); + // ensure_equals("tuple_cdr() (0) fail", std::get<0>(tup2), "abc"); + // ensure_equals("tuple_cdr() (1) fail", std::get<1>(tup2), 17); + // } + } + +} + diff --git a/indra/llcommon/tests_doctest/workqueue_test_doctest.cpp b/indra/llcommon/tests_doctest/workqueue_test_doctest.cpp new file mode 100644 index 00000000000..cc12e3dfa29 --- /dev/null +++ b/indra/llcommon/tests_doctest/workqueue_test_doctest.cpp @@ -0,0 +1,272 @@ +/** + * @file workqueue_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for workqueue + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// --------------------------------------------------------------------------- +// Auto-generated from workqueue_test.cpp at 2025-10-16T18:47:17Z +// This file is a TODO stub produced by gen_tut_to_doctest.py. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "tut_compat_doctest.h" +#include "linden_common.h" +#include "workqueue.h" +#include +#include +#include "../test/catch_and_store_what_in.h" +#include "llcond.h" +#include "llcoros.h" +#include "lleventcoro.h" +#include "llstring.h" +#include "stringize.h" + +TUT_SUITE("llcommon") +{ + TUT_CASE("workqueue_test::object_test_1") + { + DOCTEST_FAIL("TODO: convert workqueue_test.cpp::object::test<1> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<1>() + // { + // set_test_name("name"); + // ensure_equals("didn't capture name", queue.getKey(), "queue"); + // ensure("not findable", WorkSchedule::getInstance("queue") == queue.getWeak().lock()); + // WorkSchedule q2; + // ensure("has no name", LLStringUtil::startsWith(q2.getKey(), "WorkQueue")); + // } + } + + TUT_CASE("workqueue_test::object_test_2") + { + DOCTEST_FAIL("TODO: convert workqueue_test.cpp::object::test<2> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<2>() + // { + // set_test_name("post"); + // bool wasRun{ false }; + // // We only get away with binding a simple bool because we're running + // // the work on the same thread. + // queue.post([&wasRun](){ wasRun = true; }); + // queue.close(); + // ensure("ran too soon", ! wasRun); + // queue.runUntilClose(); + // ensure("didn't run", wasRun); + // } + } + + TUT_CASE("workqueue_test::object_test_3") + { + DOCTEST_FAIL("TODO: convert workqueue_test.cpp::object::test<3> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<3>() + // { + // set_test_name("postEvery"); + // // record of runs + // using Shared = std::deque; + // // This is an example of how to share data between the originator of + // // postEvery(work) and the work item itself, since usually a WorkSchedule + // // is used to dispatch work to a different thread. Neither of them + // // should call any of LLCond's wait methods: you don't want to stall + // // either the worker thread or the originating thread (conventionally + // // main). Use LLCond or a subclass even if all you want to do is + // // signal the work item that it can quit; consider LLOneShotCond. + // LLCond data; + // auto start = WorkSchedule::TimePoint::clock::now(); + // // 2s seems like a long time to wait, since it directly impacts the + // // duration of this test program. Unfortunately GitHub's Mac runners + // // are pretty wimpy, and we're getting spurious "too late" errors just + // // because the thread doesn't wake up as soon as we want. + // auto interval = 2s; + // queue.postEvery( + // interval, + // [&data, count = 0] + // () mutable + // { + // // record the timestamp at which this instance is running + // data.update_one( + // [](Shared& data) + // { + // data.push_back(WorkSchedule::TimePoint::clock::now()); + // }); + // // by the 3rd call, return false to stop + // return (++count < 3); + // }); + // // no convenient way to close() our queue while we've got a + // // postEvery() running, so run until we have exhausted the iterations + // // or we time out waiting + // for (auto finish = start + 10*interval; + // WorkSchedule::TimePoint::clock::now() < finish && + // data.get([](const Shared& data){ return data.size(); }) < 3; ) + // { + // queue.runPending(); + // std::this_thread::sleep_for(interval/10); + // } + // // Take a copy of the captured deque. + // Shared result = data.get(); + // ensure_equals("called wrong number of times", result.size(), 3); + // // postEvery() assumes you want the first call to happen right away. + // // Pretend our start time was (interval) earlier than that, to make + // // our too early/too late tests uniform for all entries. + // start -= interval; + // for (size_t i = 0; i < result.size(); ++i) + // { + // auto diff = result[i] - start; + // start += interval; + // try + // { + // ensure(STRINGIZE("call " << i << " too soon"), diff >= interval); + // ensure(STRINGIZE("call " << i << " too late"), diff < interval*1.5); + // } + // catch (const tut::failure&) + // { + // auto interval_ms = interval / 1ms; + // auto diff_ms = diff / 1ms; + // std::cerr << "interval " << interval_ms + // << "ms; diff " << diff_ms << "ms" << std::endl; + // throw; + // } + // } + // } + } + + TUT_CASE("workqueue_test::object_test_4") + { + DOCTEST_FAIL("TODO: convert workqueue_test.cpp::object::test<4> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<4>() + // { + // set_test_name("postTo"); + // WorkSchedule main("main"); + // auto qptr = WorkSchedule::getInstance("queue"); + // int result = 0; + // main.postTo( + // qptr, + // [](){ return 17; }, + // // Note that a postTo() *callback* can safely bind a reference to + // // a variable on the invoking thread, because the callback is run + // // on the invoking thread. (Of course the bound variable must + // // survive until the callback is called.) + // [&result](int i){ result = i; }); + // // this should post the callback to main + // qptr->runOne(); + // // this should run the callback + // main.runOne(); + // ensure_equals("failed to run int callback", result, 17); + + // std::string alpha; + // // postTo() handles arbitrary return types + // main.postTo( + // qptr, + // [](){ return "abc"s; }, + // [&alpha](const std::string& s){ alpha = s; }); + // qptr->runPending(); + // main.runPending(); + // ensure_equals("failed to run string callback", alpha, "abc"); + // } + } + + TUT_CASE("workqueue_test::object_test_5") + { + DOCTEST_FAIL("TODO: convert workqueue_test.cpp::object::test<5> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<5>() + // { + // set_test_name("postTo with void return"); + // WorkSchedule main("main"); + // auto qptr = WorkSchedule::getInstance("queue"); + // std::string observe; + // main.postTo( + // qptr, + // // The ONLY reason we can get away with binding a reference to + // // 'observe' in our work callable is because we're directly + // // calling qptr->runOne() on this same thread. It would be a + // // mistake to do that if some other thread were servicing 'queue'. + // [&observe](){ observe = "queue"; }, + // [&observe](){ observe.append(";main"); }); + // qptr->runOne(); + // main.runOne(); + // ensure_equals("failed to run both lambdas", observe, "queue;main"); + // } + } + + TUT_CASE("workqueue_test::object_test_6") + { + DOCTEST_FAIL("TODO: convert workqueue_test.cpp::object::test<6> from TUT to doctest"); + // Original snippet: + // template<> template<> + // void object::test<6>() + // { + // set_test_name("waitForResult"); + // std::string stored; + // // Try to call waitForResult() on this thread's main coroutine. It + // // should throw because the main coroutine must service the queue. + // auto what{ catch_what( + // [this, &stored](){ stored = queue.waitForResult( + // [](){ return "should throw"; }); }) }; + // ensure("lambda should not have run", stored.empty()); + // ensure_not("waitForResult() should have thrown", what.empty()); + // ensure(STRINGIZE("should mention waitForResult: " << what), + // what.find("waitForResult") != std::string::npos); + + // // Call waitForResult() on a coroutine, with a string result. + // LLCoros::instance().launch( + // "waitForResult string", + // [this, &stored]() + // { stored = queue.waitForResult( + // [](){ return "string result"; }); }); + // llcoro::suspend(); + // // Nothing will have happened yet because, even if the coroutine did + // // run immediately, all it did was to queue the inner lambda on + // // 'queue'. Service it. + // queue.runOne(); + // llcoro::suspend(); + // ensure_equals("bad waitForResult return", stored, "string result"); + + // // Call waitForResult() on a coroutine, with a void callable. + // stored.clear(); + // bool done = false; + // LLCoros::instance().launch( + // "waitForResult void", + // [this, &stored, &done]() + // { + // queue.waitForResult([&stored](){ stored = "ran"; }); + // done = true; + // }); + // llcoro::suspend(); + // queue.runOne(); + // llcoro::suspend(); + // ensure_equals("didn't run coroutine", stored, "ran"); + // ensure("void waitForResult() didn't return", done); + // } + } + +} + diff --git a/indra/llcorehttp/tests_doctest/bufferarray_test_doctest.cpp b/indra/llcorehttp/tests_doctest/bufferarray_test_doctest.cpp new file mode 100644 index 00000000000..62fd6b77ccc --- /dev/null +++ b/indra/llcorehttp/tests_doctest/bufferarray_test_doctest.cpp @@ -0,0 +1,206 @@ +/** + * @file bufferarray_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for bufferarray + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// DOCTEST_SKIP_AUTOGEN: hand-maintained doctest suite; see docs/testing/doctest_quickstart.md. +// --------------------------------------------------------------------------- +// Deterministic doctest coverage for LLCore::BufferArray with no network or filesystem calls. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" + +#include "bufferarray.h" + +#include +#include +#include + +using namespace LLCore; + +namespace +{ +std::vector make_data(const std::string& text) +{ + return std::vector(text.begin(), text.end()); +} +} // namespace + +TEST_SUITE("bufferarray_test") +{ + TEST_CASE("construction and empty read") + { + BufferArray* ba = new BufferArray(); + CHECK_EQ(ba->getRefCount(), 1); + CHECK_EQ(ba->size(), 0U); + + std::array scratch{}; + scratch.fill('x'); + size_t read_len = ba->read(0, scratch.data(), scratch.size()); + CHECK_EQ(read_len, 0U); + CHECK_EQ(scratch[0], 'x'); + ba->release(); + } + + TEST_CASE("single write and read") + { + BufferArray* ba = new BufferArray(); + const std::string payload = "abcdefghij"; + const auto data = make_data(payload); + + size_t written = ba->write(0, data.data(), data.size()); + CHECK_EQ(written, data.size()); + CHECK_EQ(ba->size(), data.size()); + + std::array scratch{}; + scratch.fill('?'); + size_t read_len = ba->read(2, scratch.data(), scratch.size()); + CHECK_EQ(read_len, scratch.size()); + LL_CHECK_EQ_MEM(scratch.data(), "cdef", scratch.size()); + ba->release(); + } + + TEST_CASE("multiple write append and full read") + { + BufferArray* ba = new BufferArray(); + const std::string payload = "abcdefghij"; + const auto data = make_data(payload); + + size_t written = ba->write(0, data.data(), data.size()); + CHECK_EQ(written, data.size()); + + written = ba->write(data.size(), data.data(), data.size()); + CHECK_EQ(written, data.size()); + CHECK_EQ(ba->size(), data.size() * 2); + + std::vector all(ba->size(), 0); + size_t read_len = ba->read(0, all.data(), all.size()); + CHECK_EQ(read_len, all.size()); + CHECK_EQ(std::memcmp(all.data(), data.data(), data.size()), 0); + CHECK_EQ(std::memcmp(all.data() + data.size(), data.data(), data.size()), 0); + ba->release(); + } + + TEST_CASE("overwrite region") + { + BufferArray* ba = new BufferArray(); + const std::string payload = "abcdefghijklmno"; + ba->write(0, payload.data(), payload.size()); + + const std::string replace = "----"; + ba->write(6, replace.data(), replace.size()); + + std::vector region(ba->size()); + ba->read(0, region.data(), region.size()); + CHECK_EQ(std::string(region.data(), region.size()), "abcdef----klmno"); + ba->release(); + } + + TEST_CASE("append and slice subranges") + { + BufferArray* ba = new BufferArray(); + const std::string payload = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + ba->write(0, payload.data(), payload.size()); + + std::vector middle(10); + size_t read_len = ba->read(5, middle.data(), middle.size()); + CHECK_EQ(read_len, middle.size()); + CHECK_EQ(std::string(middle.data(), middle.size()), "56789ABCDE"); + + std::vector boundary(payload.size()); + read_len = ba->read(0, boundary.data(), boundary.size()); + CHECK_EQ(read_len, boundary.size()); + CHECK_EQ(std::string(boundary.data(), boundary.size()), payload); + + ba->release(); + } + + TEST_CASE("copyOut respects offsets and zero lengths") + { + BufferArray* ba = new BufferArray(); + const std::string payload = "payload"; + ba->write(0, payload.data(), payload.size()); + + std::array chunk{}; + chunk.fill('?'); + size_t copied = ba->read(0, chunk.data(), 0); + CHECK_EQ(copied, 0U); + CHECK_EQ(chunk[0], '?'); + + copied = ba->read(2, chunk.data(), chunk.size()); + CHECK_EQ(copied, chunk.size()); + CHECK_EQ(chunk[0], 'y'); + CHECK_EQ(chunk[1], 'l'); + CHECK_EQ(chunk[2], 'o'); + CHECK_EQ(chunk[3], 'a'); + + ba->release(); + } + + TEST_CASE("out of range read throws") + { + BufferArray* ba = new BufferArray(); + const std::string payload = "xyz"; + ba->write(0, payload.data(), payload.size()); + + std::array scratch{}; + CHECK_EQ(ba->read(3, scratch.data(), scratch.size()), 0U); + CHECK_EQ(ba->read(100, scratch.data(), scratch.size()), 0U); + ba->release(); + } + + TEST_CASE("multiple block allocation via append") + { + BufferArray* ba = new BufferArray(); + const std::string chunk(70000, 'a'); + ba->append(chunk.data(), chunk.size()); + ba->append("b", 1); + + CHECK_EQ(ba->size(), chunk.size() + 1); + + std::vector tail(1); + ba->read(ba->size() - 1, tail.data(), tail.size()); + CHECK_EQ(tail[0], 'b'); + ba->release(); + } + + TEST_CASE("adjacent slices remain independent") + { + BufferArray* ba = new BufferArray(); + const std::string first = "first"; + const std::string second = "second"; + ba->append(first.data(), first.size()); + ba->append(second.data(), second.size()); + + std::vector left(first.size()); + ba->read(0, left.data(), left.size()); + LL_CHECK_EQ_MEM(left.data(), first.data(), first.size()); + + std::vector right(second.size()); + ba->read(first.size(), right.data(), right.size()); + LL_CHECK_EQ_MEM(right.data(), second.data(), second.size()); + ba->release(); + } +} diff --git a/indra/llcorehttp/tests_doctest/http_fakes.cpp b/indra/llcorehttp/tests_doctest/http_fakes.cpp new file mode 100644 index 00000000000..1ccedd027de --- /dev/null +++ b/indra/llcorehttp/tests_doctest/http_fakes.cpp @@ -0,0 +1,201 @@ +/** + * @file http_fakes.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for HTTP test fakes + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +/** + * @file http_fakes.cpp + * @brief Implementation of deterministic llcorehttp doctest fakes; see docs/testing/doctest_quickstart.md. + */ + +#include "http_fakes.h" + +namespace llcorehttp_test +{ + +FakeBufferArray::FakeBufferArray() + : mBuffer(new LLCore::BufferArray()) +{ +} + +FakeBufferArray::~FakeBufferArray() +{ + drop(); +} + +void FakeBufferArray::drop() +{ + if (mBuffer) + { + mBuffer->release(); + mBuffer = nullptr; + } +} + +void FakeBufferArray::assign(const std::string& data) +{ + if (!mBuffer) + { + mBuffer = new LLCore::BufferArray(); + } + mBuffer->append(data.data(), data.size()); +} + +FakeResponse FakeResponse::Redirect(const std::string& location) +{ + FakeResponse resp; + resp.status = LLCore::HttpStatus(302, LLCore::HE_SUCCESS); + resp.headers->append("Location", location); + resp.follow_redirect = true; + return resp; +} + +FakeResponse FakeResponse::ServerError(int http_code) +{ + FakeResponse resp; + resp.status = LLCore::HttpStatus(http_code, LLCore::HE_REPLY_ERROR); + return resp; +} + +FakeResponse FakeResponse::SuccessPayload(const std::string& payload, + const std::string& content_type) +{ + FakeResponse resp; + resp.status = LLCore::HttpStatus(200, LLCore::HE_SUCCESS); + resp.body = payload; + if (!content_type.empty()) + { + resp.headers->append("Content-Type", content_type); + } + return resp; +} + +void FakeResponse::applyToResponse(LLCore::HttpResponse* response) const +{ + response->setStatus(status); + if (headers) + { + auto copy = headers; + response->setHeaders(copy); + } + if (!body.empty()) + { + FakeBufferArray buffer; + buffer.assign(body); + response->setBody(buffer.get()); + buffer.drop(); + } +} + +FakeTransport::FakeTransport() + : mNextId(0) +{ +} + +LLCore::HttpHandle FakeTransport::issueNoOp(const LLCore::HttpHandler::ptr_t& handler) +{ + const LLCore::HttpHandle handle = nextHandle(); + queueResponse(handle, FakeResponse()); + mPending.push(Pending{handle, handler}); + return handle; +} + +LLCore::HttpHandle FakeTransport::issueWithResponse(const LLCore::HttpHandler::ptr_t& handler, + const FakeResponse& response) +{ + const LLCore::HttpHandle handle = nextHandle(); + queueResponse(handle, response); + mPending.push(Pending{handle, handler}); + return handle; +} + +void FakeTransport::queueResponse(LLCore::HttpHandle handle, const FakeResponse& response) +{ + mResponses[handle].push(Scheduled{response, false, response.follow_redirect}); +} + +void FakeTransport::cancel(LLCore::HttpHandle handle) +{ + std::queue replacement; + replacement.push(Scheduled{FakeResponse(), true, false}); + mResponses[handle] = std::move(replacement); +} + +bool FakeTransport::pump() +{ + if (mPending.empty()) + { + return false; + } + + const Pending pending = mPending.front(); + mPending.pop(); + + Scheduled scheduled; + auto found = mResponses.find(pending.handle); + if (found != mResponses.end()) + { + if (!found->second.empty()) + { + scheduled = found->second.front(); + found->second.pop(); + if (found->second.empty()) + { + mResponses.erase(found); + } + } + else + { + mResponses.erase(found); + } + } + + LLCore::HttpResponse* http_response = new LLCore::HttpResponse(); + if (scheduled.cancelled) + { + http_response->setStatus(LLCore::HttpStatus(LLCore::HttpStatus::LLCORE, LLCore::HE_OP_CANCELED)); + } + else + { + scheduled.response.applyToResponse(http_response); + } + + pending.handler->onCompleted(pending.handle, http_response); + http_response->release(); + if (scheduled.follow_redirect && mResponses.count(pending.handle)) + { + mPending.push(Pending{pending.handle, pending.handler}); + } + return true; +} + +LLCore::HttpHandle FakeTransport::nextHandle() +{ + ++mNextId; + return reinterpret_cast(mNextId); +} + +} // namespace llcorehttp_test + diff --git a/indra/llcorehttp/tests_doctest/http_fakes.h b/indra/llcorehttp/tests_doctest/http_fakes.h new file mode 100644 index 00000000000..9a5cddcc3ad --- /dev/null +++ b/indra/llcorehttp/tests_doctest/http_fakes.h @@ -0,0 +1,132 @@ +/** + * @file http_fakes.h + * @date 2025-02-18 + * @brief doctest: unit tests for HTTP test fakes + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +/** + * @file http_fakes.h + * @brief Deterministic fakes for llcorehttp doctests (no network/IO); see docs/testing/doctest_quickstart.md. + */ +#pragma once + +#include "httpcommon.h" +#include "httpheaders.h" +#include "httphandler.h" +#include "httpresponse.h" +#include "bufferarray.h" + +#include +#include +#include +#include + +namespace llcorehttp_test +{ + +struct FakeResponse +{ + LLCore::HttpStatus status; + LLCore::HttpHeaders::ptr_t headers; + std::string body; + bool follow_redirect{false}; + + FakeResponse() + : status(LLCore::HttpStatus(LLCore::HttpStatus::LLCORE, LLCore::HE_SUCCESS)), + headers(new LLCore::HttpHeaders()) + { + } + + static FakeResponse Redirect(const std::string& location); + static FakeResponse ServerError(int http_code = 500); + static FakeResponse SuccessPayload(const std::string& payload, + const std::string& content_type = "application/octet-stream"); + + void applyToResponse(LLCore::HttpResponse* response) const; +}; + +class FakeClock +{ +public: + FakeClock() : mNow(0) {} + + std::uint64_t now() const { return mNow; } + void advance(std::uint64_t delta) { mNow += delta; } + +private: + std::uint64_t mNow; +}; + +class FakeBufferArray +{ +public: + FakeBufferArray(); + ~FakeBufferArray(); + + LLCore::BufferArray* get() const { return mBuffer; } + void drop(); + + void assign(const std::string& data); + +private: + LLCore::BufferArray* mBuffer; +}; + +class FakeTransport +{ +public: + FakeTransport(); + + LLCore::HttpHandle issueNoOp(const LLCore::HttpHandler::ptr_t& handler); + LLCore::HttpHandle issueWithResponse(const LLCore::HttpHandler::ptr_t& handler, + const FakeResponse& response); + + void queueResponse(LLCore::HttpHandle handle, const FakeResponse& response); + void cancel(LLCore::HttpHandle handle); + + /// Deliver the next queued response. Returns true when work was performed. + bool pump(); + +private: + struct Pending + { + LLCore::HttpHandle handle; + LLCore::HttpHandler::ptr_t handler; + }; + + struct Scheduled + { + FakeResponse response; + bool cancelled{false}; + bool follow_redirect{false}; + }; + + LLCore::HttpHandle nextHandle(); + + std::uintptr_t mNextId; + std::queue mPending; + std::map> mResponses; +}; + +} // namespace llcorehttp_test diff --git a/indra/llcorehttp/tests_doctest/httpheaders_test_doctest.cpp b/indra/llcorehttp/tests_doctest/httpheaders_test_doctest.cpp new file mode 100644 index 00000000000..75f6e37ffe5 --- /dev/null +++ b/indra/llcorehttp/tests_doctest/httpheaders_test_doctest.cpp @@ -0,0 +1,156 @@ +/** + * @file httpheaders_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for httpheaders + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// DOCTEST_SKIP_AUTOGEN: hand-maintained doctest suite; see docs/testing/doctest_quickstart.md. +// --------------------------------------------------------------------------- +// Deterministic HttpHeaders coverage with no runtime network or file access. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" + +#include "httpheaders.h" + +#include "http_header_norm.h" + +#include + +using namespace LLCore; +using namespace llcorehttp_test; + +namespace +{ +HeaderList to_header_list(const HttpHeaders::container_t& container) +{ + HeaderList list; + list.reserve(container.size()); + for (const auto& entry : container) + { + list.emplace_back(entry.first, entry.second); + } + return list; +} +} // namespace + +TEST_SUITE("httpheaders_test") +{ + TEST_CASE("normalize helpers") + { + CHECK_EQ(normalize_header_name(" Content-Type "), "content-type"); + CHECK_EQ(normalize_header_name("ACCEPT"), "accept"); + + CHECK_EQ(normalize_header_value(" text/html "), "text/html"); + CHECK_EQ(normalize_header_value("text/html; charset=UTF-8"), + "text/html; charset=UTF-8"); + + std::string folded = "line\r\n\tcontinued\r\n more"; + CHECK_EQ(unfold_legacy_lines(folded), "line continued more"); + CHECK_EQ(normalize_header_value(folded), "line continued more"); + } + + TEST_CASE("appendNormal canonicalization") + { + HttpHeaders::ptr_t headers(new HttpHeaders()); + static char line1[] = " AcCePT : image/yourfacehere"; + static char line2[] = " next : \t\tlinejunk \t"; + static char line3[] = "FancY-PANTs::plop:-neuf-=vleem="; + static char line4[] = "all-talk-no-walk:"; + static char line5[] = ":all-talk-no-walk"; + static char line6[] = " :"; + static char line7[] = " \toskdgioasdghaosdghoowg28342908tg8902hg0hwedfhqew890v7qh0wdebv78q0wdevbhq>?M>BNM?NZ? \t"; + static char line8[] = "binary:ignorestuffontheendofthis"; + + headers->appendNormal(line1, sizeof(line1) - 1); + headers->appendNormal(line2, sizeof(line2) - 1); + headers->appendNormal(line3, sizeof(line3) - 1); + headers->appendNormal(line4, sizeof(line4) - 1); + headers->appendNormal(line5, sizeof(line5) - 1); + headers->appendNormal(line6, sizeof(line6) - 1); + headers->appendNormal(line7, sizeof(line7) - 1); + headers->appendNormal(line8, 13); // apenas prefixo + + auto canonical = canonicalize_headers(to_header_list(headers->getContainerTESTONLY())); + + HeaderList expected = { + {"accept", "image/yourfacehere"}, + {"next", "linejunk"}, + {"fancy-pants", ":plop:-neuf-=vleem="}, + {"all-talk-no-walk", ""}, + {"", "all-talk-no-walk"}, + {"", ""}, + {"oskdgioasdghaosdghoowg28342908tg8902hg0hwedfhqew890v7qh0wdebv78q0wdevbhq>?m>bnm?nz?", ""}, + {"binary", "ignore"} + }; + + CHECK_EQ(canonical.size(), expected.size()); + for (std::size_t i = 0; i < expected.size(); ++i) + { + CAPTURE(i); + LL_CHECK_EQ_STR(canonical[i].first, expected[i].first); + LL_CHECK_EQ_STR(canonical[i].second, expected[i].second); + } + } + + TEST_CASE("duplicate merge policy") + { + HttpHeaders::ptr_t headers(new HttpHeaders()); + headers->append("Accept", "text/html"); + headers->append("accept", "application/json"); + headers->append("Set-Cookie", "a=1"); + headers->append("set-cookie", "b=2"); + headers->append("Cache-Control", "no-cache"); + headers->append("Cache-Control", "max-age=100"); + + auto canonical = canonicalize_headers(to_header_list(headers->getContainerTESTONLY())); + auto buckets = merge_duplicates(canonical); + auto flattened = collapse_merged(buckets); + + HeaderList expected = { + {"accept", "text/html, application/json"}, + {"set-cookie", "a=1"}, + {"set-cookie", "b=2"}, + {"cache-control", "no-cache, max-age=100"} + }; + + CHECK_EQ(flattened.size(), expected.size()); + for (std::size_t i = 0; i < expected.size(); ++i) + { + CAPTURE(i); + LL_CHECK_EQ_STR(flattened[i].first, expected[i].first); + LL_CHECK_EQ_STR(flattened[i].second, expected[i].second); + } + } + + TEST_CASE("legacy folding handled via helper") + { + const std::string folded = "Subject: first line\r\n\tsecond line\r\n third line"; + const HeaderList raw = {{"Subject", folded}}; + auto canonical = canonicalize_headers(raw); + CHECK_EQ(canonical.size(), 1U); + LL_CHECK_EQ_STR(canonical[0].first, "subject"); + LL_CHECK_EQ_STR(canonical[0].second, "Subject: first line second line third line"); + } +} diff --git a/indra/llcorehttp/tests_doctest/httpoperation_test_doctest.cpp b/indra/llcorehttp/tests_doctest/httpoperation_test_doctest.cpp new file mode 100644 index 00000000000..a7d78c51c68 --- /dev/null +++ b/indra/llcorehttp/tests_doctest/httpoperation_test_doctest.cpp @@ -0,0 +1,193 @@ +/** + * @file httpoperation_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for httpoperation + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// DOCTEST_SKIP_AUTOGEN: hand-maintained doctest suite; see docs/testing/doctest_quickstart.md. +// --------------------------------------------------------------------------- +// Deterministic coverage for HttpOperation primitives using in-memory fakes only. +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" + +#include "_httpoperation.h" +#include "httphandler.h" + +#include "http_fakes.h" + +#include + +using namespace LLCore; +using namespace LLCoreInt; +using namespace llcorehttp_test; + +namespace +{ +class CountingHandler final : public HttpHandler +{ +public: + void onCompleted(HttpHandle handle, HttpResponse*) override + { + last_handle = handle; + ++calls; + } + + int calls{0}; + HttpHandle last_handle{LLCORE_HTTP_HANDLE_INVALID}; +}; + +class InspectingHandler final : public HttpHandler +{ +public: + void onCompleted(HttpHandle handle, HttpResponse* response) override + { + handles.push_back(handle); + if (response) + { + statuses.push_back(response->getStatus()); + if (response->getHeaders()) + { + auto headers = response->getHeaders(); + if (headers && headers->size() > 0) + { + recorded_locations.push_back(headers->find("Location") ? *headers->find("Location") : std::string()); + recorded_content_types.push_back(headers->find("Content-Type") ? *headers->find("Content-Type") : std::string()); + } + else + { + recorded_locations.emplace_back(); + recorded_content_types.emplace_back(); + } + } + else + { + recorded_locations.emplace_back(); + recorded_content_types.emplace_back(); + } + + if (response->getBody()) + { + std::string body; + body.resize(response->getBodySize()); + if (!body.empty()) + { + response->getBody()->read(0, body.data(), body.size()); + } + bodies.push_back(body); + } + else + { + bodies.emplace_back(); + } + } + } + + std::vector handles; + std::vector statuses; + std::vector recorded_locations; + std::vector recorded_content_types; + std::vector bodies; +}; +} // namespace + +TEST_SUITE("httpoperation_test") +{ + TEST_CASE("HttpOpNull retains sole reference") + { + HttpOperation::ptr_t op(new HttpOpNull()); + CHECK_EQ(op.use_count(), 1); + } + + TEST_CASE("HttpOpNull attaches reply path without altering refcount") + { + HttpOperation::ptr_t op(new HttpOpNull()); + CountingHandler handler; + op->setReplyPath(HttpOperation::HttpReplyQueuePtr_t(), HttpHandler::ptr_t(&handler, [](HttpHandler*) {})); + op->getHandle(); // ensure handle assigned + CHECK_EQ(op.use_count(), 1); + + op->visitNotifier(nullptr); + CHECK_EQ(handler.calls, 1); + CHECK(handler.last_handle != LLCORE_HTTP_HANDLE_INVALID); + } + + TEST_CASE("redirect chain yields final success") + { + auto handler = std::make_shared(); + HttpOperation::ptr_t op(new HttpOpNull()); + op->setReplyPath(HttpOperation::HttpReplyQueuePtr_t(), handler); + HttpHandle handle = op->getHandle(); + + HttpResponse* first = new HttpResponse(); + FakeResponse::Redirect("/next").applyToResponse(first); + handler->onCompleted(handle, first); + first->release(); + + HttpResponse* second = new HttpResponse(); + FakeResponse::SuccessPayload("final").applyToResponse(second); + handler->onCompleted(handle, second); + second->release(); + + CHECK_EQ(handler->statuses.size(), 2U); + CHECK(handler->statuses[0] == HttpStatus(302, HE_SUCCESS)); + CHECK(handler->statuses[1] == HttpStatus(200, HE_SUCCESS)); + CHECK_EQ(handler->recorded_locations[0], "/next"); + } + + TEST_CASE("server error surfaces failure status") + { + auto handler = std::make_shared(); + HttpOperation::ptr_t op(new HttpOpNull()); + op->setReplyPath(HttpOperation::HttpReplyQueuePtr_t(), handler); + HttpHandle handle = op->getHandle(); + + HttpResponse* error_resp = new HttpResponse(); + FakeResponse::ServerError().applyToResponse(error_resp); + handler->onCompleted(handle, error_resp); + error_resp->release(); + + REQUIRE_EQ(handler->statuses.size(), 1U); + CHECK(handler->statuses.front() == HttpStatus(500, HE_REPLY_ERROR)); + } + + TEST_CASE("payload response retains bytes") + { + auto handler = std::make_shared(); + HttpOperation::ptr_t op(new HttpOpNull()); + op->setReplyPath(HttpOperation::HttpReplyQueuePtr_t(), handler); + HttpHandle handle = op->getHandle(); + + const std::string bytes = std::string("\x01\x02\x03", 3); + HttpResponse* payload_resp = new HttpResponse(); + FakeResponse payload = FakeResponse::SuccessPayload(bytes, "application/octet-stream"); + payload.applyToResponse(payload_resp); + handler->onCompleted(handle, payload_resp); + payload_resp->release(); + + REQUIRE_EQ(handler->bodies.size(), 1U); + LL_CHECK_EQ_MEM(handler->bodies.front().data(), bytes.data(), bytes.size()); + LL_CHECK_EQ_STR(handler->recorded_content_types.front(), "application/octet-stream"); + } +} diff --git a/indra/llcorehttp/tests_doctest/httprequestqueue_test_doctest.cpp b/indra/llcorehttp/tests_doctest/httprequestqueue_test_doctest.cpp new file mode 100644 index 00000000000..d3e6e347452 --- /dev/null +++ b/indra/llcorehttp/tests_doctest/httprequestqueue_test_doctest.cpp @@ -0,0 +1,224 @@ +/** + * @file httprequestqueue_test_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for httprequestqueue + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// DOCTEST_SKIP_AUTOGEN: hand-maintained doctest suite; see docs/testing/doctest_quickstart.md. +// --------------------------------------------------------------------------- +// Deterministic HttpRequestQueue coverage using in-memory fakes (no sockets or threads). +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "ll_doctest_helpers.h" + +#include "_httprequestqueue.h" +#include "_httpoperation.h" + +#include "http_fakes.h" + +#include +#include +#include + +using namespace LLCore; +using namespace llcorehttp_test; + +namespace +{ +class QueueFixture +{ +public: + QueueFixture() + { + HttpRequestQueue::init(); + queue = HttpRequestQueue::instanceOf(); + } + + ~QueueFixture() + { + HttpRequestQueue::term(); + } + + HttpRequestQueue* queue; +}; + +class RecordingHandler final : public HttpHandler +{ +public: + RecordingHandler(std::vector& order, + std::vector& statuses) + : mOrder(order), mStatuses(statuses) {} + + void registerLabel(HttpHandle handle, const std::string& label) + { + mLabels[handle] = label; + } + + std::string labelFor(HttpHandle handle) const + { + auto it = mLabels.find(handle); + return it != mLabels.end() ? it->second : std::string(); + } + + void onCompleted(HttpHandle handle, HttpResponse* response) override + { + mOrder.push_back(labelFor(handle)); + if (response) + { + mStatuses.push_back(response->getStatus()); + } + } + +private: + std::vector& mOrder; + std::vector& mStatuses; + std::map mLabels; +}; +} // namespace + +TEST_SUITE("httprequestqueue_test") +{ + TEST_CASE("fifo ordering yields matching callbacks") + { + QueueFixture fixture; + std::vector completions; + std::vector statuses; + auto handler = std::make_shared(completions, statuses); + + const std::vector labels = {"first", "second", "third"}; + for (const auto& label : labels) + { + HttpOperation::ptr_t op(new HttpOpNull()); + const HttpHandle handle = op->getHandle(); + handler->registerLabel(handle, label); + op->mStatus = HttpStatus(HttpStatus::LLCORE, HE_SUCCESS); + op->setReplyPath(HttpOperation::HttpReplyQueuePtr_t(), handler); + fixture.queue->addOp(op); + } + + HttpRequestQueue::OpContainer fetched; + fixture.queue->fetchAll(false, fetched); + CHECK_EQ(fetched.size(), labels.size()); + for (std::size_t i = 0; i < fetched.size(); ++i) + { + CAPTURE(i); + CHECK_EQ(handler->labelFor(fetched[i]->getHandle()), labels[i]); + fetched[i]->visitNotifier(nullptr); + } + + CHECK_EQ(completions, labels); + CHECK_EQ(statuses.size(), labels.size()); + } + + TEST_CASE("cancel reports cancelled then successful") + { + QueueFixture fixture; + FakeTransport transport; + std::vector completions; + std::vector statuses; + auto handler = std::make_shared(completions, statuses); + + const std::vector labels = {"first", "second"}; + for (const auto& label : labels) + { + HttpOperation::ptr_t op(new HttpOpNull()); + handler->registerLabel(op->getHandle(), label); + op->mStatus = HttpStatus(HttpStatus::LLCORE, HE_SUCCESS); + op->setReplyPath(HttpOperation::HttpReplyQueuePtr_t(), handler); + fixture.queue->addOp(op); + } + + HttpRequestQueue::OpContainer fetched; + fixture.queue->fetchAll(false, fetched); + CHECK_EQ(fetched.size(), labels.size()); + + std::vector scheduled; + for (std::size_t i = 0; i < fetched.size(); ++i) + { + const HttpHandle handle = transport.issueWithResponse(handler, FakeResponse()); + handler->registerLabel(handle, labels[i]); + scheduled.push_back(handle); + } + + transport.cancel(scheduled.front()); + while (transport.pump()) {} + + CHECK_EQ(completions.size(), 2U); + CHECK_EQ(completions[0], labels[0]); + CHECK_EQ(completions[1], labels[1]); + CHECK_EQ(statuses.size(), 2U); + LL_CHECK_EQ_STR(statuses.front().toHex(), HttpStatus(HttpStatus::LLCORE, HE_OP_CANCELED).toHex()); + LL_CHECK_EQ_STR(statuses.back().toHex(), HttpStatus(HttpStatus::LLCORE, HE_SUCCESS).toHex()); + } + + TEST_CASE("retry can succeed after failure") + { + QueueFixture fixture; + FakeClock clock; + std::vector completions; + std::vector statuses; + auto handler = std::make_shared(completions, statuses); + + HttpOperation::ptr_t op(new HttpOpNull()); + handler->registerLabel(op->getHandle(), "retry"); + op->setReplyPath(HttpOperation::HttpReplyQueuePtr_t(), handler); + fixture.queue->addOp(op); + + HttpRequestQueue::OpContainer fetched; + fixture.queue->fetchAll(false, fetched); + REQUIRE_EQ(fetched.size(), 1U); + + op->mStatus = HttpStatus(HttpStatus::LLCORE, HE_REPLY_ERROR); + fetched.front()->visitNotifier(nullptr); + + CHECK_EQ(statuses.size(), 1U); + LL_CHECK_EQ_STR(statuses.front().toHex(), HttpStatus(HttpStatus::LLCORE, HE_REPLY_ERROR).toHex()); + + clock.advance(200); + + fixture.queue->addOp(op); + fetched.clear(); + fixture.queue->fetchAll(false, fetched); + REQUIRE_EQ(fetched.size(), 1U); + + op->mStatus = HttpStatus(HttpStatus::LLCORE, HE_SUCCESS); + fetched.front()->visitNotifier(nullptr); + + CHECK_EQ(completions.size(), 2U); + CHECK_EQ(completions[0], "retry"); + CHECK_EQ(completions[1], "retry"); + CHECK_EQ(statuses.size(), 2U); + LL_CHECK_EQ_STR(statuses.back().toHex(), HttpStatus(HttpStatus::LLCORE, HE_SUCCESS).toHex()); + CHECK_GE(clock.now(), static_cast(200)); + } + + TEST_CASE("empty queue fetch returns immediately") + { + QueueFixture fixture; + CHECK_FALSE(fixture.queue->fetchOp(false)); + HttpRequestQueue::OpContainer fetched; + fixture.queue->fetchAll(false, fetched); + CHECK(fetched.empty()); + } +} diff --git a/indra/llmath/tests_doctest/CMakeLists.txt b/indra/llmath/tests_doctest/CMakeLists.txt new file mode 100644 index 00000000000..ceb9864b25b --- /dev/null +++ b/indra/llmath/tests_doctest/CMakeLists.txt @@ -0,0 +1,30 @@ +add_executable(llmath_doctest + ${CMAKE_SOURCE_DIR}/test/doctest_main.cpp + ${CMAKE_SOURCE_DIR}/llcommon/tests_doctest/win_wstring_shim.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/llquaternion_test_doctest.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/llmatrix3_test_doctest.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/llmatrix4_test_doctest.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/v2math_test_doctest.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/v3math_test_doctest.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/v4math_test_doctest.cpp +) + +target_include_directories(llmath_doctest + PRIVATE + ${DOCTEST_INCLUDE_DIR} + ${CMAKE_SOURCE_DIR}/.. + ${CMAKE_SOURCE_DIR}/test + ${PROJECT_SOURCE_DIR}/../test + ${CMAKE_SOURCE_DIR}/llcommon + ${CMAKE_SOURCE_DIR}/llmath + ${CMAKE_SOURCE_DIR}/extern/doctest + ${CMAKE_SOURCE_DIR}/llcommon/tests_doctest +) + +target_link_libraries(llmath_doctest + PRIVATE + llmath + llcommon +) + +add_test(NAME llmath_doctest COMMAND llmath_doctest) diff --git a/indra/llmath/tests_doctest/llquaternion_test_doctest.cpp b/indra/llmath/tests_doctest/llquaternion_test_doctest.cpp new file mode 100644 index 00000000000..af0da9c09cb --- /dev/null +++ b/indra/llmath/tests_doctest/llquaternion_test_doctest.cpp @@ -0,0 +1,630 @@ +// --------------------------------------------------------------------------- +// Auto-generated from llquaternion_test.cpp at 2025-10-17T12:56:17+00:00 +// Generated by gen_tut_to_doctest.py +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "indra/test/ll_doctest_helpers.h" +#include "indra/test/tut_compat_doctest.h" +#include "linden_common.h" +#include "../v4math.h" +#include "../v3math.h" +#include "../v3dmath.h" +#include "../m4math.h" +#include "../m3math.h" +#include "../llquaternion.h" + +/** + * @file llquaternion_test.cpp + * @author Adroit + * @date 2007-03 + * @brief Test cases of llquaternion.h + * + * $LicenseInfo:firstyear=2007&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + + + +namespace tut +{ + using tut_compat::ensure; + using tut_compat::ensure_equals; + using tut_compat::ensure_not; + using tut_compat::ensure_throws; + + struct llquat_test + { + }; + + //test case for LLQuaternion::LLQuaternion(void) fn. + + + //test case for explicit LLQuaternion(const LLMatrix4 &mat) fn. + + + + + //test case for LLQuaternion(F32 x, F32 y, F32 z, F32 w), setQuatInit() and normQuat() fns. + + + //test case for conjQuat() and transQuat() fns. + + + //test case for dot(const LLQuaternion &a, const LLQuaternion &b) fn. + + + //test case for LLQuaternion &LLQuaternion::constrain(F32 radians) fn. + + + + + + + //test case for LLVector4 operator*(const LLVector4 &a, const LLQuaternion &rot) fn. + + + //test case for LLVector3 operator*(const LLVector3 &a, const LLQuaternion &rot) fn. + + + //test case for LLVector3d operator*(const LLVector3d &a, const LLQuaternion &rot) fn. + + + //test case for inline LLQuaternion operator-(const LLQuaternion &a) fn. + + + //test case for inline LLQuaternion operator*(F32 a, const LLQuaternion &q) and + //inline LLQuaternion operator*(F32 a, const LLQuaternion &q) fns. +} // namespace tut + +TUT_SUITE("llquaternion_test") +{ + TUT_CASE("llquaternion_test::llquat_test_object_t_test_1") + { + using namespace tut; + LLQuaternion llquat; + TUT_CHECK_MSG(0.f == llquat.mQ[0] && + 0.f == llquat.mQ[1] && + 0.f == llquat.mQ[2] && + 1.f == llquat.mQ[3], "LLQuaternion::LLQuaternion() failed"); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_2") + { + using namespace tut; + LLMatrix4 llmat; + LLVector4 vector1(2.0f, 1.0f, 3.0f, 6.0f); + LLVector4 vector2(5.0f, 6.0f, 0.0f, 1.0f); + LLVector4 vector3(2.0f, 1.0f, 2.0f, 9.0f); + LLVector4 vector4(3.0f, 8.0f, 1.0f, 5.0f); + + llmat.initRows(vector1, vector2, vector3, vector4); + TUT_CHECK_MSG(2.0f == llmat.mMatrix[0][0] && + 1.0f == llmat.mMatrix[0][1] && + 3.0f == llmat.mMatrix[0][2] && + 6.0f == llmat.mMatrix[0][3] && + 5.0f == llmat.mMatrix[1][0] && + 6.0f == llmat.mMatrix[1][1] && + 0.0f == llmat.mMatrix[1][2] && + 1.0f == llmat.mMatrix[1][3] && + 2.0f == llmat.mMatrix[2][0] && + 1.0f == llmat.mMatrix[2][1] && + 2.0f == llmat.mMatrix[2][2] && + 9.0f == llmat.mMatrix[2][3] && + 3.0f == llmat.mMatrix[3][0] && + 8.0f == llmat.mMatrix[3][1] && + 1.0f == llmat.mMatrix[3][2] && + 5.0f == llmat.mMatrix[3][3], "explicit LLQuaternion(const LLMatrix4 &mat) failed"); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_3") + { + using namespace tut; + LLMatrix3 llmat; + + LLVector3 vect1(3.4028234660000000f , 234.56f, 4234.442234f); + LLVector3 vect2(741.434f, 23.00034f, 6567.223423f); + LLVector3 vect3(566.003034f, 12.98705f, 234.764423f); + llmat.setRows(vect1, vect2, vect3); + + TUT_CHECK_MSG(3.4028234660000000f == llmat.mMatrix[0][0] && + 234.56f == llmat.mMatrix[0][1] && + 4234.442234f == llmat.mMatrix[0][2] && + 741.434f == llmat.mMatrix[1][0] && + 23.00034f == llmat.mMatrix[1][1] && + 6567.223423f == llmat.mMatrix[1][2] && + 566.003034f == llmat.mMatrix[2][0] && + 12.98705f == llmat.mMatrix[2][1] && + 234.764423f == llmat.mMatrix[2][2], "LLMatrix3::setRows fn failed."); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_4") + { + using namespace tut; + F32 x_val = 3.0f; + F32 y_val = 2.0f; + F32 z_val = 6.0f; + F32 w_val = 1.0f; + + LLQuaternion res_quat; + res_quat.setQuatInit(x_val, y_val, z_val, w_val); + res_quat.normQuat(); + + TUT_CHECK_MSG(is_approx_equal(0.42426407f, res_quat.mQ[0]) && + is_approx_equal(0.28284273f, res_quat.mQ[1]) && + is_approx_equal(0.84852815f, res_quat.mQ[2]) && + is_approx_equal(0.14142136f, res_quat.mQ[3]), "LLQuaternion::normQuat() fn failed"); + + x_val = 0.0f; + y_val = 0.0f; + z_val = 0.0f; + w_val = 0.0f; + + res_quat.setQuatInit(x_val, y_val, z_val, w_val); + res_quat.normQuat(); + + TUT_CHECK_MSG(is_approx_equal(0.0f, res_quat.mQ[0]) && + is_approx_equal(0.0f, res_quat.mQ[1]) && + is_approx_equal(0.0f, res_quat.mQ[2]) && + is_approx_equal(1.0f, res_quat.mQ[3]), "LLQuaternion::normQuat() fn. failed."); + + + TUT_CHECK_MSG(is_approx_equal(0.0f, res_quat.mQ[0]) && + is_approx_equal(0.0f, res_quat.mQ[1]) && + is_approx_equal(0.0f, res_quat.mQ[2]) && + is_approx_equal(1.0f, res_quat.mQ[3]), "LLQuaternion::normQuat() fn. failed."); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_5") + { + using namespace tut; + F32 x_val = 3.0f; + F32 y_val = 2.0f; + F32 z_val = 6.0f; + F32 w_val = 1.0f; + + LLQuaternion res_quat; + LLQuaternion result, result1; + result1 = result = res_quat.setQuatInit(x_val, y_val, z_val, w_val); + + result.conjQuat(); + result1.transQuat(); + + TUT_CHECK_MSG(is_approx_equal(result1.mQ[0], result.mQ[0]) && + is_approx_equal(result1.mQ[1], result.mQ[1]) && + is_approx_equal(result1.mQ[2], result.mQ[2]), "LLQuaternion::conjQuat and LLQuaternion::transQuat failed "); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_6") + { + using namespace tut; + LLQuaternion quat1(3.0f, 2.0f, 6.0f, 0.0f), quat2(1.0f, 1.0f, 1.0f, 1.0f); + TUT_CHECK_MSG(ll_round(12.000000f, 2) == ll_round(dot(quat1, quat2), 2), "1. The two values are different"); + + LLQuaternion quat0(3.0f, 9.334f, 34.5f, 23.0f), quat(34.5f, 23.23f, 2.0f, 45.5f); + TUT_CHECK_MSG(ll_round(1435.828807f, 2) == ll_round(dot(quat0, quat), 2), "2. The two values are different"); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_7") + { + using namespace tut; + F32 radian = 60.0f; + LLQuaternion quat(3.0f, 2.0f, 6.0f, 0.0f); + LLQuaternion quat1; + quat1 = quat.constrain(radian); + TUT_CHECK_MSG(is_approx_equal_fraction(-0.423442f, quat1.mQ[0], 8) && + is_approx_equal_fraction(-0.282295f, quat1.mQ[1], 8) && + is_approx_equal_fraction(-0.846884f, quat1.mQ[2], 8) && + is_approx_equal_fraction(0.154251f, quat1.mQ[3], 8), "1. LLQuaternion::constrain(F32 radians) failed"); + + + radian = 30.0f; + LLQuaternion quat0(37.50f, 12.0f, 86.023f, 40.32f); + quat1 = quat0.constrain(radian); + + TUT_CHECK_MSG(is_approx_equal_fraction(37.500000f, quat1.mQ[0], 8) && + is_approx_equal_fraction(12.0000f, quat1.mQ[1], 8) && + is_approx_equal_fraction(86.0230f, quat1.mQ[2], 8) && + is_approx_equal_fraction(40.320000f, quat1.mQ[3], 8), "2. LLQuaternion::constrain(F32 radians) failed"); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_8") + { + using namespace tut; + F32 value1 = 15.0f; + LLQuaternion quat1(1.0f, 2.0f, 4.0f, 1.0f); + LLQuaternion quat2(4.0f, 3.0f, 6.5f, 9.7f); + LLQuaternion res_lerp, res_slerp, res_nlerp; + + //test case for lerp(F32 t, const LLQuaternion &q) fn. + res_lerp = lerp(value1, quat1); + TUT_CHECK_MSG(is_approx_equal_fraction(0.181355f, res_lerp.mQ[0], 16) && + is_approx_equal_fraction(0.362711f, res_lerp.mQ[1], 16) && + is_approx_equal_fraction(0.725423f, res_lerp.mQ[2], 16) && + is_approx_equal_fraction(0.556158f, res_lerp.mQ[3], 16), "1. LLQuaternion lerp(F32 t, const LLQuaternion &q) failed"); + + //test case for lerp(F32 t, const LLQuaternion &p, const LLQuaternion &q) fn. + res_lerp = lerp(value1, quat1, quat2); + TUT_CHECK_MSG(is_approx_equal_fraction(0.314306f, res_lerp.mQ[0], 16) && + is_approx_equal_fraction(0.116156f, res_lerp.mQ[1], 16) && + is_approx_equal_fraction(0.283559f, res_lerp.mQ[2], 16) && + is_approx_equal_fraction(0.898506f, res_lerp.mQ[3], 16), "2. LLQuaternion lerp(F32 t, const LLQuaternion &p, const LLQuaternion &q) failed"); + + //test case for slerp( F32 u, const LLQuaternion &a, const LLQuaternion &b ) fn. + res_slerp = slerp(value1, quat1, quat2); + TUT_CHECK_MSG(is_approx_equal_fraction(46.000f, res_slerp.mQ[0], 16) && + is_approx_equal_fraction(17.00f, res_slerp.mQ[1], 16) && + is_approx_equal_fraction(41.5f, res_slerp.mQ[2], 16) && + is_approx_equal_fraction(131.5f, res_slerp.mQ[3], 16), "3. LLQuaternion slerp( F32 u, const LLQuaternion &a, const LLQuaternion &b) failed"); + + //test case for nlerp(F32 t, const LLQuaternion &a, const LLQuaternion &b) fn. + res_nlerp = nlerp(value1, quat1, quat2); + TUT_CHECK_MSG(is_approx_equal_fraction(0.314306f, res_nlerp.mQ[0], 16) && + is_approx_equal_fraction(0.116157f, res_nlerp.mQ[1], 16) && + is_approx_equal_fraction(0.283559f, res_nlerp.mQ[2], 16) && + is_approx_equal_fraction(0.898506f, res_nlerp.mQ[3], 16), "4. LLQuaternion nlerp(F32 t, const LLQuaternion &a, const LLQuaternion &b) failed"); + + //test case for nlerp(F32 t, const LLQuaternion &q) fn. + res_slerp = slerp(value1, quat1); + TUT_CHECK_MSG(is_approx_equal_fraction(1.0f, res_slerp.mQ[0], 16) && + is_approx_equal_fraction(2.0f, res_slerp.mQ[1], 16) && + is_approx_equal_fraction(4.0000f, res_slerp.mQ[2], 16) && + is_approx_equal_fraction(1.000f, res_slerp.mQ[3], 16), "5. LLQuaternion slerp(F32 t, const LLQuaternion &q) failed"); + + LLQuaternion quat3(2.0f, 1.0f, 5.5f, 10.5f); + LLQuaternion res_nlerp1; + value1 = 100.0f; + res_nlerp1 = nlerp(value1, quat3); + TUT_CHECK_MSG(is_approx_equal_fraction(0.268245f, res_nlerp1.mQ[0], 16) && is_approx_equal_fraction(0.134122f, res_nlerp1.mQ[1], 2) && + is_approx_equal_fraction(0.737673f, res_nlerp1.mQ[2], 16) && + is_approx_equal_fraction(0.604892f, res_nlerp1.mQ[3], 16), "6. LLQuaternion nlerp(F32 t, const LLQuaternion &q) failed"); + + //test case for lerp(F32 t, const LLQuaternion &q) fn. + res_lerp = lerp(value1, quat2); + TUT_CHECK_MSG(is_approx_equal_fraction(0.404867f, res_lerp.mQ[0], 16) && + is_approx_equal_fraction(0.303650f, res_lerp.mQ[1], 16) && + is_approx_equal_fraction(0.657909f, res_lerp.mQ[2], 16) && + is_approx_equal_fraction(0.557704f, res_lerp.mQ[3], 16), "7. LLQuaternion lerp(F32 t, const LLQuaternion &q) failed"); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_9") + { + using namespace tut; + //test case for LLQuaternion operator*(const LLQuaternion &a, const LLQuaternion &b) fn + LLQuaternion quat1(1.0f, 2.5f, 3.5f, 5.5f); + LLQuaternion quat2(4.0f, 3.0f, 5.0f, 1.0f); + LLQuaternion result = quat1 * quat2; + TUT_CHECK_MSG((21.0f == result.mQ[0]) && + (10.0f == result.mQ[1]) && + (38.0f == result.mQ[2]) && + (-23.5f == result.mQ[3]), "1. LLQuaternion Operator* failed"); + + LLQuaternion quat3(2341.340f, 2352.345f, 233.25f, 7645.5f); + LLQuaternion quat4(674.067f, 893.0897f, 578.0f, 231.0f); + result = quat3 * quat4; + TUT_CHECK_MSG((4543086.5f == result.mQ[0]) && + (8567578.0f == result.mQ[1]) && + (3967591.25f == result.mQ[2]) && + is_approx_equal(-2047783.25f, result.mQ[3]), "2. LLQuaternion Operator* failed"); + + //inline LLQuaternion operator+(const LLQuaternion &a, const LLQuaternion &b)fn. + result = quat1 + quat2; + TUT_CHECK_MSG((5.0f == result.mQ[0]) && + (5.5f == result.mQ[1]) && + (8.5f == result.mQ[2]) && + (6.5f == result.mQ[3]), "3. LLQuaternion operator+ failed"); + + result = quat3 + quat4; + TUT_CHECK_MSG(is_approx_equal(3015.407227f, result.mQ[0]) && + is_approx_equal(3245.434570f, result.mQ[1]) && + (811.25f == result.mQ[2]) && + (7876.5f == result.mQ[3]), "4. LLQuaternion operator+ failed"); + + //inline LLQuaternion operator-(const LLQuaternion &a, const LLQuaternion &b) fn + result = quat1 - quat2; + TUT_CHECK_MSG((-3.0f == result.mQ[0]) && + (-0.5f == result.mQ[1]) && + (-1.5f == result.mQ[2]) && + (4.5f == result.mQ[3]), "5. LLQuaternion operator-(const LLQuaternion &a, const LLQuaternion &b) failed"); + + result = quat3 - quat4; + TUT_CHECK_MSG(is_approx_equal(1667.273071f, result.mQ[0]) && + is_approx_equal(1459.255249f, result.mQ[1]) && + (-344.75f == result.mQ[2]) && + (7414.50f == result.mQ[3]), "6. LLQuaternion operator-(const LLQuaternion &a, const LLQuaternion &b) failed"); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_10") + { + LLVector4 vect(12.0f, 5.0f, 60.0f, 75.1f); + LLQuaternion quat(2323.034f, 23.5f, 673.23f, 57667.5f); + LLVector4 result = vect * quat; + + LL_CHECK_APPROX(result.mV[0], 39928406016.0f, 1.0f); + LL_CHECK_IN_RANGE(result.mV[1], 1457800960.0f, 1457802240.0f); + LL_CHECK_APPROX(result.mV[2], 200580612096.0f, 2.0f); + LL_CHECK_APPROX(result.mV[3], 75.099998f, 1.0e-5f); + + LLVector4 vect1(22.0f, 45.0f, 40.0f, 78.1f); + LLQuaternion quat1(2.034f, 45.5f, 37.23f, 7.5f); + result = vect1 * quat1; + + LL_CHECK_APPROX(result.mV[0], -58153.5390f, 1.0e-3f); + LL_CHECK_APPROX(result.mV[1], 183787.8125f, 1.0e-3f); + LL_CHECK_APPROX(result.mV[2], 116864.164063f, 1.0e-3f); + LL_CHECK_APPROX(result.mV[3], 78.099998f, 1.0e-5f); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_11") + { + using namespace tut; + LLVector3 vect(12.0f, 5.0f, 60.0f); + LLQuaternion quat(23.5f, 6.5f, 3.23f, 56.5f); + LLVector3 result = vect * quat; + TUT_CHECK_MSG(is_approx_equal(97182.953125f,result.mV[0]) && + is_approx_equal(-135405.640625f, result.mV[1]) && + is_approx_equal(162986.140f, result.mV[2]), "1. LLVector3 operator*(const LLVector3 &a, const LLQuaternion &rot) failed"); + + LLVector3 vect1(5.0f, 40.0f, 78.1f); + LLQuaternion quat1(2.034f, 45.5f, 37.23f, 7.5f); + result = vect1 * quat1; + TUT_CHECK_MSG(is_approx_equal(33217.703f, result.mV[0]) && + is_approx_equal(295383.8125f, result.mV[1]) && + is_approx_equal(84718.140f, result.mV[2]), "2. LLVector3 operator*(const LLVector3 &a, const LLQuaternion &rot) failed"); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_12") + { + using namespace tut; + LLVector3d vect(-2.0f, 5.0f, -6.0f); + LLQuaternion quat(-3.5f, 4.5f, 3.5f, 6.5f); + LLVector3d result = vect * quat; + TUT_CHECK_MSG((-633.0f == result.mdV[0]) && + (-300.0f == result.mdV[1]) && + (-36.0f == result.mdV[2]), "1. LLVector3d operator*(const LLVector3d &a, const LLQuaternion &rot) failed "); + + LLVector3d vect1(5.0f, -4.5f, 8.21f); + LLQuaternion quat1(2.0f, 4.5f, -7.2f, 9.5f); + result = vect1 * quat1; + TUT_CHECK_MSG(is_approx_equal_fraction(-120.29f, (F32) result.mdV[0], 8) && + is_approx_equal_fraction(-1683.958f, (F32) result.mdV[1], 8) && + is_approx_equal_fraction(516.56f, (F32) result.mdV[2], 8), "2. LLVector3d operator*(const LLVector3d &a, const LLQuaternion &rot) failed"); + + LLVector3d vect2(2.0f, 3.5f, 1.1f); + LLQuaternion quat2(1.0f, 4.0f, 2.0f, 5.0f); + result = vect2 * quat2; + TUT_CHECK_MSG(is_approx_equal_fraction(18.400001f, (F32) result.mdV[0], 8) && + is_approx_equal_fraction(188.6f, (F32) result.mdV[1], 8) && + is_approx_equal_fraction(32.20f, (F32) result.mdV[2], 8), "3. LLVector3d operator*(const LLVector3d &a, const LLQuaternion &rot) failed"); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_13") + { + using namespace tut; + LLQuaternion quat(23.5f, 34.5f, 16723.4f, 324.7f); + LLQuaternion result = -quat; + TUT_CHECK_MSG((-23.5f == result.mQ[0]) && + (-34.5f == result.mQ[1]) && + (-16723.4f == result.mQ[2]) && + (-324.7f == result.mQ[3]), "1. LLQuaternion operator-(const LLQuaternion &a) failed"); + + LLQuaternion quat1(-3.5f, -34.5f, -16.4f, -154.7f); + result = -quat1; + TUT_CHECK_MSG((3.5f == result.mQ[0]) && + (34.5f == result.mQ[1]) && + (16.4f == result.mQ[2]) && + (154.7f == result.mQ[3]), "2. LLQuaternion operator-(const LLQuaternion &a) failed."); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_14") + { + using namespace tut; + LLQuaternion quat_value(9.0f, 8.0f, 7.0f, 6.0f); + F32 a =3.5f; + LLQuaternion result = a * quat_value; + LLQuaternion result1 = quat_value * a; + + TUT_CHECK_MSG((result.mQ[0] == result1.mQ[0]) && + (result.mQ[1] == result1.mQ[1]) && + (result.mQ[2] == result1.mQ[2]) && + (result.mQ[3] == result1.mQ[3]), "1. LLQuaternion operator* failed"); + + + LLQuaternion quat_val(9454.0f, 43568.3450f, 456343247.0343f, 2346.03434f); + a =-3324.3445f; + result = a * quat_val; + result1 = quat_val * a; + + TUT_CHECK_MSG((result.mQ[0] == result1.mQ[0]) && + (result.mQ[1] == result1.mQ[1]) && + (result.mQ[2] == result1.mQ[2]) && + (result.mQ[3] == result1.mQ[3]), "2. LLQuaternion operator* failed"); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_15") + { + using namespace tut; + // test cases for inline LLQuaternion operator~(const LLQuaternion &a) + LLQuaternion quat_val(2323.634f, -43535.4f, 3455.88f, -32232.45f); + LLQuaternion result = ~quat_val; + TUT_CHECK_MSG((-2323.634f == result.mQ[0]) && + (43535.4f == result.mQ[1]) && + (-3455.88f == result.mQ[2]) && + (-32232.45f == result.mQ[3]), "1. LLQuaternion operator~(const LLQuaternion &a) failed "); + + //test case for inline bool LLQuaternion::operator==(const LLQuaternion &b) const + LLQuaternion quat_val1(2323.634f, -43535.4f, 3455.88f, -32232.45f); + LLQuaternion quat_val2(2323.634f, -43535.4f, 3455.88f, -32232.45f); + TUT_CHECK_MSG(quat_val1 == quat_val2, "2. LLQuaternion::operator==(const LLQuaternion &b) failed"); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_16") + { + using namespace tut; + //test case for inline bool LLQuaternion::operator!=(const LLQuaternion &b) const + LLQuaternion quat_val1(2323.634f, -43535.4f, 3455.88f, -32232.45f); + LLQuaternion quat_val2(0, -43535.4f, 3455.88f, -32232.45f); + TUT_CHECK_MSG(quat_val1 != quat_val2, "LLQuaternion::operator!=(const LLQuaternion &b) failed"); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_17") + { + using namespace tut; + //test case for LLQuaternion mayaQ(F32 xRot, F32 yRot, F32 zRot, LLQuaternion::Order order) + F32 x = 2.0f; + F32 y = 1.0f; + F32 z = 3.0f; + + LLQuaternion result = mayaQ(x, y, z, LLQuaternion::XYZ); + TUT_CHECK_MSG(is_approx_equal_fraction(0.0172174f, result.mQ[0], 16) && + is_approx_equal_fraction(0.009179f, result.mQ[1], 16) && + is_approx_equal_fraction(0.026020f, result.mQ[2], 16) && + is_approx_equal_fraction(0.999471f, result.mQ[3], 16), "1. LLQuaternion mayaQ(F32 xRot, F32 yRot, F32 zRot, LLQuaternion::Order order) failed for XYZ"); + + LLQuaternion result1 = mayaQ(x, y, z, LLQuaternion::YZX); + TUT_CHECK_MSG(is_approx_equal_fraction(0.017217f, result1.mQ[0], 16) && + is_approx_equal_fraction(0.008265f, result1.mQ[1], 16) && + is_approx_equal_fraction(0.026324f, result1.mQ[2], 16) && + is_approx_equal_fraction(0.999471f, result1.mQ[3], 16), "2. LLQuaternion mayaQ(F32 xRot, F32 yRot, F32 zRot, LLQuaternion::Order order) failed for XYZ"); + + LLQuaternion result2 = mayaQ(x, y, z, LLQuaternion::ZXY); + TUT_CHECK_MSG(is_approx_equal_fraction(0.017674f, result2.mQ[0], 16) && + is_approx_equal_fraction(0.008265f, result2.mQ[1], 16) && + is_approx_equal_fraction(0.026020f, result2.mQ[2], 16) && + is_approx_equal_fraction(0.999471f, result2.mQ[3], 16), "3. LLQuaternion mayaQ(F32 xRot, F32 yRot, F32 zRot, LLQuaternion::Order order) failed for ZXY"); + + LLQuaternion result3 = mayaQ(x, y, z, LLQuaternion::XZY); + TUT_CHECK_MSG(is_approx_equal_fraction(0.017674f, result3.mQ[0], 16) && + is_approx_equal_fraction(0.009179f, result3.mQ[1], 16) && + is_approx_equal_fraction(0.026020f, result3.mQ[2], 16) && + is_approx_equal_fraction(0.999463f, result3.mQ[3], 16), "4. TLLQuaternion mayaQ(F32 xRot, F32 yRot, F32 zRot, LLQuaternion::Order order) failed for XZY"); + + LLQuaternion result4 = mayaQ(x, y, z, LLQuaternion::YXZ); + TUT_CHECK_MSG(is_approx_equal_fraction(0.017217f, result4.mQ[0], 16) && + is_approx_equal_fraction(0.009179f, result4.mQ[1], 16) && + is_approx_equal_fraction(0.026324f, result4.mQ[2], 16) && + is_approx_equal_fraction(0.999463f, result4.mQ[3], 16), "5. LLQuaternion mayaQ(F32 xRot, F32 yRot, F32 zRot, LLQuaternion::Order order) failed for YXZ"); + + LLQuaternion result5 = mayaQ(x, y, z, LLQuaternion::ZYX); + TUT_CHECK_MSG(is_approx_equal_fraction(0.017674f, result5.mQ[0], 16) && + is_approx_equal_fraction(0.008265f, result5.mQ[1], 16) && + is_approx_equal_fraction(0.026324f, result5.mQ[2], 16) && + is_approx_equal_fraction(0.999463f, result5.mQ[3], 16), "6. LLQuaternion mayaQ(F32 xRot, F32 yRot, F32 zRot, LLQuaternion::Order order) failed for ZYX"); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_18") + { + using namespace tut; + // test case for friend std::ostream& operator<<(std::ostream &s, const LLQuaternion &a) fn + LLQuaternion a(1.0f, 1.0f, 1.0f, 1.0f); + std::ostringstream result_value; + result_value << a; + TUT_ENSURE_EQ("1. Operator << failed", result_value.str(), "{ 1, 1, 1, 1 }"); + + LLQuaternion b(-31.034f, 231.2340f, 3451.344320f, -341.0f); + std::ostringstream result_value1; + result_value1 << b; + TUT_ENSURE_EQ("2. Operator << failed", result_value1.str(), "{ -31.034, 231.234, 3451.34, -341 }"); + + LLQuaternion c(1.0f, 2.2f, 3.3f, 4.4f); + result_value << c; + TUT_ENSURE_EQ("3. Operator << failed", result_value.str(), "{ 1, 1, 1, 1 }{ 1, 2.2, 3.3, 4.4 }"); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_19") + { + using namespace tut; + //test case for const char *OrderToString( const LLQuaternion::Order order ) fn + const char* result = OrderToString(LLQuaternion::XYZ); + TUT_CHECK_MSG((0 == strcmp("XYZ", result)), "1. OrderToString failed for XYZ"); + + result = OrderToString(LLQuaternion::YZX); + TUT_CHECK_MSG((0 == strcmp("YZX", result)), "2. OrderToString failed for YZX"); + + result = OrderToString(LLQuaternion::ZXY); + TUT_CHECK_MSG((0 == strcmp("ZXY", result)) && + (0 != strcmp("XYZ", result)) && + (0 != strcmp("YXZ", result)) && + (0 != strcmp("ZYX", result)) && + (0 != strcmp("XYZ", result)), "3. OrderToString failed for ZXY"); + + result = OrderToString(LLQuaternion::XZY); + TUT_CHECK_MSG((0 == strcmp("XZY", result)), "4. OrderToString failed for XZY"); + + result = OrderToString(LLQuaternion::ZYX); + TUT_CHECK_MSG((0 == strcmp("ZYX", result)), "5. OrderToString failed for ZYX"); + + result = OrderToString(LLQuaternion::YXZ); + TUT_CHECK_MSG((0 == strcmp("YXZ", result)), "6.OrderToString failed for YXZ"); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_20") + { + using namespace tut; + //test case for LLQuaternion::Order StringToOrder( const char *str ) fn + int result = StringToOrder("XYZ"); + TUT_CHECK_MSG(0 == result, "1. LLQuaternion::Order StringToOrder(const char *str ) failed for XYZ"); + + result = StringToOrder("YZX"); + TUT_CHECK_MSG(1 == result, "2. LLQuaternion::Order StringToOrder(const char *str) failed for YZX"); + + result = StringToOrder("ZXY"); + TUT_CHECK_MSG(2 == result, "3. LLQuaternion::Order StringToOrder(const char *str) failed for ZXY"); + + result = StringToOrder("XZY"); + TUT_CHECK_MSG(3 == result, "4. LLQuaternion::Order StringToOrder(const char *str) failed for XZY"); + + result = StringToOrder("YXZ"); + TUT_CHECK_MSG(4 == result, "5. LLQuaternion::Order StringToOrder(const char *str) failed for YXZ"); + + result = StringToOrder("ZYX"); + TUT_CHECK_MSG(5 == result, "6. LLQuaternion::Order StringToOrder(const char *str) failed for ZYX"); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_21") + { + using namespace tut; + //void LLQuaternion::getAngleAxis(F32* angle, LLVector3 &vec) const fn + F32 angle_value = 90.0f; + LLVector3 vect(12.0f, 4.0f, 1.0f); + LLQuaternion llquat(angle_value, vect); + llquat.getAngleAxis(&angle_value, vect); + TUT_CHECK_MSG(is_approx_equal_fraction(2.035406f, angle_value, 16) && + is_approx_equal_fraction(0.315244f, vect.mV[1], 16) && + is_approx_equal_fraction(0.078811f, vect.mV[2], 16) && + is_approx_equal_fraction(0.945733f, vect.mV[0], 16), "LLQuaternion::getAngleAxis(F32* angle, LLVector3 &vec) failed"); + } + + TUT_CASE("llquaternion_test::llquat_test_object_t_test_22") + { + using namespace tut; + //test case for void LLQuaternion::getEulerAngles(F32 *roll, F32 *pitch, F32 *yaw) const fn + F32 roll = -12.0f; + F32 pitch = -22.43f; + F32 yaw = 11.0f; + + LLQuaternion llquat; + llquat.getEulerAngles(&roll, &pitch, &yaw); + TUT_CHECK_MSG(is_approx_equal(0.000f, llquat.mQ[0]) && + is_approx_equal(0.000f, llquat.mQ[1]) && + is_approx_equal(0.000f, llquat.mQ[2]) && + is_approx_equal(1.000f, llquat.mQ[3]), "LLQuaternion::getEulerAngles(F32 *roll, F32 *pitch, F32 *yaw) failed"); + } +} diff --git a/indra/llmath/tests_doctest/v2math_test_doctest.cpp b/indra/llmath/tests_doctest/v2math_test_doctest.cpp new file mode 100644 index 00000000000..c56afbc6ef2 --- /dev/null +++ b/indra/llmath/tests_doctest/v2math_test_doctest.cpp @@ -0,0 +1,462 @@ +// --------------------------------------------------------------------------- +// Auto-generated from v2math_test.cpp at 2025-10-17T19:55:29+00:00 +// Generated by gen_tut_to_doctest.py +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "indra/test/ll_doctest_helpers.h" +#include "indra/test/tut_compat_doctest.h" +#include "linden_common.h" +#include "../v2math.h" + +/** + * @file v2math_test.cpp + * @author Adroit + * @date 2007-02 + * @brief v2math test cases. + * + * $LicenseInfo:firstyear=2007&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + + + + +namespace tut +{ + using tut_compat::ensure; + using tut_compat::ensure_equals; + using tut_compat::ensure_not; + using tut_compat::ensure_throws; + + struct v2math_data + { + }; +} // namespace tut + +TUT_SUITE("v2math_test") +{ + TUT_CASE("v2math_test::v2math_object_test_1") + { + using namespace tut; + LLVector2 vec2; + TUT_CHECK_MSG((0.f == vec2.mV[VX] && 0.f == vec2.mV[VY]), "LLVector2:Fail to initialize "); + + F32 x =2.0f, y = 3.2f ; + LLVector2 vec3(x,y); + TUT_CHECK_MSG((x == vec3.mV[VX]) && (y == vec3.mV[VY]), "LLVector2(F32 x, F32 y):Fail to initialize "); + + const F32 vec[2] = {3.2f, 4.5f}; + LLVector2 vec4(vec); + TUT_CHECK_MSG((vec[0] == vec4.mV[VX]) && (vec[1] == vec4.mV[VY]), "LLVector2(const F32 *vec):Fail to initialize "); + + vec4.clearVec(); + TUT_CHECK_MSG((0.f == vec4.mV[VX] && 0.f == vec4.mV[VY]), "clearVec():Fail to clean the values "); + + vec3.zeroVec(); + TUT_CHECK_MSG((0.f == vec3.mV[VX] && 0.f == vec3.mV[VY]), "zeroVec():Fail to fill the zero "); + } + + TUT_CASE("v2math_test::v2math_object_test_2") + { + using namespace tut; + F32 x = 123.356f, y = 2387.453f; + LLVector2 vec2,vec3; + vec2.setVec(x, y); + TUT_CHECK_MSG((x == vec2.mV[VX]) && (y == vec2.mV[VY]), "1:setVec: Fail "); + + vec3.setVec(vec2); + TUT_CHECK_MSG((vec2 == vec3), "2:setVec: Fail "); + + vec3.zeroVec(); + const F32 vec[2] = {3.24653f, 457653.4f}; + vec3.setVec(vec); + TUT_CHECK_MSG((vec[0] == vec3.mV[VX]) && (vec[1] == vec3.mV[VY]), "3:setVec: Fail "); + } + + TUT_CASE("v2math_test::v2math_object_test_3") + { + using namespace tut; + F32 x = 2.2345f, y = 3.5678f ; + LLVector2 vec2(x,y); + TUT_CHECK_MSG(is_approx_equal(vec2.magVecSquared(), (x*x + y*y)), "magVecSquared:Fail "); + TUT_CHECK_MSG(is_approx_equal(vec2.magVec(), (F32) sqrt(x*x + y*y)), "magVec:Fail "); + } + + TUT_CASE("v2math_test::v2math_object_test_4") + { + using namespace tut; + F32 x =-2.0f, y = -3.0f ; + LLVector2 vec2(x,y); + TUT_ENSURE_EQ("abs():Fail", vec2.abs(), true); + TUT_CHECK_MSG(is_approx_equal(vec2.mV[VX], 2.f), "abs() x"); + TUT_CHECK_MSG(is_approx_equal(vec2.mV[VY], 3.f), "abs() y"); + + TUT_CHECK_MSG(false == vec2.isNull(), "isNull():Fail "); //Returns true if vector has a _very_small_ length + + x =.00000001f, y = .000001001f; + vec2.setVec(x, y); + TUT_CHECK_MSG(true == vec2.isNull(), "isNull(): Fail "); + } + + TUT_CASE("v2math_test::v2math_object_test_5") + { + using namespace tut; + F32 x =1.f, y = 2.f; + LLVector2 vec2(x, y), vec3; + vec3 = vec3.scaleVec(vec2); + TUT_CHECK_MSG(vec3.mV[VX] == 0. && vec3.mV[VY] == 0., "scaleVec: Fail "); + TUT_CHECK_MSG(true == vec3.isExactlyZero(), "isExactlyZero(): Fail"); + + vec3.setVec(2.f, 1.f); + vec3 = vec3.scaleVec(vec2); + TUT_CHECK_MSG((2.f == vec3.mV[VX]) && (2.f == vec3.mV[VY]), "scaleVec: Fail "); + TUT_CHECK_MSG(false == vec3.isExactlyZero(), "isExactlyZero():Fail"); + } + + TUT_CASE("v2math_test::v2math_object_test_6") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f, x2 = -2.3f, y2 = 1.11f; + F32 val1, val2; + LLVector2 vec2(x1, y1), vec3(x2, y2), vec4; + vec4 = vec2 + vec3 ; + val1 = x1+x2; + val2 = y1+y2; + TUT_CHECK_MSG((val1 == vec4.mV[VX]) && ((val2 == vec4.mV[VY])), "1:operator+ failed"); + + vec2.clearVec(); + vec3.clearVec(); + x1 = -.235f, y1 = -24.32f, x2 = -2.3f, y2 = 1.f; + vec2.setVec(x1, y1); + vec3.setVec(x2, y2); + vec4 = vec2 + vec3; + val1 = x1+x2; + val2 = y1+y2; + TUT_CHECK_MSG((val1 == vec4.mV[VX]) && ((val2 == vec4.mV[VY])), "2:operator+ failed"); + } + + TUT_CASE("v2math_test::v2math_object_test_7") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f, x2 = -2.3f, y2 = 1.11f; + F32 val1, val2; + LLVector2 vec2(x1, y1), vec3(x2, y2), vec4; + vec4 = vec2 - vec3 ; + val1 = x1-x2; + val2 = y1-y2; + TUT_CHECK_MSG((val1 == vec4.mV[VX]) && ((val2 == vec4.mV[VY])), "1:operator- failed"); + + vec2.clearVec(); + vec3.clearVec(); + vec4.clearVec(); + x1 = -.235f, y1 = -24.32f, x2 = -2.3f, y2 = 1.f; + vec2.setVec(x1, y1); + vec3.setVec(x2, y2); + vec4 = vec2 - vec3; + val1 = x1-x2; + val2 = y1-y2; + TUT_CHECK_MSG((val1 == vec4.mV[VX]) && ((val2 == vec4.mV[VY])), "2:operator- failed"); + } + + TUT_CASE("v2math_test::v2math_object_test_8") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f, x2 = -2.3f, y2 = 1.11f; + F32 val1, val2; + LLVector2 vec2(x1, y1), vec3(x2, y2); + val1 = vec2 * vec3; + val2 = x1*x2 + y1*y2; + TUT_CHECK_MSG((val1 == val2), "1:operator* failed"); + + vec3.clearVec(); + F32 mulVal = 4.332f; + vec3 = vec2 * mulVal; + val1 = x1*mulVal; + val2 = y1*mulVal; + TUT_CHECK_MSG((val1 == vec3.mV[VX]) && (val2 == vec3.mV[VY]), "2:operator* failed"); + + vec3.clearVec(); + vec3 = mulVal * vec2; + TUT_CHECK_MSG((val1 == vec3.mV[VX]) && (val2 == vec3.mV[VY]), "3:operator* failed"); + } + + TUT_CASE("v2math_test::v2math_object_test_9") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f, div = 3.2f; + F32 val1, val2; + LLVector2 vec2(x1, y1), vec3; + vec3 = vec2 / div; + val1 = x1 / div; + val2 = y1 / div; + TUT_CHECK_MSG(is_approx_equal(val1, vec3.mV[VX]) && is_approx_equal(val2, vec3.mV[VY]), "1:operator/ failed"); + + vec3.clearVec(); + x1 = -.235f, y1 = -24.32f, div = -2.2f; + vec2.setVec(x1, y1); + vec3 = vec2 / div; + val1 = x1 / div; + val2 = y1 / div; + TUT_CHECK_MSG(is_approx_equal(val1, vec3.mV[VX]) && is_approx_equal(val2, vec3.mV[VY]), "2:operator/ failed"); + } + + TUT_CASE("v2math_test::v2math_object_test_10") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f, x2 = -2.3f, y2 = 1.11f; + F32 val1, val2; + LLVector2 vec2(x1, y1), vec3(x2, y2), vec4; + vec4 = vec2 % vec3; + val1 = x1*y2 - x2*y1; + val2 = y1*x2 - y2*x1; + TUT_CHECK_MSG((val1 == vec4.mV[VX]) && (val2 == vec4.mV[VY]), "1:operator% failed"); + + vec2.clearVec(); + vec3.clearVec(); + vec4.clearVec(); + x1 = -.235f, y1 = -24.32f, x2 = -2.3f, y2 = 1.f; + vec2.setVec(x1, y1); + vec3.setVec(x2, y2); + vec4 = vec2 % vec3; + val1 = x1*y2 - x2*y1; + val2 = y1*x2 - y2*x1; + TUT_CHECK_MSG((val1 == vec4.mV[VX]) && (val2 == vec4.mV[VY]), "2:operator% failed"); + } + + TUT_CASE("v2math_test::v2math_object_test_11") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f; + LLVector2 vec2(x1, y1), vec3(x1, y1); + TUT_CHECK_MSG((vec2 == vec3), "1:operator== failed"); + + vec2.clearVec(); + vec3.clearVec(); + x1 = -.235f, y1 = -24.32f; + vec2.setVec(x1, y1); + vec3.setVec(vec2); + TUT_CHECK_MSG((vec2 == vec3), "2:operator== failed"); + } + + TUT_CASE("v2math_test::v2math_object_test_12") + { + using namespace tut; + F32 x1 = 1.f, y1 = 2.f,x2 = 2.332f, y2 = -1.23f; + LLVector2 vec2(x1, y1), vec3(x2, y2); + TUT_CHECK_MSG((vec2 != vec3), "1:operator!= failed"); + + vec2.clearVec(); + vec3.clearVec(); + vec2.setVec(x1, y1); + vec3.setVec(vec2); + TUT_CHECK_MSG((false == (vec2 != vec3)), "2:operator!= failed"); + } + + TUT_CASE("v2math_test::v2math_object_test_13") + { + using namespace tut; + F32 x1 = 1.f, y1 = 2.f,x2 = 2.332f, y2 = -1.23f; + F32 val1, val2; + LLVector2 vec2(x1, y1), vec3(x2, y2); + vec2 +=vec3; + val1 = x1+x2; + val2 = y1+y2; + TUT_CHECK_MSG((val1 == vec2.mV[VX]) && (val2 == vec2.mV[VY]), "1:operator+= failed"); + + vec2.setVec(x1, y1); + vec2 -=vec3; + val1 = x1-x2; + val2 = y1-y2; + TUT_CHECK_MSG((val1 == vec2.mV[VX]) && (val2 == vec2.mV[VY]), "2:operator-= failed"); + + vec2.clearVec(); + vec3.clearVec(); + x1 = -21.000466f, y1 = 2.98382f,x2 = 0.332f, y2 = -01.23f; + vec2.setVec(x1, y1); + vec3.setVec(x2, y2); + vec2 +=vec3; + val1 = x1+x2; + val2 = y1+y2; + TUT_CHECK_MSG((val1 == vec2.mV[VX]) && (val2 == vec2.mV[VY]), "3:operator+= failed"); + + vec2.setVec(x1, y1); + vec2 -=vec3; + val1 = x1-x2; + val2 = y1-y2; + TUT_CHECK_MSG(is_approx_equal(val1, vec2.mV[VX]) && is_approx_equal(val2, vec2.mV[VY]), "4:operator-= failed"); + } + + TUT_CASE("v2math_test::v2math_object_test_14") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f; + F32 val1, val2, mulVal = 4.332f; + LLVector2 vec2(x1, y1); + vec2 /=mulVal; + val1 = x1 / mulVal; + val2 = y1 / mulVal; + TUT_CHECK_MSG(is_approx_equal(val1, vec2.mV[VX]) && is_approx_equal(val2, vec2.mV[VY]), "1:operator/= failed"); + + vec2.clearVec(); + x1 = .213f, y1 = -2.34f, mulVal = -.23f; + vec2.setVec(x1, y1); + vec2 /=mulVal; + val1 = x1 / mulVal; + val2 = y1 / mulVal; + TUT_CHECK_MSG(is_approx_equal(val1, vec2.mV[VX]) && is_approx_equal(val2, vec2.mV[VY]), "2:operator/= failed"); + } + + TUT_CASE("v2math_test::v2math_object_test_15") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f; + F32 val1, val2, mulVal = 4.332f; + LLVector2 vec2(x1, y1); + vec2 *=mulVal; + val1 = x1*mulVal; + val2 = y1*mulVal; + TUT_CHECK_MSG((val1 == vec2.mV[VX]) && (val2 == vec2.mV[VY]), "1:operator*= failed"); + + vec2.clearVec(); + x1 = .213f, y1 = -2.34f, mulVal = -.23f; + vec2.setVec(x1, y1); + vec2 *=mulVal; + val1 = x1*mulVal; + val2 = y1*mulVal; + TUT_CHECK_MSG((val1 == vec2.mV[VX]) && (val2 == vec2.mV[VY]), "2:operator*= failed"); + } + + TUT_CASE("v2math_test::v2math_object_test_16") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f, x2 = -2.3f, y2 = 1.11f; + F32 val1, val2; + LLVector2 vec2(x1, y1), vec3(x2, y2); + vec2 %= vec3; + val1 = x1*y2 - x2*y1; + val2 = y1*x2 - y2*x1; + TUT_CHECK_MSG((val1 == vec2.mV[VX]) && (val2 == vec2.mV[VY]), "1:operator%= failed"); + } + + TUT_CASE("v2math_test::v2math_object_test_17") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f; + LLVector2 vec2(x1, y1),vec3; + vec3 = -vec2; + TUT_CHECK_MSG((-vec3 == vec2), "1:operator- failed"); + } + + TUT_CASE("v2math_test::v2math_object_test_18") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f; + std::ostringstream stream1, stream2; + LLVector2 vec2(x1, y1),vec3; + stream1 << vec2; + vec3.setVec(x1, y1); + stream2 << vec3; + TUT_CHECK_MSG((stream1.str() == stream2.str()), "1:operator << failed"); + } + + TUT_CASE("v2math_test::v2math_object_test_19") + { + using namespace tut; + F32 x1 =1.0f, y1 = 2.0f, x2 = -.32f, y2 = .2234f; + LLVector2 vec2(x1, y1),vec3(x2, y2); + TUT_CHECK_MSG((vec3 < vec2), "1:operator < failed"); + + x1 = 1.0f, y1 = 2.0f, x2 = 1.0f, y2 = 3.2234f; + vec2.setVec(x1, y1); + vec3.setVec(x2, y2); + TUT_CHECK_MSG((false == (vec3 < vec2)), "2:operator < failed"); + } + + TUT_CASE("v2math_test::v2math_object_test_20") + { + using namespace tut; + F32 x1 =1.0f, y1 = 2.0f; + LLVector2 vec2(x1, y1); + TUT_CHECK_MSG(( x1 == vec2[0]), "1:operator [] failed"); + TUT_CHECK_MSG(( y1 == vec2[1]), "2:operator [] failed"); + + vec2.clearVec(); + x1 = 23.0f, y1 = -.2361f; + vec2.setVec(x1, y1); + F32 ref1 = vec2[0]; + TUT_CHECK_MSG(( ref1 == x1), "3:operator [] failed"); + F32 ref2 = vec2[1]; + TUT_CHECK_MSG(( ref2 == y1), "4:operator [] failed"); + } + + TUT_CASE("v2math_test::v2math_object_test_21") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f, x2 = -.32f, y2 = .2234f; + F32 val1, val2; + LLVector2 vec2(x1, y1),vec3(x2, y2); + val1 = dist_vec_squared2D(vec2, vec3); + val2 = (x1 - x2)*(x1 - x2) + (y1 - y2)* (y1 - y2); + TUT_ENSURE_EQ("dist_vec_squared2D values are not equal", val2, val1); + + val1 = dist_vec_squared(vec2, vec3); + TUT_ENSURE_EQ("dist_vec_squared values are not equal", val2, val1); + + val1 = dist_vec(vec2, vec3); + val2 = (F32) sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)* (y1 - y2)); + TUT_ENSURE_EQ("dist_vec values are not equal", val2, val1); + } + + TUT_CASE("v2math_test::v2math_object_test_22") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f, x2 = -.32f, y2 = .2234f,fVal = .0121f; + F32 val1, val2; + LLVector2 vec2(x1, y1),vec3(x2, y2); + LLVector2 vec4 = lerp(vec2, vec3, fVal); + val1 = x1 + (x2 - x1) * fVal; + val2 = y1 + (y2 - y1) * fVal; + TUT_CHECK_MSG(((val1 == vec4.mV[VX]) && (val2 == vec4.mV[VY])), "lerp values are not equal"); + } + + TUT_CASE("v2math_test::v2math_object_test_23") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f; + F32 val1, val2; + LLVector2 vec2(x1, y1); + + F32 vecMag = vec2.normVec(); + F32 mag = (F32) sqrt(x1*x1 + y1*y1); + + F32 oomag = 1.f / mag; + val1 = x1 * oomag; + val2 = y1 * oomag; + + TUT_CHECK_MSG(is_approx_equal(val1, vec2.mV[VX]) && is_approx_equal(val2, vec2.mV[VY]) && is_approx_equal(vecMag, mag), "normVec failed"); + + x1 =.00000001f, y1 = 0.f; + + vec2.setVec(x1, y1); + vecMag = vec2.normVec(); + TUT_CHECK_MSG(0. == vec2.mV[VX] && 0. == vec2.mV[VY] && vecMag == 0., "normVec failed should be 0."); + } +} diff --git a/indra/llmath/tests_doctest/v3math_test_doctest.cpp b/indra/llmath/tests_doctest/v3math_test_doctest.cpp new file mode 100644 index 00000000000..83e85f9201c --- /dev/null +++ b/indra/llmath/tests_doctest/v3math_test_doctest.cpp @@ -0,0 +1,597 @@ +// --------------------------------------------------------------------------- +// Auto-generated from v3math_test.cpp at 2025-10-17T12:56:18+00:00 +// Generated by gen_tut_to_doctest.py +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "indra/test/ll_doctest_helpers.h" +#include "indra/test/tut_compat_doctest.h" +#include "linden_common.h" +#include "llsd.h" +#include "../v3dmath.h" +#include "../m3math.h" +#include "../v4math.h" +#include "../v3math.h" +#include "../llquaternion.h" +#include "../llquantize.h" + +/** + * @file v3math_test.cpp + * @author Adroit + * @date 2007-02 + * @brief v3math test cases. + * + * $LicenseInfo:firstyear=2007&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + + + + +namespace tut +{ + using tut_compat::ensure; + using tut_compat::ensure_equals; + using tut_compat::ensure_not; + using tut_compat::ensure_throws; + + struct v3math_data + { + }; +} // namespace tut + +TUT_SUITE("v3math_test") +{ + TUT_CASE("v3math_test::v3math_object_test_1") + { + using namespace tut; + LLVector3 vec3; + TUT_CHECK_MSG(((0.f == vec3.mV[VX]) && (0.f == vec3.mV[VY]) && (0.f == vec3.mV[VZ])), "1:LLVector3:Fail to initialize "); + F32 x = 2.32f, y = 1.212f, z = -.12f; + LLVector3 vec3a(x,y,z); + TUT_CHECK_MSG(((2.32f == vec3a.mV[VX]) && (1.212f == vec3a.mV[VY]) && (-.12f == vec3a.mV[VZ])), "2:LLVector3:Fail to initialize "); + const F32 vec[3] = {1.2f ,3.2f, -4.2f}; + LLVector3 vec3b(vec); + TUT_CHECK_MSG(((1.2f == vec3b.mV[VX]) && (3.2f == vec3b.mV[VY]) && (-4.2f == vec3b.mV[VZ])), "3:LLVector3:Fail to initialize "); + } + + TUT_CASE("v3math_test::v3math_object_test_2") + { + using namespace tut; + F32 x = 2.32f, y = 1.212f, z = -.12f; + LLVector3 vec3(x,y,z); + LLVector3d vector3d(vec3); + LLVector3 vec3a(vector3d); + TUT_CHECK_MSG(vec3 == vec3a, "1:LLVector3:Fail to initialize "); + LLVector4 vector4(vec3); + LLVector3 vec3b(vector4); + TUT_CHECK_MSG(vec3 == vec3b, "2:LLVector3:Fail to initialize "); + } + + TUT_CASE("v3math_test::v3math_object_test_3") + { + using namespace tut; + S32 a = 231; + LLSD llsd(a); + LLVector3 vec3(llsd); + LLSD sd = vec3.getValue(); + LLVector3 vec3a(sd); + TUT_CHECK_MSG((vec3 == vec3a), "1:LLVector3:Fail to initialize "); + } + + TUT_CASE("v3math_test::v3math_object_test_4") + { + using namespace tut; + S32 a = 231; + LLSD llsd(a); + LLVector3 vec3(llsd),vec3a; + vec3a = vec3; + TUT_CHECK_MSG((vec3 == vec3a), "1:Operator= Fail to initialize "); + } + + TUT_CASE("v3math_test::v3math_object_test_5") + { + using namespace tut; + F32 x = 2.32f, y = 1.212f, z = -.12f; + LLVector3 vec3(x,y,z); + TUT_CHECK_MSG((true == vec3.isFinite()), "1:isFinite= Fail to initialize ");//need more test cases: + vec3.clearVec(); + TUT_CHECK_MSG(((0.f == vec3.mV[VX]) && (0.f == vec3.mV[VY]) && (0.f == vec3.mV[VZ])), "2:clearVec:Fail to set values "); + vec3.setVec(x,y,z); + TUT_CHECK_MSG(((2.32f == vec3.mV[VX]) && (1.212f == vec3.mV[VY]) && (-.12f == vec3.mV[VZ])), "3:setVec:Fail to set values "); + vec3.zeroVec(); + TUT_CHECK_MSG(((0.f == vec3.mV[VX]) && (0.f == vec3.mV[VY]) && (0.f == vec3.mV[VZ])), "4:zeroVec:Fail to set values "); + } + + TUT_CASE("v3math_test::v3math_object_test_6") + { + using namespace tut; + F32 x = 2.32f, y = 1.212f, z = -.12f; + LLVector3 vec3(x,y,z),vec3a; + vec3.abs(); + TUT_CHECK_MSG(((x == vec3.mV[VX]) && (y == vec3.mV[VY]) && (-z == vec3.mV[VZ])), "1:abs:Fail "); + vec3a.setVec(vec3); + TUT_CHECK_MSG((vec3a == vec3), "2:setVec:Fail to initialize "); + const F32 vec[3] = {1.2f ,3.2f, -4.2f}; + vec3.clearVec(); + vec3.setVec(vec); + TUT_CHECK_MSG(((1.2f == vec3.mV[VX]) && (3.2f == vec3.mV[VY]) && (-4.2f == vec3.mV[VZ])), "3:setVec:Fail to initialize "); + vec3a.clearVec(); + LLVector3d vector3d(vec3); + vec3a.setVec(vector3d); + TUT_CHECK_MSG((vec3 == vec3a), "4:setVec:Fail to initialize "); + LLVector4 vector4(vec3); + vec3a.clearVec(); + vec3a.setVec(vector4); + TUT_CHECK_MSG((vec3 == vec3a), "5:setVec:Fail to initialize "); + } + + TUT_CASE("v3math_test::v3math_object_test_7") + { + using namespace tut; + F32 x = 2.32f, y = 3.212f, z = -.12f; + F32 min = 0.0001f, max = 3.0f; + LLVector3 vec3(x,y,z); + TUT_CHECK_MSG(true == vec3.clamp(min, max) && x == vec3.mV[VX] && max == vec3.mV[VY] && min == vec3.mV[VZ], "1:clamp:Fail "); + x = 1.f, y = 2.2f, z = 2.8f; + vec3.setVec(x,y,z); + TUT_CHECK_MSG(false == vec3.clamp(min, max), "2:clamp:Fail "); + } + + TUT_CASE("v3math_test::v3math_object_test_8") + { + using namespace tut; + F32 x = 2.32f, y = 1.212f, z = -.12f; + LLVector3 vec3(x,y,z); + TUT_CHECK_MSG(is_approx_equal(vec3.magVecSquared(), (x*x + y*y + z*z)), "1:magVecSquared:Fail "); + TUT_CHECK_MSG(is_approx_equal(vec3.magVec(), (F32) sqrt(x*x + y*y + z*z)), "2:magVec:Fail "); + } + + TUT_CASE("v3math_test::v3math_object_test_9") + { + using namespace tut; + F32 x =-2.0f, y = -3.0f, z = 1.23f ; + LLVector3 vec3(x,y,z); + TUT_CHECK_MSG((true == vec3.abs()), "1:abs():Fail "); + TUT_CHECK_MSG((false == vec3.isNull()), "2:isNull():Fail"); //Returns true if vector has a _very_small_ length + x =.00000001f, y = .000001001f, z = .000001001f; + vec3.setVec(x,y,z); + TUT_CHECK_MSG((true == vec3.isNull()), "3:isNull(): Fail "); + } + + TUT_CASE("v3math_test::v3math_object_test_10") + { + using namespace tut; + F32 x =-2.0f, y = -3.0f, z = 1.f ; + LLVector3 vec3(x,y,z),vec3a; + TUT_CHECK_MSG((true == vec3a.isExactlyZero()), "1:isExactlyZero():Fail "); + vec3a = vec3a.scaleVec(vec3); + TUT_CHECK_MSG(vec3a.mV[VX] == 0.f && vec3a.mV[VY] == 0.f && vec3a.mV[VZ] == 0.f, "2:scaleVec: Fail "); + vec3a.setVec(x,y,z); + vec3a = vec3a.scaleVec(vec3); + TUT_CHECK_MSG(((4 == vec3a.mV[VX]) && (9 == vec3a.mV[VY]) &&(1 == vec3a.mV[VZ])), "3:scaleVec: Fail "); + TUT_CHECK_MSG((false == vec3.isExactlyZero()), "4:isExactlyZero():Fail "); + } + + TUT_CASE("v3math_test::v3math_object_test_11") + { + using namespace tut; + F32 x =20.0f, y = 30.0f, z = 15.f ; + F32 angle = 100.f; + LLVector3 vec3(x,y,z),vec3a(1.f,2.f,3.f); + vec3a = vec3a.rotVec(angle, vec3); + LLVector3 vec3b(1.f,2.f,3.f); + vec3b = vec3b.rotVec(angle, vec3); + TUT_ENSURE_EQ("rotVec():Fail", vec3b, vec3a); + } + + TUT_CASE("v3math_test::v3math_object_test_12") + { + using namespace tut; + F32 x =-2.0f, y = -3.0f, z = 1.f ; + LLVector3 vec3(x,y,z); + TUT_CHECK_MSG(( x == vec3[0]), "1:operator [] failed"); + TUT_CHECK_MSG(( y == vec3[1]), "2:operator [] failed"); + TUT_CHECK_MSG(( z == vec3[2]), "3:operator [] failed"); + + vec3.clearVec(); + x = 23.f, y = -.2361f, z = 3.25; + vec3.setVec(x,y,z); + F32 &ref1 = vec3[0]; + TUT_CHECK_MSG(( ref1 == vec3[0]), "4:operator [] failed"); + F32 &ref2 = vec3[1]; + TUT_CHECK_MSG(( ref2 == vec3[1]), "5:operator [] failed"); + F32 &ref3 = vec3[2]; + TUT_CHECK_MSG(( ref3 == vec3[2]), "6:operator [] failed"); + } + + TUT_CASE("v3math_test::v3math_object_test_13") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f,z1 = 1.2f, x2 = -2.3f, y2 = 1.11f, z2 = 1234.234f; + F32 val1, val2, val3; + LLVector3 vec3(x1,y1,z1), vec3a(x2,y2,z2), vec3b; + vec3b = vec3 + vec3a ; + val1 = x1+x2; + val2 = y1+y2; + val3 = z1+z2; + TUT_CHECK_MSG((val1 == vec3b.mV[VX]) && (val2 == vec3b.mV[VY]) && (val3 == vec3b.mV[VZ]), "1:operator+ failed"); + + vec3.clearVec(); + vec3a.clearVec(); + vec3b.clearVec(); + x1 = -.235f, y1 = -24.32f,z1 = 2.13f, x2 = -2.3f, y2 = 1.f, z2 = 34.21f; + vec3.setVec(x1,y1,z1); + vec3a.setVec(x2,y2,z2); + vec3b = vec3 + vec3a; + val1 = x1+x2; + val2 = y1+y2; + val3 = z1+z2; + TUT_CHECK_MSG((val1 == vec3b.mV[VX]) && (val2 == vec3b.mV[VY]) && (val3 == vec3b.mV[VZ]), "2:operator+ failed"); + } + + TUT_CASE("v3math_test::v3math_object_test_14") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f,z1 = 1.2f, x2 = -2.3f, y2 = 1.11f, z2 = 1234.234f; + F32 val1, val2, val3; + LLVector3 vec3(x1,y1,z1), vec3a(x2,y2,z2), vec3b; + vec3b = vec3 - vec3a ; + val1 = x1-x2; + val2 = y1-y2; + val3 = z1-z2; + TUT_CHECK_MSG((val1 == vec3b.mV[VX]) && (val2 == vec3b.mV[VY]) && (val3 == vec3b.mV[VZ]), "1:operator- failed"); + + vec3.clearVec(); + vec3a.clearVec(); + vec3b.clearVec(); + x1 = -.235f, y1 = -24.32f,z1 = 2.13f, x2 = -2.3f, y2 = 1.f, z2 = 34.21f; + vec3.setVec(x1,y1,z1); + vec3a.setVec(x2,y2,z2); + vec3b = vec3 - vec3a; + val1 = x1-x2; + val2 = y1-y2; + val3 = z1-z2; + TUT_CHECK_MSG((val1 == vec3b.mV[VX]) && (val2 == vec3b.mV[VY]) && (val3 == vec3b.mV[VZ]), "2:operator- failed"); + } + + TUT_CASE("v3math_test::v3math_object_test_15") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f,z1 = 1.2f, x2 = -2.3f, y2 = 1.11f, z2 = 1234.234f; + F32 val1, val2, val3; + LLVector3 vec3(x1,y1,z1), vec3a(x2,y2,z2); + val1 = vec3 * vec3a; + val2 = x1*x2 + y1*y2 + z1*z2; + TUT_ENSURE_EQ("1:operator* failed", val1, val2); + + vec3a.clearVec(); + F32 mulVal = 4.332f; + vec3a = vec3 * mulVal; + val1 = x1*mulVal; + val2 = y1*mulVal; + val3 = z1*mulVal; + TUT_CHECK_MSG((val1 == vec3a.mV[VX]) && (val2 == vec3a.mV[VY])&& (val3 == vec3a.mV[VZ]), "2:operator* failed"); + vec3a.clearVec(); + vec3a = mulVal * vec3; + TUT_CHECK_MSG((val1 == vec3a.mV[VX]) && (val2 == vec3a.mV[VY])&& (val3 == vec3a.mV[VZ]), "3:operator* failed "); + } + + TUT_CASE("v3math_test::v3math_object_test_16") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f,z1 = 1.2f, x2 = -2.3f, y2 = 1.11f, z2 = 1234.234f; + F32 val1, val2, val3; + LLVector3 vec3(x1,y1,z1), vec3a(x2,y2,z2), vec3b; + vec3b = vec3 % vec3a ; + val1 = y1*z2 - y2*z1; + val2 = z1*x2 -z2*x1; + val3 = x1*y2-x2*y1; + TUT_CHECK_MSG((val1 == vec3b.mV[VX]) && (val2 == vec3b.mV[VY]) && (val3 == vec3b.mV[VZ]), "1:operator% failed"); + + vec3.clearVec(); + vec3a.clearVec(); + vec3b.clearVec(); + x1 =112.f, y1 = 22.3f,z1 = 1.2f, x2 = -2.3f, y2 = 341.11f, z2 = 1234.234f; + vec3.setVec(x1,y1,z1); + vec3a.setVec(x2,y2,z2); + vec3b = vec3 % vec3a ; + val1 = y1*z2 - y2*z1; + val2 = z1*x2 -z2*x1; + val3 = x1*y2-x2*y1; + TUT_CHECK_MSG((val1 == vec3b.mV[VX]) && (val2 == vec3b.mV[VY]) && (val3 == vec3b.mV[VZ]), "2:operator% failed "); + } + + TUT_CASE("v3math_test::v3math_object_test_17") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f,z1 = 1.2f, div = 3.2f; + F32 t = 1.f / div, val1, val2, val3; + LLVector3 vec3(x1,y1,z1), vec3a; + vec3a = vec3 / div; + val1 = x1 * t; + val2 = y1 * t; + val3 = z1 *t; + TUT_CHECK_MSG((val1 == vec3a.mV[VX]) && (val2 == vec3a.mV[VY]) && (val3 == vec3a.mV[VZ]), "1:operator/ failed"); + + vec3a.clearVec(); + x1 = -.235f, y1 = -24.32f, z1 = .342f, div = -2.2f; + t = 1.f / div; + vec3.setVec(x1,y1,z1); + vec3a = vec3 / div; + val1 = x1 * t; + val2 = y1 * t; + val3 = z1 *t; + TUT_CHECK_MSG((val1 == vec3a.mV[VX]) && (val2 == vec3a.mV[VY]) && (val3 == vec3a.mV[VZ]), "2:operator/ failed"); + } + + TUT_CASE("v3math_test::v3math_object_test_18") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f,z1 = 1.2f; + LLVector3 vec3(x1,y1,z1), vec3a(x1,y1,z1); + TUT_CHECK_MSG((vec3 == vec3a), "1:operator== failed"); + + vec3a.clearVec(); + x1 = -.235f, y1 = -24.32f, z1 = .342f; + vec3.clearVec(); + vec3a.clearVec(); + vec3.setVec(x1,y1,z1); + vec3a.setVec(x1,y1,z1); + TUT_CHECK_MSG((vec3 == vec3a), "2:operator== failed "); + } + + TUT_CASE("v3math_test::v3math_object_test_19") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f,z1 = 1.2f, x2 =112.f, y2 = 2.234f,z2 = 11.2f;; + LLVector3 vec3(x1,y1,z1), vec3a(x2,y2,z2); + TUT_CHECK_MSG((vec3a != vec3), "1:operator!= failed"); + + vec3.clearVec(); + vec3.clearVec(); + vec3a.setVec(vec3); + TUT_CHECK_MSG(( false == (vec3a != vec3)), "2:operator!= failed"); + } + + TUT_CASE("v3math_test::v3math_object_test_20") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f,z1 = 1.2f, x2 =112.f, y2 = 2.2f,z2 = 11.2f;; + LLVector3 vec3(x1,y1,z1), vec3a(x2,y2,z2); + vec3a += vec3; + F32 val1, val2, val3; + val1 = x1+x2; + val2 = y1+y2; + val3 = z1+z2; + TUT_CHECK_MSG((val1 == vec3a.mV[VX]) && (val2 == vec3a.mV[VY])&& (val3 == vec3a.mV[VZ]), "1:operator+= failed"); + } + + TUT_CASE("v3math_test::v3math_object_test_21") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f,z1 = 1.2f, x2 =112.f, y2 = 2.2f,z2 = 11.2f;; + LLVector3 vec3(x1,y1,z1), vec3a(x2,y2,z2); + vec3a -= vec3; + F32 val1, val2, val3; + val1 = x2-x1; + val2 = y2-y1; + val3 = z2-z1; + TUT_CHECK_MSG((val1 == vec3a.mV[VX]) && (val2 == vec3a.mV[VY])&& (val3 == vec3a.mV[VZ]), "1:operator-= failed"); + } + + TUT_CASE("v3math_test::v3math_object_test_22") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f,z1 = 1.2f, x2 = -2.3f, y2 = 1.11f, z2 = 1234.234f; + F32 val1,val2,val3; + LLVector3 vec3(x1,y1,z1), vec3a(x2,y2,z2); + vec3a *= vec3; + val1 = x1*x2; + val2 = y1*y2; + val3 = z1*z2; + TUT_CHECK_MSG((val1 == vec3a.mV[VX]) && (val2 == vec3a.mV[VY])&& (val3 == vec3a.mV[VZ]), "1:operator*= failed"); + + F32 mulVal = 4.332f; + vec3 *=mulVal; + val1 = x1*mulVal; + val2 = y1*mulVal; + val3 = z1*mulVal; + TUT_CHECK_MSG(is_approx_equal(val1, vec3.mV[VX]) && is_approx_equal(val2, vec3.mV[VY]) && is_approx_equal(val3, vec3.mV[VZ]), "2:operator*= failed "); + } + + TUT_CASE("v3math_test::v3math_object_test_23") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f,z1 = 1.2f, x2 = -2.3f, y2 = 1.11f, z2 = 1234.234f; + LLVector3 vec3(x1,y1,z1), vec3a(x2,y2,z2),vec3b; + vec3b = vec3a % vec3; + vec3a %= vec3; + TUT_ENSURE_EQ("1:operator%= failed", vec3a, vec3b); + } + + TUT_CASE("v3math_test::v3math_object_test_24") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f,z1 = 1.2f, div = 3.2f; + F32 t = 1.f / div, val1, val2, val3; + LLVector3 vec3a(x1,y1,z1); + vec3a /= div; + val1 = x1 * t; + val2 = y1 * t; + val3 = z1 *t; + TUT_CHECK_MSG((val1 == vec3a.mV[VX]) && (val2 == vec3a.mV[VY]) && (val3 == vec3a.mV[VZ]), "1:operator/= failed"); + } + + TUT_CASE("v3math_test::v3math_object_test_25") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f,z1 = 1.2f; + LLVector3 vec3(x1,y1,z1), vec3a; + vec3a = -vec3; + TUT_CHECK_MSG((-vec3a == vec3), "1:operator- failed"); + } + + TUT_CASE("v3math_test::v3math_object_test_26") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f,z1 = 1.2f; + std::ostringstream stream1, stream2; + LLVector3 vec3(x1,y1,z1), vec3a; + stream1 << vec3; + vec3a.setVec(x1,y1,z1); + stream2 << vec3a; + TUT_CHECK_MSG((stream1.str() == stream2.str()), "1:operator << failed"); + } + + TUT_CASE("v3math_test::v3math_object_test_27") + { + using namespace tut; + F32 x1 =-2.3f, y1 = 2.f,z1 = 1.2f, x2 = 1.3f, y2 = 1.11f, z2 = 1234.234f; + LLVector3 vec3(x1,y1,z1), vec3a(x2,y2,z2); + TUT_CHECK_MSG((true == (vec3 < vec3a)), "1:operator< failed"); + x1 =-2.3f, y1 = 2.f,z1 = 1.2f, x2 = 1.3f, y2 = 2.f, z2 = 1234.234f; + vec3.setVec(x1,y1,z1); + vec3a.setVec(x2,y2,z2); + TUT_CHECK_MSG((true == (vec3 < vec3a)), "2:operator< failed "); + x1 =2.3f, y1 = 2.f,z1 = 1.2f, x2 = 1.3f, + vec3.setVec(x1,y1,z1); + vec3a.setVec(x2,y2,z2); + TUT_CHECK_MSG((false == (vec3 < vec3a)), "3:operator< failed "); + } + + TUT_CASE("v3math_test::v3math_object_test_28") + { + using namespace tut; + F32 x1 =1.23f, y1 = 2.f,z1 = 4.f; + std::string buf("1.23 2. 4"); + LLVector3 vec3, vec3a(x1,y1,z1); + LLVector3::parseVector3(buf, &vec3); + TUT_ENSURE_EQ("1:parseVector3 failed", vec3, vec3a); + } + + TUT_CASE("v3math_test::v3math_object_test_29") + { + using namespace tut; + F32 x1 =1.f, y1 = 2.f,z1 = 4.f; + LLVector3 vec3(x1,y1,z1),vec3a,vec3b; + vec3a.setVec(1,1,1); + vec3a.scaleVec(vec3); + TUT_ENSURE_EQ("1:scaleVec failed", vec3, vec3a); + vec3a.clearVec(); + vec3a.setVec(x1,y1,z1); + vec3a.scaleVec(vec3); + TUT_CHECK_MSG(((1.f ==vec3a.mV[VX])&& (4.f ==vec3a.mV[VY]) && (16.f ==vec3a.mV[VZ])), "2:scaleVec failed"); + } + + TUT_CASE("v3math_test::v3math_object_test_30") + { + using namespace tut; + F32 x1 =-2.3f, y1 = 2.f,z1 = 1.2f, x2 = 1.3f, y2 = 1.11f, z2 = 1234.234f; + F32 val = 2.3f,val1,val2,val3; + val1 = x1 + (x2 - x1)* val; + val2 = y1 + (y2 - y1)* val; + val3 = z1 + (z2 - z1)* val; + LLVector3 vec3(x1,y1,z1),vec3a(x2,y2,z2); + LLVector3 vec3b = lerp(vec3,vec3a,val); + TUT_CHECK_MSG(((val1 ==vec3b.mV[VX])&& (val2 ==vec3b.mV[VY]) && (val3 ==vec3b.mV[VZ])), "1:lerp failed"); + } + + TUT_CASE("v3math_test::v3math_object_test_31") + { + using namespace tut; + F32 x1 =-2.3f, y1 = 2.f,z1 = 1.2f, x2 = 1.3f, y2 = 1.f, z2 = 1.f; + F32 val1,val2; + LLVector3 vec3(x1,y1,z1),vec3a(x2,y2,z2); + val1 = dist_vec(vec3,vec3a); + val2 = (F32) sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)* (y1 - y2) + (z1 - z2)* (z1 -z2)); + TUT_ENSURE_EQ("1:dist_vec: Fail ", val2, val1); + val1 = dist_vec_squared(vec3,vec3a); + val2 =((x1 - x2)*(x1 - x2) + (y1 - y2)* (y1 - y2) + (z1 - z2)* (z1 -z2)); + TUT_ENSURE_EQ("2:dist_vec_squared: Fail ", val2, val1); + val1 = dist_vec_squared2D(vec3, vec3a); + val2 =(x1 - x2)*(x1 - x2) + (y1 - y2)* (y1 - y2); + TUT_ENSURE_EQ("3:dist_vec_squared2D: Fail ", val2, val1); + } + + TUT_CASE("v3math_test::v3math_object_test_32") + { + using namespace tut; + F32 x =12.3524f, y = -342.f,z = 4.126341f; + LLVector3 vec3(x,y,z); + F32 mag = vec3.normVec(); + mag = 1.f/ mag; + F32 val1 = x* mag, val2 = y* mag, val3 = z* mag; + TUT_CHECK_MSG(is_approx_equal(val1, vec3.mV[VX]) && is_approx_equal(val2, vec3.mV[VY]) && is_approx_equal(val3, vec3.mV[VZ]), "1:normVec: Fail "); + x = 0.000000001f, y = 0.f, z = 0.f; + vec3.clearVec(); + vec3.setVec(x,y,z); + mag = vec3.normVec(); + val1 = x* mag, val2 = y* mag, val3 = z* mag; + TUT_CHECK_MSG((mag == 0.) && (0. == vec3.mV[VX]) && (0. == vec3.mV[VY])&& (0. == vec3.mV[VZ]), "2:normVec: Fail "); + } + + TUT_CASE("v3math_test::v3math_object_test_33") + { + using namespace tut; + F32 x = -202.23412f, y = 123.2312f, z = -89.f; + LLVector3 vec(x,y,z); + vec.snap(2); + TUT_CHECK_MSG(is_approx_equal(-202.23f, vec.mV[VX]) && is_approx_equal(123.23f, vec.mV[VY]) && is_approx_equal(-89.f, vec.mV[VZ]), "1:snap: Fail "); + } + + TUT_CASE("v3math_test::v3math_object_test_34") + { + using namespace tut; + F32 x = 10.f, y = 20.f, z = -15.f; + F32 x1, y1, z1; + F32 lowerxy = 0.f, upperxy = 1.0f, lowerz = -1.0f, upperz = 1.f; + LLVector3 vec3(x,y,z); + vec3.quantize16(lowerxy,upperxy,lowerz,upperz); + x1 = U16_to_F32(F32_to_U16(x, lowerxy, upperxy), lowerxy, upperxy); + y1 = U16_to_F32(F32_to_U16(y, lowerxy, upperxy), lowerxy, upperxy); + z1 = U16_to_F32(F32_to_U16(z, lowerz, upperz), lowerz, upperz); + TUT_CHECK_MSG(is_approx_equal(x1, vec3.mV[VX]) && is_approx_equal(y1, vec3.mV[VY]) && is_approx_equal(z1, vec3.mV[VZ]), "1:quantize16: Fail "); + LLVector3 vec3a(x,y,z); + vec3a.quantize8(lowerxy,upperxy,lowerz,upperz); + x1 = U8_to_F32(F32_to_U8(x, lowerxy, upperxy), lowerxy, upperxy); + y1 = U8_to_F32(F32_to_U8(y, lowerxy, upperxy), lowerxy, upperxy); + z1 = U8_to_F32(F32_to_U8(z, lowerz, upperz), lowerz, upperz); + TUT_CHECK_MSG(is_approx_equal(x1, vec3a.mV[VX]) && is_approx_equal(y1, vec3a.mV[VY]) && is_approx_equal(z1, vec3a.mV[VZ]), "2:quantize8: Fail "); + } + + TUT_CASE("v3math_test::v3math_object_test_35") + { + using namespace tut; + LLSD sd = LLSD::emptyArray(); + sd[0] = 1.f; + + LLVector3 parsed_1(sd); + TUT_CHECK_MSG(is_approx_equal(parsed_1.mV[VX], 1.f) && is_approx_equal(parsed_1.mV[VY], 0.f) && is_approx_equal(parsed_1.mV[VZ], 0.f), "1:LLSD parse: Fail "); + + sd[1] = 2.f; + LLVector3 parsed_2(sd); + TUT_CHECK_MSG(is_approx_equal(parsed_2.mV[VX], 1.f) && is_approx_equal(parsed_2.mV[VY], 2.f) && is_approx_equal(parsed_2.mV[VZ], 0.f), "2:LLSD parse: Fail "); + + sd[2] = 3.f; + LLVector3 parsed_3(sd); + TUT_CHECK_MSG(is_approx_equal(parsed_3.mV[VX], 1.f) && is_approx_equal(parsed_3.mV[VY], 2.f) && is_approx_equal(parsed_3.mV[VZ], 3.f), "3:LLSD parse: Fail "); + } +} diff --git a/indra/llmath/tests_doctest/v4math_test_doctest.cpp b/indra/llmath/tests_doctest/v4math_test_doctest.cpp new file mode 100644 index 00000000000..e51eed63025 --- /dev/null +++ b/indra/llmath/tests_doctest/v4math_test_doctest.cpp @@ -0,0 +1,396 @@ +// --------------------------------------------------------------------------- +// Auto-generated from v4math_test.cpp at 2025-10-17T19:55:29+00:00 +// Generated by gen_tut_to_doctest.py +// --------------------------------------------------------------------------- +#include "doctest.h" +#include "indra/test/ll_doctest_helpers.h" +#include "indra/test/tut_compat_doctest.h" +#include "linden_common.h" +#include "llsd.h" +#include "../m4math.h" +#include "../v4math.h" +#include "../llquaternion.h" + +/** + * @file v4math_test.cpp + * @author Adroit + * @date 2007-03 + * @brief v4math test cases. + * + * $LicenseInfo:firstyear=2007&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + + + +namespace tut +{ + using tut_compat::ensure; + using tut_compat::ensure_equals; + using tut_compat::ensure_not; + using tut_compat::ensure_throws; + + struct v4math_data + { + }; +} // namespace tut + +TUT_SUITE("v4math_test") +{ + TUT_CASE("v4math_test::v4math_object_test_1") + { + using namespace tut; + LLVector4 vec4; + TUT_CHECK_MSG(((0 == vec4.mV[VX]) && (0 == vec4.mV[VY]) && (0 == vec4.mV[VZ])&& (1.0f == vec4.mV[VW])), "1:LLVector4:Fail to initialize "); + F32 x = 10.f, y = -2.3f, z = -.023f, w = -2.0f; + LLVector4 vec4a(x,y,z); + TUT_CHECK_MSG(((x == vec4a.mV[VX]) && (y == vec4a.mV[VY]) && (z == vec4a.mV[VZ])&& (1.0f == vec4a.mV[VW])), "2:LLVector4:Fail to initialize "); + LLVector4 vec4b(x,y,z,w); + TUT_CHECK_MSG(((x == vec4b.mV[VX]) && (y == vec4b.mV[VY]) && (z == vec4b.mV[VZ])&& (w == vec4b.mV[VW])), "3:LLVector4:Fail to initialize "); + const F32 vec[4] = {.112f ,23.2f, -4.2f, -.0001f}; + LLVector4 vec4c(vec); + TUT_CHECK_MSG(((vec[0] == vec4c.mV[VX]) && (vec[1] == vec4c.mV[VY]) && (vec[2] == vec4c.mV[VZ])&& (vec[3] == vec4c.mV[VW])), "4:LLVector4:Fail to initialize "); + LLVector3 vec3(-2.23f,1.01f,42.3f); + LLVector4 vec4d(vec3); + TUT_CHECK_MSG(((vec3.mV[VX] == vec4d.mV[VX]) && (vec3.mV[VY] == vec4d.mV[VY]) && (vec3.mV[VZ] == vec4d.mV[VZ])&& (1.f == vec4d.mV[VW])), "5:LLVector4:Fail to initialize "); + F32 w1 = -.234f; + LLVector4 vec4e(vec3,w1); + TUT_CHECK_MSG(((vec3.mV[VX] == vec4e.mV[VX]) && (vec3.mV[VY] == vec4e.mV[VY]) && (vec3.mV[VZ] == vec4e.mV[VZ])&& (w1 == vec4e.mV[VW])), "6:LLVector4:Fail to initialize "); + } + + TUT_CASE("v4math_test::v4math_object_test_2") + { + using namespace tut; + F32 x = 10.f, y = -2.3f, z = -.023f, w = -2.0f; + LLVector4 vec4; + vec4.setVec(x,y,z); + TUT_CHECK_MSG(((x == vec4.mV[VX]) && (y == vec4.mV[VY]) && (z == vec4.mV[VZ])&& (1.0f == vec4.mV[VW])), "1:setVec:Fail to initialize "); + vec4.clearVec(); + TUT_CHECK_MSG(((0 == vec4.mV[VX]) && (0 == vec4.mV[VY]) && (0 == vec4.mV[VZ])&& (1.0f == vec4.mV[VW])), "2:clearVec:Fail "); + vec4.setVec(x,y,z,w); + TUT_CHECK_MSG(((x == vec4.mV[VX]) && (y == vec4.mV[VY]) && (z == vec4.mV[VZ])&& (w == vec4.mV[VW])), "3:setVec:Fail to initialize "); + vec4.zeroVec(); + TUT_CHECK_MSG(((0 == vec4.mV[VX]) && (0 == vec4.mV[VY]) && (0 == vec4.mV[VZ])&& (0 == vec4.mV[VW])), "4:zeroVec:Fail "); + LLVector3 vec3(-2.23f,1.01f,42.3f); + vec4.clearVec(); + vec4.setVec(vec3); + TUT_CHECK_MSG(((vec3.mV[VX] == vec4.mV[VX]) && (vec3.mV[VY] == vec4.mV[VY]) && (vec3.mV[VZ] == vec4.mV[VZ])&& (1.f == vec4.mV[VW])), "5:setVec:Fail to initialize "); + F32 w1 = -.234f; + vec4.zeroVec(); + vec4.setVec(vec3,w1); + TUT_CHECK_MSG(((vec3.mV[VX] == vec4.mV[VX]) && (vec3.mV[VY] == vec4.mV[VY]) && (vec3.mV[VZ] == vec4.mV[VZ])&& (w1 == vec4.mV[VW])), "6:setVec:Fail to initialize "); + const F32 vec[4] = {.112f ,23.2f, -4.2f, -.0001f}; + LLVector4 vec4a; + vec4a.setVec(vec); + TUT_CHECK_MSG(((vec[0] == vec4a.mV[VX]) && (vec[1] == vec4a.mV[VY]) && (vec[2] == vec4a.mV[VZ])&& (vec[3] == vec4a.mV[VW])), "7:setVec:Fail to initialize "); + } + + TUT_CASE("v4math_test::v4math_object_test_3") + { + using namespace tut; + F32 x = 10.f, y = -2.3f, z = -.023f; + LLVector4 vec4(x,y,z); + TUT_CHECK_MSG(is_approx_equal(vec4.magVec(), (F32) sqrt(x*x + y*y + z*z)), "magVec:Fail "); + TUT_CHECK_MSG(is_approx_equal(vec4.magVecSquared(), (x*x + y*y + z*z)), "magVecSquared:Fail "); + } + + TUT_CASE("v4math_test::v4math_object_test_4") + { + using namespace tut; + F32 x = 10.f, y = -2.3f, z = -.023f; + LLVector4 vec4(x,y,z); + F32 mag = vec4.normVec(); + mag = 1.f/ mag; + TUT_CHECK_MSG(is_approx_equal(mag*x,vec4.mV[VX]) && is_approx_equal(mag*y, vec4.mV[VY])&& is_approx_equal(mag*z, vec4.mV[VZ]), "1:normVec: Fail "); + x = 0.000000001f, y = 0.000000001f, z = 0.000000001f; + vec4.clearVec(); + vec4.setVec(x,y,z); + mag = vec4.normVec(); + TUT_CHECK_MSG(is_approx_equal(mag*x,vec4.mV[VX]) && is_approx_equal(mag*y, vec4.mV[VY])&& is_approx_equal(mag*z, vec4.mV[VZ]), "2:normVec: Fail "); + } + + TUT_CASE("v4math_test::v4math_object_test_5") + { + using namespace tut; + F32 x = 10.f, y = -2.3f, z = -.023f, w = -2.0f; + LLVector4 vec4(x,y,z,w); + vec4.abs(); + TUT_CHECK_MSG(((x == vec4.mV[VX]) && (-y == vec4.mV[VY]) && (-z == vec4.mV[VZ])&& (-w == vec4.mV[VW])), "abs:Fail "); + vec4.clearVec(); + TUT_CHECK_MSG((true == vec4.isExactlyClear()), "isExactlyClear:Fail "); + vec4.zeroVec(); + TUT_CHECK_MSG((true == vec4.isExactlyZero()), "isExactlyZero:Fail "); + } + + TUT_CASE("v4math_test::v4math_object_test_6") + { + using namespace tut; + F32 x = 10.f, y = -2.3f, z = -.023f, w = -2.0f; + LLVector4 vec4(x,y,z,w),vec4a; + vec4a = vec4.scaleVec(vec4); + TUT_CHECK_MSG((is_approx_equal(x*x, vec4a.mV[VX]) && is_approx_equal(y*y, vec4a.mV[VY]) && is_approx_equal(z*z, vec4a.mV[VZ])&& is_approx_equal(w*w, vec4a.mV[VW])), "scaleVec:Fail "); + } + + TUT_CASE("v4math_test::v4math_object_test_7") + { + using namespace tut; + F32 x = 10.f, y = -2.3f, z = -.023f, w = -2.0f; + LLVector4 vec4(x,y,z,w); + TUT_CHECK_MSG(( x == vec4[0]), "1:operator [] failed "); + TUT_CHECK_MSG(( y == vec4[1]), "2:operator [] failed "); + TUT_CHECK_MSG(( z == vec4[2]), "3:operator [] failed "); + TUT_CHECK_MSG(( w == vec4[3]), "4:operator [] failed "); + x = 23.f, y = -.2361f, z = 3.25; + vec4.setVec(x,y,z); + F32 &ref1 = vec4[0]; + TUT_CHECK_MSG(( ref1 == vec4[0]), "5:operator [] failed "); + F32 &ref2 = vec4[1]; + TUT_CHECK_MSG(( ref2 == vec4[1]), "6:operator [] failed "); + F32 &ref3 = vec4[2]; + TUT_CHECK_MSG(( ref3 == vec4[2]), "7:operator [] failed "); + F32 &ref4 = vec4[3]; + TUT_CHECK_MSG(( ref4 == vec4[3]), "8:operator [] failed "); + } + + TUT_CASE("v4math_test::v4math_object_test_8") + { + using namespace tut; + F32 x = 10.f, y = -2.3f, z = -.023f, w = -2.0f; + const F32 val[16] = { + 1.f, 2.f, 3.f, 0.f, + .34f, .1f, -.5f, 0.f, + 2.f, 1.23f, 1.234f, 0.f, + .89f, 0.f, 0.f, 0.f + }; + LLMatrix4 mat(val); + LLVector4 vec4(x,y,z,w),vec4a; + vec4.rotVec(mat); + vec4a.setVec(x,y,z,w); + vec4a.rotVec(mat); + TUT_ENSURE_EQ("1:rotVec: Fail ", vec4a, vec4); + F32 a = 2.32f, b = -23.2f, c = -34.1112f, d = 1.010112f; + LLQuaternion q(a,b,c,d); + LLVector4 vec4b(a,b,c,d),vec4c; + vec4b.rotVec(q); + vec4c.setVec(a, b, c, d); + vec4c.rotVec(q); + TUT_ENSURE_EQ("2:rotVec: Fail ", vec4b, vec4c); + } + + TUT_CASE("v4math_test::v4math_object_test_9") + { + using namespace tut; + F32 x = 10.f, y = -2.3f, z = -.023f, w = -2.0f; + LLVector4 vec4(x,y,z,w),vec4a;; + std::ostringstream stream1, stream2; + stream1 << vec4; + vec4a.setVec(x,y,z,w); + stream2 << vec4a; + TUT_CHECK_MSG((stream1.str() == stream2.str()), "operator << failed"); + } + + TUT_CASE("v4math_test::v4math_object_test_10") + { + using namespace tut; + F32 x1 = 1.f, y1 = 2.f, z1 = -1.1f, w1 = .23f; + F32 x2 = 1.2f, y2 = 2.5f, z2 = 1.f, w2 = 1.3f; + LLVector4 vec4(x1,y1,z1,w1),vec4a(x2,y2,z2,w2),vec4b; + vec4b = vec4a + vec4; + TUT_CHECK_MSG((is_approx_equal(x1+x2,vec4b.mV[VX]) && is_approx_equal(y1+y2,vec4b.mV[VY]) && is_approx_equal(z1+z2,vec4b.mV[VZ])), "1:operator+:Fail to initialize "); + x1 = -2.45f, y1 = 2.1f, z1 = 3.0f; + vec4.clearVec(); + vec4a.clearVec(); + vec4.setVec(x1,y1,z1); + vec4a +=vec4; + TUT_ENSURE_EQ("2:operator+=: Fail to initialize", vec4a, vec4); + vec4a += vec4; + TUT_CHECK_MSG((is_approx_equal(2*x1,vec4a.mV[VX]) && is_approx_equal(2*y1,vec4a.mV[VY]) && is_approx_equal(2*z1,vec4a.mV[VZ])), "3:operator+=:Fail to initialize "); + } + + TUT_CASE("v4math_test::v4math_object_test_11") + { + using namespace tut; + F32 x1 = 1.f, y1 = 2.f, z1 = -1.1f, w1 = .23f; + F32 x2 = 1.2f, y2 = 2.5f, z2 = 1.f, w2 = 1.3f; + LLVector4 vec4(x1,y1,z1,w1),vec4a(x2,y2,z2,w2),vec4b; + vec4b = vec4a - vec4; + TUT_CHECK_MSG((is_approx_equal(x2-x1,vec4b.mV[VX]) && is_approx_equal(y2-y1,vec4b.mV[VY]) && is_approx_equal(z2-z1,vec4b.mV[VZ])), "1:operator-:Fail to initialize "); + x1 = -2.45f, y1 = 2.1f, z1 = 3.0f; + vec4.clearVec(); + vec4a.clearVec(); + vec4.setVec(x1,y1,z1); + vec4a -=vec4; + TUT_ENSURE_EQ("2:operator-=: Fail to initialize", vec4a, -vec4); + vec4a -=vec4; + TUT_CHECK_MSG((is_approx_equal(-2*x1,vec4a.mV[VX]) && is_approx_equal(-2*y1,vec4a.mV[VY]) && is_approx_equal(-2*z1,vec4a.mV[VZ])), "3:operator-=:Fail to initialize "); + } + + TUT_CASE("v4math_test::v4math_object_test_12") + { + using namespace tut; + F32 x1 = 1.f, y1 = 2.f, z1 = -1.1f; + F32 x2 = 1.2f, y2 = 2.5f, z2 = 1.f; + LLVector4 vec4(x1,y1,z1),vec4a(x2,y2,z2); + F32 res = vec4 * vec4a; + TUT_CHECK_MSG(is_approx_equal(res, x1*x2 + y1*y2 + z1*z2), "1:operator* failed "); + vec4a.clearVec(); + F32 mulVal = 4.2f; + vec4a = vec4 * mulVal; + TUT_CHECK_MSG(is_approx_equal(x1*mulVal,vec4a.mV[VX]) && is_approx_equal(y1*mulVal, vec4a.mV[VY])&& is_approx_equal(z1*mulVal, vec4a.mV[VZ]), "2:operator* failed "); + vec4a.clearVec(); + vec4a = mulVal * vec4 ; + TUT_CHECK_MSG(is_approx_equal(x1*mulVal, vec4a.mV[VX]) && is_approx_equal(y1*mulVal, vec4a.mV[VY])&& is_approx_equal(z1*mulVal, vec4a.mV[VZ]), "3:operator* failed "); + vec4 *= mulVal; + TUT_CHECK_MSG(is_approx_equal(x1*mulVal, vec4.mV[VX]) && is_approx_equal(y1*mulVal, vec4.mV[VY])&& is_approx_equal(z1*mulVal, vec4.mV[VZ]), "4:operator*= failed "); + } + + TUT_CASE("v4math_test::v4math_object_test_13") + { + using namespace tut; + F32 x1 = 1.f, y1 = 2.f, z1 = -1.1f; + F32 x2 = 1.2f, y2 = 2.5f, z2 = 1.f; + LLVector4 vec4(x1,y1,z1),vec4a(x2,y2,z2),vec4b; + vec4b = vec4 % vec4a; + TUT_CHECK_MSG(is_approx_equal(y1*z2 - y2*z1, vec4b.mV[VX]) && is_approx_equal(z1*x2 -z2*x1, vec4b.mV[VY]) && is_approx_equal(x1*y2-x2*y1, vec4b.mV[VZ]), "1:operator% failed "); + vec4 %= vec4a; + TUT_ENSURE_EQ("operator%= failed ", vec4, vec4b); + } + + TUT_CASE("v4math_test::v4math_object_test_14") + { + using namespace tut; + F32 x = 1.f, y = 2.f, z = -1.1f,div = 4.2f; + F32 t = 1.f / div; + LLVector4 vec4(x,y,z), vec4a; + vec4a = vec4/div; + TUT_CHECK_MSG(is_approx_equal(x*t, vec4a.mV[VX]) && is_approx_equal(y*t, vec4a.mV[VY])&& is_approx_equal(z*t, vec4a.mV[VZ]), "1:operator/ failed "); + x = 1.23f, y = 4.f, z = -2.32f; + vec4.clearVec(); + vec4a.clearVec(); + vec4.setVec(x,y,z); + vec4a = vec4/div; + TUT_CHECK_MSG(is_approx_equal(x*t, vec4a.mV[VX]) && is_approx_equal(y*t, vec4a.mV[VY])&& is_approx_equal(z*t, vec4a.mV[VZ]), "2:operator/ failed "); + vec4 /= div; + TUT_CHECK_MSG(is_approx_equal(x*t, vec4.mV[VX]) && is_approx_equal(y*t, vec4.mV[VY])&& is_approx_equal(z*t, vec4.mV[VZ]), "3:operator/ failed "); + } + + TUT_CASE("v4math_test::v4math_object_test_15") + { + using namespace tut; + F32 x = 1.f, y = 2.f, z = -1.1f; + LLVector4 vec4(x,y,z), vec4a; + TUT_CHECK_MSG((vec4 != vec4a), "operator!= failed "); + vec4a = vec4; + TUT_CHECK_MSG((vec4 ==vec4a), "operator== failed "); + } + + TUT_CASE("v4math_test::v4math_object_test_16") + { + using namespace tut; + F32 x = 1.f, y = 2.f, z = -1.1f; + LLVector4 vec4(x,y,z), vec4a; + vec4a = - vec4; + TUT_CHECK_MSG((vec4 == - vec4a), "operator- failed "); + } + + TUT_CASE("v4math_test::v4math_object_test_17") + { + using namespace tut; + F32 x = 1.f, y = 2.f, z = -1.1f,epsilon = .23425f; + LLVector4 vec4(x,y,z), vec4a(x,y,z); + TUT_CHECK_MSG((true == are_parallel(vec4a,vec4,epsilon)), "1:are_parallel: Fail "); + x = 21.f, y = 12.f, z = -123.1f; + vec4a.clearVec(); + vec4a.setVec(x,y,z); + TUT_CHECK_MSG((false == are_parallel(vec4a,vec4,epsilon)), "2:are_parallel: Fail "); + } + + TUT_CASE("v4math_test::v4math_object_test_18") + { + using namespace tut; + F32 x = 1.f, y = 2.f, z = -1.1f; + F32 angle1, angle2; + LLVector4 vec4(x,y,z), vec4a(x,y,z); + angle1 = angle_between(vec4, vec4a); + vec4.normVec(); + vec4a.normVec(); + angle2 = acos(vec4 * vec4a); + TUT_CHECK_MSG((angle1) == doctest::Approx(angle2).epsilon(8), "1:angle_between: Fail "); + F32 x1 = 21.f, y1 = 2.23f, z1 = -1.1f; + LLVector4 vec4b(x,y,z), vec4c(x1,y1,z1); + angle1 = angle_between(vec4b, vec4c); + vec4b.normVec(); + vec4c.normVec(); + angle2 = acos(vec4b * vec4c); + TUT_CHECK_MSG((angle1) == doctest::Approx(angle2).epsilon(8), "2:angle_between: Fail "); + } + + TUT_CASE("v4math_test::v4math_object_test_19") + { + using namespace tut; + F32 x1 =-2.3f, y1 = 2.f,z1 = 1.2f, x2 = 1.3f, y2 = 1.f, z2 = 1.f; + F32 val1,val2; + LLVector4 vec4(x1,y1,z1),vec4a(x2,y2,z2); + val1 = dist_vec(vec4,vec4a); + val2 = (F32) sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)* (y1 - y2) + (z1 - z2)* (z1 -z2)); + TUT_ENSURE_EQ("dist_vec: Fail ", val2, val1); + val1 = dist_vec_squared(vec4,vec4a); + val2 =((x1 - x2)*(x1 - x2) + (y1 - y2)* (y1 - y2) + (z1 - z2)* (z1 -z2)); + TUT_ENSURE_EQ("dist_vec_squared: Fail ", val2, val1); + } + + TUT_CASE("v4math_test::v4math_object_test_20") + { + using namespace tut; + F32 x1 =-2.3f, y1 = 2.f,z1 = 1.2f, w1 = -.23f, x2 = 1.3f, y2 = 1.f, z2 = 1.f,w2 = .12f; + F32 val = 2.3f,val1,val2,val3,val4; + LLVector4 vec4(x1,y1,z1,w1),vec4a(x2,y2,z2,w2); + val1 = x1 + (x2 - x1)* val; + val2 = y1 + (y2 - y1)* val; + val3 = z1 + (z2 - z1)* val; + val4 = w1 + (w2 - w1)* val; + LLVector4 vec4b = lerp(vec4,vec4a,val); + LLVector4 check(val1, val2, val3, val4); + TUT_ENSURE_EQ("lerp failed", check, vec4b); + } + + TUT_CASE("v4math_test::v4math_object_test_21") + { + using namespace tut; + F32 x = 1.f, y = 2.f, z = -1.1f; + LLVector4 vec4(x,y,z); + LLVector3 vec3 = vec4to3(vec4); + TUT_CHECK_MSG(((x == vec3.mV[VX])&& (y == vec3.mV[VY]) && (z == vec3.mV[VZ])), "vec4to3 failed"); + LLVector4 vec4a = vec3to4(vec3); + TUT_ENSURE_EQ("vec3to4 failed", vec4a, vec4); + } + + TUT_CASE("v4math_test::v4math_object_test_22") + { + using namespace tut; + F32 x = 1.f, y = 2.f, z = -1.1f; + LLVector4 vec4(x,y,z); + LLSD llsd = vec4.getValue(); + LLVector3 vec3(llsd); + LLVector4 vec4a = vec3to4(vec3); + TUT_ENSURE_EQ("getValue failed", vec4a, vec4); + } +} diff --git a/indra/test/doctest_main.cpp b/indra/test/doctest_main.cpp new file mode 100644 index 00000000000..8d515f8a9c0 --- /dev/null +++ b/indra/test/doctest_main.cpp @@ -0,0 +1,29 @@ +/** + * @file doctest_main.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for shared doctest entry point + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +#include "doctest.h" diff --git a/indra/test/ll_doctest_helpers.h b/indra/test/ll_doctest_helpers.h new file mode 100644 index 00000000000..0bf6fd60ffd --- /dev/null +++ b/indra/test/ll_doctest_helpers.h @@ -0,0 +1,106 @@ +/** + * @file ll_doctest_helpers.h + * @date 2025-02-18 + * @brief doctest: unit tests for shared doctest helpers + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#pragma once + +/** + * @file ll_doctest_helpers.h + * @brief Reusable assertion helpers for doctest-based unit tests. + * + * Usage guidelines: + * - Prefer `LL_CHECK_MSG` when you want to attach a readable failure message to a boolean expression. + * Example: + * LL_CHECK_MSG(result.success(), "login should succeed with valid credentials"); + * + * - Use `LL_CHECK_APPROX` for floating-point comparisons that require a tolerance. + * Example: + * LL_CHECK_APPROX(actual_value, expected_value, 1.0e-5); + * + * - Employ `LL_CHECK_EQ_RANGE` when validating contiguous buffers or array contents. + * It will emit the first mismatching index to ease debugging. + * Example: + * LL_CHECK_EQ_RANGE(buffer_a.data(), buffer_b.data(), buffer_a.size()); + */ + +#include "doctest.h" + +#include +#include + +namespace ll::test::detail +{ +template +inline void check_range_equal( + const TLeft* lhs, + const TRight* rhs, + std::size_t length, + const char* lhs_expr, + const char* rhs_expr) +{ + bool match = true; + std::size_t mismatch_index = 0; + + for (std::size_t index = 0; index < length; ++index) + { + if (!(lhs[index] == rhs[index])) + { + match = false; + mismatch_index = index; + break; + } + } + + if (!match) + { + std::ostringstream description; + description << lhs_expr << "[" << mismatch_index << "] (" + << lhs[mismatch_index] << ") differs from " + << rhs_expr << "[" << mismatch_index << "] (" + << rhs[mismatch_index] << ")"; + INFO("range length: " << length); + INFO("mismatch index: " << mismatch_index); + CHECK_MESSAGE(false, description.str()); + return; + } + + CHECK(match); +} +} // namespace ll::test::detail + +#define LL_CHECK_APPROX(actual, expected, epsilon) \ + CHECK((actual) == doctest::Approx(expected).epsilon(epsilon)) + +#define LL_CHECK_EQ_RANGE(ptrA, ptrB, len) \ + do \ + { \ + const auto* _ll_ptrA = (ptrA); \ + const auto* _ll_ptrB = (ptrB); \ + const std::size_t _ll_length = static_cast(len); \ + ::ll::test::detail::check_range_equal(_ll_ptrA, _ll_ptrB, _ll_length, #ptrA, #ptrB); \ + } while (false) + +#define LL_CHECK_MSG(condition, message) CHECK_MESSAGE((condition), (message)) diff --git a/indra/test/tut_compat_doctest.h b/indra/test/tut_compat_doctest.h new file mode 100644 index 00000000000..075fde90f01 --- /dev/null +++ b/indra/test/tut_compat_doctest.h @@ -0,0 +1,117 @@ +/** + * @file tut_compat_doctest.h + * @date 2025-02-18 + * @brief doctest: unit tests for TUT compatibility helpers + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#pragma once + +/** + * @file tut_compat_doctest.h + * @brief Lightweight compatibility layer allowing generated TUT-style tests + * to build on top of doctest. + * + * This header is intended for auto-generated sources only. It maps the + * most common TUT primitives to doctest while providing safe fallbacks. + * Unsupported constructs should be replaced by the generator with explicit + * DOCTEST_FAIL markers. + */ + +#include "doctest.h" +#include "ll_doctest_helpers.h" + +#include +#include +#include + +namespace tut_compat +{ +inline void ensure(bool condition) +{ + CHECK(condition); +} + +inline void ensure(const char* message, bool condition) +{ + CHECK_MESSAGE(condition, message); +} + +template +inline void ensure_equals(const Left& lhs, const Right& rhs) +{ + CHECK(lhs == rhs); +} + +template +inline void ensure_equals(const char* message, const Left& lhs, const Right& rhs) +{ + CHECK_MESSAGE(lhs == rhs, message); +} + +template +inline void ensure_not(const Expr& value) +{ + CHECK_FALSE(value); +} + +template +inline void ensure_not(const char* message, const Expr& value) +{ + CHECK_MESSAGE(!value, message); +} + +template +inline void ensure_throws(Func&& fn) +{ + CHECK_THROWS(fn()); +} + +template +inline void ensure_throws(const char* message, Func&& fn, Exception) +{ + (void)message; + CHECK_THROWS_AS(fn(), Exception); +} + +inline void set_test_name(const char* name) +{ + INFO("test name: " << (name ? name : "")); +} + +inline void skip(const char* reason) +{ + INFO("skip requested: " << (reason ? reason : "")); + DOCTEST_FAIL("TODO: original test requested skip"); +} +} // namespace tut_compat + +#define TUT_ENSURE(...) ::tut_compat::ensure(__VA_ARGS__) +#define TUT_ENSURE_EQ(...) ::tut_compat::ensure_equals(__VA_ARGS__) +#define TUT_ENSURE_NOT(...) ::tut_compat::ensure_not(__VA_ARGS__) +#define TUT_ENSURE_THROWS(expr) ::tut_compat::ensure_throws([&]() { expr; }) +#define TUT_CHECK_MSG(cond, msg) CHECK_MESSAGE((cond), (msg)) +#define TUT_SUITE(name) TEST_SUITE(name) +#define TUT_CASE(name) TEST_CASE(name) +#define TUT_SET_TEST_NAME(name) ::tut_compat::set_test_name(name) +#define TUT_SKIP(reason) ::tut_compat::skip(reason) diff --git a/indra/viewer_components/login/CMakeLists.txt b/indra/viewer_components/login/CMakeLists.txt index 8381803b038..b59c0ee4d59 100644 --- a/indra/viewer_components/login/CMakeLists.txt +++ b/indra/viewer_components/login/CMakeLists.txt @@ -5,6 +5,7 @@ project(login) include(00-Common) if(LL_TESTS) include(LLAddBuildTest) + include(Doctest) endif(LL_TESTS) include(LLCommon) include(LLCoreHttp) @@ -36,6 +37,7 @@ target_link_libraries(lllogin ) if(LL_TESTS) + enable_testing() SET(lllogin_TEST_SOURCE_FILES lllogin.cpp ) @@ -46,4 +48,28 @@ if(LL_TESTS) ) LL_ADD_PROJECT_UNIT_TESTS(lllogin "${lllogin_TEST_SOURCE_FILES}") + + add_executable(login_doctest + tests/lllogin_doctest.cpp + ${CMAKE_SOURCE_DIR}/test/doctest_main.cpp + ) + + target_include_directories(login_doctest + PRIVATE + ${DOCTEST_INCLUDE_DIR} + ${CMAKE_SOURCE_DIR}/test + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/tests + ) + + target_link_libraries(login_doctest + lllogin + llmessage + llcorehttp + llcommon + llmath + llxml + ) + + add_test(NAME login_doctest COMMAND login_doctest) endif(LL_TESTS) diff --git a/indra/viewer_components/login/tests/lllogin_doctest.cpp b/indra/viewer_components/login/tests/lllogin_doctest.cpp new file mode 100644 index 00000000000..3015faccd3d --- /dev/null +++ b/indra/viewer_components/login/tests/lllogin_doctest.cpp @@ -0,0 +1,284 @@ +/** + * @file lllogin_doctest.cpp + * @date 2025-02-18 + * @brief doctest: unit tests for viewer login workflow + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include "linden_common.h" + +#include "doctest.h" +#include "ll_doctest_helpers.h" +#include "../lllogin.h" + +#include "llevents.h" +#include "lleventcoro.h" +#include "llsd.h" + +#include "../../../test/lltestapp.h" + +#include + +#include +#include +#include +#include +#include + +namespace +{ +class LoginListener : public LLEventTrackable +{ +public: + explicit LoginListener(std::string name) + : mName(std::move(name)) + { + } + + bool call(const LLSD& event) + { + mLastEvent = event; + ++mCalls; + return false; + } + + LLBoundListener listenTo(LLEventPump& pump) + { + return pump.listen(mName, boost::bind(&LoginListener::call, this, _1)); + } + + const LLSD& lastEvent() const { return mLastEvent; } + + size_t getCalls() const { return mCalls; } + + template + LLSD waitFor(const std::string& description, Predicate&& predicate, double timeout_seconds = 2.0) const + { + auto start = std::chrono::steady_clock::now(); + while (!predicate()) + { + auto elapsed = std::chrono::steady_clock::now() - start; + if (std::chrono::duration(elapsed).count() > timeout_seconds) + { + std::ostringstream message; + message << description << " not observed within " << timeout_seconds << " seconds"; + FAIL_CHECK(message.str().c_str()); + break; + } + llcoro::suspend(); + } + return lastEvent(); + } + + LLSD waitFor(size_t previousCalls, double timeout_seconds) const + { + return waitFor( + "listener to receive new event", + [this, previousCalls]() { return getCalls() > previousCalls; }, + timeout_seconds); + } + +private: + std::string mName; + mutable LLSD mLastEvent; + mutable size_t mCalls{0}; +}; + +class LLXMLRPCListener : public LLEventTrackable +{ +public: + LLXMLRPCListener(std::string name, bool immediate_response = false, LLSD response = LLSD()) + : mName(std::move(name)), + mImmediateResponse(immediate_response), + mResponse(std::move(response)) + { + if (mResponse.isUndefined()) + { + mResponse["status"] = "Complete"; + mResponse["errorcode"] = 0; + mResponse["error"] = "dummy response"; + mResponse["transfer_rate"] = 0; + mResponse["responses"]["login"] = true; + } + } + + void setResponse(const LLSD& response) { mResponse = response; } + + bool handleEvent(const LLSD& event) + { + mEvent = event; + if (mImmediateResponse) + { + sendReply(); + } + return false; + } + + void sendReply() + { + LLEventPumps::instance().obtain(mEvent["reply"]).post(mResponse); + } + + LLBoundListener listenTo(LLEventPump& pump) + { + return pump.listen(mName, boost::bind(&LLXMLRPCListener::handleEvent, this, _1)); + } + +private: + std::string mName; + bool mImmediateResponse{false}; + LLSD mResponse; + LLSD mEvent; +}; + +struct LoginTestEnvironment +{ + LoginTestEnvironment() + : pumps(LLEventPumps::instance()) + { + } + + ~LoginTestEnvironment() + { + pumps.clear(); + } + + LLEventPumps& pumps; + LLTestApp testApp; +}; +} // namespace + +TEST_SUITE("login") +{ + TEST_CASE("connects with immediate xmlrpc response") + { + LoginTestEnvironment env; + LLEventStream xmlrpcPump("LLXMLRPCTransaction"); + + const bool respond_immediately = true; + LLXMLRPCListener dummyXMLRPC("dummy_xmlrpc", respond_immediately); + LLTempBoundListener conn1 = dummyXMLRPC.listenTo(xmlrpcPump); + + LLLogin login; + + LoginListener listener("test_ear"); + LLTempBoundListener conn2 = listener.listenTo(login.getEventPump()); + + LLSD credentials; + credentials["first"] = "foo"; + credentials["last"] = "bar"; + credentials["passwd"] = "secret"; + + login.connect("login.bar.com", credentials); + LLSD event = listener.waitFor( + "online state", + [&listener]() { return listener.lastEvent()["state"].asString() == "online"; }); + + LL_CHECK_MSG( + event["state"].asString() == "online", + "Successful login should report state 'online'"); + } + + TEST_CASE("failed login transitions offline") + { + LoginTestEnvironment env; + LLEventStream xmlrpcPump("LLXMLRPCTransaction"); + + LLXMLRPCListener dummyXMLRPC("dummy_xmlrpc"); + LLTempBoundListener conn1 = dummyXMLRPC.listenTo(xmlrpcPump); + + LLLogin login; + LoginListener listener("test_ear"); + LLTempBoundListener conn2 = listener.listenTo(login.getEventPump()); + + LLSD credentials; + credentials["first"] = "who"; + credentials["last"] = "what"; + credentials["passwd"] = "badpasswd"; + + login.connect("login.bar.com", credentials); + llcoro::suspend(); + + LL_CHECK_MSG( + listener.lastEvent()["change"].asString() == "authenticating", + "Login must announce 'authenticating' before processing the response"); + + size_t previous = listener.getCalls(); + + LLSD data; + data["status"] = "Complete"; + data["errorcode"] = 0; + data["error"] = "dummy response"; + data["transfer_rate"] = 0; + data["responses"]["login"] = "false"; + dummyXMLRPC.setResponse(data); + dummyXMLRPC.sendReply(); + + listener.waitFor(previous, 11.0); + + LL_CHECK_MSG( + listener.lastEvent()["state"].asString() == "offline", + "Failed credentials should transition the client to 'offline'"); + } + + TEST_CASE("error response transitions offline") + { + LoginTestEnvironment env; + LLEventStream xmlrpcPump("LLXMLRPCTransaction"); + + LLXMLRPCListener dummyXMLRPC("dummy_xmlrpc"); + LLTempBoundListener conn1 = dummyXMLRPC.listenTo(xmlrpcPump); + + LLLogin login; + LoginListener listener("test_ear"); + LLTempBoundListener conn2 = listener.listenTo(login.getEventPump()); + + LLSD credentials; + credentials["first"] = "these"; + credentials["last"] = "don't"; + credentials["passwd"] = "matter"; + + login.connect("login.bar.com", credentials); + llcoro::suspend(); + + LL_CHECK_MSG( + listener.lastEvent()["change"].asString() == "authenticating", + "Login must announce 'authenticating' before processing the error response"); + + size_t previous = listener.getCalls(); + + LLSD data; + data["status"] = "OtherError"; + data["errorcode"] = 0; + data["error"] = "dummy response"; + data["transfer_rate"] = 0; + dummyXMLRPC.setResponse(data); + dummyXMLRPC.sendReply(); + + listener.waitFor(previous, 11.0); + + LL_CHECK_MSG( + listener.lastEvent()["state"].asString() == "offline", + "Unexpected error responses should transition the client to 'offline'"); + } +} diff --git a/tools/testing/gen_tut_to_doctest.py b/tools/testing/gen_tut_to_doctest.py new file mode 100644 index 00000000000..e32d38ef888 --- /dev/null +++ b/tools/testing/gen_tut_to_doctest.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +""" +@file gen_tut_to_doctest.py +@date 2025-02-18 +@brief doctest: unit tests for TUT to doctest generator + +$LicenseInfo:firstyear=2025&license=viewerlgpl$ +Second Life Viewer Source Code +Copyright (C) 2025, Linden Research, Inc. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; +version 2.1 of the License only. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA +$/LicenseInfo$ +""" + +from __future__ import annotations + +import argparse +import datetime +import pathlib +import re +import textwrap +from typing import Iterable, List, Tuple + + +TEST_RE = re.compile( + r"template\s*<>\s*template\s*<>\s*void\s+" + r"(?P[A-Za-z_]\w*)::test<\s*(?P\d+)\s*>\s*\(\s*\)\s*{", + re.MULTILINE, +) + +INCLUDE_RE = re.compile(r"^\s*#\s*include\s+[<\"].+[>\"]\s*$", re.MULTILINE) + + +def extract_block(source: str, start_index: int) -> Tuple[str, int]: + """Extract a block delimited by braces starting at start_index.""" + depth = 0 + end_index = start_index + for idx in range(start_index, len(source)): + char = source[idx] + if char == "{": + depth += 1 + elif char == "}": + depth -= 1 + if depth == 0: + end_index = idx + break + # body without surrounding braces + body = source[start_index + 1 : end_index] + return body, end_index + 1 + + +def collect_includes(source: str) -> List[str]: + includes = INCLUDE_RE.findall(source) + cleaned: List[str] = [] + filtered_keywords = ("lltut.h", "tut/") + windows_excludes = ( + "sys/wait.h", + "unistd.h", + "llallocator.h", + "llallocator_heap_profile.h", + "llmemtype.h", + "lllazy.h", + "netinet/in.h", + "StringVec.h", + ) + for line in includes: + if any(keyword in line for keyword in filtered_keywords): + continue + if any(keyword in line for keyword in windows_excludes): + cleaned.append("// " + line.strip() + " // not available on Windows") + continue + cleaned.append(line.strip()) + return cleaned + + +def discover_tests(source: str) -> List[Tuple[str, str, str]]: + tests: List[Tuple[str, str, str]] = [] + for match in TEST_RE.finditer(source): + object_name = match.group("object") + index = match.group("index") + body, end_index = extract_block(source, match.end() - 1) + snippet = source[match.start() : end_index] + tests.append((object_name, index, snippet)) + return tests + + +def make_case_name(stem: str, object_name: str, index: str) -> str: + return f"{stem}::{object_name}_test_{index}" + + +def generate_doctest_file( + src_path: pathlib.Path, dst_path: pathlib.Path, includes: Iterable[str], tests: List[Tuple[str, str, str]] +) -> None: + timestamp = datetime.datetime.utcnow().isoformat(timespec="seconds") + "Z" + lines: List[str] = [] + lines.append("// ---------------------------------------------------------------------------") + lines.append(f"// Auto-generated from {src_path.name} at {timestamp}") + lines.append("// This file is a TODO stub produced by gen_tut_to_doctest.py.") + lines.append("// ---------------------------------------------------------------------------") + lines.append('#include "doctest.h"') + lines.append('#include "ll_doctest_helpers.h"') + lines.append('#include "tut_compat_doctest.h"') + for inc in includes: + lines.append(inc) + lines.append("") + lines.append('TUT_SUITE("llcommon")') + lines.append("{") + + if not tests: + lines.append(" TUT_CASE(\"{0}::no_tests_detected\")".format(src_path.stem)) + lines.append(" {") + lines.append(' DOCTEST_FAIL("TODO: no TUT tests discovered in source file");') + lines.append(" }") + else: + for object_name, index, snippet in tests: + case_name = make_case_name(src_path.stem, object_name, index) + lines.append(f' TUT_CASE("{case_name}")') + lines.append(" {") + lines.append( + f' DOCTEST_FAIL("TODO: convert {src_path.name}::{object_name}::test<{index}> from TUT to doctest");' + ) + lines.append(" // Original snippet:") + snippet_comment = textwrap.indent(textwrap.dedent(snippet).rstrip(), " // ") + lines.extend(snippet_comment.splitlines()) + lines.append(" }") + lines.append("") + lines.append("}") + lines.append("") + + dst_path.parent.mkdir(parents=True, exist_ok=True) + dst_path.write_text("\n".join(lines) + "\n", encoding="utf-8") + + +def main() -> None: + parser = argparse.ArgumentParser(description="Generate doctest stubs from TUT sources.") + parser.add_argument("--src", required=True, help="Directory containing TUT sources.") + parser.add_argument("--dst", required=True, help="Directory where doctest files will be written.") + args = parser.parse_args() + + src_dir = pathlib.Path(args.src).resolve() + dst_dir = pathlib.Path(args.dst).resolve() + + if not src_dir.exists(): + raise SystemExit(f"Source directory {src_dir} does not exist") + + dst_dir.mkdir(parents=True, exist_ok=True) + + mappings: List[Tuple[pathlib.Path, pathlib.Path]] = [] + + for cpp_path in sorted(src_dir.glob("*.cpp")): + source = cpp_path.read_text(encoding="utf-8") + includes = collect_includes(source) + tests = discover_tests(source) + + dest_filename = cpp_path.stem + "_doctest.cpp" + dest_path = dst_dir / dest_filename + + generate_doctest_file(cpp_path, dest_path, includes, tests) + mappings.append((cpp_path.relative_to(src_dir), dest_path.relative_to(dst_dir))) + + index_lines = [f"{src} -> {dst}" for src, dst in mappings] + (dst_dir / "generated.index").write_text("\n".join(index_lines) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + main()