diff options
author | bulatman <bulatman@yandex-team.ru> | 2022-02-10 16:45:50 +0300 |
---|---|---|
committer | Daniil Cherednik <dcherednik@yandex-team.ru> | 2022-02-10 16:45:50 +0300 |
commit | 6560e4993b14d193f8c879e33a3de5e5eba6e21d (patch) | |
tree | cfd2e2baa05c3196f2caacbb63c32e1df40bc3de /library | |
parent | 7489e4682331202b9c7d863c0898eb83d7b12c2b (diff) | |
download | ydb-6560e4993b14d193f8c879e33a3de5e5eba6e21d.tar.gz |
Restoring authorship annotation for <bulatman@yandex-team.ru>. Commit 1 of 2.
Diffstat (limited to 'library')
69 files changed, 1686 insertions, 1686 deletions
diff --git a/library/cpp/accurate_accumulate/benchmark/ya.make b/library/cpp/accurate_accumulate/benchmark/ya.make index 20fd877389..cd86bc5a63 100644 --- a/library/cpp/accurate_accumulate/benchmark/ya.make +++ b/library/cpp/accurate_accumulate/benchmark/ya.make @@ -1,6 +1,6 @@ OWNER(yazevnul) -Y_BENCHMARK() +Y_BENCHMARK() SRCS( main.cpp diff --git a/library/cpp/actors/interconnect/interconnect_stream.h b/library/cpp/actors/interconnect/interconnect_stream.h index 074adc6e74..717ea18786 100644 --- a/library/cpp/actors/interconnect/interconnect_stream.h +++ b/library/cpp/actors/interconnect/interconnect_stream.h @@ -12,8 +12,8 @@ #include <memory> -#include <sys/uio.h> - +#include <sys/uio.h> + namespace NInterconnect { class TSocket: public NActors::TSharedDescriptor, public TNonCopyable { protected: diff --git a/library/cpp/actors/interconnect/ya.make b/library/cpp/actors/interconnect/ya.make index 60d29b0fc0..0c6ea9acff 100644 --- a/library/cpp/actors/interconnect/ya.make +++ b/library/cpp/actors/interconnect/ya.make @@ -72,7 +72,7 @@ IF (OS_LINUX) ENDIF() PEERDIR( - contrib/libs/libc_compat + contrib/libs/libc_compat contrib/libs/openssl library/cpp/actors/core library/cpp/actors/dnscachelib diff --git a/library/cpp/containers/comptrie/benchmark/ya.make b/library/cpp/containers/comptrie/benchmark/ya.make index 16fa19530d..cfd0839da8 100644 --- a/library/cpp/containers/comptrie/benchmark/ya.make +++ b/library/cpp/containers/comptrie/benchmark/ya.make @@ -1,4 +1,4 @@ -Y_BENCHMARK() +Y_BENCHMARK() OWNER(smirnovpavel) diff --git a/library/cpp/containers/flat_hash/benchmark/ya.make b/library/cpp/containers/flat_hash/benchmark/ya.make index 6f9aedf50d..2a86bf458e 100644 --- a/library/cpp/containers/flat_hash/benchmark/ya.make +++ b/library/cpp/containers/flat_hash/benchmark/ya.make @@ -1,4 +1,4 @@ -Y_BENCHMARK() +Y_BENCHMARK() OWNER(tender-bum) diff --git a/library/cpp/coroutine/engine/helper.cpp b/library/cpp/coroutine/engine/helper.cpp index bffe208dc8..c3e36bffb6 100644 --- a/library/cpp/coroutine/engine/helper.cpp +++ b/library/cpp/coroutine/engine/helper.cpp @@ -1,37 +1,37 @@ -#include "helper.h" - -#include "impl.h" -#include "network.h" - -namespace NCoro { - - bool TryConnect(const TString& host, ui16 port, TDuration timeout) { - bool connected = false; - - auto f = [&connected, &host, port, timeout](TCont* c) { - TSocketHolder socket; - TNetworkAddress address(host, port); - connected = (0 == NCoro::ConnectT(c, socket, address, timeout)); - }; - - TContExecutor e(128 * 1024); - e.Create(f, "try_connect"); - e.Execute(); - return connected; - } - - bool WaitUntilConnectable(const TString& host, ui16 port, TDuration timeout) { - const TInstant deadline = timeout.ToDeadLine(); - - for (size_t i = 1; Now() < deadline; ++i) { - const TDuration waitTime = TDuration::MilliSeconds(100) * i * i; - SleepUntil(Min(Now() + waitTime, deadline)); - - if (TryConnect(host, port, waitTime)) { - return true; - } - } - - return false; - } -} +#include "helper.h" + +#include "impl.h" +#include "network.h" + +namespace NCoro { + + bool TryConnect(const TString& host, ui16 port, TDuration timeout) { + bool connected = false; + + auto f = [&connected, &host, port, timeout](TCont* c) { + TSocketHolder socket; + TNetworkAddress address(host, port); + connected = (0 == NCoro::ConnectT(c, socket, address, timeout)); + }; + + TContExecutor e(128 * 1024); + e.Create(f, "try_connect"); + e.Execute(); + return connected; + } + + bool WaitUntilConnectable(const TString& host, ui16 port, TDuration timeout) { + const TInstant deadline = timeout.ToDeadLine(); + + for (size_t i = 1; Now() < deadline; ++i) { + const TDuration waitTime = TDuration::MilliSeconds(100) * i * i; + SleepUntil(Min(Now() + waitTime, deadline)); + + if (TryConnect(host, port, waitTime)) { + return true; + } + } + + return false; + } +} diff --git a/library/cpp/coroutine/engine/helper.h b/library/cpp/coroutine/engine/helper.h index ec2711ba52..0c3e978699 100644 --- a/library/cpp/coroutine/engine/helper.h +++ b/library/cpp/coroutine/engine/helper.h @@ -1,15 +1,15 @@ -#pragma once - -#include <util/generic/string.h> -#include <util/datetime/base.h> - -namespace NCoro { - - // @brief check that address `host`:`port` is connectable - bool TryConnect(const TString& host, ui16 port, TDuration timeout = TDuration::Seconds(1)); - - // @brief waits until address `host`:`port` became connectable, but not more than timeout - // @return true on success, false if timeout exceeded - bool WaitUntilConnectable(const TString& host, ui16 port, TDuration timeout); - -} +#pragma once + +#include <util/generic/string.h> +#include <util/datetime/base.h> + +namespace NCoro { + + // @brief check that address `host`:`port` is connectable + bool TryConnect(const TString& host, ui16 port, TDuration timeout = TDuration::Seconds(1)); + + // @brief waits until address `host`:`port` became connectable, but not more than timeout + // @return true on success, false if timeout exceeded + bool WaitUntilConnectable(const TString& host, ui16 port, TDuration timeout); + +} diff --git a/library/cpp/coroutine/engine/network.cpp b/library/cpp/coroutine/engine/network.cpp index 85b647d210..b5ece3d580 100644 --- a/library/cpp/coroutine/engine/network.cpp +++ b/library/cpp/coroutine/engine/network.cpp @@ -4,7 +4,7 @@ #include <util/generic/scope.h> #include <util/generic/xrange.h> -#include <sys/uio.h> +#include <sys/uio.h> #if defined(_bionic_) # define IOV_MAX 1024 @@ -18,11 +18,11 @@ namespace NCoro { } ssize_t DoReadVector(SOCKET fd, TContIOVector* vec) noexcept { - return readv(fd, (const iovec*) vec->Parts(), Min(IOV_MAX, (int) vec->Count())); + return readv(fd, (const iovec*) vec->Parts(), Min(IOV_MAX, (int) vec->Count())); } ssize_t DoWriteVector(SOCKET fd, TContIOVector* vec) noexcept { - return writev(fd, (const iovec*) vec->Parts(), Min(IOV_MAX, (int) vec->Count())); + return writev(fd, (const iovec*) vec->Parts(), Min(IOV_MAX, (int) vec->Count())); } } diff --git a/library/cpp/coroutine/engine/ya.make b/library/cpp/coroutine/engine/ya.make index 8c20b9afc3..50012181a7 100644 --- a/library/cpp/coroutine/engine/ya.make +++ b/library/cpp/coroutine/engine/ya.make @@ -9,13 +9,13 @@ GENERATE_ENUM_SERIALIZATION(poller.h) GENERATE_ENUM_SERIALIZATION(stack/stack_common.h) PEERDIR( - contrib/libs/libc_compat + contrib/libs/libc_compat library/cpp/containers/intrusive_rb_tree ) SRCS( cont_poller.cpp - helper.cpp + helper.cpp impl.cpp iostatus.cpp network.cpp diff --git a/library/cpp/digest/argonish/benchmark/ya.make b/library/cpp/digest/argonish/benchmark/ya.make index 5aad1b238f..76db5a107f 100644 --- a/library/cpp/digest/argonish/benchmark/ya.make +++ b/library/cpp/digest/argonish/benchmark/ya.make @@ -1,6 +1,6 @@ OWNER(e-sidorov) -Y_BENCHMARK() +Y_BENCHMARK() PEERDIR( library/cpp/digest/argonish diff --git a/library/cpp/int128/bench/ya.make b/library/cpp/int128/bench/ya.make index 4800e7883d..628b932521 100644 --- a/library/cpp/int128/bench/ya.make +++ b/library/cpp/int128/bench/ya.make @@ -2,7 +2,7 @@ OWNER( vladon ) -Y_BENCHMARK() +Y_BENCHMARK() SRCS( main.cpp diff --git a/library/cpp/logger/global/common.h b/library/cpp/logger/global/common.h index 7dcf650dec..94327bf745 100644 --- a/library/cpp/logger/global/common.h +++ b/library/cpp/logger/global/common.h @@ -21,46 +21,46 @@ T* CreateDefaultLogger() { return nullptr; } -namespace NLoggingImpl { - template<class T, class TTraits> - class TOperatorBase { - struct TPtr { - TPtr() - : Instance(TTraits::CreateDefault()) - { - } - - THolder<T> Instance; - }; - - public: - inline static bool Usage() { +namespace NLoggingImpl { + template<class T, class TTraits> + class TOperatorBase { + struct TPtr { + TPtr() + : Instance(TTraits::CreateDefault()) + { + } + + THolder<T> Instance; + }; + + public: + inline static bool Usage() { return SingletonWithPriority<TPtr, SingletonPriority>()->Instance.Get(); } - inline static T* Get() { + inline static T* Get() { return SingletonWithPriority<TPtr, SingletonPriority>()->Instance.Get(); - } - - inline static void Set(T* v) { + } + + inline static void Set(T* v) { SingletonWithPriority<TPtr, SingletonPriority>()->Instance.Reset(v); - } + } }; - template<class T> - struct TLoggerTraits { - static T* CreateDefault() { - return CreateDefaultLogger<T>(); - } - }; -} - -template <class T> -class TLoggerOperator : public NLoggingImpl::TOperatorBase<T, NLoggingImpl::TLoggerTraits<T>> { -public: + template<class T> + struct TLoggerTraits { + static T* CreateDefault() { + return CreateDefaultLogger<T>(); + } + }; +} + +template <class T> +class TLoggerOperator : public NLoggingImpl::TOperatorBase<T, NLoggingImpl::TLoggerTraits<T>> { +public: inline static TLog& Log() { - Y_ASSERT(TLoggerOperator::Usage()); - return *TLoggerOperator::Get(); + Y_ASSERT(TLoggerOperator::Usage()); + return *TLoggerOperator::Get(); } }; @@ -70,11 +70,11 @@ namespace NLoggingImpl { // Returns correct log type to use TString PrepareToOpenLog(TString logType, int logLevel, bool rotation, bool startAsDaemon); - - template <class TLoggerType> - void InitLogImpl(TString logType, const int logLevel, const bool rotation, const bool startAsDaemon) { + + template <class TLoggerType> + void InitLogImpl(TString logType, const int logLevel, const bool rotation, const bool startAsDaemon) { TLoggerOperator<TLoggerType>::Set(new TLoggerType(PrepareToOpenLog(logType, logLevel, rotation, startAsDaemon), (ELogPriority)logLevel)); - } + } } struct TLogRecordContext { diff --git a/library/cpp/logger/global/global.cpp b/library/cpp/logger/global/global.cpp index 9fbd10f666..beca88d5fa 100644 --- a/library/cpp/logger/global/global.cpp +++ b/library/cpp/logger/global/global.cpp @@ -1,11 +1,11 @@ #include "global.h" -static void DoInitGlobalLog(THolder<TGlobalLog> logger, THolder<ILoggerFormatter> formatter) { - TLoggerOperator<TGlobalLog>::Set(logger.Release()); - if (!formatter) { - formatter.Reset(CreateRtyLoggerFormatter()); - } - TLoggerFormatterOperator::Set(formatter.Release()); +static void DoInitGlobalLog(THolder<TGlobalLog> logger, THolder<ILoggerFormatter> formatter) { + TLoggerOperator<TGlobalLog>::Set(logger.Release()); + if (!formatter) { + formatter.Reset(CreateRtyLoggerFormatter()); + } + TLoggerFormatterOperator::Set(formatter.Release()); } void DoInitGlobalLog(const TString& logType, const int logLevel, const bool rotation, const bool startAsDaemon, THolder<ILoggerFormatter> formatter, bool threaded) { @@ -18,10 +18,10 @@ void DoInitGlobalLog(const TString& logType, const int logLevel, const bool rota std::move(formatter)); } -void DoInitGlobalLog(THolder<TLogBackend> backend, THolder<ILoggerFormatter> formatter) { +void DoInitGlobalLog(THolder<TLogBackend> backend, THolder<ILoggerFormatter> formatter) { DoInitGlobalLog(THolder(new TGlobalLog(std::move(backend))), std::move(formatter)); -} - +} + bool GlobalLogInitialized() { return TLoggerOperator<TGlobalLog>::Usage(); } diff --git a/library/cpp/logger/global/global.h b/library/cpp/logger/global/global.h index cbe71b16ea..97907558d6 100644 --- a/library/cpp/logger/global/global.h +++ b/library/cpp/logger/global/global.h @@ -7,7 +7,7 @@ bool GlobalLogInitialized(); void DoInitGlobalLog(const TString& logType, const int logLevel, const bool rotation, const bool startAsDaemon, THolder<ILoggerFormatter> formatter = {}, bool threaded = false); -void DoInitGlobalLog(THolder<TLogBackend> backend, THolder<ILoggerFormatter> formatter = {}); +void DoInitGlobalLog(THolder<TLogBackend> backend, THolder<ILoggerFormatter> formatter = {}); inline void InitGlobalLog2Null() { DoInitGlobalLog("null", TLOG_EMERG, false, false); diff --git a/library/cpp/logger/global/rty_formater.cpp b/library/cpp/logger/global/rty_formater.cpp index 305f8470c5..2b86b68a0e 100644 --- a/library/cpp/logger/global/rty_formater.cpp +++ b/library/cpp/logger/global/rty_formater.cpp @@ -62,33 +62,33 @@ namespace NLoggingImpl { } } -namespace { - class TRtyLoggerFormatter : public ILoggerFormatter { - public: - void Format(const TLogRecordContext& context, TLogElement& elem) const override { - elem << context.CustomMessage << ": " << NLoggingImpl::GetLocalTimeS() << " " - << NLoggingImpl::StripFileName(context.SourceLocation.File) << ":" << context.SourceLocation.Line; - if (context.Priority > TLOG_RESOURCES && !ExitStarted()) { - elem << NLoggingImpl::GetSystemResources(); - } - elem << " "; - } - }; -} - -ILoggerFormatter* CreateRtyLoggerFormatter() { - return new TRtyLoggerFormatter(); -} - +namespace { + class TRtyLoggerFormatter : public ILoggerFormatter { + public: + void Format(const TLogRecordContext& context, TLogElement& elem) const override { + elem << context.CustomMessage << ": " << NLoggingImpl::GetLocalTimeS() << " " + << NLoggingImpl::StripFileName(context.SourceLocation.File) << ":" << context.SourceLocation.Line; + if (context.Priority > TLOG_RESOURCES && !ExitStarted()) { + elem << NLoggingImpl::GetSystemResources(); + } + elem << " "; + } + }; +} + +ILoggerFormatter* CreateRtyLoggerFormatter() { + return new TRtyLoggerFormatter(); +} + bool TRTYMessageFormater::CheckLoggingContext(TLog& /*logger*/, const TLogRecordContext& /*context*/) { return true; } TSimpleSharedPtr<TLogElement> TRTYMessageFormater::StartRecord(TLog& logger, const TLogRecordContext& context, TSimpleSharedPtr<TLogElement> earlier) { - if (!earlier) { + if (!earlier) { earlier.Reset(new TLogElement(&logger)); - } - - TLoggerFormatterOperator::Get()->Format(context, *earlier); + } + + TLoggerFormatterOperator::Get()->Format(context, *earlier); return earlier; } diff --git a/library/cpp/logger/global/rty_formater.h b/library/cpp/logger/global/rty_formater.h index 6532e1d769..b89b50776a 100644 --- a/library/cpp/logger/global/rty_formater.h +++ b/library/cpp/logger/global/rty_formater.h @@ -6,15 +6,15 @@ namespace NMemInfo { struct TMemInfo; } -class ILoggerFormatter { -public: - virtual ~ILoggerFormatter() = default; - - virtual void Format(const TLogRecordContext&, TLogElement&) const = 0; -}; - -ILoggerFormatter* CreateRtyLoggerFormatter(); - +class ILoggerFormatter { +public: + virtual ~ILoggerFormatter() = default; + + virtual void Format(const TLogRecordContext&, TLogElement&) const = 0; +}; + +ILoggerFormatter* CreateRtyLoggerFormatter(); + namespace NLoggingImpl { class TLocalTimeS { public: @@ -42,17 +42,17 @@ namespace NLoggingImpl { TString GetSystemResources(); TString PrintSystemResources(const NMemInfo::TMemInfo& info); - - struct TLoggerFormatterTraits { - static ILoggerFormatter* CreateDefault() { - return CreateRtyLoggerFormatter(); - } - }; + + struct TLoggerFormatterTraits { + static ILoggerFormatter* CreateDefault() { + return CreateRtyLoggerFormatter(); + } + }; } -class TLoggerFormatterOperator : public NLoggingImpl::TOperatorBase<ILoggerFormatter, NLoggingImpl::TLoggerFormatterTraits> { -}; - +class TLoggerFormatterOperator : public NLoggingImpl::TOperatorBase<ILoggerFormatter, NLoggingImpl::TLoggerFormatterTraits> { +}; + struct TRTYMessageFormater { static bool CheckLoggingContext(TLog& logger, const TLogRecordContext& context); static TSimpleSharedPtr<TLogElement> StartRecord(TLog& logger, const TLogRecordContext& context, TSimpleSharedPtr<TLogElement> earlier); diff --git a/library/cpp/pop_count/benchmark/ya.make b/library/cpp/pop_count/benchmark/ya.make index 7fb54a519a..f355d6b856 100644 --- a/library/cpp/pop_count/benchmark/ya.make +++ b/library/cpp/pop_count/benchmark/ya.make @@ -1,6 +1,6 @@ OWNER(g:util) -Y_BENCHMARK() +Y_BENCHMARK() PEERDIR( util/draft diff --git a/library/cpp/streams/ya.make b/library/cpp/streams/ya.make index 7426a874ee..11e5d88c01 100644 --- a/library/cpp/streams/ya.make +++ b/library/cpp/streams/ya.make @@ -21,6 +21,6 @@ RECURSE( special/ut xz zc_memory_input - zstd - zstd/ut + zstd + zstd/ut ) diff --git a/library/cpp/streams/zstd/ut/ya.make b/library/cpp/streams/zstd/ut/ya.make index 1b98f0ad5e..64cfcabf84 100644 --- a/library/cpp/streams/zstd/ut/ya.make +++ b/library/cpp/streams/zstd/ut/ya.make @@ -1,12 +1,12 @@ UNITTEST_FOR(library/cpp/streams/zstd) - -OWNER( - bulatman - g:util -) - -SRCS( - zstd_ut.cpp -) - -END() + +OWNER( + bulatman + g:util +) + +SRCS( + zstd_ut.cpp +) + +END() diff --git a/library/cpp/streams/zstd/ya.make b/library/cpp/streams/zstd/ya.make index c284deeeff..3de497d626 100644 --- a/library/cpp/streams/zstd/ya.make +++ b/library/cpp/streams/zstd/ya.make @@ -1,16 +1,16 @@ -LIBRARY() - -OWNER( - bulatman - g:util -) - -PEERDIR( - contrib/libs/zstd -) - -SRCS( - zstd.cpp -) - -END() +LIBRARY() + +OWNER( + bulatman + g:util +) + +PEERDIR( + contrib/libs/zstd +) + +SRCS( + zstd.cpp +) + +END() diff --git a/library/cpp/streams/zstd/zstd.cpp b/library/cpp/streams/zstd/zstd.cpp index 29816f6d4c..8f7cec7569 100644 --- a/library/cpp/streams/zstd/zstd.cpp +++ b/library/cpp/streams/zstd/zstd.cpp @@ -1,173 +1,173 @@ -#include "zstd.h" - -#include <util/generic/buffer.h> -#include <util/generic/yexception.h> - -#define ZSTD_STATIC_LINKING_ONLY +#include "zstd.h" + +#include <util/generic/buffer.h> +#include <util/generic/yexception.h> + +#define ZSTD_STATIC_LINKING_ONLY #include <contrib/libs/zstd/include/zstd.h> - -namespace { - inline void CheckError(const char* op, size_t code) { - if (::ZSTD_isError(code)) { + +namespace { + inline void CheckError(const char* op, size_t code) { + if (::ZSTD_isError(code)) { ythrow yexception() << op << TStringBuf(" zstd error: ") << ::ZSTD_getErrorName(code); - } - } - - struct DestroyZCStream { - static void Destroy(::ZSTD_CStream* p) noexcept { - ::ZSTD_freeCStream(p); - } - }; - - struct DestroyZDStream { - static void Destroy(::ZSTD_DStream* p) noexcept { - ::ZSTD_freeDStream(p); - } - }; -} - -class TZstdCompress::TImpl { -public: - TImpl(IOutputStream* slave, int quality) - : Slave_(slave) - , ZCtx_(::ZSTD_createCStream()) - , Buffer_(::ZSTD_CStreamOutSize()) // do reserve - { - Y_ENSURE(nullptr != ZCtx_.Get(), "Failed to allocate ZSTD_CStream"); - Y_ENSURE(0 != Buffer_.Capacity(), "ZSTD_CStreamOutSize was too small"); - CheckError("init", ZSTD_initCStream(ZCtx_.Get(), quality)); - } - - void Write(const void* buffer, size_t size) { - ::ZSTD_inBuffer zIn{buffer, size, 0}; - auto zOut = OutBuffer(); - - while (0 != zIn.size) { - CheckError("compress", ::ZSTD_compressStream(ZCtx_.Get(), &zOut, &zIn)); - DoWrite(zOut); - // forget about the data we already compressed - zIn.src = static_cast<const unsigned char*>(zIn.src) + zIn.pos; - zIn.size -= zIn.pos; - zIn.pos = 0; - } - } - - void Flush() { - auto zOut = OutBuffer(); - CheckError("flush", ::ZSTD_flushStream(ZCtx_.Get(), &zOut)); - DoWrite(zOut); - } - - void Finish() { - auto zOut = OutBuffer(); - size_t returnCode; - do { - returnCode = ::ZSTD_endStream(ZCtx_.Get(), &zOut); - CheckError("finish", returnCode); - DoWrite(zOut); - } while (0 != returnCode); // zero means there is no more bytes to flush - } - -private: - ::ZSTD_outBuffer OutBuffer() { - return {Buffer_.Data(), Buffer_.Capacity(), 0}; - } - - void DoWrite(::ZSTD_outBuffer& buffer) { - Slave_->Write(buffer.dst, buffer.pos); - buffer.pos = 0; - } -private: - IOutputStream* Slave_; - THolder<::ZSTD_CStream, DestroyZCStream> ZCtx_; - TBuffer Buffer_; -}; - -TZstdCompress::TZstdCompress(IOutputStream* slave, int quality) - : Impl_(new TImpl(slave, quality)) { -} - -TZstdCompress::~TZstdCompress() { - try { - Finish(); - } catch (...) { - } -} - -void TZstdCompress::DoWrite(const void* buffer, size_t size) { - Y_ENSURE(Impl_, "Cannot use stream after finish."); - Impl_->Write(buffer, size); -} - -void TZstdCompress::DoFlush() { - Y_ENSURE(Impl_, "Cannot use stream after finish."); - Impl_->Flush(); -} - -void TZstdCompress::DoFinish() { - // Finish should be idempotent - if (Impl_) { - auto impl = std::move(Impl_); - impl->Finish(); - } -} - -//////////////////////////////////////////////////////////////////////////////// - -class TZstdDecompress::TImpl { -public: - TImpl(IInputStream* slave, size_t bufferSize) - : Slave_(slave) - , ZCtx_(::ZSTD_createDStream()) - , Buffer_(bufferSize) // do reserve - , Offset_(0) - { - Y_ENSURE(nullptr != ZCtx_.Get(), "Failed to allocate ZSTD_DStream"); - Y_ENSURE(0 != Buffer_.Capacity(), "Buffer size was too small"); - } - - size_t Read(void* buffer, size_t size) { - Y_ASSERT(size > 0); - - ::ZSTD_outBuffer zOut{buffer, size, 0}; - ::ZSTD_inBuffer zIn{Buffer_.Data(), Buffer_.Size(), Offset_}; - - size_t returnCode = 0; - while (zOut.pos != zOut.size) { - if (zIn.pos == zIn.size) { - zIn.size = Slave_->Read(Buffer_.Data(), Buffer_.Capacity()); - Buffer_.Resize(zIn.size); - zIn.pos = Offset_ = 0; - if (0 == zIn.size) { - // end of stream, need to check that there is no uncompleted blocks - Y_ENSURE(0 == returnCode, "Incomplete block"); - break; - } - } - returnCode = ::ZSTD_decompressStream(ZCtx_.Get(), &zOut, &zIn); - CheckError("decompress", returnCode); - if (0 == returnCode) { - // The frame is over, prepare to (maybe) start a new frame - ZSTD_initDStream(ZCtx_.Get()); - } - } - Offset_ = zIn.pos; - return zOut.pos; - } - -private: - IInputStream* Slave_; - THolder<::ZSTD_DStream, DestroyZDStream> ZCtx_; - TBuffer Buffer_; - size_t Offset_; -}; - -TZstdDecompress::TZstdDecompress(IInputStream* slave, size_t bufferSize) - : Impl_(new TImpl(slave, bufferSize)) { -} - -TZstdDecompress::~TZstdDecompress() = default; - -size_t TZstdDecompress::DoRead(void* buffer, size_t size) { - return Impl_->Read(buffer, size); -} + } + } + + struct DestroyZCStream { + static void Destroy(::ZSTD_CStream* p) noexcept { + ::ZSTD_freeCStream(p); + } + }; + + struct DestroyZDStream { + static void Destroy(::ZSTD_DStream* p) noexcept { + ::ZSTD_freeDStream(p); + } + }; +} + +class TZstdCompress::TImpl { +public: + TImpl(IOutputStream* slave, int quality) + : Slave_(slave) + , ZCtx_(::ZSTD_createCStream()) + , Buffer_(::ZSTD_CStreamOutSize()) // do reserve + { + Y_ENSURE(nullptr != ZCtx_.Get(), "Failed to allocate ZSTD_CStream"); + Y_ENSURE(0 != Buffer_.Capacity(), "ZSTD_CStreamOutSize was too small"); + CheckError("init", ZSTD_initCStream(ZCtx_.Get(), quality)); + } + + void Write(const void* buffer, size_t size) { + ::ZSTD_inBuffer zIn{buffer, size, 0}; + auto zOut = OutBuffer(); + + while (0 != zIn.size) { + CheckError("compress", ::ZSTD_compressStream(ZCtx_.Get(), &zOut, &zIn)); + DoWrite(zOut); + // forget about the data we already compressed + zIn.src = static_cast<const unsigned char*>(zIn.src) + zIn.pos; + zIn.size -= zIn.pos; + zIn.pos = 0; + } + } + + void Flush() { + auto zOut = OutBuffer(); + CheckError("flush", ::ZSTD_flushStream(ZCtx_.Get(), &zOut)); + DoWrite(zOut); + } + + void Finish() { + auto zOut = OutBuffer(); + size_t returnCode; + do { + returnCode = ::ZSTD_endStream(ZCtx_.Get(), &zOut); + CheckError("finish", returnCode); + DoWrite(zOut); + } while (0 != returnCode); // zero means there is no more bytes to flush + } + +private: + ::ZSTD_outBuffer OutBuffer() { + return {Buffer_.Data(), Buffer_.Capacity(), 0}; + } + + void DoWrite(::ZSTD_outBuffer& buffer) { + Slave_->Write(buffer.dst, buffer.pos); + buffer.pos = 0; + } +private: + IOutputStream* Slave_; + THolder<::ZSTD_CStream, DestroyZCStream> ZCtx_; + TBuffer Buffer_; +}; + +TZstdCompress::TZstdCompress(IOutputStream* slave, int quality) + : Impl_(new TImpl(slave, quality)) { +} + +TZstdCompress::~TZstdCompress() { + try { + Finish(); + } catch (...) { + } +} + +void TZstdCompress::DoWrite(const void* buffer, size_t size) { + Y_ENSURE(Impl_, "Cannot use stream after finish."); + Impl_->Write(buffer, size); +} + +void TZstdCompress::DoFlush() { + Y_ENSURE(Impl_, "Cannot use stream after finish."); + Impl_->Flush(); +} + +void TZstdCompress::DoFinish() { + // Finish should be idempotent + if (Impl_) { + auto impl = std::move(Impl_); + impl->Finish(); + } +} + +//////////////////////////////////////////////////////////////////////////////// + +class TZstdDecompress::TImpl { +public: + TImpl(IInputStream* slave, size_t bufferSize) + : Slave_(slave) + , ZCtx_(::ZSTD_createDStream()) + , Buffer_(bufferSize) // do reserve + , Offset_(0) + { + Y_ENSURE(nullptr != ZCtx_.Get(), "Failed to allocate ZSTD_DStream"); + Y_ENSURE(0 != Buffer_.Capacity(), "Buffer size was too small"); + } + + size_t Read(void* buffer, size_t size) { + Y_ASSERT(size > 0); + + ::ZSTD_outBuffer zOut{buffer, size, 0}; + ::ZSTD_inBuffer zIn{Buffer_.Data(), Buffer_.Size(), Offset_}; + + size_t returnCode = 0; + while (zOut.pos != zOut.size) { + if (zIn.pos == zIn.size) { + zIn.size = Slave_->Read(Buffer_.Data(), Buffer_.Capacity()); + Buffer_.Resize(zIn.size); + zIn.pos = Offset_ = 0; + if (0 == zIn.size) { + // end of stream, need to check that there is no uncompleted blocks + Y_ENSURE(0 == returnCode, "Incomplete block"); + break; + } + } + returnCode = ::ZSTD_decompressStream(ZCtx_.Get(), &zOut, &zIn); + CheckError("decompress", returnCode); + if (0 == returnCode) { + // The frame is over, prepare to (maybe) start a new frame + ZSTD_initDStream(ZCtx_.Get()); + } + } + Offset_ = zIn.pos; + return zOut.pos; + } + +private: + IInputStream* Slave_; + THolder<::ZSTD_DStream, DestroyZDStream> ZCtx_; + TBuffer Buffer_; + size_t Offset_; +}; + +TZstdDecompress::TZstdDecompress(IInputStream* slave, size_t bufferSize) + : Impl_(new TImpl(slave, bufferSize)) { +} + +TZstdDecompress::~TZstdDecompress() = default; + +size_t TZstdDecompress::DoRead(void* buffer, size_t size) { + return Impl_->Read(buffer, size); +} diff --git a/library/cpp/streams/zstd/zstd.h b/library/cpp/streams/zstd/zstd.h index 667a0494b7..4f1583d067 100644 --- a/library/cpp/streams/zstd/zstd.h +++ b/library/cpp/streams/zstd/zstd.h @@ -1,53 +1,53 @@ -#pragma once - -#include <util/generic/ptr.h> -#include <util/stream/input.h> -#include <util/stream/output.h> - -/** - * @addtogroup Streams_Archs - * @{ - */ - -// @brief Stream to compress into zstd archive -class TZstdCompress: public IOutputStream { -public: - /** - @param slave stream to write compressed data to - @param quality, higher quality - slower but better compression. +#pragma once + +#include <util/generic/ptr.h> +#include <util/stream/input.h> +#include <util/stream/output.h> + +/** + * @addtogroup Streams_Archs + * @{ + */ + +// @brief Stream to compress into zstd archive +class TZstdCompress: public IOutputStream { +public: + /** + @param slave stream to write compressed data to + @param quality, higher quality - slower but better compression. 0 is default compression (see constant ZSTD_CLEVEL_DEFAULT(3)) - max compression is ZSTD_MAX_CLEVEL (22) - */ + max compression is ZSTD_MAX_CLEVEL (22) + */ explicit TZstdCompress(IOutputStream* slave, int quality = 0); - ~TZstdCompress() override; -private: - void DoWrite(const void* buffer, size_t size) override; - void DoFlush() override; - void DoFinish() override; - -public: - class TImpl; - THolder<TImpl> Impl_; -}; - -//////////////////////////////////////////////////////////////////////////////// - -// @brief Buffered stream to decompress from zstd archive -class TZstdDecompress: public IInputStream { -public: - /** - @param slave stream to read compressed data from - @param bufferSize approximate size of buffer compressed data is read in - */ - explicit TZstdDecompress(IInputStream* slave, size_t bufferSize = 8 * 1024); - ~TZstdDecompress() override; - -private: - size_t DoRead(void* buffer, size_t size) override; - -private: - class TImpl; - THolder<TImpl> Impl_; -}; - -/** @} */ + ~TZstdCompress() override; +private: + void DoWrite(const void* buffer, size_t size) override; + void DoFlush() override; + void DoFinish() override; + +public: + class TImpl; + THolder<TImpl> Impl_; +}; + +//////////////////////////////////////////////////////////////////////////////// + +// @brief Buffered stream to decompress from zstd archive +class TZstdDecompress: public IInputStream { +public: + /** + @param slave stream to read compressed data from + @param bufferSize approximate size of buffer compressed data is read in + */ + explicit TZstdDecompress(IInputStream* slave, size_t bufferSize = 8 * 1024); + ~TZstdDecompress() override; + +private: + size_t DoRead(void* buffer, size_t size) override; + +private: + class TImpl; + THolder<TImpl> Impl_; +}; + +/** @} */ diff --git a/library/cpp/streams/zstd/zstd_ut.cpp b/library/cpp/streams/zstd/zstd_ut.cpp index ef479fdd97..01618193fa 100644 --- a/library/cpp/streams/zstd/zstd_ut.cpp +++ b/library/cpp/streams/zstd/zstd_ut.cpp @@ -1,94 +1,94 @@ -#include "zstd.h" - +#include "zstd.h" + #include <library/cpp/testing/unittest/registar.h> - -#include <util/random/fast.h> -#include <util/stream/null.h> -#include <util/stream/str.h> - -Y_UNIT_TEST_SUITE(TZstdTestSuite) { - TString Compress(TString data, int quality = -1) { - TString compressed; - TStringOutput output(compressed); - TZstdCompress compressStream(&output, quality); - compressStream.Write(data.data(), data.size()); - compressStream.Finish(); - output.Finish(); - return compressed; - } - - TString Decompress(TString data) { - TStringInput input(data); - TZstdDecompress decompressStream(&input); - return decompressStream.ReadAll(); - } - - void TestCase(const TString& s) { - UNIT_ASSERT_VALUES_EQUAL(s, Decompress(Compress(s, -1))); - UNIT_ASSERT_VALUES_EQUAL(s, Decompress(Compress(s, 0))); - UNIT_ASSERT_VALUES_EQUAL(s, Decompress(Compress(s, 22))); - UNIT_ASSERT_VALUES_EQUAL(s, Decompress(Compress(s, 11))); - UNIT_ASSERT_VALUES_EQUAL(s, Decompress(Compress(s, 100500))); - } - - TString GenerateRandomString(size_t size) { - TReallyFastRng32 rng(42); - TString result; - result.reserve(size + sizeof(ui64)); - while (result.size() < size) { - ui64 value = rng.GenRand64(); - result += TStringBuf(reinterpret_cast<const char*>(&value), sizeof(value)); - } - result.resize(size); - return result; - } - - Y_UNIT_TEST(TestHelloWorld) { - TestCase("hello world"); - } - - Y_UNIT_TEST(TestSeveralStreamsWithSameQuality) { - auto s1 = GenerateRandomString(1 << 15); - auto s2 = GenerateRandomString(1 << 15); - auto c1 = Compress(s1); - auto c2 = Compress(s2); - UNIT_ASSERT_VALUES_EQUAL(s1 + s2, Decompress(c1 + c2)); - } - - Y_UNIT_TEST(TestSeveralStreamsWithDifferentQuality) { - auto s1 = GenerateRandomString(1 << 15); - auto s2 = GenerateRandomString(1 << 15); - auto c1 = Compress(s1, 1); - auto c2 = Compress(s2, 2); - UNIT_ASSERT_VALUES_EQUAL(s1 + s2, Decompress(c1 + c2)); - } - - Y_UNIT_TEST(TestIncompleteStream) { - TString manyAs(64 * 1024, 'a'); - auto compressed = Compress(manyAs); - TString truncated(compressed.data(), compressed.size() - 1); - UNIT_CHECK_GENERATED_EXCEPTION(Decompress(truncated), std::exception); - } - - Y_UNIT_TEST(Test64KB) { - auto manyAs = TString(64 * 1024, 'a'); - TString str("Hello from the Matrix!@#% How are you?}{\n\t\a"); - TestCase(manyAs + str + manyAs); - } - - Y_UNIT_TEST(Test1MB) { - TestCase(GenerateRandomString(1 * 1024 * 1024)); - } - - Y_UNIT_TEST(TestEmpty) { - TestCase(""); - } - - Y_UNIT_TEST(TestWriteAfterFinish) { - TNullOutput output; - TZstdCompress compressStream(&output); - compressStream.Finish(); - UNIT_ASSERT_EXCEPTION_CONTAINS(compressStream.Write("a", 1), std::exception, "Cannot use stream after finish."); - UNIT_ASSERT_EXCEPTION_CONTAINS(compressStream.Flush(), std::exception, "Cannot use stream after finish."); - } -} + +#include <util/random/fast.h> +#include <util/stream/null.h> +#include <util/stream/str.h> + +Y_UNIT_TEST_SUITE(TZstdTestSuite) { + TString Compress(TString data, int quality = -1) { + TString compressed; + TStringOutput output(compressed); + TZstdCompress compressStream(&output, quality); + compressStream.Write(data.data(), data.size()); + compressStream.Finish(); + output.Finish(); + return compressed; + } + + TString Decompress(TString data) { + TStringInput input(data); + TZstdDecompress decompressStream(&input); + return decompressStream.ReadAll(); + } + + void TestCase(const TString& s) { + UNIT_ASSERT_VALUES_EQUAL(s, Decompress(Compress(s, -1))); + UNIT_ASSERT_VALUES_EQUAL(s, Decompress(Compress(s, 0))); + UNIT_ASSERT_VALUES_EQUAL(s, Decompress(Compress(s, 22))); + UNIT_ASSERT_VALUES_EQUAL(s, Decompress(Compress(s, 11))); + UNIT_ASSERT_VALUES_EQUAL(s, Decompress(Compress(s, 100500))); + } + + TString GenerateRandomString(size_t size) { + TReallyFastRng32 rng(42); + TString result; + result.reserve(size + sizeof(ui64)); + while (result.size() < size) { + ui64 value = rng.GenRand64(); + result += TStringBuf(reinterpret_cast<const char*>(&value), sizeof(value)); + } + result.resize(size); + return result; + } + + Y_UNIT_TEST(TestHelloWorld) { + TestCase("hello world"); + } + + Y_UNIT_TEST(TestSeveralStreamsWithSameQuality) { + auto s1 = GenerateRandomString(1 << 15); + auto s2 = GenerateRandomString(1 << 15); + auto c1 = Compress(s1); + auto c2 = Compress(s2); + UNIT_ASSERT_VALUES_EQUAL(s1 + s2, Decompress(c1 + c2)); + } + + Y_UNIT_TEST(TestSeveralStreamsWithDifferentQuality) { + auto s1 = GenerateRandomString(1 << 15); + auto s2 = GenerateRandomString(1 << 15); + auto c1 = Compress(s1, 1); + auto c2 = Compress(s2, 2); + UNIT_ASSERT_VALUES_EQUAL(s1 + s2, Decompress(c1 + c2)); + } + + Y_UNIT_TEST(TestIncompleteStream) { + TString manyAs(64 * 1024, 'a'); + auto compressed = Compress(manyAs); + TString truncated(compressed.data(), compressed.size() - 1); + UNIT_CHECK_GENERATED_EXCEPTION(Decompress(truncated), std::exception); + } + + Y_UNIT_TEST(Test64KB) { + auto manyAs = TString(64 * 1024, 'a'); + TString str("Hello from the Matrix!@#% How are you?}{\n\t\a"); + TestCase(manyAs + str + manyAs); + } + + Y_UNIT_TEST(Test1MB) { + TestCase(GenerateRandomString(1 * 1024 * 1024)); + } + + Y_UNIT_TEST(TestEmpty) { + TestCase(""); + } + + Y_UNIT_TEST(TestWriteAfterFinish) { + TNullOutput output; + TZstdCompress compressStream(&output); + compressStream.Finish(); + UNIT_ASSERT_EXCEPTION_CONTAINS(compressStream.Write("a", 1), std::exception, "Cannot use stream after finish."); + UNIT_ASSERT_EXCEPTION_CONTAINS(compressStream.Flush(), std::exception, "Cannot use stream after finish."); + } +} diff --git a/library/cpp/string_utils/base64/bench/ya.make b/library/cpp/string_utils/base64/bench/ya.make index 5ac5f3d6ce..2bfd823ff2 100644 --- a/library/cpp/string_utils/base64/bench/ya.make +++ b/library/cpp/string_utils/base64/bench/ya.make @@ -3,7 +3,7 @@ OWNER( g:util ) -Y_BENCHMARK() +Y_BENCHMARK() SRCS( main.cpp diff --git a/library/cpp/terminate_handler/segv_handler.cpp b/library/cpp/terminate_handler/segv_handler.cpp index f24ece4125..6a42b7a7a3 100644 --- a/library/cpp/terminate_handler/segv_handler.cpp +++ b/library/cpp/terminate_handler/segv_handler.cpp @@ -7,7 +7,7 @@ #include <signal.h> #include <errno.h> #include <stdlib.h> -#include <unistd.h> +#include <unistd.h> #endif #include "segv_handler.h" diff --git a/library/cpp/testing/README.md b/library/cpp/testing/README.md index e8e0391be4..15740c3ec6 100644 --- a/library/cpp/testing/README.md +++ b/library/cpp/testing/README.md @@ -6,11 +6,11 @@ * `common` — независимые вспомогательные функции. Например функции для получения аркадийных путей. * `gmock` — прокси-библиотека для подключения `contrib/resticted/googltest/googlemock` без нарушения PEERDIR policy. * `gtest` — реализация модуля `GTEST` — средства для интеграции фреймворка _googletest_ в Аркадию. -* `gtest_boost_extensions` — расширения gtest и gmock, улучшающие поддержку типов из boost. +* `gtest_boost_extensions` — расширения gtest и gmock, улучшающие поддержку типов из boost. * `gtest_extensions` — расширения gtest и gmock, улучшающие поддержку Аркадийных типов. Все расширения включены в модуле `GTEST` по-умолчаниiю. * `gtest_main` — реализация `int main(argc, argv)` для модуля `GTEST` (вынесена в отдельную библиотеку, чтобы в перспективе была возможна реализация `GTEST_WITH_CUSTOM_ENTRY_POINT`). -* `gtest_protobuf` — утилиты для работы с протобуфом в тестах. -* `hook` — хуки для выполнения пользовательских функций в тестах и бенчмарках. +* `gtest_protobuf` — утилиты для работы с протобуфом в тестах. +* `hook` — хуки для выполнения пользовательских функций в тестах и бенчмарках. * `mock_server` — реализация http-сервера для тестов. * `unittest` — реализация модуля UNITTEST — основного средства для тестирования тестов на С++ в Аркадии. * `unittest_main` — реализация `int main(argc, argv)` для модуля UNITTEST (она вынесена в отдельную библиотеку, чтобы оставить возможность для реализации `UNITTEST_WITH_CUSTOM_ENTRY_POINT` и `YT_UNITTEST`. diff --git a/library/cpp/testing/benchmark/bench.cpp b/library/cpp/testing/benchmark/bench.cpp index 08d8708005..14598848ff 100644 --- a/library/cpp/testing/benchmark/bench.cpp +++ b/library/cpp/testing/benchmark/bench.cpp @@ -512,7 +512,7 @@ namespace { .Help("run benchmarks in parallel"); opts.AddLongOption('f', "format") - .AddLongName("benchmark_format") + .AddLongName("benchmark_format") .StoreResult(&OutFormat) .RequiredArgument("FORMAT") .DefaultValue("console") diff --git a/library/cpp/testing/benchmark/examples/ya.make b/library/cpp/testing/benchmark/examples/ya.make index 7e696e127a..14d2c0d11f 100644 --- a/library/cpp/testing/benchmark/examples/ya.make +++ b/library/cpp/testing/benchmark/examples/ya.make @@ -3,7 +3,7 @@ OWNER( yazevnul ) -Y_BENCHMARK() +Y_BENCHMARK() SRCS( main.cpp diff --git a/library/cpp/testing/common/env.cpp b/library/cpp/testing/common/env.cpp index fa3a47fe16..a6acf90e2c 100644 --- a/library/cpp/testing/common/env.cpp +++ b/library/cpp/testing/common/env.cpp @@ -1,5 +1,5 @@ -#include "env.h" - +#include "env.h" + #include <build/scripts/c_templates/svnversion.h> #include <util/folder/dirut.h> @@ -32,14 +32,14 @@ TString BuildRoot() { } } -TString ArcadiaFromCurrentLocation(TStringBuf where, TStringBuf path) { - return (TFsPath(ArcadiaSourceRoot()) / TFsPath(where).Parent() / path).Fix(); -} - -TString BinaryPath(TStringBuf path) { - return (TFsPath(BuildRoot()) / path).Fix(); -} - +TString ArcadiaFromCurrentLocation(TStringBuf where, TStringBuf path) { + return (TFsPath(ArcadiaSourceRoot()) / TFsPath(where).Parent() / path).Fix(); +} + +TString BinaryPath(TStringBuf path) { + return (TFsPath(BuildRoot()) / path).Fix(); +} + TString GetArcadiaTestsData() { TString atdRoot = NPrivate::GetTestEnv().ArcadiaTestsDataDir; if (atdRoot) { @@ -47,21 +47,21 @@ TString GetArcadiaTestsData() { } TString path = NPrivate::GetCwd(); - const char pathsep = GetDirectorySeparator(); + const char pathsep = GetDirectorySeparator(); while (!path.empty()) { TString dataDir = path + "/arcadia_tests_data"; - if (IsDir(dataDir)) { + if (IsDir(dataDir)) { return dataDir; - } + } - size_t pos = path.find_last_of(pathsep); - if (pos == TString::npos) { + size_t pos = path.find_last_of(pathsep); + if (pos == TString::npos) { pos = 0; - } + } path.erase(pos); } - return {}; + return {}; } TString GetWorkPath() { @@ -143,7 +143,7 @@ void StopProcessCoreWatching(int pid) { } } -bool FromYaTest() { +bool FromYaTest() { return NPrivate::GetTestEnv().IsRunningFromTest; } diff --git a/library/cpp/testing/common/env.h b/library/cpp/testing/common/env.h index 7b89aa1bed..6846ba3016 100644 --- a/library/cpp/testing/common/env.h +++ b/library/cpp/testing/common/env.h @@ -4,39 +4,39 @@ #include <util/folder/path.h> #include <util/generic/string.h> -#include <util/generic/strbuf.h> -#include <util/system/src_location.h> +#include <util/generic/strbuf.h> +#include <util/system/src_location.h> -// @brief return full path to arcadia root -TString ArcadiaSourceRoot(); +// @brief return full path to arcadia root +TString ArcadiaSourceRoot(); -// @brief return full path for file or folder specified by known source location `where` and `path` which is relative to parent folder of `where` +// @brief return full path for file or folder specified by known source location `where` and `path` which is relative to parent folder of `where` // for the instance: there is 2 files in folder test example_ut.cpp and example.data, so full path to test/example.data can be obtained -// from example_ut.cpp as ArcadiaFromCurrentLocation(__SOURCE_FILE__, "example.data") -TString ArcadiaFromCurrentLocation(TStringBuf where, TStringBuf path); +// from example_ut.cpp as ArcadiaFromCurrentLocation(__SOURCE_FILE__, "example.data") +TString ArcadiaFromCurrentLocation(TStringBuf where, TStringBuf path); -// @brief return build folder path -TString BuildRoot(); +// @brief return build folder path +TString BuildRoot(); -// @brief return full path to built artefact, where path is relative from arcadia root -TString BinaryPath(TStringBuf path); +// @brief return full path to built artefact, where path is relative from arcadia root +TString BinaryPath(TStringBuf path); -// @brief return true if environment is testenv otherwise false -bool FromYaTest(); +// @brief return true if environment is testenv otherwise false +bool FromYaTest(); -// @brief returns TestsData dir (from env:ARCADIA_TESTS_DATA_DIR or path to existing folder `arcadia_tests_data` within parent folders) -TString GetArcadiaTestsData(); +// @brief returns TestsData dir (from env:ARCADIA_TESTS_DATA_DIR or path to existing folder `arcadia_tests_data` within parent folders) +TString GetArcadiaTestsData(); -// @brief return current working dir (from env:TEST_WORK_PATH or cwd) -TString GetWorkPath(); +// @brief return current working dir (from env:TEST_WORK_PATH or cwd) +TString GetWorkPath(); -// @brief return tests output path (workdir + testing_out_stuff) -TFsPath GetOutputPath(); +// @brief return tests output path (workdir + testing_out_stuff) +TFsPath GetOutputPath(); -// @brief return path from env:YA_TEST_RAM_DRIVE_PATH +// @brief return path from env:YA_TEST_RAM_DRIVE_PATH const TString& GetRamDrivePath(); -// @brief return path from env:YA_TEST_OUTPUT_RAM_DRIVE_PATH +// @brief return path from env:YA_TEST_OUTPUT_RAM_DRIVE_PATH const TString& GetOutputRamDrivePath(); // @brief return test parameter by name. If not exists, return an empty string @@ -54,7 +54,7 @@ void WatchProcessCore(int pid, const TFsPath& binaryPath, const TFsPath& cwd = T // @brief mark the process as successfully completed - a test machinery won't try to recover core dump file for the process void StopProcessCoreWatching(int pid); -#define SRC_(path) ArcadiaFromCurrentLocation(__SOURCE_FILE__, path) +#define SRC_(path) ArcadiaFromCurrentLocation(__SOURCE_FILE__, path) namespace NPrivate { class TTestEnv { diff --git a/library/cpp/testing/common/network.cpp b/library/cpp/testing/common/network.cpp index 230c50ee6d..b06670b8d0 100644 --- a/library/cpp/testing/common/network.cpp +++ b/library/cpp/testing/common/network.cpp @@ -1,208 +1,208 @@ -#include "network.h" - -#include <util/folder/dirut.h> -#include <util/folder/path.h> -#include <util/generic/singleton.h> -#include <util/generic/utility.h> -#include <util/generic/vector.h> -#include <util/generic/ylimits.h> -#include <util/network/address.h> -#include <util/network/sock.h> -#include <util/random/random.h> -#include <util/stream/file.h> -#include <util/string/split.h> -#include <util/system/env.h> -#include <util/system/error.h> -#include <util/system/file_lock.h> -#include <util/system/fs.h> - -#ifdef _darwin_ -#include <sys/types.h> -#include <sys/sysctl.h> -#endif - -namespace { -#define Y_VERIFY_SYSERROR(expr) \ - do { \ - if (!(expr)) { \ - Y_FAIL(#expr ", errno=%d", LastSystemError()); \ - } \ - } while (false) - - class TPortGuard : public NTesting::IPort { - public: - TPortGuard(ui16 port, THolder<TFileLock> lock) - : Lock_(std::move(lock)) - , Port_(port) - { - } - +#include "network.h" + +#include <util/folder/dirut.h> +#include <util/folder/path.h> +#include <util/generic/singleton.h> +#include <util/generic/utility.h> +#include <util/generic/vector.h> +#include <util/generic/ylimits.h> +#include <util/network/address.h> +#include <util/network/sock.h> +#include <util/random/random.h> +#include <util/stream/file.h> +#include <util/string/split.h> +#include <util/system/env.h> +#include <util/system/error.h> +#include <util/system/file_lock.h> +#include <util/system/fs.h> + +#ifdef _darwin_ +#include <sys/types.h> +#include <sys/sysctl.h> +#endif + +namespace { +#define Y_VERIFY_SYSERROR(expr) \ + do { \ + if (!(expr)) { \ + Y_FAIL(#expr ", errno=%d", LastSystemError()); \ + } \ + } while (false) + + class TPortGuard : public NTesting::IPort { + public: + TPortGuard(ui16 port, THolder<TFileLock> lock) + : Lock_(std::move(lock)) + , Port_(port) + { + } + ~TPortGuard() override { - Y_VERIFY_SYSERROR(NFs::Remove(Lock_->GetName())); - } - - ui16 Get() override { - return Port_; - } - - private: - THolder<TFileLock> Lock_; - ui16 Port_; - }; - - std::pair<ui16, ui16> GetEphemeralRange() { - // IANA suggestion - std::pair<ui16, ui16> pair{(1 << 15) + (1 << 14), (1 << 16) - 1}; - #ifdef _linux_ - if (NFs::Exists("/proc/sys/net/ipv4/ip_local_port_range")) { - TIFStream fileStream("/proc/sys/net/ipv4/ip_local_port_range"); - fileStream >> pair.first >> pair.second; - } - #endif - #ifdef _darwin_ - ui32 first, last; - size_t size; - sysctlbyname("net.inet.ip.portrange.first", &first, &size, NULL, 0); - sysctlbyname("net.inet.ip.portrange.last", &last, &size, NULL, 0); - pair.first = first; - pair.second = last; - #endif - return pair; - } - - TVector<std::pair<ui16, ui16>> GetPortRanges() { - TString givenRange = GetEnv("VALID_PORT_RANGE"); - TVector<std::pair<ui16, ui16>> ranges; - if (givenRange.Contains(':')) { - auto res = StringSplitter(givenRange).Split(':').Limit(2).ToList<TString>(); - ranges.emplace_back(FromString<ui16>(res.front()), FromString<ui16>(res.back())); - } else { - const ui16 firstValid = 1025; - const ui16 lastValid = Max<ui16>(); - - auto [firstEphemeral, lastEphemeral] = GetEphemeralRange(); - const ui16 firstInvalid = Max(firstEphemeral, firstValid); - const ui16 lastInvalid = Min(lastEphemeral, lastValid); - - if (firstInvalid > firstValid) - ranges.emplace_back(firstValid, firstInvalid - 1); - if (lastInvalid < lastValid) - ranges.emplace_back(lastInvalid + 1, lastValid); - } - return ranges; - } - - class TPortManager { - static constexpr size_t Retries = 20; - public: - TPortManager() - : SyncDir_(GetEnv("PORT_SYNC_PATH")) - , Ranges_(GetPortRanges()) - , TotalCount_(0) - { - if (!SyncDir_.IsDefined()) { - SyncDir_ = TFsPath(GetSystemTempDir()) / "yandex_port_locks"; - } - Y_VERIFY(SyncDir_.IsDefined()); - NFs::MakeDirectoryRecursive(SyncDir_); - - for (auto [left, right] : Ranges_) { - TotalCount_ += right - left; - } - Y_VERIFY(0 != TotalCount_); - } - - NTesting::TPortHolder GetFreePort() const { - ui16 salt = RandomNumber<ui16>(); - for (ui16 attempt = 0; attempt < TotalCount_; ++attempt) { - ui16 probe = (salt + attempt) % TotalCount_; - - for (auto [left, right] : Ranges_) { - if (probe >= right - left) - probe -= right - left; - else { - probe += left; - break; - } - } - - auto port = TryAcquirePort(probe); - if (port) { - return NTesting::TPortHolder{std::move(port)}; - } - } - - Y_FAIL("Cannot get free port!"); - } - - TVector<NTesting::TPortHolder> GetFreePortsRange(size_t count) const { - Y_VERIFY(count > 0); - TVector<NTesting::TPortHolder> ports(Reserve(count)); - for (size_t i = 0; i < Retries; ++i) { - for (auto[left, right] : Ranges_) { - if (right - left < count) { - continue; - } - ui16 start = left + RandomNumber<ui16>((right - left) / 2); - if (right - start < count) { - continue; - } - for (ui16 probe = start; probe < right; ++probe) { - auto port = TryAcquirePort(probe); - if (port) { - ports.emplace_back(std::move(port)); - } else { - ports.clear(); - } - if (ports.size() == count) { - return ports; - } - } - // Can't find required number of ports without gap in the current range - ports.clear(); - } - } - Y_FAIL("Cannot get range of %zu ports!", count); - } - - private: - THolder<NTesting::IPort> TryAcquirePort(ui16 port) const { - auto lock = MakeHolder<TFileLock>(TString(SyncDir_ / ::ToString(port))); - if (!lock->TryAcquire()) { - return nullptr; - } - - TInet6StreamSocket sock; - Y_VERIFY_SYSERROR(INVALID_SOCKET != static_cast<SOCKET>(sock)); - - TSockAddrInet6 addr("::", port); - if (sock.Bind(&addr) != 0) { - lock->Release(); - Y_VERIFY(EADDRINUSE == LastSystemError(), "unexpected error: %d", LastSystemError()); - return nullptr; - } - return MakeHolder<TPortGuard>(port, std::move(lock)); - } - - private: - TFsPath SyncDir_; - TVector<std::pair<ui16, ui16>> Ranges_; - size_t TotalCount_; - }; -} - -namespace NTesting { - TPortHolder GetFreePort() { - return Singleton<TPortManager>()->GetFreePort(); - } - - namespace NLegacy { - TVector<TPortHolder> GetFreePortsRange(size_t count) { - return Singleton<TPortManager>()->GetFreePortsRange(count); - } - } + Y_VERIFY_SYSERROR(NFs::Remove(Lock_->GetName())); + } + + ui16 Get() override { + return Port_; + } + + private: + THolder<TFileLock> Lock_; + ui16 Port_; + }; + + std::pair<ui16, ui16> GetEphemeralRange() { + // IANA suggestion + std::pair<ui16, ui16> pair{(1 << 15) + (1 << 14), (1 << 16) - 1}; + #ifdef _linux_ + if (NFs::Exists("/proc/sys/net/ipv4/ip_local_port_range")) { + TIFStream fileStream("/proc/sys/net/ipv4/ip_local_port_range"); + fileStream >> pair.first >> pair.second; + } + #endif + #ifdef _darwin_ + ui32 first, last; + size_t size; + sysctlbyname("net.inet.ip.portrange.first", &first, &size, NULL, 0); + sysctlbyname("net.inet.ip.portrange.last", &last, &size, NULL, 0); + pair.first = first; + pair.second = last; + #endif + return pair; + } + + TVector<std::pair<ui16, ui16>> GetPortRanges() { + TString givenRange = GetEnv("VALID_PORT_RANGE"); + TVector<std::pair<ui16, ui16>> ranges; + if (givenRange.Contains(':')) { + auto res = StringSplitter(givenRange).Split(':').Limit(2).ToList<TString>(); + ranges.emplace_back(FromString<ui16>(res.front()), FromString<ui16>(res.back())); + } else { + const ui16 firstValid = 1025; + const ui16 lastValid = Max<ui16>(); + + auto [firstEphemeral, lastEphemeral] = GetEphemeralRange(); + const ui16 firstInvalid = Max(firstEphemeral, firstValid); + const ui16 lastInvalid = Min(lastEphemeral, lastValid); + + if (firstInvalid > firstValid) + ranges.emplace_back(firstValid, firstInvalid - 1); + if (lastInvalid < lastValid) + ranges.emplace_back(lastInvalid + 1, lastValid); + } + return ranges; + } + + class TPortManager { + static constexpr size_t Retries = 20; + public: + TPortManager() + : SyncDir_(GetEnv("PORT_SYNC_PATH")) + , Ranges_(GetPortRanges()) + , TotalCount_(0) + { + if (!SyncDir_.IsDefined()) { + SyncDir_ = TFsPath(GetSystemTempDir()) / "yandex_port_locks"; + } + Y_VERIFY(SyncDir_.IsDefined()); + NFs::MakeDirectoryRecursive(SyncDir_); + + for (auto [left, right] : Ranges_) { + TotalCount_ += right - left; + } + Y_VERIFY(0 != TotalCount_); + } + + NTesting::TPortHolder GetFreePort() const { + ui16 salt = RandomNumber<ui16>(); + for (ui16 attempt = 0; attempt < TotalCount_; ++attempt) { + ui16 probe = (salt + attempt) % TotalCount_; + + for (auto [left, right] : Ranges_) { + if (probe >= right - left) + probe -= right - left; + else { + probe += left; + break; + } + } + + auto port = TryAcquirePort(probe); + if (port) { + return NTesting::TPortHolder{std::move(port)}; + } + } + + Y_FAIL("Cannot get free port!"); + } + + TVector<NTesting::TPortHolder> GetFreePortsRange(size_t count) const { + Y_VERIFY(count > 0); + TVector<NTesting::TPortHolder> ports(Reserve(count)); + for (size_t i = 0; i < Retries; ++i) { + for (auto[left, right] : Ranges_) { + if (right - left < count) { + continue; + } + ui16 start = left + RandomNumber<ui16>((right - left) / 2); + if (right - start < count) { + continue; + } + for (ui16 probe = start; probe < right; ++probe) { + auto port = TryAcquirePort(probe); + if (port) { + ports.emplace_back(std::move(port)); + } else { + ports.clear(); + } + if (ports.size() == count) { + return ports; + } + } + // Can't find required number of ports without gap in the current range + ports.clear(); + } + } + Y_FAIL("Cannot get range of %zu ports!", count); + } + + private: + THolder<NTesting::IPort> TryAcquirePort(ui16 port) const { + auto lock = MakeHolder<TFileLock>(TString(SyncDir_ / ::ToString(port))); + if (!lock->TryAcquire()) { + return nullptr; + } + + TInet6StreamSocket sock; + Y_VERIFY_SYSERROR(INVALID_SOCKET != static_cast<SOCKET>(sock)); + + TSockAddrInet6 addr("::", port); + if (sock.Bind(&addr) != 0) { + lock->Release(); + Y_VERIFY(EADDRINUSE == LastSystemError(), "unexpected error: %d", LastSystemError()); + return nullptr; + } + return MakeHolder<TPortGuard>(port, std::move(lock)); + } + + private: + TFsPath SyncDir_; + TVector<std::pair<ui16, ui16>> Ranges_; + size_t TotalCount_; + }; +} + +namespace NTesting { + TPortHolder GetFreePort() { + return Singleton<TPortManager>()->GetFreePort(); + } + + namespace NLegacy { + TVector<TPortHolder> GetFreePortsRange(size_t count) { + return Singleton<TPortManager>()->GetFreePortsRange(count); + } + } IOutputStream& operator<<(IOutputStream& out, const TPortHolder& port) { return out << static_cast<ui16>(port); } -} +} diff --git a/library/cpp/testing/common/network.h b/library/cpp/testing/common/network.h index eb4d32f3a1..66fb2b0c40 100644 --- a/library/cpp/testing/common/network.h +++ b/library/cpp/testing/common/network.h @@ -1,52 +1,52 @@ -#pragma once - -#include <util/generic/ptr.h> -#include <util/generic/vector.h> - -namespace NTesting { - - //@brief network port holder interface - class IPort { - public: - virtual ~IPort() {} - - virtual ui16 Get() = 0; - }; - - class TPortHolder : private THolder<IPort> { - using TBase = THolder<IPort>; - public: - using TBase::TBase; - using TBase::Release; - using TBase::Reset; - - operator ui16() const& { - return (*this)->Get(); - } - - operator ui16() const&& = delete; - }; - +#pragma once + +#include <util/generic/ptr.h> +#include <util/generic/vector.h> + +namespace NTesting { + + //@brief network port holder interface + class IPort { + public: + virtual ~IPort() {} + + virtual ui16 Get() = 0; + }; + + class TPortHolder : private THolder<IPort> { + using TBase = THolder<IPort>; + public: + using TBase::TBase; + using TBase::Release; + using TBase::Reset; + + operator ui16() const& { + return (*this)->Get(); + } + + operator ui16() const&& = delete; + }; + IOutputStream& operator<<(IOutputStream& out, const TPortHolder& port); - //@brief Get first free port. - [[nodiscard]] TPortHolder GetFreePort(); - - namespace NLegacy { - // Do not use this method, it needs only for TPortManager from unittests. - // Returns continuous sequence of the specified number of ports. - [[nodiscard]] TVector<TPortHolder> GetFreePortsRange(size_t count); - } - - //@brief helper class for inheritance - struct TFreePortOwner { - TFreePortOwner() : Port_(GetFreePort()) {} - - ui16 GetPort() const { - return Port_; - } - - private: - TPortHolder Port_; - }; -} + //@brief Get first free port. + [[nodiscard]] TPortHolder GetFreePort(); + + namespace NLegacy { + // Do not use this method, it needs only for TPortManager from unittests. + // Returns continuous sequence of the specified number of ports. + [[nodiscard]] TVector<TPortHolder> GetFreePortsRange(size_t count); + } + + //@brief helper class for inheritance + struct TFreePortOwner { + TFreePortOwner() : Port_(GetFreePort()) {} + + ui16 GetPort() const { + return Port_; + } + + private: + TPortHolder Port_; + }; +} diff --git a/library/cpp/testing/common/probe.cpp b/library/cpp/testing/common/probe.cpp index 73f2fb6360..c0d7f46ba6 100644 --- a/library/cpp/testing/common/probe.cpp +++ b/library/cpp/testing/common/probe.cpp @@ -1 +1 @@ -#include "probe.h" +#include "probe.h" diff --git a/library/cpp/testing/common/probe.h b/library/cpp/testing/common/probe.h index 19910979b5..ba5a83a83e 100644 --- a/library/cpp/testing/common/probe.h +++ b/library/cpp/testing/common/probe.h @@ -1,140 +1,140 @@ #pragma once -#include <util/system/yassert.h> +#include <util/system/yassert.h> namespace NTesting { - //////////////////////////////////////////////////////////////////////////////// - - // Below there is a serie of probe classes for testing construction/destruction copying/moving of class. - // for examples see tests in probe_ut.cpp - - struct TProbeState { - int Constructors = 0; - int Destructors = 0; - int ShadowDestructors = 0; - int CopyConstructors = 0; - int CopyAssignments = 0; - int MoveConstructors = 0; - int MoveAssignments = 0; - int Touches = 0; - - TProbeState() = default; - - void Reset() { - *this = TProbeState{}; - } - }; - - // Used for probing the number of copies that occur if a type must be coerced. - class TCoercibleToProbe { - public: - TProbeState* State; - TProbeState* ShadowState; - - public: - explicit TCoercibleToProbe(TProbeState* state) - : State(state) - , ShadowState(state) - {} - - private: - TCoercibleToProbe(const TCoercibleToProbe&); - TCoercibleToProbe(TCoercibleToProbe&&); - TCoercibleToProbe& operator=(const TCoercibleToProbe&); - TCoercibleToProbe& operator=(TCoercibleToProbe&&); - }; - - // Used for probing the number of copies in an argument. - class TProbe { - public: - TProbeState* State; - TProbeState* ShadowState; - - public: - static TProbe ExplicitlyCreateInvalidProbe() { - return TProbe(); - } - - explicit TProbe(TProbeState* state) - : State(state) - , ShadowState(state) - { - Y_ASSERT(State); - ++State->Constructors; - } - - ~TProbe() { - if (State) { - ++State->Destructors; - } - if (ShadowState) { - ++ShadowState->ShadowDestructors; - } - } - - TProbe(const TProbe& other) - : State(other.State) - , ShadowState(other.ShadowState) - { - Y_ASSERT(State); - ++State->CopyConstructors; - } - - TProbe(TProbe&& other) - : State(other.State) - , ShadowState(other.ShadowState) - { - Y_ASSERT(State); - other.State = nullptr; - ++State->MoveConstructors; - } - - TProbe(const TCoercibleToProbe& other) - : State(other.State) - , ShadowState(other.ShadowState) - { - Y_ASSERT(State); - ++State->CopyConstructors; - } - - TProbe(TCoercibleToProbe&& other) - : State(other.State) - , ShadowState(other.ShadowState) - { - Y_ASSERT(State); - other.State = nullptr; - ++State->MoveConstructors; - } - - TProbe& operator=(const TProbe& other) { - State = other.State; - ShadowState = other.ShadowState; - Y_ASSERT(State); - ++State->CopyAssignments; - return *this; - } - - TProbe& operator=(TProbe&& other) { - State = other.State; - ShadowState = other.ShadowState; - Y_ASSERT(State); - other.State = nullptr; - ++State->MoveAssignments; - return *this; + //////////////////////////////////////////////////////////////////////////////// + + // Below there is a serie of probe classes for testing construction/destruction copying/moving of class. + // for examples see tests in probe_ut.cpp + + struct TProbeState { + int Constructors = 0; + int Destructors = 0; + int ShadowDestructors = 0; + int CopyConstructors = 0; + int CopyAssignments = 0; + int MoveConstructors = 0; + int MoveAssignments = 0; + int Touches = 0; + + TProbeState() = default; + + void Reset() { + *this = TProbeState{}; + } + }; + + // Used for probing the number of copies that occur if a type must be coerced. + class TCoercibleToProbe { + public: + TProbeState* State; + TProbeState* ShadowState; + + public: + explicit TCoercibleToProbe(TProbeState* state) + : State(state) + , ShadowState(state) + {} + + private: + TCoercibleToProbe(const TCoercibleToProbe&); + TCoercibleToProbe(TCoercibleToProbe&&); + TCoercibleToProbe& operator=(const TCoercibleToProbe&); + TCoercibleToProbe& operator=(TCoercibleToProbe&&); + }; + + // Used for probing the number of copies in an argument. + class TProbe { + public: + TProbeState* State; + TProbeState* ShadowState; + + public: + static TProbe ExplicitlyCreateInvalidProbe() { + return TProbe(); + } + + explicit TProbe(TProbeState* state) + : State(state) + , ShadowState(state) + { + Y_ASSERT(State); + ++State->Constructors; + } + + ~TProbe() { + if (State) { + ++State->Destructors; + } + if (ShadowState) { + ++ShadowState->ShadowDestructors; + } + } + + TProbe(const TProbe& other) + : State(other.State) + , ShadowState(other.ShadowState) + { + Y_ASSERT(State); + ++State->CopyConstructors; + } + + TProbe(TProbe&& other) + : State(other.State) + , ShadowState(other.ShadowState) + { + Y_ASSERT(State); + other.State = nullptr; + ++State->MoveConstructors; + } + + TProbe(const TCoercibleToProbe& other) + : State(other.State) + , ShadowState(other.ShadowState) + { + Y_ASSERT(State); + ++State->CopyConstructors; } - - void Touch() const { - Y_ASSERT(State); - ++State->Touches; - } - - bool IsValid() const { - return nullptr != State; + + TProbe(TCoercibleToProbe&& other) + : State(other.State) + , ShadowState(other.ShadowState) + { + Y_ASSERT(State); + other.State = nullptr; + ++State->MoveConstructors; } - private: - TProbe() - : State(nullptr) - {} - }; + TProbe& operator=(const TProbe& other) { + State = other.State; + ShadowState = other.ShadowState; + Y_ASSERT(State); + ++State->CopyAssignments; + return *this; + } + + TProbe& operator=(TProbe&& other) { + State = other.State; + ShadowState = other.ShadowState; + Y_ASSERT(State); + other.State = nullptr; + ++State->MoveAssignments; + return *this; + } + + void Touch() const { + Y_ASSERT(State); + ++State->Touches; + } + + bool IsValid() const { + return nullptr != State; + } + + private: + TProbe() + : State(nullptr) + {} + }; } // namespace NTesting diff --git a/library/cpp/testing/common/scope.cpp b/library/cpp/testing/common/scope.cpp index c70d695c1b..5efa7cb0d2 100644 --- a/library/cpp/testing/common/scope.cpp +++ b/library/cpp/testing/common/scope.cpp @@ -1 +1 @@ -#include "scope.h" +#include "scope.h" diff --git a/library/cpp/testing/common/scope.h b/library/cpp/testing/common/scope.h index a2ca0e77e4..af12bda3c4 100644 --- a/library/cpp/testing/common/scope.h +++ b/library/cpp/testing/common/scope.h @@ -1,39 +1,39 @@ -#pragma once - -#include <util/generic/string.h> -#include <util/generic/vector.h> -#include <util/system/env.h> - -#include <utility> - -namespace NTesting { - // @brief Assigns new values to the given environment variables and restores old values upon destruction. - // @note if there was no env variable with given name, it will be set to empty string upon destruction IGNIETFERRO-1486 - struct TScopedEnvironment { - TScopedEnvironment(const TString& name, const TString& value) - : PreviousState{1, {name, ::GetEnv(name)}} - { - ::SetEnv(name, value); - } - - TScopedEnvironment(const TVector<std::pair<TString, TString>>& vars) - : PreviousState(Reserve(vars.size())) - { - for (const auto& [k, v] : vars) { - PreviousState.emplace_back(k, ::GetEnv(k)); - ::SetEnv(k, v); - } - } - - ~TScopedEnvironment() { - for (const auto& [k, v] : PreviousState) { - ::SetEnv(k, v); - } - } - - TScopedEnvironment(const TScopedEnvironment&) = delete; - TScopedEnvironment& operator=(const TScopedEnvironment&) = delete; - private: - TVector<std::pair<TString, TString>> PreviousState; - }; -} +#pragma once + +#include <util/generic/string.h> +#include <util/generic/vector.h> +#include <util/system/env.h> + +#include <utility> + +namespace NTesting { + // @brief Assigns new values to the given environment variables and restores old values upon destruction. + // @note if there was no env variable with given name, it will be set to empty string upon destruction IGNIETFERRO-1486 + struct TScopedEnvironment { + TScopedEnvironment(const TString& name, const TString& value) + : PreviousState{1, {name, ::GetEnv(name)}} + { + ::SetEnv(name, value); + } + + TScopedEnvironment(const TVector<std::pair<TString, TString>>& vars) + : PreviousState(Reserve(vars.size())) + { + for (const auto& [k, v] : vars) { + PreviousState.emplace_back(k, ::GetEnv(k)); + ::SetEnv(k, v); + } + } + + ~TScopedEnvironment() { + for (const auto& [k, v] : PreviousState) { + ::SetEnv(k, v); + } + } + + TScopedEnvironment(const TScopedEnvironment&) = delete; + TScopedEnvironment& operator=(const TScopedEnvironment&) = delete; + private: + TVector<std::pair<TString, TString>> PreviousState; + }; +} diff --git a/library/cpp/testing/common/ut/env_ut.cpp b/library/cpp/testing/common/ut/env_ut.cpp index 2aed1e4a25..889e8073e8 100644 --- a/library/cpp/testing/common/ut/env_ut.cpp +++ b/library/cpp/testing/common/ut/env_ut.cpp @@ -1,104 +1,104 @@ -#include <library/cpp/testing/common/env.h> -#include <library/cpp/testing/common/scope.h> +#include <library/cpp/testing/common/env.h> +#include <library/cpp/testing/common/scope.h> #include <library/cpp/testing/gtest/gtest.h> - -#include <util/folder/dirut.h> + +#include <util/folder/dirut.h> #include <util/stream/file.h> -#include <util/system/env.h> -#include <util/system/execpath.h> +#include <util/system/env.h> +#include <util/system/execpath.h> #include <util/system/fs.h> - - -TEST(Runtime, ArcadiaSourceRoot) { + + +TEST(Runtime, ArcadiaSourceRoot) { NTesting::TScopedEnvironment contextGuard("YA_TEST_CONTEXT_FILE", ""); // remove context filename - { - auto tmpDir = ::GetSystemTempDir(); - NTesting::TScopedEnvironment guard("ARCADIA_SOURCE_ROOT", tmpDir); + { + auto tmpDir = ::GetSystemTempDir(); + NTesting::TScopedEnvironment guard("ARCADIA_SOURCE_ROOT", tmpDir); Singleton<NPrivate::TTestEnv>()->ReInitialize(); - EXPECT_EQ(tmpDir, ArcadiaSourceRoot()); - } - { - NTesting::TScopedEnvironment guard("ARCADIA_SOURCE_ROOT", ""); + EXPECT_EQ(tmpDir, ArcadiaSourceRoot()); + } + { + NTesting::TScopedEnvironment guard("ARCADIA_SOURCE_ROOT", ""); Singleton<NPrivate::TTestEnv>()->ReInitialize(); - EXPECT_FALSE(ArcadiaSourceRoot().empty()); - } -} - -TEST(Runtime, BuildRoot) { + EXPECT_FALSE(ArcadiaSourceRoot().empty()); + } +} + +TEST(Runtime, BuildRoot) { NTesting::TScopedEnvironment contextGuard("YA_TEST_CONTEXT_FILE", ""); // remove context filename - { - auto tmpDir = ::GetSystemTempDir(); - NTesting::TScopedEnvironment guard("ARCADIA_BUILD_ROOT", tmpDir); + { + auto tmpDir = ::GetSystemTempDir(); + NTesting::TScopedEnvironment guard("ARCADIA_BUILD_ROOT", tmpDir); Singleton<NPrivate::TTestEnv>()->ReInitialize(); - EXPECT_EQ(tmpDir, BuildRoot()); - } - { - NTesting::TScopedEnvironment guard("ARCADIA_BUILD_ROOT", ""); + EXPECT_EQ(tmpDir, BuildRoot()); + } + { + NTesting::TScopedEnvironment guard("ARCADIA_BUILD_ROOT", ""); Singleton<NPrivate::TTestEnv>()->ReInitialize(); - EXPECT_FALSE(BuildRoot().empty()); - } -} - -TEST(Runtime, BinaryPath) { + EXPECT_FALSE(BuildRoot().empty()); + } +} + +TEST(Runtime, BinaryPath) { NTesting::TScopedEnvironment contextGuard("YA_TEST_CONTEXT_FILE", ""); // remove context filename Singleton<NPrivate::TTestEnv>()->ReInitialize(); - EXPECT_TRUE(TFsPath(BinaryPath("library/cpp/testing/common/ut")).Exists()); -} - -TEST(Runtime, GetArcadiaTestsData) { + EXPECT_TRUE(TFsPath(BinaryPath("library/cpp/testing/common/ut")).Exists()); +} + +TEST(Runtime, GetArcadiaTestsData) { NTesting::TScopedEnvironment contextGuard("YA_TEST_CONTEXT_FILE", ""); // remove context filename - { - auto tmpDir = ::GetSystemTempDir(); - NTesting::TScopedEnvironment guard("ARCADIA_TESTS_DATA_DIR", tmpDir); + { + auto tmpDir = ::GetSystemTempDir(); + NTesting::TScopedEnvironment guard("ARCADIA_TESTS_DATA_DIR", tmpDir); Singleton<NPrivate::TTestEnv>()->ReInitialize(); - EXPECT_EQ(tmpDir, GetArcadiaTestsData()); - } - { - NTesting::TScopedEnvironment guard("ARCADIA_TESTS_DATA_DIR", ""); + EXPECT_EQ(tmpDir, GetArcadiaTestsData()); + } + { + NTesting::TScopedEnvironment guard("ARCADIA_TESTS_DATA_DIR", ""); Singleton<NPrivate::TTestEnv>()->ReInitialize(); - auto path = GetArcadiaTestsData(); - // it is not error if path is empty - const bool ok = (path.empty() || GetBaseName(path) == "arcadia_tests_data"); - EXPECT_TRUE(ok); - } -} - -TEST(Runtime, GetWorkPath) { + auto path = GetArcadiaTestsData(); + // it is not error if path is empty + const bool ok = (path.empty() || GetBaseName(path) == "arcadia_tests_data"); + EXPECT_TRUE(ok); + } +} + +TEST(Runtime, GetWorkPath) { NTesting::TScopedEnvironment contextGuard("YA_TEST_CONTEXT_FILE", ""); // remove context filename - { - auto tmpDir = ::GetSystemTempDir(); - NTesting::TScopedEnvironment guard("TEST_WORK_PATH", tmpDir); + { + auto tmpDir = ::GetSystemTempDir(); + NTesting::TScopedEnvironment guard("TEST_WORK_PATH", tmpDir); Singleton<NPrivate::TTestEnv>()->ReInitialize(); - EXPECT_EQ(tmpDir, GetWorkPath()); - } - { - NTesting::TScopedEnvironment guard("TEST_WORK_PATH", ""); + EXPECT_EQ(tmpDir, GetWorkPath()); + } + { + NTesting::TScopedEnvironment guard("TEST_WORK_PATH", ""); Singleton<NPrivate::TTestEnv>()->ReInitialize(); - EXPECT_TRUE(!GetWorkPath().empty()); - } -} - -TEST(Runtime, GetOutputPath) { + EXPECT_TRUE(!GetWorkPath().empty()); + } +} + +TEST(Runtime, GetOutputPath) { NTesting::TScopedEnvironment contextGuard("YA_TEST_CONTEXT_FILE", ""); // remove context filename Singleton<NPrivate::TTestEnv>()->ReInitialize(); - EXPECT_EQ(GetOutputPath().Basename(), "testing_out_stuff"); -} - -TEST(Runtime, GetRamDrivePath) { + EXPECT_EQ(GetOutputPath().Basename(), "testing_out_stuff"); +} + +TEST(Runtime, GetRamDrivePath) { NTesting::TScopedEnvironment contextGuard("YA_TEST_CONTEXT_FILE", ""); // remove context filename - auto tmpDir = ::GetSystemTempDir(); - NTesting::TScopedEnvironment guard("YA_TEST_RAM_DRIVE_PATH", tmpDir); + auto tmpDir = ::GetSystemTempDir(); + NTesting::TScopedEnvironment guard("YA_TEST_RAM_DRIVE_PATH", tmpDir); Singleton<NPrivate::TTestEnv>()->ReInitialize(); - EXPECT_EQ(tmpDir, GetRamDrivePath()); -} - -TEST(Runtime, GetOutputRamDrivePath) { + EXPECT_EQ(tmpDir, GetRamDrivePath()); +} + +TEST(Runtime, GetOutputRamDrivePath) { NTesting::TScopedEnvironment contextGuard("YA_TEST_CONTEXT_FILE", ""); // remove context filename - auto tmpDir = ::GetSystemTempDir(); - NTesting::TScopedEnvironment guard("YA_TEST_OUTPUT_RAM_DRIVE_PATH", tmpDir); + auto tmpDir = ::GetSystemTempDir(); + NTesting::TScopedEnvironment guard("YA_TEST_OUTPUT_RAM_DRIVE_PATH", tmpDir); Singleton<NPrivate::TTestEnv>()->ReInitialize(); - EXPECT_EQ(tmpDir, GetOutputRamDrivePath()); -} + EXPECT_EQ(tmpDir, GetOutputRamDrivePath()); +} #ifdef _linux_ TEST(Runtime, GdbPath) { diff --git a/library/cpp/testing/common/ut/network_ut.cpp b/library/cpp/testing/common/ut/network_ut.cpp index 6a40775fd9..11ba48fd5d 100644 --- a/library/cpp/testing/common/ut/network_ut.cpp +++ b/library/cpp/testing/common/ut/network_ut.cpp @@ -1,54 +1,54 @@ -#include <library/cpp/testing/common/network.h> -#include <library/cpp/testing/common/scope.h> - -#include <util/generic/hash_set.h> - -#include <util/folder/dirut.h> -#include <util/folder/path.h> -#include <util/folder/tempdir.h> -#include <util/network/sock.h> -#include <util/system/fs.h> - -#include <library/cpp/testing/gtest/gtest.h> - -static TTempDir TmpDir; - -TEST(NetworkTest, FreePort) { - NTesting::TScopedEnvironment envGuard("PORT_SYNC_PATH", TmpDir.Name()); - - TVector<NTesting::TPortHolder> ports(Reserve(100)); - - for (size_t i = 0; i < 100; ++i) { - ports.push_back(NTesting::GetFreePort()); - } - - THashSet<ui16> uniqPorts; - for (auto& port : ports) { - const TString guardPath = TmpDir.Path() / ToString(static_cast<ui16>(port)); - EXPECT_TRUE(NFs::Exists(guardPath)); - EXPECT_TRUE(uniqPorts.emplace(port).second); - - TInetStreamSocket sock; - TSockAddrInet addr(TIpHost{INADDR_ANY}, port); - ASSERT_EQ(0, SetSockOpt(sock, SOL_SOCKET, SO_REUSEADDR, 1)); - EXPECT_EQ(0, sock.Bind(&addr)); - } - ports.clear(); - for (ui16 port : uniqPorts) { - const TString guardPath = TmpDir.Path() / ToString(port); - EXPECT_FALSE(NFs::Exists(guardPath)); - } -} - - -TEST(FreePortTest, FreePortsRange) { - NTesting::TScopedEnvironment envGuard("PORT_SYNC_PATH", TmpDir.Name()); - - for (ui16 i = 2; i < 10; ++i) { - TVector<NTesting::TPortHolder> ports = NTesting::NLegacy::GetFreePortsRange(i); - ASSERT_EQ(i, ports.size()); - for (ui16 j = 1; j < i; ++j) { - EXPECT_EQ(static_cast<ui16>(ports[j]), static_cast<ui16>(ports[0]) + j); - } - } -} +#include <library/cpp/testing/common/network.h> +#include <library/cpp/testing/common/scope.h> + +#include <util/generic/hash_set.h> + +#include <util/folder/dirut.h> +#include <util/folder/path.h> +#include <util/folder/tempdir.h> +#include <util/network/sock.h> +#include <util/system/fs.h> + +#include <library/cpp/testing/gtest/gtest.h> + +static TTempDir TmpDir; + +TEST(NetworkTest, FreePort) { + NTesting::TScopedEnvironment envGuard("PORT_SYNC_PATH", TmpDir.Name()); + + TVector<NTesting::TPortHolder> ports(Reserve(100)); + + for (size_t i = 0; i < 100; ++i) { + ports.push_back(NTesting::GetFreePort()); + } + + THashSet<ui16> uniqPorts; + for (auto& port : ports) { + const TString guardPath = TmpDir.Path() / ToString(static_cast<ui16>(port)); + EXPECT_TRUE(NFs::Exists(guardPath)); + EXPECT_TRUE(uniqPorts.emplace(port).second); + + TInetStreamSocket sock; + TSockAddrInet addr(TIpHost{INADDR_ANY}, port); + ASSERT_EQ(0, SetSockOpt(sock, SOL_SOCKET, SO_REUSEADDR, 1)); + EXPECT_EQ(0, sock.Bind(&addr)); + } + ports.clear(); + for (ui16 port : uniqPorts) { + const TString guardPath = TmpDir.Path() / ToString(port); + EXPECT_FALSE(NFs::Exists(guardPath)); + } +} + + +TEST(FreePortTest, FreePortsRange) { + NTesting::TScopedEnvironment envGuard("PORT_SYNC_PATH", TmpDir.Name()); + + for (ui16 i = 2; i < 10; ++i) { + TVector<NTesting::TPortHolder> ports = NTesting::NLegacy::GetFreePortsRange(i); + ASSERT_EQ(i, ports.size()); + for (ui16 j = 1; j < i; ++j) { + EXPECT_EQ(static_cast<ui16>(ports[j]), static_cast<ui16>(ports[0]) + j); + } + } +} diff --git a/library/cpp/testing/common/ut/scope_ut.cpp b/library/cpp/testing/common/ut/scope_ut.cpp index 4fb82c2466..4bbbd6b41c 100644 --- a/library/cpp/testing/common/ut/scope_ut.cpp +++ b/library/cpp/testing/common/ut/scope_ut.cpp @@ -1,28 +1,28 @@ -#include <library/cpp/testing/common/scope.h> - -#include <util/system/env.h> - -#include <library/cpp/testing/gtest/gtest.h> - -TEST(TScopedEnvironment, SingleValue) { - auto before = GetEnv("ARCADIA_SOURCE_ROOT"); - { - NTesting::TScopedEnvironment guard("ARCADIA_SOURCE_ROOT", "source"); - EXPECT_EQ("source", GetEnv("ARCADIA_SOURCE_ROOT")); - } - EXPECT_EQ(before, GetEnv("ARCADIA_SOURCE_ROOT")); -} - -TEST(TScopedEnvironment, MultiValue) { - TVector<TString> before{GetEnv("ARCADIA_SOURCE_ROOT"), GetEnv("ARCADIA_BUILD_ROOT")}; - { - NTesting::TScopedEnvironment guard{{ - {"ARCADIA_SOURCE_ROOT", "source"}, - {"ARCADIA_BUILD_ROOT", "build"}, - }}; - EXPECT_EQ("source", GetEnv("ARCADIA_SOURCE_ROOT")); - EXPECT_EQ("build", GetEnv("ARCADIA_BUILD_ROOT")); - } - TVector<TString> after{GetEnv("ARCADIA_SOURCE_ROOT"), GetEnv("ARCADIA_BUILD_ROOT")}; - EXPECT_EQ(before, after); -} +#include <library/cpp/testing/common/scope.h> + +#include <util/system/env.h> + +#include <library/cpp/testing/gtest/gtest.h> + +TEST(TScopedEnvironment, SingleValue) { + auto before = GetEnv("ARCADIA_SOURCE_ROOT"); + { + NTesting::TScopedEnvironment guard("ARCADIA_SOURCE_ROOT", "source"); + EXPECT_EQ("source", GetEnv("ARCADIA_SOURCE_ROOT")); + } + EXPECT_EQ(before, GetEnv("ARCADIA_SOURCE_ROOT")); +} + +TEST(TScopedEnvironment, MultiValue) { + TVector<TString> before{GetEnv("ARCADIA_SOURCE_ROOT"), GetEnv("ARCADIA_BUILD_ROOT")}; + { + NTesting::TScopedEnvironment guard{{ + {"ARCADIA_SOURCE_ROOT", "source"}, + {"ARCADIA_BUILD_ROOT", "build"}, + }}; + EXPECT_EQ("source", GetEnv("ARCADIA_SOURCE_ROOT")); + EXPECT_EQ("build", GetEnv("ARCADIA_BUILD_ROOT")); + } + TVector<TString> after{GetEnv("ARCADIA_SOURCE_ROOT"), GetEnv("ARCADIA_BUILD_ROOT")}; + EXPECT_EQ(before, after); +} diff --git a/library/cpp/testing/common/ut/ya.make b/library/cpp/testing/common/ut/ya.make index 053aa38079..fbe866c479 100644 --- a/library/cpp/testing/common/ut/ya.make +++ b/library/cpp/testing/common/ut/ya.make @@ -1,19 +1,19 @@ GTEST() -OWNER( - amatanhead - bulatman - thegeorg - g:cpp-contrib -) - -SRCS( - env_ut.cpp - network_ut.cpp - scope_ut.cpp -) - -PEERDIR( - library/cpp/testing/common -) - -END() +OWNER( + amatanhead + bulatman + thegeorg + g:cpp-contrib +) + +SRCS( + env_ut.cpp + network_ut.cpp + scope_ut.cpp +) + +PEERDIR( + library/cpp/testing/common +) + +END() diff --git a/library/cpp/testing/common/ya.make b/library/cpp/testing/common/ya.make index 2f4b0ce26e..1c3b68328e 100644 --- a/library/cpp/testing/common/ya.make +++ b/library/cpp/testing/common/ya.make @@ -1,23 +1,23 @@ -LIBRARY() - -OWNER( - amatanhead - bulatman - thegeorg - g:cpp-contrib -) - -SRCS( - env.cpp - network.cpp +LIBRARY() + +OWNER( + amatanhead + bulatman + thegeorg + g:cpp-contrib +) + +SRCS( + env.cpp + network.cpp probe.cpp - scope.cpp -) - + scope.cpp +) + PEERDIR( library/cpp/json ) -END() - -RECURSE_FOR_TESTS(ut) +END() + +RECURSE_FOR_TESTS(ut) diff --git a/library/cpp/testing/gmock_in_unittest/ya.make b/library/cpp/testing/gmock_in_unittest/ya.make index 5de68ad98d..e909ebeb2e 100644 --- a/library/cpp/testing/gmock_in_unittest/ya.make +++ b/library/cpp/testing/gmock_in_unittest/ya.make @@ -3,8 +3,8 @@ LIBRARY() OWNER(galaxycrab) PEERDIR( - contrib/restricted/googletest/googlemock - contrib/restricted/googletest/googletest + contrib/restricted/googletest/googlemock + contrib/restricted/googletest/googletest library/cpp/testing/gtest_extensions library/cpp/testing/unittest ) diff --git a/library/cpp/testing/gtest_extensions/assertions.h b/library/cpp/testing/gtest_extensions/assertions.h index e8ea07b5df..30b9c645ff 100644 --- a/library/cpp/testing/gtest_extensions/assertions.h +++ b/library/cpp/testing/gtest_extensions/assertions.h @@ -2,8 +2,8 @@ #include <util/generic/string.h> -#include <gtest/gtest.h> -#include <gmock/gmock.h> +#include <gtest/gtest.h> +#include <gmock/gmock.h> /** * Check that the given statement throws an exception of the given type, diff --git a/library/cpp/testing/gtest_extensions/gtest_extensions.h b/library/cpp/testing/gtest_extensions/gtest_extensions.h index e20532241e..3c2800c2b6 100644 --- a/library/cpp/testing/gtest_extensions/gtest_extensions.h +++ b/library/cpp/testing/gtest_extensions/gtest_extensions.h @@ -3,4 +3,4 @@ #include "assertions.h" #include "matchers.h" #include "pretty_printers.h" -#include "probe.h" +#include "probe.h" diff --git a/library/cpp/testing/gtest_extensions/matchers.h b/library/cpp/testing/gtest_extensions/matchers.h index 044c1c3ee4..01f26f54e4 100644 --- a/library/cpp/testing/gtest_extensions/matchers.h +++ b/library/cpp/testing/gtest_extensions/matchers.h @@ -2,8 +2,8 @@ #include <util/generic/string.h> -#include <gtest/gtest.h> -#include <gmock/gmock.h> +#include <gtest/gtest.h> +#include <gmock/gmock.h> namespace testing { /** @@ -19,11 +19,11 @@ namespace testing { : internal::MatcherBase<const TBasicStringBuf<T, TT>&>(impl) { } - template <typename M, typename = typename std::remove_reference<M>::type::is_gtest_matcher> - Matcher(M&& m) - : internal::MatcherBase<const TBasicStringBuf<T, TT>&>(std::forward<M>(m)) { - } - + template <typename M, typename = typename std::remove_reference<M>::type::is_gtest_matcher> + Matcher(M&& m) + : internal::MatcherBase<const TBasicStringBuf<T, TT>&>(std::forward<M>(m)) { + } + Matcher(const TBasicString<T, TT>& s) { *this = Eq(TBasicStringBuf<T, TT>(s)); } @@ -54,11 +54,11 @@ namespace testing { : internal::MatcherBase<TBasicStringBuf<T, TT>>(impl) { } - template <typename M, typename = typename std::remove_reference<M>::type::is_gtest_matcher> - Matcher(M&& m) - : internal::MatcherBase<TBasicStringBuf<T, TT>>(std::forward<M>(m)) { - } - + template <typename M, typename = typename std::remove_reference<M>::type::is_gtest_matcher> + Matcher(M&& m) + : internal::MatcherBase<TBasicStringBuf<T, TT>>(std::forward<M>(m)) { + } + Matcher(const TBasicString<T, TT>& s) { *this = Eq(TBasicString<T, TT>(s)); } @@ -89,11 +89,11 @@ namespace testing { *this = Eq(s); } - template <typename M, typename = typename std::remove_reference<M>::type::is_gtest_matcher> - Matcher(M&& m) - : internal::MatcherBase<const TBasicString<T, TT>&>(std::forward<M>(m)) { - } - + template <typename M, typename = typename std::remove_reference<M>::type::is_gtest_matcher> + Matcher(M&& m) + : internal::MatcherBase<const TBasicString<T, TT>&>(std::forward<M>(m)) { + } + Matcher(const T* s) { *this = Eq(TBasicString<T, TT>(s)); } @@ -116,11 +116,11 @@ namespace testing { : internal::MatcherBase<TBasicString<T, TT>>(impl) { } - template <typename M, typename = typename std::remove_reference<M>::type::is_gtest_matcher> - Matcher(M&& m) - : internal::MatcherBase<TBasicString<T, TT>>(std::forward<M>(m)) { - } - + template <typename M, typename = typename std::remove_reference<M>::type::is_gtest_matcher> + Matcher(M&& m) + : internal::MatcherBase<TBasicString<T, TT>>(std::forward<M>(m)) { + } + Matcher(const TBasicString<T, TT>& s) { *this = Eq(s); } diff --git a/library/cpp/testing/gtest_extensions/pretty_printers.h b/library/cpp/testing/gtest_extensions/pretty_printers.h index 14d8284446..15f07e4fe8 100644 --- a/library/cpp/testing/gtest_extensions/pretty_printers.h +++ b/library/cpp/testing/gtest_extensions/pretty_printers.h @@ -8,8 +8,8 @@ #include <util/stream/str.h> #include <util/datetime/base.h> -#include <gtest/gtest.h> -#include <gmock/gmock.h> +#include <gtest/gtest.h> +#include <gmock/gmock.h> /** * Automatically define GTest pretty printer for type that can print itself to util's `IOutputStream`. diff --git a/library/cpp/testing/gtest_extensions/probe.cpp b/library/cpp/testing/gtest_extensions/probe.cpp index c3a49b9323..f8d59ebd6b 100644 --- a/library/cpp/testing/gtest_extensions/probe.cpp +++ b/library/cpp/testing/gtest_extensions/probe.cpp @@ -1,13 +1,13 @@ -#include "probe.h" - -#include <ostream> - +#include "probe.h" + +#include <ostream> + namespace testing { - void PrintTo(const TProbeState& state, ::std::ostream* os) { - int copies = state.CopyConstructors + state.CopyAssignments; - int moves = state.MoveConstructors + state.MoveAssignments; - *os << state.Constructors << " ctors, " << state.Destructors << " dtors; " - << "copies: " << copies << " = " << state.CopyConstructors << " + " << state.CopyAssignments << "; " - << "moves: " << moves << " = " << state.MoveConstructors << " + " << state.MoveAssignments; - } + void PrintTo(const TProbeState& state, ::std::ostream* os) { + int copies = state.CopyConstructors + state.CopyAssignments; + int moves = state.MoveConstructors + state.MoveAssignments; + *os << state.Constructors << " ctors, " << state.Destructors << " dtors; " + << "copies: " << copies << " = " << state.CopyConstructors << " + " << state.CopyAssignments << "; " + << "moves: " << moves << " = " << state.MoveConstructors << " + " << state.MoveAssignments; + } } // namespace testing diff --git a/library/cpp/testing/gtest_extensions/probe.h b/library/cpp/testing/gtest_extensions/probe.h index 7d1fee83d3..3b18502555 100644 --- a/library/cpp/testing/gtest_extensions/probe.h +++ b/library/cpp/testing/gtest_extensions/probe.h @@ -1,81 +1,81 @@ #pragma once -#include <util/system/yassert.h> +#include <util/system/yassert.h> #include <library/cpp/testing/common/probe.h> -#include <gtest/gtest.h> -#include <gmock/gmock.h> +#include <gtest/gtest.h> +#include <gmock/gmock.h> namespace testing { using NTesting::TProbe; using NTesting::TProbeState; using NTesting::TCoercibleToProbe; - // A helper functor which extracts from probe-like objectss their state. - struct TProbableTraits { - static const TProbeState& ExtractState(const TProbeState& probe) { - return probe; - } + // A helper functor which extracts from probe-like objectss their state. + struct TProbableTraits { + static const TProbeState& ExtractState(const TProbeState& probe) { + return probe; + } - static const TProbeState& ExtractState(const TProbeState* probe) { - return *probe; - } + static const TProbeState& ExtractState(const TProbeState* probe) { + return *probe; + } - static const TProbeState& ExtractState(const TProbe& probe) { - return *probe.State; - } + static const TProbeState& ExtractState(const TProbe& probe) { + return *probe.State; + } - static const TProbeState& ExtractState(const TCoercibleToProbe& probe) { - return *probe.State; - } - }; + static const TProbeState& ExtractState(const TCoercibleToProbe& probe) { + return *probe.State; + } + }; - void PrintTo(const TProbeState& state, ::std::ostream* os); + void PrintTo(const TProbeState& state, ::std::ostream* os); - inline void PrintTo(const TProbe& probe, ::std::ostream* os) { - PrintTo(TProbableTraits::ExtractState(probe), os); + inline void PrintTo(const TProbe& probe, ::std::ostream* os) { + PrintTo(TProbableTraits::ExtractState(probe), os); } - inline void PrintTo(const TCoercibleToProbe& probe, ::std::ostream* os) { - PrintTo(TProbableTraits::ExtractState(probe), os); + inline void PrintTo(const TCoercibleToProbe& probe, ::std::ostream* os) { + PrintTo(TProbableTraits::ExtractState(probe), os); } - MATCHER(IsAlive, "is alive") { - Y_UNUSED(result_listener); + MATCHER(IsAlive, "is alive") { + Y_UNUSED(result_listener); const auto& state = TProbableTraits::ExtractState(arg); - return state.Destructors < state.Constructors + state.CopyConstructors + state.CopyAssignments; + return state.Destructors < state.Constructors + state.CopyConstructors + state.CopyAssignments; } - MATCHER(IsDead, "is dead") { - Y_UNUSED(result_listener); + MATCHER(IsDead, "is dead") { + Y_UNUSED(result_listener); const auto& state = TProbableTraits::ExtractState(arg); - return state.Destructors == state.Constructors + state.CopyConstructors + state.CopyAssignments; + return state.Destructors == state.Constructors + state.CopyConstructors + state.CopyAssignments; } - MATCHER_P2(HasCopyMoveCounts, copyCount, moveCount, "" + \ - PrintToString(copyCount) + " copy constructors and " + \ - PrintToString(moveCount) + " move constructors were called") { - Y_UNUSED(result_listener); + MATCHER_P2(HasCopyMoveCounts, copyCount, moveCount, "" + \ + PrintToString(copyCount) + " copy constructors and " + \ + PrintToString(moveCount) + " move constructors were called") { + Y_UNUSED(result_listener); const auto& state = TProbableTraits::ExtractState(arg); - return state.CopyConstructors == copyCount && state.MoveConstructors == moveCount; - } + return state.CopyConstructors == copyCount && state.MoveConstructors == moveCount; + } - MATCHER(NoCopies, "no copies were made") { - Y_UNUSED(result_listener); + MATCHER(NoCopies, "no copies were made") { + Y_UNUSED(result_listener); const auto& state = TProbableTraits::ExtractState(arg); - return 0 == state.CopyConstructors && 0 == state.CopyAssignments; - } + return 0 == state.CopyConstructors && 0 == state.CopyAssignments; + } - MATCHER(NoMoves, "no moves were made") { - Y_UNUSED(result_listener); + MATCHER(NoMoves, "no moves were made") { + Y_UNUSED(result_listener); const auto& state = TProbableTraits::ExtractState(arg); - return 0 == state.MoveConstructors && 0 == state.MoveAssignments; - } + return 0 == state.MoveConstructors && 0 == state.MoveAssignments; + } - MATCHER(NoAssignments, "no assignments were made") { - Y_UNUSED(result_listener); + MATCHER(NoAssignments, "no assignments were made") { + Y_UNUSED(result_listener); const auto& state = TProbableTraits::ExtractState(arg); - return 0 == state.CopyAssignments && 0 == state.MoveAssignments; - } + return 0 == state.CopyAssignments && 0 == state.MoveAssignments; + } } diff --git a/library/cpp/testing/gtest_extensions/ut/gtest_extensions_ut.cpp b/library/cpp/testing/gtest_extensions/ut/gtest_extensions_ut.cpp index 81cdfd0427..7fb0fd7a21 100644 --- a/library/cpp/testing/gtest_extensions/ut/gtest_extensions_ut.cpp +++ b/library/cpp/testing/gtest_extensions/ut/gtest_extensions_ut.cpp @@ -52,7 +52,7 @@ std::pair<bool, std::string> Match(T&& t, M&& m) { } TEST(Matchers, Throws) { - auto matcher = testing::Throws<std::runtime_error>(); + auto matcher = testing::Throws<std::runtime_error>(); { std::stringstream ss; @@ -78,7 +78,7 @@ TEST(Matchers, Throws) { { auto [matched, explanation] = Match([]() { throw 10; }, matcher); EXPECT_FALSE(matched); - EXPECT_THAT(explanation, testing::HasSubstr("throws an exception of an unknown type")); + EXPECT_THAT(explanation, testing::HasSubstr("throws an exception of an unknown type")); } { @@ -89,7 +89,7 @@ TEST(Matchers, Throws) { } TEST(Matchers, ThrowsMessage) { - auto matcher = testing::ThrowsMessage<std::runtime_error>(testing::HasSubstr("error message")); + auto matcher = testing::ThrowsMessage<std::runtime_error>(testing::HasSubstr("error message")); { std::stringstream ss; @@ -122,7 +122,7 @@ TEST(Matchers, ThrowsMessage) { { auto [matched, explanation] = Match([]() { throw 10; }, matcher); EXPECT_FALSE(matched); - EXPECT_THAT(explanation, testing::HasSubstr("throws an exception of an unknown type")); + EXPECT_THAT(explanation, testing::HasSubstr("throws an exception of an unknown type")); } { @@ -133,7 +133,7 @@ TEST(Matchers, ThrowsMessage) { } TEST(Matchers, ThrowsMessageHasSubstr) { - auto matcher = testing::ThrowsMessage<std::runtime_error>(testing::HasSubstr("error message")); + auto matcher = testing::ThrowsMessage<std::runtime_error>(testing::HasSubstr("error message")); { std::stringstream ss; @@ -166,7 +166,7 @@ TEST(Matchers, ThrowsMessageHasSubstr) { { auto [matched, explanation] = Match([]() { throw 10; }, matcher); EXPECT_FALSE(matched); - EXPECT_THAT(explanation, testing::HasSubstr("throws an exception of an unknown type")); + EXPECT_THAT(explanation, testing::HasSubstr("throws an exception of an unknown type")); } { @@ -177,7 +177,7 @@ TEST(Matchers, ThrowsMessageHasSubstr) { } TEST(Matchers, ThrowsCondition) { - auto matcher = testing::Throws<std::runtime_error>( + auto matcher = testing::Throws<std::runtime_error>( testing::Property(&std::exception::what, testing::HasSubstr("error message"))); { @@ -212,7 +212,7 @@ TEST(Matchers, ThrowsCondition) { { auto [matched, explanation] = Match([]() { throw 10; }, matcher); EXPECT_FALSE(matched); - EXPECT_THAT(explanation, testing::HasSubstr("throws an exception of an unknown type")); + EXPECT_THAT(explanation, testing::HasSubstr("throws an exception of an unknown type")); } { diff --git a/library/cpp/testing/gtest_extensions/ut/probe_ut.cpp b/library/cpp/testing/gtest_extensions/ut/probe_ut.cpp index a9d53f896a..428f313b9e 100644 --- a/library/cpp/testing/gtest_extensions/ut/probe_ut.cpp +++ b/library/cpp/testing/gtest_extensions/ut/probe_ut.cpp @@ -1,54 +1,54 @@ -#include <library/cpp/testing/gtest/gtest.h> - -using namespace testing; - -TEST(ProbeStateTest, Example) { - // check that our test function does not make a copy of passed argument - auto copyless = [](auto&& x) { - TProbe p(std::move(x)); - p.Touch(); - return p; - }; - - TProbeState state; - auto probe = copyless(TProbe(&state)); - EXPECT_EQ(1, state.Touches); - EXPECT_THAT(state, HasCopyMoveCounts(0, 2)); -} - -TEST(ProbeTest, Construct) { - TProbeState state; - { - TProbe probe(&state); - EXPECT_THAT(state, IsAlive()); - } - EXPECT_THAT(state, IsDead()); -} - -TEST(ProbeTest, Copy) { - TProbeState state; - - TProbe probe(&state); - TProbe copy(probe); - EXPECT_THAT(state, HasCopyMoveCounts(1, 0)); - EXPECT_THAT(state, NoAssignments()); - EXPECT_THAT(state, NoMoves()); - - TProbe copy2 = TProbe::ExplicitlyCreateInvalidProbe(); - copy2 = probe; - EXPECT_EQ(1, state.CopyAssignments); -} - -TEST(ProbeTest, Move) { - TProbeState state; - TProbe probe(&state); - TProbe probe2(std::move(probe)); - EXPECT_FALSE(probe.IsValid()); - EXPECT_THAT(state, NoCopies()); - - EXPECT_THAT(state, HasCopyMoveCounts(0, 1)); - - TProbe probe3 = TProbe::ExplicitlyCreateInvalidProbe(); - probe3 = std::move(probe2); - EXPECT_EQ(1, state.MoveAssignments); -} +#include <library/cpp/testing/gtest/gtest.h> + +using namespace testing; + +TEST(ProbeStateTest, Example) { + // check that our test function does not make a copy of passed argument + auto copyless = [](auto&& x) { + TProbe p(std::move(x)); + p.Touch(); + return p; + }; + + TProbeState state; + auto probe = copyless(TProbe(&state)); + EXPECT_EQ(1, state.Touches); + EXPECT_THAT(state, HasCopyMoveCounts(0, 2)); +} + +TEST(ProbeTest, Construct) { + TProbeState state; + { + TProbe probe(&state); + EXPECT_THAT(state, IsAlive()); + } + EXPECT_THAT(state, IsDead()); +} + +TEST(ProbeTest, Copy) { + TProbeState state; + + TProbe probe(&state); + TProbe copy(probe); + EXPECT_THAT(state, HasCopyMoveCounts(1, 0)); + EXPECT_THAT(state, NoAssignments()); + EXPECT_THAT(state, NoMoves()); + + TProbe copy2 = TProbe::ExplicitlyCreateInvalidProbe(); + copy2 = probe; + EXPECT_EQ(1, state.CopyAssignments); +} + +TEST(ProbeTest, Move) { + TProbeState state; + TProbe probe(&state); + TProbe probe2(std::move(probe)); + EXPECT_FALSE(probe.IsValid()); + EXPECT_THAT(state, NoCopies()); + + EXPECT_THAT(state, HasCopyMoveCounts(0, 1)); + + TProbe probe3 = TProbe::ExplicitlyCreateInvalidProbe(); + probe3 = std::move(probe2); + EXPECT_EQ(1, state.MoveAssignments); +} diff --git a/library/cpp/testing/gtest_extensions/ut/ya.make b/library/cpp/testing/gtest_extensions/ut/ya.make index 39b41cecfd..ca333b4905 100644 --- a/library/cpp/testing/gtest_extensions/ut/ya.make +++ b/library/cpp/testing/gtest_extensions/ut/ya.make @@ -10,7 +10,7 @@ OWNER( SRCS( gtest_extensions_ut.cpp - probe_ut.cpp + probe_ut.cpp ) PEERDIR( diff --git a/library/cpp/testing/gtest_extensions/ya.make b/library/cpp/testing/gtest_extensions/ya.make index e24e81e8bd..4537d0153f 100644 --- a/library/cpp/testing/gtest_extensions/ya.make +++ b/library/cpp/testing/gtest_extensions/ya.make @@ -9,8 +9,8 @@ OWNER( ) PEERDIR( - contrib/restricted/googletest/googlemock - contrib/restricted/googletest/googletest + contrib/restricted/googletest/googlemock + contrib/restricted/googletest/googletest ) SRCS( @@ -18,7 +18,7 @@ SRCS( gtest_extensions.cpp matchers.cpp pretty_printers.cpp - probe.cpp + probe.cpp ) END() diff --git a/library/cpp/testing/hook/README.md b/library/cpp/testing/hook/README.md index fac8b32ef5..ffab40a960 100644 --- a/library/cpp/testing/hook/README.md +++ b/library/cpp/testing/hook/README.md @@ -1,25 +1,25 @@ -# Hook for google benchmark and gtest - -Y_TEST_HOOK_BEFORE_INIT - вызывается перед инициализацией соотвествующего фреймворка -Y_TEST_HOOK_BEFORE_RUN - вызывается перед запуском тестов -Y_TEST_HOOK_AFTER_RUN - вызывается всегда после завершения выполнения тестов, - если этап инициализации был успешным - -## Примеры: - -``` -Y_TEST_HOOK_BEFORE_INIT(SetupMyApp) { - // ваш код для выполнения перед инициализацией фреймворка -} - -Y_TEST_HOOK_BEFORE_RUN(InitMyApp) { - // ваш код для выполнения перед запуском тестов -} - -Y_TEST_HOOK_AFTER_RUN(CleanMyApp) { - // ваш код для выполнения после завершения тестов -} -``` - -## Тесты: -тесты лаунчерах соотвествующих фреймворков (gtest, gbenchmark и unittest) +# Hook for google benchmark and gtest + +Y_TEST_HOOK_BEFORE_INIT - вызывается перед инициализацией соотвествующего фреймворка +Y_TEST_HOOK_BEFORE_RUN - вызывается перед запуском тестов +Y_TEST_HOOK_AFTER_RUN - вызывается всегда после завершения выполнения тестов, + если этап инициализации был успешным + +## Примеры: + +``` +Y_TEST_HOOK_BEFORE_INIT(SetupMyApp) { + // ваш код для выполнения перед инициализацией фреймворка +} + +Y_TEST_HOOK_BEFORE_RUN(InitMyApp) { + // ваш код для выполнения перед запуском тестов +} + +Y_TEST_HOOK_AFTER_RUN(CleanMyApp) { + // ваш код для выполнения после завершения тестов +} +``` + +## Тесты: +тесты лаунчерах соотвествующих фреймворков (gtest, gbenchmark и unittest) diff --git a/library/cpp/testing/hook/hook.cpp b/library/cpp/testing/hook/hook.cpp index b3c599da89..f5daca11cb 100644 --- a/library/cpp/testing/hook/hook.cpp +++ b/library/cpp/testing/hook/hook.cpp @@ -1,45 +1,45 @@ -#include "hook.h" - -namespace { - NTesting::THook* BeforeInitHead = nullptr; - NTesting::THook* BeforeRunHead = nullptr; - NTesting::THook* AfterRunHead = nullptr; - - void RegisterHook(NTesting::THook*& head, NTesting::THook* hook) { - hook->Next = head; - head = hook; - } - - void CallHooks(NTesting::THook* head) { - while (nullptr != head) { - if (nullptr != head->Fn) { - (*head->Fn)(); - } - head = head->Next; - } - } -} - -void NTesting::THook::RegisterBeforeInit(NTesting::THook* hook) noexcept { - RegisterHook(BeforeInitHead, hook); -} - -void NTesting::THook::CallBeforeInit() { - CallHooks(BeforeInitHead); -} - -void NTesting::THook::RegisterBeforeRun(NTesting::THook* hook) noexcept { - RegisterHook(BeforeRunHead, hook); -} - -void NTesting::THook::CallBeforeRun() { - CallHooks(BeforeRunHead); -} - -void NTesting::THook::RegisterAfterRun(NTesting::THook* hook) noexcept { - RegisterHook(AfterRunHead, hook); -} - -void NTesting::THook::CallAfterRun() { - CallHooks(AfterRunHead); -} +#include "hook.h" + +namespace { + NTesting::THook* BeforeInitHead = nullptr; + NTesting::THook* BeforeRunHead = nullptr; + NTesting::THook* AfterRunHead = nullptr; + + void RegisterHook(NTesting::THook*& head, NTesting::THook* hook) { + hook->Next = head; + head = hook; + } + + void CallHooks(NTesting::THook* head) { + while (nullptr != head) { + if (nullptr != head->Fn) { + (*head->Fn)(); + } + head = head->Next; + } + } +} + +void NTesting::THook::RegisterBeforeInit(NTesting::THook* hook) noexcept { + RegisterHook(BeforeInitHead, hook); +} + +void NTesting::THook::CallBeforeInit() { + CallHooks(BeforeInitHead); +} + +void NTesting::THook::RegisterBeforeRun(NTesting::THook* hook) noexcept { + RegisterHook(BeforeRunHead, hook); +} + +void NTesting::THook::CallBeforeRun() { + CallHooks(BeforeRunHead); +} + +void NTesting::THook::RegisterAfterRun(NTesting::THook* hook) noexcept { + RegisterHook(AfterRunHead, hook); +} + +void NTesting::THook::CallAfterRun() { + CallHooks(AfterRunHead); +} diff --git a/library/cpp/testing/hook/hook.h b/library/cpp/testing/hook/hook.h index c45289cb22..1287e946c0 100644 --- a/library/cpp/testing/hook/hook.h +++ b/library/cpp/testing/hook/hook.h @@ -1,128 +1,128 @@ -#pragma once - -namespace NTesting { - /** - * Hook class and registration system. - * - * Default implementation of the `main` function for G_BENCHMARK and GTEST calls these hooks when executing. - * This is a useful feature if you want to customize behaviour of the `main` function, - * but you don't want to write `main` yourself. - * - * Hooks form an intrusive linked list that's built at application startup. Note that hooks execute - * in arbitrary order. - * - * Use macros below to define hooks. - */ - struct THook { - using TFn = void (*)(); - - TFn Fn = nullptr; - THook* Next = nullptr; - - static void RegisterBeforeInit(THook* hook) noexcept; - - static void CallBeforeInit(); - - struct TRegisterBeforeInit { - explicit TRegisterBeforeInit(THook* hook) noexcept { - THook::RegisterBeforeInit(hook); - } - }; - - static void RegisterBeforeRun(THook* hook) noexcept; - - static void CallBeforeRun(); - - struct TRegisterBeforeRun { - explicit TRegisterBeforeRun(THook* hook) noexcept { - THook::RegisterBeforeRun(hook); - } - }; - - static void RegisterAfterRun(THook* hook) noexcept; - - static void CallAfterRun(); - - struct TRegisterAfterRun { - explicit TRegisterAfterRun(THook* hook) noexcept { - THook::RegisterAfterRun(hook); - } - }; - }; - - /** - * Called right before initializing test programm - * - * This hook is intended for setting up default parameters. If you're doing initialization, consider - * using `Y_TEST_HOOK_BEFORE_RUN` instead. - * - * *Note:* hooks execute in arbitrary order. - * - * - * # Usage - * - * Instantiate this class in a cpp file. Pass a unique name for your hook, - * implement body right after macro instantiation: - * - * ``` - * Y_TEST_HOOK_BEFORE_INIT(SetupParams) { - * // hook code - * } - * ``` - */ -#define Y_TEST_HOOK_BEFORE_INIT(N) \ - void N(); \ - ::NTesting::THook N##Hook{&N, nullptr}; \ - ::NTesting::THook::TRegisterBeforeInit N##HookReg{&N##Hook}; \ - void N() - - /** - * Called right before launching tests. - * - * Hooks execute in arbitrary order. As such, we recommend using this hook to set up an event listener, - * and performing initialization and cleanup in the corresponding event handlers. This is better than performing - * initialization and cleanup directly in the hook's code because it gives more control over - * order in which initialization is performed. - * - * - * # Usage - * - * Instantiate this class in a cpp file. Pass a unique name for your hook, - * implement body right after macro instantiation: - * - * ``` - * Y_TEST_HOOK_BEFORE_RUN(InitMyApp) { - * // hook code - * } - * ``` - */ -#define Y_TEST_HOOK_BEFORE_RUN(N) \ - void N(); \ - ::NTesting::THook N##Hook{&N, nullptr}; \ - ::NTesting::THook::TRegisterBeforeRun N##HookReg{&N##Hook}; \ - void N() - - /** - * Called after all tests has finished, just before program exit. - * - * This hook is intended for simple cleanup routines that don't care about order in which hooks are executed. - * For more complex cases, we recommend using `Y_TEST_HOOK_BEFORE_RUN`. - * - * - * # Usage - * - * Instantiate this class in a cpp file. Pass a unique name for your hook, - * implement body right after macro instantiation: - * - * ``` - * Y_TEST_HOOK_AFTER_RUN(StopMyApp) { - * // hook code - * } - * ``` - */ -#define Y_TEST_HOOK_AFTER_RUN(N) \ - void N(); \ - ::NTesting::THook N##Hook{&N, nullptr}; \ - ::NTesting::THook::TRegisterAfterRun N##HookReg{&N##Hook}; \ - void N() -} +#pragma once + +namespace NTesting { + /** + * Hook class and registration system. + * + * Default implementation of the `main` function for G_BENCHMARK and GTEST calls these hooks when executing. + * This is a useful feature if you want to customize behaviour of the `main` function, + * but you don't want to write `main` yourself. + * + * Hooks form an intrusive linked list that's built at application startup. Note that hooks execute + * in arbitrary order. + * + * Use macros below to define hooks. + */ + struct THook { + using TFn = void (*)(); + + TFn Fn = nullptr; + THook* Next = nullptr; + + static void RegisterBeforeInit(THook* hook) noexcept; + + static void CallBeforeInit(); + + struct TRegisterBeforeInit { + explicit TRegisterBeforeInit(THook* hook) noexcept { + THook::RegisterBeforeInit(hook); + } + }; + + static void RegisterBeforeRun(THook* hook) noexcept; + + static void CallBeforeRun(); + + struct TRegisterBeforeRun { + explicit TRegisterBeforeRun(THook* hook) noexcept { + THook::RegisterBeforeRun(hook); + } + }; + + static void RegisterAfterRun(THook* hook) noexcept; + + static void CallAfterRun(); + + struct TRegisterAfterRun { + explicit TRegisterAfterRun(THook* hook) noexcept { + THook::RegisterAfterRun(hook); + } + }; + }; + + /** + * Called right before initializing test programm + * + * This hook is intended for setting up default parameters. If you're doing initialization, consider + * using `Y_TEST_HOOK_BEFORE_RUN` instead. + * + * *Note:* hooks execute in arbitrary order. + * + * + * # Usage + * + * Instantiate this class in a cpp file. Pass a unique name for your hook, + * implement body right after macro instantiation: + * + * ``` + * Y_TEST_HOOK_BEFORE_INIT(SetupParams) { + * // hook code + * } + * ``` + */ +#define Y_TEST_HOOK_BEFORE_INIT(N) \ + void N(); \ + ::NTesting::THook N##Hook{&N, nullptr}; \ + ::NTesting::THook::TRegisterBeforeInit N##HookReg{&N##Hook}; \ + void N() + + /** + * Called right before launching tests. + * + * Hooks execute in arbitrary order. As such, we recommend using this hook to set up an event listener, + * and performing initialization and cleanup in the corresponding event handlers. This is better than performing + * initialization and cleanup directly in the hook's code because it gives more control over + * order in which initialization is performed. + * + * + * # Usage + * + * Instantiate this class in a cpp file. Pass a unique name for your hook, + * implement body right after macro instantiation: + * + * ``` + * Y_TEST_HOOK_BEFORE_RUN(InitMyApp) { + * // hook code + * } + * ``` + */ +#define Y_TEST_HOOK_BEFORE_RUN(N) \ + void N(); \ + ::NTesting::THook N##Hook{&N, nullptr}; \ + ::NTesting::THook::TRegisterBeforeRun N##HookReg{&N##Hook}; \ + void N() + + /** + * Called after all tests has finished, just before program exit. + * + * This hook is intended for simple cleanup routines that don't care about order in which hooks are executed. + * For more complex cases, we recommend using `Y_TEST_HOOK_BEFORE_RUN`. + * + * + * # Usage + * + * Instantiate this class in a cpp file. Pass a unique name for your hook, + * implement body right after macro instantiation: + * + * ``` + * Y_TEST_HOOK_AFTER_RUN(StopMyApp) { + * // hook code + * } + * ``` + */ +#define Y_TEST_HOOK_AFTER_RUN(N) \ + void N(); \ + ::NTesting::THook N##Hook{&N, nullptr}; \ + ::NTesting::THook::TRegisterAfterRun N##HookReg{&N##Hook}; \ + void N() +} diff --git a/library/cpp/testing/hook/ya.make b/library/cpp/testing/hook/ya.make index db58f4e0ae..9f15673651 100644 --- a/library/cpp/testing/hook/ya.make +++ b/library/cpp/testing/hook/ya.make @@ -1,13 +1,13 @@ -LIBRARY() -OWNER( - amatanhead - bulatman - thegeorg - g:cpp-contrib -) - -SRCS( - hook.cpp -) - -END() +LIBRARY() +OWNER( + amatanhead + bulatman + thegeorg + g:cpp-contrib +) + +SRCS( + hook.cpp +) + +END() diff --git a/library/cpp/testing/unittest/env.h b/library/cpp/testing/unittest/env.h index 4807539ab2..ed4236e314 100644 --- a/library/cpp/testing/unittest/env.h +++ b/library/cpp/testing/unittest/env.h @@ -1,3 +1,3 @@ -// just shortcut -#include <library/cpp/testing/common/env.h> +// just shortcut +#include <library/cpp/testing/common/env.h> diff --git a/library/cpp/testing/unittest/plugin.h b/library/cpp/testing/unittest/plugin.h index 102f2c1469..abf70764d4 100644 --- a/library/cpp/testing/unittest/plugin.h +++ b/library/cpp/testing/unittest/plugin.h @@ -3,7 +3,7 @@ #include <util/generic/ptr.h> namespace NUnitTest { - // Plugins are deprecated, please use Y_TEST_HOOK_* from library/cpp/hook/hook.h + // Plugins are deprecated, please use Y_TEST_HOOK_* from library/cpp/hook/hook.h namespace NPlugin { class IPlugin { public: diff --git a/library/cpp/testing/unittest/tests_data.cpp b/library/cpp/testing/unittest/tests_data.cpp index b51cbc4b87..d7c7a40a0f 100644 --- a/library/cpp/testing/unittest/tests_data.cpp +++ b/library/cpp/testing/unittest/tests_data.cpp @@ -1,59 +1,59 @@ #include "tests_data.h" #include "registar.h" -#include <library/cpp/testing/common/network.h> - -#include <util/system/env.h> -#include <util/system/mutex.h> +#include <library/cpp/testing/common/network.h> +#include <util/system/env.h> +#include <util/system/mutex.h> + class TPortManager::TPortManagerImpl { public: - TPortManagerImpl(bool reservePortsForCurrentTest) - : EnableReservePortsForCurrentTest(reservePortsForCurrentTest) - , DisableRandomPorts(!GetEnv("NO_RANDOM_PORTS").empty()) + TPortManagerImpl(bool reservePortsForCurrentTest) + : EnableReservePortsForCurrentTest(reservePortsForCurrentTest) + , DisableRandomPorts(!GetEnv("NO_RANDOM_PORTS").empty()) { } ui16 GetPort(ui16 port) { - if (port && DisableRandomPorts) { + if (port && DisableRandomPorts) { return port; } - TAtomicSharedPtr<NTesting::IPort> holder(NTesting::GetFreePort().Release()); - ReservePortForCurrentTest(holder); + TAtomicSharedPtr<NTesting::IPort> holder(NTesting::GetFreePort().Release()); + ReservePortForCurrentTest(holder); - TGuard<TMutex> g(Lock); - ReservedPorts.push_back(holder); - return holder->Get(); - } + TGuard<TMutex> g(Lock); + ReservedPorts.push_back(holder); + return holder->Get(); + } - ui16 GetUdpPort(ui16 port) { - return GetPort(port); - } + ui16 GetUdpPort(ui16 port) { + return GetPort(port); + } - ui16 GetTcpPort(ui16 port) { - return GetPort(port); + ui16 GetTcpPort(ui16 port) { + return GetPort(port); } ui16 GetTcpAndUdpPort(ui16 port) { - return GetPort(port); + return GetPort(port); } ui16 GetPortsRange(const ui16 startPort, const ui16 range) { - Y_UNUSED(startPort); - auto ports = NTesting::NLegacy::GetFreePortsRange(range); - ui16 first = ports[0]; + Y_UNUSED(startPort); + auto ports = NTesting::NLegacy::GetFreePortsRange(range); + ui16 first = ports[0]; TGuard<TMutex> g(Lock); - for (auto& port : ports) { - ReservedPorts.emplace_back(port.Release()); - ReservePortForCurrentTest(ReservedPorts.back()); + for (auto& port : ports) { + ReservedPorts.emplace_back(port.Release()); + ReservePortForCurrentTest(ReservedPorts.back()); } - return first; + return first; } private: - void ReservePortForCurrentTest(const TAtomicSharedPtr<NTesting::IPort>& portGuard) { - if (EnableReservePortsForCurrentTest) { + void ReservePortForCurrentTest(const TAtomicSharedPtr<NTesting::IPort>& portGuard) { + if (EnableReservePortsForCurrentTest) { TTestBase* currentTest = NUnitTest::NPrivate::GetCurrentTest(); if (currentTest != nullptr) { currentTest->RunAfterTest([guard = portGuard]() mutable { @@ -65,13 +65,13 @@ private: private: TMutex Lock; - TVector<TAtomicSharedPtr<NTesting::IPort>> ReservedPorts; - const bool EnableReservePortsForCurrentTest; - const bool DisableRandomPorts; + TVector<TAtomicSharedPtr<NTesting::IPort>> ReservedPorts; + const bool EnableReservePortsForCurrentTest; + const bool DisableRandomPorts; }; -TPortManager::TPortManager(bool reservePortsForCurrentTest) - : Impl_(new TPortManagerImpl(reservePortsForCurrentTest)) +TPortManager::TPortManager(bool reservePortsForCurrentTest) + : Impl_(new TPortManagerImpl(reservePortsForCurrentTest)) { } @@ -99,6 +99,6 @@ ui16 TPortManager::GetPortsRange(const ui16 startPort, const ui16 range) { } ui16 GetRandomPort() { - TPortManager* pm = Singleton<TPortManager>(false); + TPortManager* pm = Singleton<TPortManager>(false); return pm->GetPort(); } diff --git a/library/cpp/testing/unittest/tests_data.h b/library/cpp/testing/unittest/tests_data.h index 6536bc1ae6..ff542d2c64 100644 --- a/library/cpp/testing/unittest/tests_data.h +++ b/library/cpp/testing/unittest/tests_data.h @@ -1,7 +1,7 @@ #pragma once -#include <library/cpp/testing/common/env.h> - +#include <library/cpp/testing/common/env.h> + #include <util/generic/noncopyable.h> #include <util/generic/ptr.h> #include <util/generic/string.h> @@ -29,7 +29,7 @@ void SetReuseAddressAndPort(const TSocketType& sock) { class TPortManager: public TNonCopyable { public: - TPortManager(bool reservePortsForCurrentTest = true); + TPortManager(bool reservePortsForCurrentTest = true); ~TPortManager(); // Gets free TCP port diff --git a/library/cpp/testing/unittest/utmain.cpp b/library/cpp/testing/unittest/utmain.cpp index 305bc6b40f..a5b74ee801 100644 --- a/library/cpp/testing/unittest/utmain.cpp +++ b/library/cpp/testing/unittest/utmain.cpp @@ -7,13 +7,13 @@ #include <library/cpp/json/writer/json.h> #include <library/cpp/json/writer/json_value.h> #include <library/cpp/testing/common/env.h> -#include <library/cpp/testing/hook/hook.h> +#include <library/cpp/testing/hook/hook.h> #include <util/datetime/base.h> #include <util/generic/hash.h> #include <util/generic/hash_set.h> -#include <util/generic/scope.h> +#include <util/generic/scope.h> #include <util/generic/string.h> #include <util/generic/yexception.h> @@ -647,7 +647,7 @@ int NUnitTest::RunMain(int argc, char** argv) { Y_VERIFY(!sigaction(SIGUSR2, &sa, nullptr)); } #endif - NTesting::THook::CallBeforeInit(); + NTesting::THook::CallBeforeInit(); InitNetworkSubSystem(); try { @@ -658,11 +658,11 @@ int NUnitTest::RunMain(int argc, char** argv) { #ifndef UT_SKIP_EXCEPTIONS try { #endif - NTesting::THook::CallBeforeRun(); - Y_DEFER { NTesting::THook::CallAfterRun(); }; - + NTesting::THook::CallBeforeRun(); + Y_DEFER { NTesting::THook::CallAfterRun(); }; + NPlugin::OnStartMain(argc, argv); - Y_DEFER { NPlugin::OnStopMain(argc, argv); }; + Y_DEFER { NPlugin::OnStopMain(argc, argv); }; TColoredProcessor processor(GetExecPath()); IOutputStream* listStream = &Cout; @@ -749,18 +749,18 @@ int NUnitTest::RunMain(int argc, char** argv) { TTestFactory::Instance().SetProcessor(&processor); - unsigned ret; + unsigned ret; for (;;) { - ret = TTestFactory::Instance().Execute(); + ret = TTestFactory::Instance().Execute(); if (!processor.GetIsForked() && ret && processor.GetPrintSummary()) { Cerr << "SOME TESTS FAILED!!!!" << Endl; } - if (0 != ret || !processor.IsLoop()) { - break; + if (0 != ret || !processor.IsLoop()) { + break; } } - return ret; + return ret; #ifndef UT_SKIP_EXCEPTIONS } catch (...) { Cerr << "caught exception in test suite(" << CurrentExceptionMessage() << ")" << Endl; diff --git a/library/cpp/testing/unittest/ya.make b/library/cpp/testing/unittest/ya.make index aaa4f2ba85..f291fec2cb 100644 --- a/library/cpp/testing/unittest/ya.make +++ b/library/cpp/testing/unittest/ya.make @@ -12,8 +12,8 @@ PEERDIR( library/cpp/dbg_output library/cpp/diff library/cpp/json/writer - library/cpp/testing/common - library/cpp/testing/hook + library/cpp/testing/common + library/cpp/testing/hook ) SRCS( @@ -26,8 +26,8 @@ SRCS( ) END() - -RECURSE_FOR_TESTS( - fat - ut -) + +RECURSE_FOR_TESTS( + fat + ut +) diff --git a/library/cpp/testing/ya.make b/library/cpp/testing/ya.make index 6a57ac2ee6..735b4f678b 100644 --- a/library/cpp/testing/ya.make +++ b/library/cpp/testing/ya.make @@ -1,5 +1,5 @@ RECURSE( - common + common benchmark benchmark/examples benchmark/examples/metrics @@ -7,16 +7,16 @@ RECURSE( boost_test boost_test_main dump_clang_coverage - gbenchmark_main + gbenchmark_main gmock gmock_in_unittest gmock_in_unittest/example_ut gtest - gtest_boost_extensions + gtest_boost_extensions gtest_extensions gtest_main - gtest_protobuf - hook + gtest_protobuf + hook mock_server unittest unittest_main diff --git a/library/cpp/threading/future/perf/ya.make b/library/cpp/threading/future/perf/ya.make index 943d585d4b..b29a408f49 100644 --- a/library/cpp/threading/future/perf/ya.make +++ b/library/cpp/threading/future/perf/ya.make @@ -1,4 +1,4 @@ -Y_BENCHMARK(library-threading-future-perf) +Y_BENCHMARK(library-threading-future-perf) OWNER( g:rtmr diff --git a/library/cpp/yt/memory/intrusive_ptr.h b/library/cpp/yt/memory/intrusive_ptr.h index 3dead7db1d..6aa0f0dc90 100644 --- a/library/cpp/yt/memory/intrusive_ptr.h +++ b/library/cpp/yt/memory/intrusive_ptr.h @@ -223,38 +223,38 @@ Y_FORCE_INLINE TIntrusivePtr<T> DangerousGetPtr(T* object) //////////////////////////////////////////////////////////////////////////////// -template <class T, class U> -TIntrusivePtr<T> StaticPointerCast(const TIntrusivePtr<U>& ptr) -{ - return {static_cast<T*>(ptr.Get())}; -} - -template <class T, class U> -TIntrusivePtr<T> StaticPointerCast(TIntrusivePtr<U>&& ptr) -{ - return {static_cast<T*>(ptr.Release()), false}; -} - -template <class T, class U> -TIntrusivePtr<T> ConstPointerCast(const TIntrusivePtr<U>& ptr) -{ - return {const_cast<T*>(ptr.Get())}; -} - -template <class T, class U> -TIntrusivePtr<T> ConstPointerCast(TIntrusivePtr<U>&& ptr) -{ - return {const_cast<T*>(ptr.Release()), false}; -} - -template <class T, class U> -TIntrusivePtr<T> DynamicPointerCast(const TIntrusivePtr<U>& ptr) -{ - return {dynamic_cast<T*>(ptr.Get())}; -} - -//////////////////////////////////////////////////////////////////////////////// - +template <class T, class U> +TIntrusivePtr<T> StaticPointerCast(const TIntrusivePtr<U>& ptr) +{ + return {static_cast<T*>(ptr.Get())}; +} + +template <class T, class U> +TIntrusivePtr<T> StaticPointerCast(TIntrusivePtr<U>&& ptr) +{ + return {static_cast<T*>(ptr.Release()), false}; +} + +template <class T, class U> +TIntrusivePtr<T> ConstPointerCast(const TIntrusivePtr<U>& ptr) +{ + return {const_cast<T*>(ptr.Get())}; +} + +template <class T, class U> +TIntrusivePtr<T> ConstPointerCast(TIntrusivePtr<U>&& ptr) +{ + return {const_cast<T*>(ptr.Release()), false}; +} + +template <class T, class U> +TIntrusivePtr<T> DynamicPointerCast(const TIntrusivePtr<U>& ptr) +{ + return {dynamic_cast<T*>(ptr.Get())}; +} + +//////////////////////////////////////////////////////////////////////////////// + template <class T> bool operator<(const TIntrusivePtr<T>& lhs, const TIntrusivePtr<T>& rhs) { @@ -321,30 +321,30 @@ bool operator!=(T* lhs, const TIntrusivePtr<U>& rhs) return lhs != rhs.Get(); } -template <class T> -bool operator==(std::nullptr_t, const TIntrusivePtr<T>& rhs) -{ - return nullptr == rhs.Get(); -} - -template <class T> -bool operator!=(std::nullptr_t, const TIntrusivePtr<T>& rhs) -{ - return nullptr != rhs.Get(); -} - -template <class T> -bool operator==(const TIntrusivePtr<T>& lhs, std::nullptr_t) -{ - return nullptr == lhs.Get(); -} - -template <class T> -bool operator!=(const TIntrusivePtr<T>& lhs, std::nullptr_t) -{ - return nullptr != lhs.Get(); -} - +template <class T> +bool operator==(std::nullptr_t, const TIntrusivePtr<T>& rhs) +{ + return nullptr == rhs.Get(); +} + +template <class T> +bool operator!=(std::nullptr_t, const TIntrusivePtr<T>& rhs) +{ + return nullptr != rhs.Get(); +} + +template <class T> +bool operator==(const TIntrusivePtr<T>& lhs, std::nullptr_t) +{ + return nullptr == lhs.Get(); +} + +template <class T> +bool operator!=(const TIntrusivePtr<T>& lhs, std::nullptr_t) +{ + return nullptr != lhs.Get(); +} + //////////////////////////////////////////////////////////////////////////////// } //namespace NYT diff --git a/library/cpp/yt/memory/ref_counted-inl.h b/library/cpp/yt/memory/ref_counted-inl.h index e6d64fec18..89894619bd 100644 --- a/library/cpp/yt/memory/ref_counted-inl.h +++ b/library/cpp/yt/memory/ref_counted-inl.h @@ -143,7 +143,7 @@ struct TRefCountedHelper return reinterpret_cast<const TRefCounter*>(obj) - 1; } - Y_FORCE_INLINE static void Destroy(const T* obj) + Y_FORCE_INLINE static void Destroy(const T* obj) { auto* refCounter = GetRefCounter(obj); @@ -163,7 +163,7 @@ struct TRefCountedHelper } } - Y_FORCE_INLINE static void Deallocate(const T* obj) + Y_FORCE_INLINE static void Deallocate(const T* obj) { char* ptr = reinterpret_cast<char*>(const_cast<TRefCounter*>(GetRefCounter(obj))); TMemoryReleaser<T>::Do(ptr - RefCounterOffset, RefCounterSpace); @@ -196,19 +196,19 @@ struct TRefCountedHelper<T, true> //////////////////////////////////////////////////////////////////////////////// template <class T> -Y_FORCE_INLINE const TRefCounter* GetRefCounter(const T* obj) +Y_FORCE_INLINE const TRefCounter* GetRefCounter(const T* obj) { return TRefCountedHelper<T>::GetRefCounter(obj); } template <class T> -Y_FORCE_INLINE void DestroyRefCounted(const T* obj) +Y_FORCE_INLINE void DestroyRefCounted(const T* obj) { TRefCountedHelper<T>::Destroy(obj); } template <class T> -Y_FORCE_INLINE void DeallocateRefCounted(const T* obj) +Y_FORCE_INLINE void DeallocateRefCounted(const T* obj) { TRefCountedHelper<T>::Deallocate(obj); } diff --git a/library/cpp/yt/memory/ref_counted.h b/library/cpp/yt/memory/ref_counted.h index b683615b83..2443675def 100644 --- a/library/cpp/yt/memory/ref_counted.h +++ b/library/cpp/yt/memory/ref_counted.h @@ -90,13 +90,13 @@ private: //////////////////////////////////////////////////////////////////////////////// template <class T> -const TRefCounter* GetRefCounter(const T* obj); +const TRefCounter* GetRefCounter(const T* obj); template <class T> -void DestroyRefCounted(const T* obj); +void DestroyRefCounted(const T* obj); template <class T> -void DeallocateRefCounted(const T* obj); +void DeallocateRefCounted(const T* obj); //////////////////////////////////////////////////////////////////////////////// diff --git a/library/python/pytest/plugins/fixtures.py b/library/python/pytest/plugins/fixtures.py index 6f7e0a27e4..8035a2bb20 100644 --- a/library/python/pytest/plugins/fixtures.py +++ b/library/python/pytest/plugins/fixtures.py @@ -1,6 +1,6 @@ import os import pytest -import six +import six MAX_ALLOWED_LINKS_COUNT = 10 @@ -21,35 +21,35 @@ def metrics(request): @classmethod def set_benchmark(cls, benchmark_values): - # report of google has key 'benchmarks' which is a list of benchmark results - # yandex benchmark has key 'benchmark', which is a list of benchmark results - # use this to differentiate which kind of result it is - if 'benchmarks' in benchmark_values: - cls.set_gbenchmark(benchmark_values) - else: - cls.set_ybenchmark(benchmark_values) - - @classmethod - def set_ybenchmark(cls, benchmark_values): + # report of google has key 'benchmarks' which is a list of benchmark results + # yandex benchmark has key 'benchmark', which is a list of benchmark results + # use this to differentiate which kind of result it is + if 'benchmarks' in benchmark_values: + cls.set_gbenchmark(benchmark_values) + else: + cls.set_ybenchmark(benchmark_values) + + @classmethod + def set_ybenchmark(cls, benchmark_values): for benchmark in benchmark_values["benchmark"]: name = benchmark["name"] for key, value in six.iteritems(benchmark): if key != "name": cls.set("{}_{}".format(name, key), value) - @classmethod - def set_gbenchmark(cls, benchmark_values): - time_unit_multipliers = {"ns": 1, "us": 1000, "ms": 1000000} - time_keys = {"real_time", "cpu_time"} - ignore_keys = {"name", "run_name", "time_unit", "run_type", "repetition_index"} - for benchmark in benchmark_values["benchmarks"]: - name = benchmark["name"].replace('/', '_') # ci does not work properly with '/' in metric name - time_unit_mult = time_unit_multipliers[benchmark.get("time_unit", "ns")] - for k, v in six.iteritems(benchmark): - if k in time_keys: - cls.set("{}_{}".format(name, k), v * time_unit_mult) - elif k not in ignore_keys and isinstance(v, (float, int)): - cls.set("{}_{}".format(name, k), v) + @classmethod + def set_gbenchmark(cls, benchmark_values): + time_unit_multipliers = {"ns": 1, "us": 1000, "ms": 1000000} + time_keys = {"real_time", "cpu_time"} + ignore_keys = {"name", "run_name", "time_unit", "run_type", "repetition_index"} + for benchmark in benchmark_values["benchmarks"]: + name = benchmark["name"].replace('/', '_') # ci does not work properly with '/' in metric name + time_unit_mult = time_unit_multipliers[benchmark.get("time_unit", "ns")] + for k, v in six.iteritems(benchmark): + if k in time_keys: + cls.set("{}_{}".format(name, k), v * time_unit_mult) + elif k not in ignore_keys and isinstance(v, (float, int)): + cls.set("{}_{}".format(name, k), v) return Metrics diff --git a/library/python/testing/yatest_common/yatest/common/benchmark.py b/library/python/testing/yatest_common/yatest/common/benchmark.py index c3784cbe4c..766d3a8968 100644 --- a/library/python/testing/yatest_common/yatest/common/benchmark.py +++ b/library/python/testing/yatest_common/yatest/common/benchmark.py @@ -8,12 +8,12 @@ def execute_benchmark(path, budget=None, threads=None): """ Run benchmark and return values :param path: path to benchmark binary - :param budget: time budget, sec (supported only by ybenchmark) - :param threads: number of threads to run benchmark (supported only by ybenchmark) + :param budget: time budget, sec (supported only by ybenchmark) + :param threads: number of threads to run benchmark (supported only by ybenchmark) :return: map of benchmark values """ benchmark_path = runtime.binary_path(path) - cmd = [benchmark_path, "--benchmark_format=json"] + cmd = [benchmark_path, "--benchmark_format=json"] if budget is not None: cmd += ["-b", str(budget)] if threads is not None: |