Cleaned up Azure::Core::Context API surface (#5676)

* Deprecated Azure::Core::ApplicationContext because its use is confusing and inconsistent with the original design. 

---------

Co-authored-by: Rick Winter <rick.winter@microsoft.com>
Co-authored-by: Anton Kolesnyk <41349689+antkmsft@users.noreply.github.com>
Co-authored-by: Ahson Khan <ahkha@microsoft.com>
This commit is contained in:
Larry Osterman 2024-07-17 12:38:30 -07:00 коммит произвёл GitHub
Родитель 2b987eeed8
Коммит 90089ad326
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: B5690EEEBB952194
59 изменённых файлов: 521 добавлений и 269 удалений

Просмотреть файл

@ -256,7 +256,7 @@ Running the above commands will create the test executable and run it. While it
If the coverage data has been previously generated (for example, if you manually run the unit tests), you can define `CODE_COVERAGE_COLLECT_ONLY` environment variable (set it to any value) and then the report will be generated without running the tests again. This is how the coverage reports are generated on CI, where the tests runs prior to code coverage step. If the coverage data has been previously generated (for example, if you manually run the unit tests), you can define `CODE_COVERAGE_COLLECT_ONLY` environment variable (set it to any value) and then the report will be generated without running the tests again. This is how the coverage reports are generated on CI, where the tests runs prior to code coverage step.
### Visual Studio 2019 ### Visual Studio 2019 or newer
You can also build the project by simply opening the repo directory in Visual Studio. Visual Studio will detect the `CMake` file and will configure itself to generate, build and run tests. You can also build the project by simply opening the repo directory in Visual Studio. Visual Studio will detect the `CMake` file and will configure itself to generate, build and run tests.

Просмотреть файл

@ -188,6 +188,69 @@ You can intermittently poll whether the operation has finished by using the `Pol
} }
``` ```
#### `Azure::Core::Context`
Most Azure SDK Service Client methods accept an optional `Azure::Core::Context` parameter, which is used to enable cancellation of the operation or to
establish an absolute deadline for the operation.
This is useful when you want to assign a time limit on an operation to ensure that it completes in a "reasonable" timeframe. For instance, the
snippet below will cancel a blob client upload after 5 seconds.
<!-- @insert_snippet: CreateBlobContext -->
```cpp
Azure::Core::Context cancelledIn5s{
std::chrono::system_clock::now() + std::chrono::seconds(5)};
auto containerClient = BlobContainerClient::CreateFromConnectionString(
GetConnectionString(), containerName + std::to_string(i));
containerClient.CreateIfNotExists({}, cancelledIn5s);
for (int j = 0; j < 3; ++j)
{
BlockBlobClient blobClient
= containerClient.GetBlockBlobClient(blobName + std::to_string(j));
blobClient.UploadFrom(
reinterpret_cast<const uint8_t*>(blobContent.data()),
blobContent.size(),
{},
cancelledIn5s);
}
```
`Context` objects can also be directly cancelled using the `Cancel()` method.
`Context` objects form a directed tree, where a child context can be created from a parent context.
The context tree is unidirectional and acyclic.
These are the basic operations that can be performed on a `Context` object:
* Create a child context from a parent context with a Key/Value pair. This is useful for associating metadata with a context.
* Create a child context from a parent context with a deadline. This is useful for setting a timeout.
* Cancel a context. This will cancel the context and all its children. Note that there is no way of un-cancelling a context.
* Check if a context is cancelled.
When a context is copied from another context, the copied context will share state with the original context.
This means that if the original context is cancelled, the copied context will also be cancelled.
Cancellation of a `Context` is a permanent operation. Once a context is cancelled, it cannot be un-cancelled.
When a client operation fails with an `Azure::Core::OperationCancelledException`, it is typically due to a `Context` getting cancelled. This exception can be caught and handled by the application.
#### Public, Private, and Internal Types
For the most part, the APIs defined in the Azure SDK for C++ fall into three categories:
- **Public**: These are the types that are intended to be used by the consumers of the SDK.
They are part of the public API and are stable. Breaking changes to these types will be avoided as much
as possible. All public types and functions are located are in the `Azure` root namespace.
- **Internal**: These are the types that are used internally by the packages within the SDK.
They are intended for use by the packages which make up the Azure SDK. They are NOT intended to be used by the consumers of the SDK.
Breaking changes to these types are allowed, within certain constraints. These types are located in an `Azure` namespace within the `_internal` terminal namespace (for instance, `Azure::Core::Http::Policies::_internal::RequestActivityPolicy`).
- **Private**: These are the types that are used internally to individual Azure SDK Packages.
They are not intended to be used by the consumers of the SDK, nor by other SDK packages. Breaking changes
to these types are allowed. These types are located in an `Azure` namespace within the `_detail` terminal namespace.
Within the source tree, Internal types are typically declared in directories named "internal", and Private types are typically declared in directories named "private".
#### Interacting with Azure SDK for C++ #### Interacting with Azure SDK for C++
Static SDK members should not be accessed and SDK functions should not be called before the static initialization phase is finished. Static SDK members should not be accessed and SDK functions should not be called before the static initialization phase is finished.
@ -338,3 +401,4 @@ Azure SDK for C++ is licensed under the [MIT](https://github.com/Azure/azure-sdk
This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow [Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/legal/intellectualproperty/trademarks/usage/general). Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies. This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow [Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/legal/intellectualproperty/trademarks/usage/general). Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.
![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-cpp%2FREADME.png) ![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-cpp%2FREADME.png)

Просмотреть файл

@ -61,7 +61,7 @@ Contains one cpp file that contains the main method defintion
Service::Namespace::Test::TestName::GetTestMetadata(), Service::Namespace::Test::TestName::GetTestMetadata(),
}; };
Azure::Perf::Program::Run(Azure::Core::Context::ApplicationContext, tests, argc, argv); Azure::Perf::Program::Run(Azure::Core::Context{}, tests, argc, argv);
return 0; return 0;
} }

Просмотреть файл

@ -34,7 +34,7 @@ namespace Azure { namespace Service {
// token, which is not critical for the intended demonstration purposes. And if user runs this, // token, which is not critical for the intended demonstration purposes. And if user runs this,
// and authentication is unsuccessful, it may draw an unnecessary attention to an irrelevant (to // and authentication is unsuccessful, it may draw an unnecessary attention to an irrelevant (to
// the demo) point. // the demo) point.
void DoSomething(const Core::Context& context) const; void DoSomething(const Core::Context& context = {}) const;
}; };
}} // namespace Azure::Service }} // namespace Azure::Service

Просмотреть файл

@ -184,7 +184,7 @@ namespace Azure { namespace Security { namespace Attestation {
* specified service instance. * specified service instance.
*/ */
Response<Models::OpenIdMetadata> GetOpenIdMetadata( Response<Models::OpenIdMetadata> GetOpenIdMetadata(
Azure::Core::Context const& context = Azure::Core::Context::ApplicationContext) const; Azure::Core::Context const& context = {}) const;
/** /**
* @brief Retrieve the attestation signing certificates for this attestation instance. * @brief Retrieve the attestation signing certificates for this attestation instance.

Просмотреть файл

@ -168,8 +168,7 @@ namespace Azure { namespace Core { namespace Amqp { namespace Tests {
// Ensure that we got an OnComplete callback within 5 seconds. // Ensure that we got an OnComplete callback within 5 seconds.
auto transport = listenerEvents.WaitForResult( auto transport = listenerEvents.WaitForResult(
listener, listener,
Azure::Core::Context::ApplicationContext.WithDeadline( Azure::Core::Context{std::chrono::system_clock::now() + std::chrono::seconds(5)});
std::chrono::system_clock::now() + std::chrono::seconds(5)));
// Now we can close the connection. // Now we can close the connection.
connection.Close("xxx", "yyy", {}); connection.Close("xxx", "yyy", {});

Просмотреть файл

@ -359,8 +359,8 @@ namespace Azure { namespace Core { namespace Amqp { namespace Tests {
Azure::Core::Amqp::Common::_internal::AsyncOperationQueue<LinkState> m_linkStateQueue; Azure::Core::Amqp::Common::_internal::AsyncOperationQueue<LinkState> m_linkStateQueue;
}; };
Azure::Core::Context timeoutContext = Azure::Core::Context::ApplicationContext.WithDeadline( Azure::Core::Context timeoutContext
Azure::DateTime::clock::now() + std::chrono::seconds(60)); = Azure::Core::Context{Azure::DateTime::clock::now() + std::chrono::seconds(60)};
Link keepAliveLink{ Link keepAliveLink{
session, "KeepConnectionAlive", SessionRole::Receiver, "MyTarget", "TestReceiver"}; session, "KeepConnectionAlive", SessionRole::Receiver, "MyTarget", "TestReceiver"};
keepAliveLink.Attach(); keepAliveLink.Attach();

Просмотреть файл

@ -579,7 +579,7 @@ namespace Azure { namespace Core { namespace Amqp { namespace Tests {
"Type", "Type",
"Locales", "Locales",
messageToSend, messageToSend,
Azure::Core::Context::ApplicationContext.WithDeadline( Azure::Core::Context{}.WithDeadline(
std::chrono::system_clock::now() + std::chrono::seconds(10))); std::chrono::system_clock::now() + std::chrono::seconds(10)));
EXPECT_EQ(response.Status, ManagementOperationStatus::Error); EXPECT_EQ(response.Status, ManagementOperationStatus::Error);
EXPECT_EQ(response.StatusCode, 500); EXPECT_EQ(response.StatusCode, 500);

Просмотреть файл

@ -314,8 +314,8 @@ namespace Azure { namespace Core { namespace Amqp { namespace Tests {
Session session{connection.CreateSession()}; Session session{connection.CreateSession()};
// Set up a 30 second deadline on the receiver. // Set up a 30 second deadline on the receiver.
Azure::Core::Context receiveContext = Azure::Core::Context::ApplicationContext.WithDeadline( Azure::Core::Context receiveContext
Azure::DateTime::clock::now() + std::chrono::seconds(15)); = Azure::Core::Context{Azure::DateTime::clock::now() + std::chrono::seconds(15)};
// Ensure that the thread is started before we start using the message sender. // Ensure that the thread is started before we start using the message sender.
mockServer.StartListening(); mockServer.StartListening();
@ -793,8 +793,8 @@ namespace Azure { namespace Core { namespace Amqp { namespace Tests {
// Receive a message with a 15 second timeout. It shouldn't throw. // Receive a message with a 15 second timeout. It shouldn't throw.
{ {
Azure::Core::Context receiveContext{Azure::Core::Context::ApplicationContext.WithDeadline( Azure::Core::Context receiveContext{
std::chrono::system_clock::now() + std::chrono::seconds(15))}; std::chrono::system_clock::now() + std::chrono::seconds(15)};
// Tell the server it should send a message in the polling loop. // Tell the server it should send a message in the polling loop.
serviceEndpoint->ShouldSendMessage(true); serviceEndpoint->ShouldSendMessage(true);

Просмотреть файл

@ -148,8 +148,8 @@ Accept: */*
TEST_F(TestSocketTransport, SimpleOpen) TEST_F(TestSocketTransport, SimpleOpen)
{ {
// Wait until we receive data from the www.microsoft.com server, with a 10 second timeout. // Wait until we receive data from the www.microsoft.com server, with a 10 second timeout.
Azure::Core::Context completionContext = Azure::Core::Context::ApplicationContext.WithDeadline( Azure::Core::Context completionContext
std::chrono::system_clock::now() + std::chrono::seconds(10)); = Azure::Core::Context{std::chrono::system_clock::now() + std::chrono::seconds(10)};
{ {
Transport transport{SocketTransportFactory::Create("www.microsoft.com", 80)}; Transport transport{SocketTransportFactory::Create("www.microsoft.com", 80)};
@ -206,8 +206,7 @@ Accept: */*
// Wait until we receive data from the www.microsoft.com server, with a 10 second timeout. // Wait until we receive data from the www.microsoft.com server, with a 10 second timeout.
Azure::Core::Context completionContext Azure::Core::Context completionContext
= Azure::Core::Context::ApplicationContext.WithDeadline( = Azure::Core::Context{std::chrono::system_clock::now() + std::chrono::seconds(10)};
std::chrono::system_clock::now() + std::chrono::seconds(10));
ASSERT_EQ(TransportOpenStatus::Ok, transport.Open(completionContext)); ASSERT_EQ(TransportOpenStatus::Ok, transport.Open(completionContext));
unsigned char val[] = R"(GET / HTTP/1.1 unsigned char val[] = R"(GET / HTTP/1.1
@ -400,8 +399,7 @@ Host: www.microsoft.com)";
GTEST_LOG_(INFO) << "Wait for received event."; GTEST_LOG_(INFO) << "Wait for received event.";
events.WaitForReceive( events.WaitForReceive(
*listenerTransport, *listenerTransport,
Azure::Core::Context::ApplicationContext.WithDeadline( Azure::Core::Context{std::chrono::system_clock::now() + std::chrono::seconds(10)});
std::chrono::system_clock::now() + std::chrono::seconds(10)));
GTEST_LOG_(INFO) << "Listener received the bytes we just sent, now wait until the sender " GTEST_LOG_(INFO) << "Listener received the bytes we just sent, now wait until the sender "
"received those bytes back."; "received those bytes back.";

Просмотреть файл

@ -20,7 +20,7 @@
{ {
"name": "azure-core-cpp", "name": "azure-core-cpp",
"default-features": false, "default-features": false,
"version>=": "1.11.3" "version>=": "1.14.0-beta.1"
}, },
"azure-macro-utils-c", "azure-macro-utils-c",
"umock-c", "umock-c",

Просмотреть файл

@ -13,12 +13,6 @@ if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang|AppleClang")
add_compile_options(-Wno-error=deprecated-declarations) add_compile_options(-Wno-error=deprecated-declarations)
endif() endif()
if (CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
# Disable deprecation warnings.
add_compile_options(/wd4996)
endif()
project (azure-core-tracing-opentelemetry-test LANGUAGES CXX) project (azure-core-tracing-opentelemetry-test LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED True) set(CMAKE_CXX_STANDARD_REQUIRED True)

Просмотреть файл

@ -4,8 +4,14 @@
### Features Added ### Features Added
- Added new constructor for `Azure::Core::Context` that takes a `std::chrono::system_clock::time_point` deadline. This enables creating a new context directly with a deadline.
### Breaking Changes ### Breaking Changes
- Deprecated the `Azure::Core::Context::ApplicationContext` object.
- If customer code is using `Azure::Core::Context::ApplicationContext`, the customer should instead create their own root context object which is used
wherever the customer would have previously used `Azure::Core::Context::ApplicationContext`, i.e. `Azure::Core::Context(deadline)` instead of `Azure::Core::Context::ApplicationContext.WithDeadline(deadline)`.
### Bugs Fixed ### Bugs Fixed
### Other Changes ### Other Changes

Просмотреть файл

@ -10,7 +10,6 @@
#include "azure/core/azure_assert.hpp" #include "azure/core/azure_assert.hpp"
#include "azure/core/datetime.hpp" #include "azure/core/datetime.hpp"
#include "azure/core/dll_import_export.hpp"
#include "azure/core/rtti.hpp" #include "azure/core/rtti.hpp"
#include <atomic> #include <atomic>
@ -41,7 +40,34 @@ namespace Azure { namespace Core {
}; };
/** /**
* @brief A context is a node within a tree that represents deadlines and key/value pairs. * @brief A context is a node within a unidirectional tree that represents deadlines and key/value
* pairs.
*
* Most Azure Service Client operations accept a Context object. The Context object allows the
* caller to cancel the operation if it is taking too long, or to ensure that the operation
* completes before a specific deadline. This allows an application to apply timeouts to
* operations, or to cancel operations that need to be abandoned.
*
* After cancelling a Context, all service operations which have the cancelled context
* as a parent context will be cancelled. Cancellation is indicated by throwing an
* Azure::Core::OperationCancelledException from the operation.
*
* Context objects support the following operations to create new contexts:
* - WithDeadline(DateTime): creates a new child context with a deadline.
* - WithValue(Key, T): creates a new child context with a key/value pair.
*
* Context objects support the following operations to retrieve data:
* - GetDeadline(): gets the deadline for the context.
* - TryGetValue(Key, T): gets the value associated with a key.
*
* Context objects support two operations to manage the context:
* - Cancel(): cancels the context.
* - IsCancelled(): checks if the context is cancelled.
*
* Context objects support the following operation to throw if the context is cancelled:
* - ThrowIfCancelled(): throws an OperationCancelledException if the context is cancelled.
*
*
*/ */
class Context final { class Context final {
public: public:
@ -97,6 +123,14 @@ namespace Azure { namespace Core {
return DateTime(DateTime::time_point(DateTime::duration(dtRepresentation))); return DateTime(DateTime::time_point(DateTime::duration(dtRepresentation)));
} }
ContextSharedState(ContextSharedState const&) = delete;
ContextSharedState(ContextSharedState&&) = delete;
ContextSharedState& operator=(ContextSharedState const&) = delete;
ContextSharedState&& operator=(ContextSharedState&&) = delete;
/**
* @brief Creates a new ContextSharedState object with no deadline and no value.
*/
explicit ContextSharedState() explicit ContextSharedState()
: Deadline(ToDateTimeRepresentation((DateTime::max)())), Value(nullptr) : Deadline(ToDateTimeRepresentation((DateTime::max)())), Value(nullptr)
#if defined(AZ_CORE_RTTI) #if defined(AZ_CORE_RTTI)
@ -106,9 +140,16 @@ namespace Azure { namespace Core {
{ {
} }
/**
* @brief Create a new ContextSharedState from another ContextSharedState with a deadline.
*
* @param parent The parent context to create a child context from.
* @param deadline The deadline for the new context.
*
*/
explicit ContextSharedState( explicit ContextSharedState(
const std::shared_ptr<ContextSharedState>& parent, const std::shared_ptr<ContextSharedState>& parent,
DateTime const& deadline) DateTime const& deadline = (DateTime::max)())
: Parent(parent), Deadline(ToDateTimeRepresentation(deadline)), Value(nullptr) : Parent(parent), Deadline(ToDateTimeRepresentation(deadline)), Value(nullptr)
#if defined(AZ_CORE_RTTI) #if defined(AZ_CORE_RTTI)
, ,
@ -117,6 +158,17 @@ namespace Azure { namespace Core {
{ {
} }
/**
* @brief Create a new ContextSharedState from another ContextSharedState with a deadline and
* a key value pair.
*
* @tparam T The type of the value to be stored with the key.
* @param parent The parent context to create a child context from.
* @param deadline The deadline for the new context.
* @param key The key to associate with the value.
* @param value The value to associate with the key.
*
*/
template <class T> template <class T>
explicit ContextSharedState( explicit ContextSharedState(
const std::shared_ptr<ContextSharedState>& parent, const std::shared_ptr<ContextSharedState>& parent,
@ -142,13 +194,78 @@ namespace Azure { namespace Core {
public: public:
/** /**
* @brief Constructs a new context with no deadline, and no value associated. * @brief Constructs a context with no deadline, and no value associated.
* *
*/ */
Context() : m_contextSharedState(std::make_shared<ContextSharedState>()) {} Context() : m_contextSharedState(std::make_shared<ContextSharedState>()) {}
/** /**
* @brief Creates a context with a deadline. * @brief Constructs a context with a deadline
* object.
*
* @param deadline A point in time after which a context expires.
*
*/
explicit Context(DateTime const& deadline)
: m_contextSharedState(std::make_shared<ContextSharedState>(nullptr, deadline))
{
}
/**
* @brief Copies a context.
*
* This operation copies one context to another. Context objects are copied by reference,
* so the new context will share the same state as the original context. This also means
* that cancelling one context cancels all contexts which are copied from the original
* context.
*
* @param other Another context to copy.
*
*/
Context(Context const&) = default;
/**
* @brief Assigns a context.
*
* This operation assigns one context to another. Context objects are copied by reference, so
* the new context will share the same state as the original context. This also means that
* cancelling one context cancels all contexts which are copied from the original context.
*
* @param other Another context to assign.
*
* @return A new Context referencing the state of the original context.
*/
Context& operator=(Context const& other) = default;
/**
* @brief Moves a context.
*
* This operation moves one context to another.
*
* @param other The context to move.
*
*/
Context(Context&& other) = default;
/**
* @brief Moves a context.
*
* This operation moves one context to another.
*
* @param other The context to move.
* @return A new Context referencing the state of the original context.
*
*/
Context& operator=(Context&& other) = default;
/**
* @brief Destroys a context.
*
*/
~Context() = default;
/**
* @brief Creates a context with a deadline from an existing Context object.
* *
* @param deadline A point in time after which a context expires. * @param deadline A point in time after which a context expires.
* *
@ -160,13 +277,14 @@ namespace Azure { namespace Core {
} }
/** /**
* @brief Creates a context without a deadline, but with \p key and \p value associated with it. * @brief Creates a new child context with \p key and \p value
* associated with it.
* *
* @tparam T The type of the value to be stored with the key. * @tparam T The type of the value to be stored with the key.
* @param key A key to associate with this context. * @param key A key to associate with this context.
* @param value A value to associate with this context. * @param value A value to associate with this context.
* *
* @return A child context with no deadline and the \p key and \p value associated with it. * @return A child context with the \p key and \p value associated with it.
*/ */
template <class T> Context WithValue(Key const& key, T&& value) const template <class T> Context WithValue(Key const& key, T&& value) const
{ {
@ -200,7 +318,7 @@ namespace Azure { namespace Core {
*/ */
template <class T> bool TryGetValue(Key const& key, T& outputValue) const template <class T> bool TryGetValue(Key const& key, T& outputValue) const
{ {
for (auto ptr = m_contextSharedState; ptr; ptr = ptr->Parent) for (std::shared_ptr<ContextSharedState> ptr = m_contextSharedState; ptr; ptr = ptr->Parent)
{ {
if (ptr->Key == key) if (ptr->Key == key)
{ {
@ -217,7 +335,14 @@ namespace Azure { namespace Core {
} }
/** /**
* @brief Cancels the context. * @brief Cancels the context. All operations which share this Context will be cancelled.
*
* @note Cancellation of a Context is a best-faith effort. Because of the synchronous nature of
* Azure C++ SDK APIs, it is possible that the operation will not be cancelled immediately. Each
* operation explicitly checks the context's state to determine if it has been cancelled,
* those checks may not happen immediately, or at all.
*
* @note Once a context has been cancelled, the cancellation cannot be undone.
* *
*/ */
void Cancel() void Cancel()
@ -232,10 +357,9 @@ namespace Azure { namespace Core {
*/ */
bool IsCancelled() const { return GetDeadline() < std::chrono::system_clock::now(); } bool IsCancelled() const { return GetDeadline() < std::chrono::system_clock::now(); }
/** /** @brief Throws if the context is cancelled.
* @brief Checks if the context is cancelled.
* @throw #Azure::Core::OperationCancelledException if the context is cancelled.
* *
* @throw #Azure::Core::OperationCancelledException if the context is cancelled.
*/ */
void ThrowIfCancelled() const void ThrowIfCancelled() const
{ {
@ -245,10 +369,15 @@ namespace Azure { namespace Core {
} }
} }
/** /** @brief The `ApplicationContext` is a deprecated singleton Context object.
* @brief The application context (root). *
* @note: The `ApplicationContext` object is deprecated and will be removed in a future release.
* If your application is using `ApplicationContext`, you should create your own root context
* and use it where you would have otherwise used `ApplicationContext`.
* *
*/ */
static const AZ_CORE_DLLEXPORT Context ApplicationContext; [[deprecated(
"ApplicationContext is no longer supported. Instead customers should create their "
"own root context objects.")]] static const AZ_CORE_DLLEXPORT Context ApplicationContext;
}; };
}} // namespace Azure::Core }} // namespace Azure::Core

Просмотреть файл

@ -179,7 +179,7 @@ namespace Azure { namespace Core {
{ {
// In the cases where the customer doesn't want to use a context we new one up and pass it // In the cases where the customer doesn't want to use a context we new one up and pass it
// through // through
return Poll(Context::ApplicationContext); return Poll(Context{});
} }
/** /**

Просмотреть файл

@ -5,14 +5,34 @@
using namespace Azure::Core; using namespace Azure::Core;
// Disable deprecation warning
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4996)
#elif defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
const Context Context::ApplicationContext; const Context Context::ApplicationContext;
#if defined(_MSC_VER)
#pragma warning(pop)
#elif defined(__clang__)
#pragma clang diagnostic pop
#elif defined(__GNUC__)
#pragma GCC diagnostic pop
#endif // _MSC_VER
Azure::DateTime Azure::Core::Context::GetDeadline() const Azure::DateTime Azure::Core::Context::GetDeadline() const
{ {
// Contexts form a tree. Here, we walk from a node all the way back to the root in order to find // Contexts form a tree. Here, we walk from a node all the way back to the root in order to find
// the earliest deadline value. // the earliest deadline value.
auto result = (DateTime::max)(); auto result = (DateTime::max)();
for (auto ptr = m_contextSharedState; ptr; ptr = ptr->Parent) for (std::shared_ptr<ContextSharedState> ptr = m_contextSharedState; ptr; ptr = ptr->Parent)
{ {
auto deadline = ContextSharedState::FromDateTimeRepresentation(ptr->Deadline); auto deadline = ContextSharedState::FromDateTimeRepresentation(ptr->Deadline);
if (result > deadline) if (result > deadline)

Просмотреть файл

@ -30,7 +30,7 @@ int main(int argc, char** argv)
Azure::Core::Test::PipelineTest::GetTestMetadata(), Azure::Core::Test::PipelineTest::GetTestMetadata(),
Azure::Core::Test::UuidTest::GetTestMetadata()}; Azure::Core::Test::UuidTest::GetTestMetadata()};
Azure::Perf::Program::Run(Azure::Core::Context::ApplicationContext, tests, argc, argv); Azure::Perf::Program::Run(Azure::Core::Context{}, tests, argc, argv);
return 0; return 0;
} }

Просмотреть файл

@ -50,9 +50,9 @@ namespace Azure { namespace Core { namespace Test {
auto session auto session
= std::make_unique<Azure::Core::Http::CurlSession>(req, std::move(connection), options); = std::make_unique<Azure::Core::Http::CurlSession>(req, std::move(connection), options);
session->Perform(Azure::Core::Context::ApplicationContext); session->Perform(Azure::Core::Context{});
// Reading all the response // Reading all the response
session->ReadToEnd(Azure::Core::Context::ApplicationContext); session->ReadToEnd(Azure::Core::Context{});
// If all three of these conditions are true, the connection should be moved to the connection // If all three of these conditions are true, the connection should be moved to the connection
// pool. // pool.

Просмотреть файл

@ -68,9 +68,9 @@ TEST(BodyStream, BadInput)
{ {
TestBodyStream tb; TestBodyStream tb;
ASSERT_DEATH(tb.Read(NULL, 1), ""); ASSERT_DEATH(tb.Read(NULL, 1), "");
ASSERT_DEATH(tb.Read(NULL, 1, Azure::Core::Context::ApplicationContext), ""); ASSERT_DEATH(tb.Read(NULL, 1, Azure::Core::Context{}), "");
ASSERT_DEATH(tb.ReadToCount(NULL, 1), ""); ASSERT_DEATH(tb.ReadToCount(NULL, 1), "");
ASSERT_DEATH(tb.ReadToCount(NULL, 1, Azure::Core::Context::ApplicationContext), ""); ASSERT_DEATH(tb.ReadToCount(NULL, 1, Azure::Core::Context{}), "");
} }
TEST(MemoryBodyStream, BadInput) { ASSERT_DEATH(MemoryBodyStream(NULL, 1), ""); } TEST(MemoryBodyStream, BadInput) { ASSERT_DEATH(MemoryBodyStream(NULL, 1), ""); }
@ -100,7 +100,7 @@ TEST(FileBodyStream, Length)
Azure::Core::IO::FileBodyStream stream(testDataPath); Azure::Core::IO::FileBodyStream stream(testDataPath);
EXPECT_EQ(stream.Length(), FileSize); EXPECT_EQ(stream.Length(), FileSize);
auto readResult = stream.ReadToEnd(Azure::Core::Context::ApplicationContext); auto readResult = stream.ReadToEnd(Azure::Core::Context{});
EXPECT_EQ(readResult.size(), FileSize); EXPECT_EQ(readResult.size(), FileSize);
stream.Rewind(); stream.Rewind();
@ -120,7 +120,7 @@ TEST(FileBodyStream, Read)
stream.Rewind(); stream.Rewind();
readResult = stream.ReadToEnd(Azure::Core::Context::ApplicationContext); readResult = stream.ReadToEnd(Azure::Core::Context{});
EXPECT_EQ(readResult.size(), FileSize); EXPECT_EQ(readResult.size(), FileSize);
stream.Rewind(); stream.Rewind();
@ -134,7 +134,7 @@ TEST(FileBodyStream, Read)
stream.Rewind(); stream.Rewind();
readSize = stream.ReadToCount(buffer.data(), 10, Azure::Core::Context::ApplicationContext); readSize = stream.ReadToCount(buffer.data(), 10, Azure::Core::Context{});
EXPECT_EQ(readSize, 10); EXPECT_EQ(readSize, 10);
EXPECT_EQ(buffer[10], 0); EXPECT_EQ(buffer[10], 0);
@ -147,7 +147,7 @@ TEST(FileBodyStream, Read)
stream.Rewind(); stream.Rewind();
readSize = stream.Read(buffer.data(), buffer.size(), Azure::Core::Context::ApplicationContext); readSize = stream.Read(buffer.data(), buffer.size(), Azure::Core::Context{});
EXPECT_EQ(readSize, FileSize); EXPECT_EQ(readSize, FileSize);
EXPECT_EQ(buffer[FileSize], 0); EXPECT_EQ(buffer[FileSize], 0);
} }

Просмотреть файл

@ -76,23 +76,21 @@ TEST(ClientOptions, copyWithOperator)
options.PerRetryPolicies.emplace_back(std::make_unique<PerRetryPolicy>()); options.PerRetryPolicies.emplace_back(std::make_unique<PerRetryPolicy>());
// Now Copy // Now Copy
auto copyOptions = options; ClientOptions copyOptions = options;
// Compare // Compare
EXPECT_EQ(1, copyOptions.Retry.MaxRetries); EXPECT_EQ(1, copyOptions.Retry.MaxRetries);
EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId); EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId);
Request r(HttpMethod::Get, Url("")); Request r(HttpMethod::Get, Url(""));
auto result = copyOptions.Transport.Transport->Send(r, Context::ApplicationContext); auto result = copyOptions.Transport.Transport->Send(r, Context{});
EXPECT_EQ(nullptr, result); EXPECT_EQ(nullptr, result);
EXPECT_EQ(1, copyOptions.PerOperationPolicies.size()); EXPECT_EQ(1, copyOptions.PerOperationPolicies.size());
result = copyOptions.PerOperationPolicies[0]->Send( result = copyOptions.PerOperationPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{});
r, NextHttpPolicy(0, {}), Context::ApplicationContext);
EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase()); EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase());
EXPECT_EQ(1, copyOptions.PerRetryPolicies.size()); EXPECT_EQ(1, copyOptions.PerRetryPolicies.size());
result = copyOptions.PerRetryPolicies[0]->Send( result = copyOptions.PerRetryPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{});
r, NextHttpPolicy(0, {}), Context::ApplicationContext);
EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase()); EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase());
} }
@ -113,17 +111,15 @@ TEST(ClientOptions, copyWithConstructor)
EXPECT_EQ(1, copyOptions.Retry.MaxRetries); EXPECT_EQ(1, copyOptions.Retry.MaxRetries);
EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId); EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId);
Request r(HttpMethod::Get, Url("")); Request r(HttpMethod::Get, Url(""));
auto result = copyOptions.Transport.Transport->Send(r, Context::ApplicationContext); auto result = copyOptions.Transport.Transport->Send(r, Context{});
EXPECT_EQ(nullptr, result); EXPECT_EQ(nullptr, result);
EXPECT_EQ(1, copyOptions.PerOperationPolicies.size()); EXPECT_EQ(1, copyOptions.PerOperationPolicies.size());
result = copyOptions.PerOperationPolicies[0]->Send( result = copyOptions.PerOperationPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{});
r, NextHttpPolicy(0, {}), Context::ApplicationContext);
EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase()); EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase());
EXPECT_EQ(1, copyOptions.PerRetryPolicies.size()); EXPECT_EQ(1, copyOptions.PerRetryPolicies.size());
result = copyOptions.PerRetryPolicies[0]->Send( result = copyOptions.PerRetryPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{});
r, NextHttpPolicy(0, {}), Context::ApplicationContext);
EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase()); EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase());
} }
@ -151,17 +147,15 @@ TEST(ClientOptions, copyDerivedClassConstructor)
EXPECT_EQ(1, copyOptions.Retry.MaxRetries); EXPECT_EQ(1, copyOptions.Retry.MaxRetries);
EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId); EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId);
Request r(HttpMethod::Get, Url("")); Request r(HttpMethod::Get, Url(""));
auto result = copyOptions.Transport.Transport->Send(r, Context::ApplicationContext); auto result = copyOptions.Transport.Transport->Send(r, Context{});
EXPECT_EQ(nullptr, result); EXPECT_EQ(nullptr, result);
EXPECT_EQ(1, copyOptions.PerOperationPolicies.size()); EXPECT_EQ(1, copyOptions.PerOperationPolicies.size());
result = copyOptions.PerOperationPolicies[0]->Send( result = copyOptions.PerOperationPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{});
r, NextHttpPolicy(0, {}), Context::ApplicationContext);
EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase()); EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase());
EXPECT_EQ(1, copyOptions.PerRetryPolicies.size()); EXPECT_EQ(1, copyOptions.PerRetryPolicies.size());
result = copyOptions.PerRetryPolicies[0]->Send( result = copyOptions.PerRetryPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{});
r, NextHttpPolicy(0, {}), Context::ApplicationContext);
EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase()); EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase());
} }
@ -182,24 +176,22 @@ TEST(ClientOptions, copyDerivedClassOperator)
options.PerRetryPolicies.emplace_back(std::make_unique<PerRetryPolicy>()); options.PerRetryPolicies.emplace_back(std::make_unique<PerRetryPolicy>());
// Now Copy // Now Copy
auto copyOptions = options; ServiceClientOptions copyOptions = options;
// Compare // Compare
EXPECT_EQ("I am not real!", copyOptions.ApiVersion); EXPECT_EQ("I am not real!", copyOptions.ApiVersion);
EXPECT_EQ(1, copyOptions.Retry.MaxRetries); EXPECT_EQ(1, copyOptions.Retry.MaxRetries);
EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId); EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId);
Request r(HttpMethod::Get, Url("")); Request r(HttpMethod::Get, Url(""));
auto result = copyOptions.Transport.Transport->Send(r, Context::ApplicationContext); auto result = copyOptions.Transport.Transport->Send(r, Context{});
EXPECT_EQ(nullptr, result); EXPECT_EQ(nullptr, result);
EXPECT_EQ(1, copyOptions.PerOperationPolicies.size()); EXPECT_EQ(1, copyOptions.PerOperationPolicies.size());
result = copyOptions.PerOperationPolicies[0]->Send( result = copyOptions.PerOperationPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{});
r, NextHttpPolicy(0, {}), Context::ApplicationContext);
EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase()); EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase());
EXPECT_EQ(1, copyOptions.PerRetryPolicies.size()); EXPECT_EQ(1, copyOptions.PerRetryPolicies.size());
result = copyOptions.PerRetryPolicies[0]->Send( result = copyOptions.PerRetryPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{});
r, NextHttpPolicy(0, {}), Context::ApplicationContext);
EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase()); EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase());
} }
@ -227,16 +219,14 @@ TEST(ClientOptions, moveConstruct)
EXPECT_EQ(1, copyOptions.Retry.MaxRetries); EXPECT_EQ(1, copyOptions.Retry.MaxRetries);
EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId); EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId);
Request r(HttpMethod::Get, Url("")); Request r(HttpMethod::Get, Url(""));
auto result = copyOptions.Transport.Transport->Send(r, Context::ApplicationContext); auto result = copyOptions.Transport.Transport->Send(r, Context{});
EXPECT_EQ(nullptr, result); EXPECT_EQ(nullptr, result);
EXPECT_EQ(1, copyOptions.PerOperationPolicies.size()); EXPECT_EQ(1, copyOptions.PerOperationPolicies.size());
result = copyOptions.PerOperationPolicies[0]->Send( result = copyOptions.PerOperationPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{});
r, NextHttpPolicy(0, {}), Context::ApplicationContext);
EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase()); EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase());
EXPECT_EQ(1, copyOptions.PerRetryPolicies.size()); EXPECT_EQ(1, copyOptions.PerRetryPolicies.size());
result = copyOptions.PerRetryPolicies[0]->Send( result = copyOptions.PerRetryPolicies[0]->Send(r, NextHttpPolicy(0, {}), Context{});
r, NextHttpPolicy(0, {}), Context::ApplicationContext);
EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase()); EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase());
} }

Просмотреть файл

@ -1,14 +1,12 @@
// Copyright (c) Microsoft Corporation. // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License. // Licensed under the MIT License.
#include <azure/core/context.hpp> #include "azure/core/context.hpp"
#include <azure/core/tracing/tracing.hpp>
#include <chrono> #include <chrono>
#include <memory> #include <memory>
#include <string> #include <string>
#include <thread> #include <thread>
#include <vector>
#include <gtest/gtest.h> #include <gtest/gtest.h>
@ -241,7 +239,7 @@ struct SomeStructForContext final
TEST(Context, InstanceValue) TEST(Context, InstanceValue)
{ {
Context::Key const key; Context::Key const key;
auto contextP = Context::ApplicationContext.WithValue(key, SomeStructForContext()); auto contextP = Context{}.WithValue(key, SomeStructForContext());
SomeStructForContext contextValueRef; SomeStructForContext contextValueRef;
EXPECT_TRUE(contextP.TryGetValue<SomeStructForContext>(key, contextValueRef)); EXPECT_TRUE(contextP.TryGetValue<SomeStructForContext>(key, contextValueRef));
EXPECT_EQ(contextValueRef.someField, 12345); EXPECT_EQ(contextValueRef.someField, 12345);
@ -251,7 +249,7 @@ TEST(Context, Ptr)
{ {
Context::Key const key; Context::Key const key;
SomeStructForContext value; SomeStructForContext value;
auto contextP = Context::ApplicationContext.WithValue(key, &value); auto contextP = Context{}.WithValue(key, &value);
SomeStructForContext* contextValueRef; SomeStructForContext* contextValueRef;
EXPECT_TRUE(contextP.TryGetValue<SomeStructForContext*>(key, contextValueRef)); EXPECT_TRUE(contextP.TryGetValue<SomeStructForContext*>(key, contextValueRef));
@ -277,7 +275,7 @@ TEST(Context, NestedClassPtr)
Context::Key const key; Context::Key const key;
auto context = Context::ApplicationContext.WithValue(key, sharedPtr); auto context = Context{}.WithValue(key, sharedPtr);
EXPECT_EQ(sharedPtr.use_count(), 2); EXPECT_EQ(sharedPtr.use_count(), 2);
std::shared_ptr<TestClass> foundPtr; std::shared_ptr<TestClass> foundPtr;

Просмотреть файл

@ -311,8 +311,7 @@ namespace Azure { namespace Core { namespace Test {
// Now check the pool until the clean thread until finishes removing the connections or // Now check the pool until the clean thread until finishes removing the connections or
// fail after 5 minutes (indicates a problem with the clean routine) // fail after 5 minutes (indicates a problem with the clean routine)
auto timeOut auto timeOut = Context{std::chrono::system_clock::now() + 5min};
= Context::ApplicationContext.WithDeadline(std::chrono::system_clock::now() + 5min);
bool poolIsEmpty = false; bool poolIsEmpty = false;
while (!poolIsEmpty && !timeOut.IsCancelled()) while (!poolIsEmpty && !timeOut.IsCancelled())
{ {
@ -373,13 +372,13 @@ namespace Azure { namespace Core { namespace Test {
// .ConnectionPoolIndex[hostKey] // .ConnectionPoolIndex[hostKey]
// .begin(); // .begin();
// EXPECT_EQ( // EXPECT_EQ(
// connectionIt->get()->ReadFromSocket(nullptr, 0, Context::ApplicationContext), // connectionIt->get()->ReadFromSocket(nullptr, 0, Context{}),
// 2000 - 1); // starting from zero // 2000 - 1); // starting from zero
// connectionIt = --(Azure::Core::Http::_detail::CurlConnectionPool::g_curlConnectionPool // connectionIt = --(Azure::Core::Http::_detail::CurlConnectionPool::g_curlConnectionPool
// .ConnectionPoolIndex[hostKey] // .ConnectionPoolIndex[hostKey]
// .end()); // .end());
// EXPECT_EQ( // EXPECT_EQ(
// connectionIt->get()->ReadFromSocket(nullptr, 0, Context::ApplicationContext), // connectionIt->get()->ReadFromSocket(nullptr, 0, Context{}),
// 2000 - 1024); // 2000 - 1024);
// // Check the pool will take other host-key // // Check the pool will take other host-key
@ -603,7 +602,7 @@ namespace Azure { namespace Core { namespace Test {
// Check that CURLE_SEND_ERROR is produced when trying to use the connection. // Check that CURLE_SEND_ERROR is produced when trying to use the connection.
auto session auto session
= std::make_unique<Azure::Core::Http::CurlSession>(req, std::move(connection), options); = std::make_unique<Azure::Core::Http::CurlSession>(req, std::move(connection), options);
auto r = session->Perform(Azure::Core::Context::ApplicationContext); auto r = session->Perform(Azure::Core::Context{});
EXPECT_EQ(CURLE_SEND_ERROR, r); EXPECT_EQ(CURLE_SEND_ERROR, r);
} }
} }
@ -623,7 +622,7 @@ namespace Azure { namespace Core { namespace Test {
auto session auto session
= std::make_unique<Azure::Core::Http::CurlSession>(req, std::move(connection), options); = std::make_unique<Azure::Core::Http::CurlSession>(req, std::move(connection), options);
auto r = session->Perform(Azure::Core::Context::ApplicationContext); auto r = session->Perform(Azure::Core::Context{});
EXPECT_EQ(CURLE_OK, r); EXPECT_EQ(CURLE_OK, r);
auto response = session->ExtractResponse(); auto response = session->ExtractResponse();
EXPECT_EQ(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::SwitchingProtocols); EXPECT_EQ(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::SwitchingProtocols);
@ -652,7 +651,7 @@ namespace Azure { namespace Core { namespace Test {
{ {
// Create a pipeline to send the request and dispose after it. // Create a pipeline to send the request and dispose after it.
Azure::Core::Http::_internal::HttpPipeline pipeline({}, "test", "test", {}, {}); Azure::Core::Http::_internal::HttpPipeline pipeline({}, "test", "test", {}, {});
auto response = pipeline.Send(req, Azure::Core::Context::ApplicationContext); auto response = pipeline.Send(req, Azure::Core::Context{});
EXPECT_PRED2( EXPECT_PRED2(
[](Azure::Core::Http::HttpStatusCode a, Azure::Core::Http::HttpStatusCode b) { [](Azure::Core::Http::HttpStatusCode a, Azure::Core::Http::HttpStatusCode b) {
return a == b; return a == b;

Просмотреть файл

@ -4,15 +4,16 @@
#include <azure/core/context.hpp> #include <azure/core/context.hpp>
#include <azure/core/http/http.hpp> #include <azure/core/http/http.hpp>
#include <azure/core/http/policies/policy.hpp> #include <azure/core/http/policies/policy.hpp>
#include <azure/core/http/transport.hpp>
#include <azure/core/internal/http/pipeline.hpp> #include <azure/core/internal/http/pipeline.hpp>
#include <azure/core/response.hpp> #include <azure/core/platform.hpp>
#include <gtest/gtest.h> #include <gtest/gtest.h>
#if defined(BUILD_CURL_HTTP_TRANSPORT_ADAPTER) #if defined(BUILD_CURL_HTTP_TRANSPORT_ADAPTER)
#include "azure/core/http/curl_transport.hpp" #include "azure/core/http/curl_transport.hpp"
#include "openssl/x509.h" #if defined(AZ_PLATFORM_POSIX)
#include <openssl/x509.h>
#endif
#endif #endif
#include "transport_adapter_base_test.hpp" #include "transport_adapter_base_test.hpp"
@ -22,7 +23,6 @@
#include <http/curl/curl_connection_pool_private.hpp> #include <http/curl/curl_connection_pool_private.hpp>
#include <http/curl/curl_connection_private.hpp> #include <http/curl/curl_connection_private.hpp>
#include <http/curl/curl_session_private.hpp>
namespace Azure { namespace Core { namespace Test { namespace Azure { namespace Core { namespace Test {
@ -49,7 +49,7 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url); Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url);
std::unique_ptr<Azure::Core::Http::RawResponse> response; std::unique_ptr<Azure::Core::Http::RawResponse> response;
EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context::ApplicationContext)); EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context{}));
auto responseCode = response->GetStatusCode(); auto responseCode = response->GetStatusCode();
int expectedCode = 200; int expectedCode = 200;
EXPECT_PRED2( EXPECT_PRED2(
@ -79,7 +79,7 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url); Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url);
std::unique_ptr<Azure::Core::Http::RawResponse> response; std::unique_ptr<Azure::Core::Http::RawResponse> response;
EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context::ApplicationContext)); EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context{}));
if (response) if (response)
{ {
auto responseCode = response->GetStatusCode(); auto responseCode = response->GetStatusCode();
@ -136,7 +136,7 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url); Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url);
std::unique_ptr<Azure::Core::Http::RawResponse> response; std::unique_ptr<Azure::Core::Http::RawResponse> response;
EXPECT_NO_THROW(response = pipeline.Send(Azure::Core::Context::ApplicationContext, EXPECT_NO_THROW(response = pipeline.Send(Azure::Core::Context{},
request)); auto responseCode = response->GetStatusCode(); int expectedCode = 200; EXPECT_PRED2( request)); auto responseCode = response->GetStatusCode(); int expectedCode = 200; EXPECT_PRED2(
[](int expected, int code) { return expected == code; }, [](int expected, int code) { return expected == code; },
expectedCode, expectedCode,
@ -162,7 +162,7 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url); Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url);
std::unique_ptr<Azure::Core::Http::RawResponse> response; std::unique_ptr<Azure::Core::Http::RawResponse> response;
EXPECT_NO_THROW(response = pipeline.Send(Azure::Core::Context::ApplicationContext, EXPECT_NO_THROW(response = pipeline.Send(Azure::Core::Context{},
request)); auto responseCode = response->GetStatusCode(); int expectedCode = 200; EXPECT_PRED2( request)); auto responseCode = response->GetStatusCode(); int expectedCode = 200; EXPECT_PRED2(
[](int expected, int code) { return expected == code; }, [](int expected, int code) { return expected == code; },
expectedCode, expectedCode,
@ -188,7 +188,7 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url); Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url);
std::unique_ptr<Azure::Core::Http::RawResponse> response; std::unique_ptr<Azure::Core::Http::RawResponse> response;
EXPECT_NO_THROW(response = pipeline.Send(Azure::Core::Context::ApplicationContext, EXPECT_NO_THROW(response = pipeline.Send(Azure::Core::Context{},
request)); auto responseCode = response->GetStatusCode(); int expectedCode = 200; EXPECT_PRED2( request)); auto responseCode = response->GetStatusCode(); int expectedCode = 200; EXPECT_PRED2(
[](int expected, int code) { return expected == code; }, [](int expected, int code) { return expected == code; },
expectedCode, expectedCode,
@ -220,7 +220,7 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url); Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url);
std::unique_ptr<Azure::Core::Http::RawResponse> response; std::unique_ptr<Azure::Core::Http::RawResponse> response;
EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context::ApplicationContext)); EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context{}));
auto responseCode = response->GetStatusCode(); auto responseCode = response->GetStatusCode();
int expectedCode = 200; int expectedCode = 200;
EXPECT_PRED2( EXPECT_PRED2(
@ -270,7 +270,7 @@ namespace Azure { namespace Core { namespace Test {
#if defined(AZ_PLATFORM_LINUX) #if defined(AZ_PLATFORM_LINUX)
std::unique_ptr<Azure::Core::Http::RawResponse> response; std::unique_ptr<Azure::Core::Http::RawResponse> response;
EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context::ApplicationContext)); EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context{}));
EXPECT_EQ(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::Ok); EXPECT_EQ(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::Ok);
// Clean the connection from the pool *Windows fails to clean if we leave to be clean upon // Clean the connection from the pool *Windows fails to clean if we leave to be clean upon
@ -279,11 +279,10 @@ namespace Azure { namespace Core { namespace Test {
.ConnectionPoolIndex.clear()); .ConnectionPoolIndex.clear());
#else #else
EXPECT_THROW( EXPECT_THROW(
pipeline.Send(request, Azure::Core::Context::ApplicationContext), pipeline.Send(request, Azure::Core::Context{}), Azure::Core::Http::TransportException);
Azure::Core::Http::TransportException);
try try
{ {
pipeline.Send(request, Azure::Core::Context::ApplicationContext); pipeline.Send(request, Azure::Core::Context{});
} }
catch (Azure::Core::Http::TransportException& e) catch (Azure::Core::Http::TransportException& e)
{ {
@ -313,7 +312,7 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url); Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url);
std::unique_ptr<Azure::Core::Http::RawResponse> response; std::unique_ptr<Azure::Core::Http::RawResponse> response;
EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context::ApplicationContext)); EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context{}));
auto responseCode = response->GetStatusCode(); auto responseCode = response->GetStatusCode();
int expectedCode = 200; int expectedCode = 200;
EXPECT_PRED2( EXPECT_PRED2(
@ -350,7 +349,7 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url); Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url);
std::unique_ptr<Azure::Core::Http::RawResponse> response; std::unique_ptr<Azure::Core::Http::RawResponse> response;
EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context::ApplicationContext)); EXPECT_NO_THROW(response = pipeline.Send(request, Azure::Core::Context{}));
auto responseCode = response->GetStatusCode(); auto responseCode = response->GetStatusCode();
int expectedCode = 200; int expectedCode = 200;
EXPECT_PRED2( EXPECT_PRED2(

Просмотреть файл

@ -46,7 +46,7 @@ namespace Azure { namespace Core { namespace Test {
auto session = std::make_unique<Azure::Core::Http::CurlSession>( auto session = std::make_unique<Azure::Core::Http::CurlSession>(
request, std::move(uniqueCurlMock), transportOptions); request, std::move(uniqueCurlMock), transportOptions);
EXPECT_NO_THROW(session->Perform(Azure::Core::Context::ApplicationContext)); EXPECT_NO_THROW(session->Perform(Azure::Core::Context{}));
} }
TEST_F(CurlSession, chunkResponseSizeZero) TEST_F(CurlSession, chunkResponseSizeZero)
@ -83,7 +83,7 @@ namespace Azure { namespace Core { namespace Test {
auto session = std::make_unique<Azure::Core::Http::CurlSession>( auto session = std::make_unique<Azure::Core::Http::CurlSession>(
request, std::move(uniqueCurlMock), transportOptions); request, std::move(uniqueCurlMock), transportOptions);
EXPECT_NO_THROW(session->Perform(Azure::Core::Context::ApplicationContext)); EXPECT_NO_THROW(session->Perform(Azure::Core::Context{}));
} }
// Clear the connections from the pool to invoke clean routine // Clear the connections from the pool to invoke clean routine
Azure::Core::Http::_detail::CurlConnectionPool::g_curlConnectionPool.ConnectionPoolIndex Azure::Core::Http::_detail::CurlConnectionPool::g_curlConnectionPool.ConnectionPoolIndex
@ -128,15 +128,13 @@ namespace Azure { namespace Core { namespace Test {
auto session = std::make_unique<Azure::Core::Http::CurlSession>( auto session = std::make_unique<Azure::Core::Http::CurlSession>(
request, std::move(uniqueCurlMock), transportOptions); request, std::move(uniqueCurlMock), transportOptions);
EXPECT_NO_THROW(session->Perform(Azure::Core::Context::ApplicationContext)); EXPECT_NO_THROW(session->Perform(Azure::Core::Context{}));
auto r = session->ExtractResponse(); auto r = session->ExtractResponse();
r->SetBodyStream(std::move(session)); r->SetBodyStream(std::move(session));
auto bodyS = r->ExtractBodyStream(); auto bodyS = r->ExtractBodyStream();
// Read the bodyStream to get all chunks // Read the bodyStream to get all chunks
EXPECT_THROW( EXPECT_THROW(bodyS->ReadToEnd(Azure::Core::Context{}), Azure::Core::Http::TransportException);
bodyS->ReadToEnd(Azure::Core::Context::ApplicationContext),
Azure::Core::Http::TransportException);
} }
// Clear the connections from the pool to invoke clean routine // Clear the connections from the pool to invoke clean routine
Azure::Core::Http::_detail::CurlConnectionPool::g_curlConnectionPool.ConnectionPoolIndex Azure::Core::Http::_detail::CurlConnectionPool::g_curlConnectionPool.ConnectionPoolIndex
@ -171,7 +169,7 @@ namespace Azure { namespace Core { namespace Test {
auto session = std::make_unique<Azure::Core::Http::CurlSession>( auto session = std::make_unique<Azure::Core::Http::CurlSession>(
request, std::move(uniqueCurlMock), transportOptions); request, std::move(uniqueCurlMock), transportOptions);
EXPECT_THROW(session->Perform(Azure::Core::Context::ApplicationContext), std::invalid_argument); EXPECT_THROW(session->Perform(Azure::Core::Context{}), std::invalid_argument);
} }
TEST_F(CurlSession, emptyHeaderValue) TEST_F(CurlSession, emptyHeaderValue)
@ -202,7 +200,7 @@ namespace Azure { namespace Core { namespace Test {
auto session = std::make_unique<Azure::Core::Http::CurlSession>( auto session = std::make_unique<Azure::Core::Http::CurlSession>(
request, std::move(uniqueCurlMock), transportOptions); request, std::move(uniqueCurlMock), transportOptions);
EXPECT_NO_THROW(session->Perform(Azure::Core::Context::ApplicationContext)); EXPECT_NO_THROW(session->Perform(Azure::Core::Context{}));
} }
TEST_F(CurlSession, headerValueWhitespace) TEST_F(CurlSession, headerValueWhitespace)
@ -233,7 +231,7 @@ namespace Azure { namespace Core { namespace Test {
auto session = std::make_unique<Azure::Core::Http::CurlSession>( auto session = std::make_unique<Azure::Core::Http::CurlSession>(
request, std::move(uniqueCurlMock), transportOptions); request, std::move(uniqueCurlMock), transportOptions);
EXPECT_NO_THROW(session->Perform(Azure::Core::Context::ApplicationContext)); EXPECT_NO_THROW(session->Perform(Azure::Core::Context{}));
} }
TEST_F(CurlSession, chunkSegmentedResponse) TEST_F(CurlSession, chunkSegmentedResponse)
@ -310,13 +308,13 @@ namespace Azure { namespace Core { namespace Test {
auto session = std::make_unique<Azure::Core::Http::CurlSession>( auto session = std::make_unique<Azure::Core::Http::CurlSession>(
request, std::move(uniqueCurlMock), transportOptions); request, std::move(uniqueCurlMock), transportOptions);
EXPECT_NO_THROW(session->Perform(Azure::Core::Context::ApplicationContext)); EXPECT_NO_THROW(session->Perform(Azure::Core::Context{}));
auto response = session->ExtractResponse(); auto response = session->ExtractResponse();
response->SetBodyStream(std::move(session)); response->SetBodyStream(std::move(session));
auto bodyS = response->ExtractBodyStream(); auto bodyS = response->ExtractBodyStream();
// Read the bodyStream to get all chunks // Read the bodyStream to get all chunks
EXPECT_NO_THROW(bodyS->ReadToEnd(Azure::Core::Context::ApplicationContext)); EXPECT_NO_THROW(bodyS->ReadToEnd(Azure::Core::Context{}));
} }
// Clear the connections from the pool to invoke clean routine // Clear the connections from the pool to invoke clean routine
Azure::Core::Http::_detail::CurlConnectionPool::g_curlConnectionPool.ConnectionPoolIndex Azure::Core::Http::_detail::CurlConnectionPool::g_curlConnectionPool.ConnectionPoolIndex
@ -348,7 +346,7 @@ namespace Azure { namespace Core { namespace Test {
auto session = std::make_unique<Azure::Core::Http::CurlSession>( auto session = std::make_unique<Azure::Core::Http::CurlSession>(
request, std::move(uniqueCurlMock), transportOptions); request, std::move(uniqueCurlMock), transportOptions);
auto returnCode = session->Perform(Azure::Core::Context::ApplicationContext); auto returnCode = session->Perform(Azure::Core::Context{});
EXPECT_EQ(CURLE_SEND_ERROR, returnCode); EXPECT_EQ(CURLE_SEND_ERROR, returnCode);
} }
// Check connection pool is empty (connection was not moved to the pool) // Check connection pool is empty (connection was not moved to the pool)

Просмотреть файл

@ -13,13 +13,24 @@
#include <azure/core/context.hpp> #include <azure/core/context.hpp>
#include <chrono> #include <chrono>
#include <string>
#include <thread> #include <thread>
#include <gtest/gtest.h> #include <gtest/gtest.h>
using namespace Azure::Core; using namespace Azure::Core;
// Disable deprecation warning
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4996)
#elif defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
TEST(Context, ApplicationContext) TEST(Context, ApplicationContext)
{ {
Context appContext = Context::ApplicationContext; Context appContext = Context::ApplicationContext;
@ -41,3 +52,10 @@ TEST(Context, ApplicationContext)
Context appContext2 = Context::ApplicationContext; Context appContext2 = Context::ApplicationContext;
EXPECT_TRUE(appContext2.IsCancelled()); EXPECT_TRUE(appContext2.IsCancelled());
} }
#if defined(_MSC_VER)
#pragma warning(pop)
#elif defined(__clang__)
#pragma clang diagnostic pop
#elif defined(__GNUC__)
#pragma GCC diagnostic pop
#endif // _MSC_VER

Просмотреть файл

@ -220,7 +220,7 @@ namespace Azure { namespace Core { namespace Test {
// Change the offset of the stream to be non-zero by reading a byte. // Change the offset of the stream to be non-zero by reading a byte.
std::vector<uint8_t> temp(2); std::vector<uint8_t> temp(2);
EXPECT_EQ(stream.ReadToCount(temp.data(), 1, Context::ApplicationContext), 1); EXPECT_EQ(stream.ReadToCount(temp.data(), 1, Context{}), 1);
EXPECT_EQ(temp[0], 1); EXPECT_EQ(temp[0], 1);
EXPECT_EQ(temp[1], 0); EXPECT_EQ(temp[1], 0);
@ -242,7 +242,7 @@ namespace Azure { namespace Core { namespace Test {
// Verify that StartTry rewound the stream back. // Verify that StartTry rewound the stream back.
auto getStream = req.GetBodyStream(); auto getStream = req.GetBodyStream();
EXPECT_EQ(getStream->ReadToCount(temp.data(), 2, Context::ApplicationContext), 2); EXPECT_EQ(getStream->ReadToCount(temp.data(), 2, Context{}), 2);
EXPECT_EQ(temp[0], 1); EXPECT_EQ(temp[0], 1);
EXPECT_EQ(temp[1], 2); EXPECT_EQ(temp[1], 2);

Просмотреть файл

@ -117,8 +117,7 @@ TEST(Policy, throwWhenNoTransportPolicy)
Azure::Core::Http::_internal::HttpPipeline pipeline(policies); Azure::Core::Http::_internal::HttpPipeline pipeline(policies);
Azure::Core::Url url(""); Azure::Core::Url url("");
Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url); Azure::Core::Http::Request request(Azure::Core::Http::HttpMethod::Get, url);
EXPECT_THROW( EXPECT_THROW(pipeline.Send(request, Azure::Core::Context{}), std::invalid_argument);
pipeline.Send(request, Azure::Core::Context::ApplicationContext), std::invalid_argument);
} }
TEST(Policy, throwWhenNoTransportPolicyMessage) TEST(Policy, throwWhenNoTransportPolicyMessage)
@ -140,7 +139,7 @@ TEST(Policy, throwWhenNoTransportPolicyMessage)
try try
{ {
pipeline.Send(request, Azure::Core::Context::ApplicationContext); pipeline.Send(request, Azure::Core::Context{});
} }
catch (const std::invalid_argument& ex) catch (const std::invalid_argument& ex)
{ {
@ -159,7 +158,7 @@ TEST(Policy, RetryPolicyCounter)
retryCounterState = 0; retryCounterState = 0;
// Check when there's no info about retry on the context // Check when there's no info about retry on the context
auto initialContext = Context::ApplicationContext; Azure::Core::Context initialContext;
EXPECT_EQ(-1, RetryPolicy::GetRetryCount(initialContext)); EXPECT_EQ(-1, RetryPolicy::GetRetryCount(initialContext));
// Pipeline with retry test // Pipeline with retry test
@ -196,7 +195,7 @@ TEST(Policy, RetryPolicyRetryCycle)
HttpPipeline pipeline(policies); HttpPipeline pipeline(policies);
Request request(HttpMethod::Get, Url("url")); Request request(HttpMethod::Get, Url("url"));
pipeline.Send(request, Context::ApplicationContext); pipeline.Send(request, Context{});
} }
// Makes sure that the context tree is not corrupted/broken by some policy // Makes sure that the context tree is not corrupted/broken by some policy
@ -221,6 +220,6 @@ TEST(Policy, RetryPolicyKeepContext)
HttpPipeline pipeline(policies); HttpPipeline pipeline(policies);
Request request(HttpMethod::Get, Url("url")); Request request(HttpMethod::Get, Url("url"));
auto withValueContext = Context::ApplicationContext.WithValue(TheKey, std::string("TheValue")); auto withValueContext = Context{}.WithValue(TheKey, std::string("TheValue"));
pipeline.Send(request, withValueContext); pipeline.Send(request, withValueContext);
} }

Просмотреть файл

@ -165,7 +165,7 @@ TEST(RequestActivityPolicy, Basic)
Azure::Core::Tracing::_internal::TracingContextFactory serviceTrace( Azure::Core::Tracing::_internal::TracingContextFactory serviceTrace(
clientOptions, "My.Service", "my-service-cpp", "1.0b2"); clientOptions, "My.Service", "my-service-cpp", "1.0b2");
auto contextAndSpan = serviceTrace.CreateTracingContext("My API", {}); auto contextAndSpan = serviceTrace.CreateTracingContext("My API", Context{});
Azure::Core::Context callContext = std::move(contextAndSpan.Context); Azure::Core::Context callContext = std::move(contextAndSpan.Context);
Request request(HttpMethod::Get, Url("https://www.microsoft.com")); Request request(HttpMethod::Get, Url("https://www.microsoft.com"));
@ -197,7 +197,7 @@ TEST(RequestActivityPolicy, Basic)
clientOptions.Telemetry.TracingProvider = testTracer; clientOptions.Telemetry.TracingProvider = testTracer;
Azure::Core::Tracing::_internal::TracingContextFactory serviceTrace( Azure::Core::Tracing::_internal::TracingContextFactory serviceTrace(
clientOptions, "Azure.Service", "service", "1.0.0.beta-2"); clientOptions, "Azure.Service", "service", "1.0.0.beta-2");
auto contextAndSpan = serviceTrace.CreateTracingContext("My API", {}); auto contextAndSpan = serviceTrace.CreateTracingContext("My API", Context{});
Azure::Core::Context callContext = std::move(contextAndSpan.Context); Azure::Core::Context callContext = std::move(contextAndSpan.Context);
Request request(HttpMethod::Get, Url("https://www.microsoft.com")); Request request(HttpMethod::Get, Url("https://www.microsoft.com"));

Просмотреть файл

@ -87,7 +87,7 @@ TEST(TracingContextFactory, SimpleServiceSpanTests)
Azure::Core::Tracing::_internal::TracingContextFactory serviceTrace( Azure::Core::Tracing::_internal::TracingContextFactory serviceTrace(
clientOptions, "my.service", "my-service-cpp", "1.0b2"); clientOptions, "my.service", "my-service-cpp", "1.0b2");
auto contextAndSpan = serviceTrace.CreateTracingContext("My API", {}); auto contextAndSpan = serviceTrace.CreateTracingContext("My API", Context{});
EXPECT_FALSE(contextAndSpan.Context.IsCancelled()); EXPECT_FALSE(contextAndSpan.Context.IsCancelled());
} }
} }
@ -184,7 +184,7 @@ TEST(TracingContextFactory, BasicServiceSpanTests)
Azure::Core::Tracing::_internal::TracingContextFactory serviceTrace( Azure::Core::Tracing::_internal::TracingContextFactory serviceTrace(
clientOptions, "My.Service", "my-service-cpp", "1.0b2"); clientOptions, "My.Service", "my-service-cpp", "1.0b2");
auto contextAndSpan = serviceTrace.CreateTracingContext("My API", {}); auto contextAndSpan = serviceTrace.CreateTracingContext("My API", Context{});
ServiceSpan span = std::move(contextAndSpan.Span); ServiceSpan span = std::move(contextAndSpan.Span);
span.End(); span.End();
@ -200,7 +200,7 @@ TEST(TracingContextFactory, BasicServiceSpanTests)
Azure::Core::Tracing::_internal::TracingContextFactory serviceTrace( Azure::Core::Tracing::_internal::TracingContextFactory serviceTrace(
clientOptions, "My.Service", "my-service-cpp", "1.0b2"); clientOptions, "My.Service", "my-service-cpp", "1.0b2");
auto contextAndSpan = serviceTrace.CreateTracingContext("My API", {}); auto contextAndSpan = serviceTrace.CreateTracingContext("My API", Context{});
ServiceSpan span = std::move(contextAndSpan.Span); ServiceSpan span = std::move(contextAndSpan.Span);
span.End(); span.End();
@ -221,7 +221,7 @@ TEST(TracingContextFactory, BasicServiceSpanTests)
Azure::Core::Tracing::_internal::TracingContextFactory serviceTrace( Azure::Core::Tracing::_internal::TracingContextFactory serviceTrace(
clientOptions, "My.Service", "my-service-cpp", "1.0b2"); clientOptions, "My.Service", "my-service-cpp", "1.0b2");
auto contextAndSpan = serviceTrace.CreateTracingContext("My API", {}); auto contextAndSpan = serviceTrace.CreateTracingContext("My API", Context{});
ServiceSpan span = std::move(contextAndSpan.Span); ServiceSpan span = std::move(contextAndSpan.Span);
span.End(); span.End();

Просмотреть файл

@ -1,26 +1,13 @@
// Copyright (c) Microsoft Corporation. // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License. // Licensed under the MIT License.
#include <azure/core/platform.hpp>
#include <azure/core/rtti.hpp>
#if defined(AZ_PLATFORM_POSIX)
#include <fcntl.h>
#elif defined(AZ_PLATFORM_WINDOWS)
#if !defined(WIN32_LEAN_AND_MEAN)
#define WIN32_LEAN_AND_MEAN
#endif
#if !defined(NOMINMAX)
#define NOMINMAX
#endif
#include <windows.h>
#endif
#include "transport_adapter_base_test.hpp" #include "transport_adapter_base_test.hpp"
#include <azure/core/context.hpp> #include <azure/core/context.hpp>
#include <azure/core/internal/json/json.hpp> #include <azure/core/internal/json/json.hpp>
#include <azure/core/platform.hpp>
#include <azure/core/response.hpp> #include <azure/core/response.hpp>
#include <azure/core/rtti.hpp>
#include <iostream> #include <iostream>
#include <string> #include <string>
@ -35,7 +22,7 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Url host(AzureSdkHttpbinServer::Get()); Azure::Core::Url host(AzureSdkHttpbinServer::Get());
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length"));
CheckBodyFromBuffer(*response, expectedResponseBodySize); CheckBodyFromBuffer(*response, expectedResponseBodySize);
@ -44,7 +31,7 @@ namespace Azure { namespace Core { namespace Test {
request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host);
// Add a header and send again. RawResponse should return that header in the body // Add a header and send again. RawResponse should return that header in the body
request.SetHeader("123", "456"); request.SetHeader("123", "456");
response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); response = m_pipeline->Send(request, Context{});
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
auto body = response->GetBody(); auto body = response->GetBody();
@ -60,7 +47,7 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Url host("http://mt3.google.com/generate_204"); Azure::Core::Url host("http://mt3.google.com/generate_204");
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
checkResponseCode(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::NoContent); checkResponseCode(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::NoContent);
auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length"));
CheckBodyFromBuffer(*response, expectedResponseBodySize); CheckBodyFromBuffer(*response, expectedResponseBodySize);
@ -75,7 +62,7 @@ namespace Azure { namespace Core { namespace Test {
// loop sending request // loop sending request
for (auto i = 0; i < 50; i++) for (auto i = 0; i < 50; i++)
{ {
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length"));
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
CheckBodyFromBuffer(*response, expectedResponseBodySize); CheckBodyFromBuffer(*response, expectedResponseBodySize);
@ -88,7 +75,7 @@ namespace Azure { namespace Core { namespace Test {
auto expectedResponseBodySize = 0; auto expectedResponseBodySize = 0;
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Head, host); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Head, host);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
CheckBodyFromBuffer(*response, expectedResponseBodySize); CheckBodyFromBuffer(*response, expectedResponseBodySize);
@ -106,7 +93,7 @@ namespace Azure { namespace Core { namespace Test {
auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector); auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector);
auto request auto request
= Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, host, &bodyRequest); = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, host, &bodyRequest);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length"));
@ -129,7 +116,7 @@ namespace Azure { namespace Core { namespace Test {
auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector); auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector);
auto request auto request
= Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Delete, host, &bodyRequest); = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Delete, host, &bodyRequest);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length"));
@ -145,7 +132,7 @@ namespace Azure { namespace Core { namespace Test {
auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector); auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector);
auto request auto request
= Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Patch, host, &bodyRequest); = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Patch, host, &bodyRequest);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length"));
@ -164,7 +151,7 @@ namespace Azure { namespace Core { namespace Test {
"sent to a client.</h5></body></html>"); "sent to a client.</h5></body></html>");
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
CheckBodyFromBuffer(*response, expectedResponseBodySize, expectedChunkResponse); CheckBodyFromBuffer(*response, expectedResponseBodySize, expectedChunkResponse);
@ -183,7 +170,7 @@ namespace Azure { namespace Core { namespace Test {
auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector); auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector);
auto request auto request
= Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, host, &bodyRequest); = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, host, &bodyRequest);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
} }
} }
@ -196,7 +183,7 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Url host(AzureSdkHttpbinServer::Get()); Azure::Core::Url host(AzureSdkHttpbinServer::Get());
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host, false); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host, false);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length"));
CheckBodyFromStream(*response, expectedResponseBodySize); CheckBodyFromStream(*response, expectedResponseBodySize);
@ -204,11 +191,11 @@ namespace Azure { namespace Core { namespace Test {
request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host, false); request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host, false);
// Add a header and send again. Response should return that header in the body // Add a header and send again. Response should return that header in the body
request.SetHeader("123", "456"); request.SetHeader("123", "456");
response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); response = m_pipeline->Send(request, Context{});
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
auto body = response->ExtractBodyStream(); auto body = response->ExtractBodyStream();
std::vector<uint8_t> responseBody = body->ReadToEnd(Azure::Core::Context::ApplicationContext); std::vector<uint8_t> responseBody = body->ReadToEnd(Context{});
auto jsonBody = json::parse(responseBody); auto jsonBody = json::parse(responseBody);
// Look for the header we added in the second request. // Look for the header we added in the second request.
@ -225,7 +212,7 @@ namespace Azure { namespace Core { namespace Test {
// loop sending request // loop sending request
for (auto i = 0; i < 50; i++) for (auto i = 0; i < 50; i++)
{ {
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length"));
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
CheckBodyFromStream(*response, expectedResponseBodySize); CheckBodyFromStream(*response, expectedResponseBodySize);
@ -238,7 +225,7 @@ namespace Azure { namespace Core { namespace Test {
auto expectedResponseBodySize = 0; auto expectedResponseBodySize = 0;
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Head, host, false); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Head, host, false);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
CheckBodyFromStream(*response, expectedResponseBodySize); CheckBodyFromStream(*response, expectedResponseBodySize);
@ -256,7 +243,7 @@ namespace Azure { namespace Core { namespace Test {
auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector); auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector);
auto request auto request
= Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, host, &bodyRequest, false); = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, host, &bodyRequest, false);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length"));
@ -272,7 +259,7 @@ namespace Azure { namespace Core { namespace Test {
auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector); auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector);
auto request = Azure::Core::Http::Request( auto request = Azure::Core::Http::Request(
Azure::Core::Http::HttpMethod::Delete, host, &bodyRequest, false); Azure::Core::Http::HttpMethod::Delete, host, &bodyRequest, false);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length"));
@ -288,7 +275,7 @@ namespace Azure { namespace Core { namespace Test {
auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector); auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector);
auto request = Azure::Core::Http::Request( auto request = Azure::Core::Http::Request(
Azure::Core::Http::HttpMethod::Patch, host, &bodyRequest, false); Azure::Core::Http::HttpMethod::Patch, host, &bodyRequest, false);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
if (response->GetStatusCode() == Http::HttpStatusCode::Ok) if (response->GetStatusCode() == Http::HttpStatusCode::Ok)
@ -310,7 +297,7 @@ namespace Azure { namespace Core { namespace Test {
"sent to a client.</h5></body></html>"); "sent to a client.</h5></body></html>");
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host, false); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host, false);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
CheckBodyFromStream(*response, expectedResponseBodySize, expectedChunkResponse); CheckBodyFromStream(*response, expectedResponseBodySize, expectedChunkResponse);
@ -322,7 +309,7 @@ namespace Azure { namespace Core { namespace Test {
std::string expectedType("This is the Response Type"); std::string expectedType("This is the Response Type");
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host, true); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host, true);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
Azure::Response<std::string> responseT(expectedType, std::move(response)); Azure::Response<std::string> responseT(expectedType, std::move(response));
auto& r = responseT.RawResponse; auto& r = responseT.RawResponse;
@ -352,7 +339,7 @@ namespace Azure { namespace Core { namespace Test {
= Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, host, &bodyRequest); = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, host, &bodyRequest);
// Make transport adapter to read all stream content for uploading instead of chunks // Make transport adapter to read all stream content for uploading instead of chunks
{ {
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length"));
CheckBodyFromBuffer(*response, expectedResponseBodySize); CheckBodyFromBuffer(*response, expectedResponseBodySize);
@ -369,7 +356,7 @@ namespace Azure { namespace Core { namespace Test {
auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector); auto bodyRequest = Azure::Core::IO::MemoryBodyStream(requestBodyVector);
auto request auto request
= Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, host, &bodyRequest, false); = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Put, host, &bodyRequest, false);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
checkResponseCode( checkResponseCode(
response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::MethodNotAllowed); response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::MethodNotAllowed);
auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length"));
@ -407,8 +394,8 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Url hostPath(AzureSdkHttpbinServer::Delay() + "/2"); // 2 seconds delay on server Azure::Core::Url hostPath(AzureSdkHttpbinServer::Delay() + "/2"); // 2 seconds delay on server
for (int i = 0; i < 10; i++) for (int i = 0; i < 10; i++)
{ {
Azure::Core::Context cancelThis = Azure::Core::Context::ApplicationContext.WithDeadline( Azure::Core::Context cancelThis
std::chrono::system_clock::now() + std::chrono::milliseconds(500)); = Context{std::chrono::system_clock::now() + std::chrono::milliseconds(500)};
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, hostPath); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, hostPath);
@ -461,9 +448,7 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Url host("http://unresolvedHost.org/get"); Azure::Core::Url host("http://unresolvedHost.org/get");
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host);
EXPECT_THROW( EXPECT_THROW(m_pipeline->Send(request, Context{}), Azure::Core::RequestFailedException);
m_pipeline->Send(request, Azure::Core::Context::ApplicationContext),
Azure::Core::RequestFailedException);
} }
TEST_P(TransportAdapter, validNonAsciiHost) TEST_P(TransportAdapter, validNonAsciiHost)
@ -472,33 +457,25 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Url host(u8"http://unresolvedHost\u6F22\u5B57.org/get"); Azure::Core::Url host(u8"http://unresolvedHost\u6F22\u5B57.org/get");
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host);
EXPECT_THROW( EXPECT_THROW(m_pipeline->Send(request, Context{}), Azure::Core::Http::TransportException);
m_pipeline->Send(request, Azure::Core::Context::ApplicationContext),
Azure::Core::Http::TransportException);
} }
{ {
Azure::Core::Url host("http://unresolvedHost\xE9\x87\x91.org/get"); Azure::Core::Url host("http://unresolvedHost\xE9\x87\x91.org/get");
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host);
EXPECT_THROW( EXPECT_THROW(m_pipeline->Send(request, Context{}), Azure::Core::Http::TransportException);
m_pipeline->Send(request, Azure::Core::Context::ApplicationContext),
Azure::Core::Http::TransportException);
} }
{ {
Azure::Core::Url host(u8"http://unresolvedHost\uC328.org/get"); Azure::Core::Url host(u8"http://unresolvedHost\uC328.org/get");
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host);
EXPECT_THROW( EXPECT_THROW(m_pipeline->Send(request, Context{}), Azure::Core::Http::TransportException);
m_pipeline->Send(request, Azure::Core::Context::ApplicationContext),
Azure::Core::Http::TransportException);
} }
{ {
Azure::Core::Url host("http://\0/get"); Azure::Core::Url host("http://\0/get");
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host);
EXPECT_THROW( EXPECT_THROW(m_pipeline->Send(request, Context{}), Azure::Core::Http::TransportException);
m_pipeline->Send(request, Azure::Core::Context::ApplicationContext),
Azure::Core::Http::TransportException);
} }
} }
@ -508,25 +485,19 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Url host("http://unresolvedHost\xC0\x41\x42\xFE\xFE\xFF\xFF.org/get"); Azure::Core::Url host("http://unresolvedHost\xC0\x41\x42\xFE\xFE\xFF\xFF.org/get");
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host);
EXPECT_THROW( EXPECT_THROW(m_pipeline->Send(request, Context{}), Azure::Core::Http::TransportException);
m_pipeline->Send(request, Azure::Core::Context::ApplicationContext),
Azure::Core::Http::TransportException);
} }
{ {
Azure::Core::Url host("http://\xC0\x76\x77/get"); Azure::Core::Url host("http://\xC0\x76\x77/get");
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host);
EXPECT_THROW( EXPECT_THROW(m_pipeline->Send(request, Context{}), Azure::Core::Http::TransportException);
m_pipeline->Send(request, Azure::Core::Context::ApplicationContext),
Azure::Core::Http::TransportException);
} }
{ {
Azure::Core::Url host("http://\xD8\x00\x01\x00/get"); Azure::Core::Url host("http://\xD8\x00\x01\x00/get");
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, host);
EXPECT_THROW( EXPECT_THROW(m_pipeline->Send(request, Context{}), Azure::Core::Http::TransportException);
m_pipeline->Send(request, Azure::Core::Context::ApplicationContext),
Azure::Core::Http::TransportException);
} }
} }
@ -539,7 +510,7 @@ namespace Azure { namespace Core { namespace Test {
// test dynamic cast // test dynamic cast
try try
{ {
auto result = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto result = m_pipeline->Send(request, Context{});
} }
catch (const Azure::Core::RequestFailedException& err) catch (const Azure::Core::RequestFailedException& err)
{ {
@ -568,7 +539,7 @@ namespace Azure { namespace Core { namespace Test {
auto request = Azure::Core::Http::Request( auto request = Azure::Core::Http::Request(
Azure::Core::Http::HttpMethod::Put, host, &requestBodyStream, false); Azure::Core::Http::HttpMethod::Put, host, &requestBodyStream, false);
{ {
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length"));
@ -594,7 +565,7 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Http::HttpMethod::Put, host, &requestBodyStream, false); Azure::Core::Http::HttpMethod::Put, host, &requestBodyStream, false);
// Make transport adapter to read default chunk size // Make transport adapter to read default chunk size
{ {
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length"));
@ -619,7 +590,7 @@ namespace Azure { namespace Core { namespace Test {
auto request = Azure::Core::Http::Request( auto request = Azure::Core::Http::Request(
Azure::Core::Http::HttpMethod::Put, host, &requestBodyStream, false); Azure::Core::Http::HttpMethod::Put, host, &requestBodyStream, false);
{ {
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Context{});
checkResponseCode(response->GetStatusCode()); checkResponseCode(response->GetStatusCode());
auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length")); auto expectedResponseBodySize = std::stoull(response->GetHeaders().at("content-length"));
@ -670,7 +641,7 @@ namespace Azure { namespace Core { namespace Test {
auto body = response.ExtractBodyStream(); auto body = response.ExtractBodyStream();
EXPECT_NE(body, nullptr); EXPECT_NE(body, nullptr);
std::vector<uint8_t> bodyVector = body->ReadToEnd(Azure::Core::Context::ApplicationContext); std::vector<uint8_t> bodyVector = body->ReadToEnd(Context{});
int64_t bodySize = body->Length(); int64_t bodySize = body->Length();
EXPECT_EQ(bodySize, size); EXPECT_EQ(bodySize, size);
bodySize = bodyVector.size(); bodySize = bodyVector.size();

Просмотреть файл

@ -234,7 +234,7 @@ namespace Azure { namespace Core { namespace Test {
auto body = response.ExtractBodyStream(); auto body = response.ExtractBodyStream();
EXPECT_NE(body, nullptr); EXPECT_NE(body, nullptr);
std::vector<uint8_t> bodyVector = body->ReadToEnd(Azure::Core::Context::ApplicationContext); std::vector<uint8_t> bodyVector = body->ReadToEnd(Azure::Core::Context{});
int64_t bodySize = body->Length(); int64_t bodySize = body->Length();
EXPECT_EQ(bodySize, size); EXPECT_EQ(bodySize, size);
@ -446,7 +446,7 @@ namespace Azure { namespace Core { namespace Test {
HttpPipeline pipeline(CreateHttpPipeline(transportOptions)); HttpPipeline pipeline(CreateHttpPipeline(transportOptions));
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, testUrl); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, testUrl);
auto response = pipeline.Send(request, Azure::Core::Context::ApplicationContext); auto response = pipeline.Send(request, Azure::Core::Context{});
EXPECT_EQ(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::Ok); EXPECT_EQ(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::Ok);
} }
catch (Azure::Core::Http::TransportException const&) catch (Azure::Core::Http::TransportException const&)
@ -506,7 +506,7 @@ namespace Azure { namespace Core { namespace Test {
{ {
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, testUrl); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, testUrl);
auto response = pipeline.Send(request, Azure::Core::Context::ApplicationContext); auto response = pipeline.Send(request, Azure::Core::Context{});
EXPECT_EQ(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::Ok); EXPECT_EQ(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::Ok);
} }
} }
@ -521,8 +521,7 @@ namespace Azure { namespace Core { namespace Test {
{ {
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, testUrl); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, testUrl);
EXPECT_THROW( EXPECT_THROW(
pipeline.Send(request, Azure::Core::Context::ApplicationContext), pipeline.Send(request, Azure::Core::Context{}), Azure::Core::Http::TransportException);
Azure::Core::Http::TransportException);
} }
} }
{ {
@ -544,7 +543,7 @@ namespace Azure { namespace Core { namespace Test {
{ {
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, testUrl); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, testUrl);
auto response = pipeline.Send(request, Azure::Core::Context::ApplicationContext); auto response = pipeline.Send(request, Azure::Core::Context{});
EXPECT_EQ(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::Ok); EXPECT_EQ(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::Ok);
} }
} }
@ -692,7 +691,7 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Url url(AzureSdkHttpbinServer::Get()); Azure::Core::Url url(AzureSdkHttpbinServer::Get());
auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, url); auto request = Azure::Core::Http::Request(Azure::Core::Http::HttpMethod::Get, url);
auto response = pipeline.Send(request, Azure::Core::Context::ApplicationContext); auto response = pipeline.Send(request, Azure::Core::Context{});
EXPECT_EQ(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::Ok); EXPECT_EQ(response->GetStatusCode(), Azure::Core::Http::HttpStatusCode::Ok);
} }
#endif #endif
@ -816,7 +815,7 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Url(TestProxyUrl() + "/record/start"), Azure::Core::Url(TestProxyUrl() + "/record/start"),
&postBody); &postBody);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Azure::Core::Context{});
auto& responseHeaders = response->GetHeaders(); auto& responseHeaders = response->GetHeaders();
auto responseId = responseHeaders.find("x-recording-id"); auto responseId = responseHeaders.find("x-recording-id");
return Azure::Response<std::string>(responseId->second, std::move(response)); return Azure::Response<std::string>(responseId->second, std::move(response));
@ -828,7 +827,7 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Http::HttpMethod::Post, Azure::Core::Url(TestProxyUrl() + "/record/stop")); Azure::Core::Http::HttpMethod::Post, Azure::Core::Url(TestProxyUrl() + "/record/stop"));
request.SetHeader("x-recording-id", recordingId); request.SetHeader("x-recording-id", recordingId);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Azure::Core::Context{});
auto responseCode = response->GetStatusCode(); auto responseCode = response->GetStatusCode();
return Azure::Response<Azure::Core::Http::HttpStatusCode>( return Azure::Response<Azure::Core::Http::HttpStatusCode>(
responseCode, std::move(response)); responseCode, std::move(response));
@ -847,7 +846,7 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Url(TestProxyUrl() + "/playback/start"), Azure::Core::Url(TestProxyUrl() + "/playback/start"),
&postBody); &postBody);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Azure::Core::Context{});
auto& responseHeaders = response->GetHeaders(); auto& responseHeaders = response->GetHeaders();
auto responseId = responseHeaders.find("x-recording-id"); auto responseId = responseHeaders.find("x-recording-id");
return Azure::Response<std::string>(responseId->second, std::move(response)); return Azure::Response<std::string>(responseId->second, std::move(response));
@ -861,7 +860,7 @@ namespace Azure { namespace Core { namespace Test {
Azure::Core::Url(TestProxyUrl() + "/playback/stop")); Azure::Core::Url(TestProxyUrl() + "/playback/stop"));
request.SetHeader("x-recording-id", recordingId); request.SetHeader("x-recording-id", recordingId);
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Azure::Core::Context{});
auto responseCode = response->GetStatusCode(); auto responseCode = response->GetStatusCode();
return Azure::Response<Azure::Core::Http::HttpStatusCode>( return Azure::Response<Azure::Core::Http::HttpStatusCode>(
responseCode, std::move(response)); responseCode, std::move(response));
@ -881,7 +880,7 @@ namespace Azure { namespace Core { namespace Test {
request.SetHeader("x-recording-id", recordingId); request.SetHeader("x-recording-id", recordingId);
request.SetHeader("x-recording-mode", (isRecording ? "record" : "playback")); request.SetHeader("x-recording-mode", (isRecording ? "record" : "playback"));
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Azure::Core::Context{});
std::string responseBody(response->GetBody().begin(), response->GetBody().end()); std::string responseBody(response->GetBody().begin(), response->GetBody().end());
return Azure::Response<std::string>(responseBody, std::move(response)); return Azure::Response<std::string>(responseBody, std::move(response));
} }
@ -891,7 +890,7 @@ namespace Azure { namespace Core { namespace Test {
auto request = Azure::Core::Http::Request( auto request = Azure::Core::Http::Request(
Azure::Core::Http::HttpMethod::Get, Azure::Core::Http::HttpMethod::Get,
Azure::Core::Url(TestProxyUrl() + "/Admin/IsAlive")); Azure::Core::Url(TestProxyUrl() + "/Admin/IsAlive"));
auto response = m_pipeline->Send(request, Azure::Core::Context::ApplicationContext); auto response = m_pipeline->Send(request, Azure::Core::Context{});
auto statusCode = response->GetStatusCode(); auto statusCode = response->GetStatusCode();
return Azure::Response<Azure::Core::Http::HttpStatusCode>(statusCode, std::move(response)); return Azure::Response<Azure::Core::Http::HttpStatusCode>(statusCode, std::move(response));
} }

Просмотреть файл

@ -154,7 +154,7 @@ int main(int argc, char** argv)
}}}; }}};
// Call the `Run` method with a context, the tests and the application arguments to launch the program. // Call the `Run` method with a context, the tests and the application arguments to launch the program.
Azure::Perf::Program::Run(Azure::Core::Context::ApplicationContext, tests, argc, argv); Azure::Perf::Program::Run(Azure::Core::Context{}, tests, argc, argv);
return 0; return 0;
} }

Просмотреть файл

@ -16,11 +16,11 @@ TEST(circular_stream, basic)
std::vector<uint8_t> buffer2(chunk); std::vector<uint8_t> buffer2(chunk);
// 1st read // 1st read
auto count = r_stream->Read(buffer.data(), chunk, Azure::Core::Context::ApplicationContext); auto count = r_stream->Read(buffer.data(), chunk, Azure::Core::Context{});
EXPECT_EQ(count, chunk); EXPECT_EQ(count, chunk);
// 2nd read // 2nd read
count = r_stream->Read(buffer2.data(), chunk, Azure::Core::Context::ApplicationContext); count = r_stream->Read(buffer2.data(), chunk, Azure::Core::Context{});
EXPECT_EQ(count, chunk); EXPECT_EQ(count, chunk);
for (size_t i = 0; i != chunk; i++) for (size_t i = 0; i != chunk; i++)
{ {
@ -28,7 +28,7 @@ TEST(circular_stream, basic)
} }
// 3nd read // 3nd read
count = r_stream->Read(buffer.data(), chunk, Azure::Core::Context::ApplicationContext); count = r_stream->Read(buffer.data(), chunk, Azure::Core::Context{});
EXPECT_EQ(count, chunk); EXPECT_EQ(count, chunk);
for (size_t i = 0; i != chunk; i++) for (size_t i = 0; i != chunk; i++)
{ {
@ -36,7 +36,7 @@ TEST(circular_stream, basic)
} }
// 4nd read // 4nd read
count = r_stream->Read(buffer.data(), chunk, Azure::Core::Context::ApplicationContext); count = r_stream->Read(buffer.data(), chunk, Azure::Core::Context{});
EXPECT_EQ(count, 0U); EXPECT_EQ(count, 0U);
// should not change buffer // should not change buffer
for (size_t i = 0; i != chunk; i++) for (size_t i = 0; i != chunk; i++)

Просмотреть файл

@ -12,7 +12,7 @@ int main(int argc, char** argv)
std::vector<Azure::Perf::TestMetadata> tests{ std::vector<Azure::Perf::TestMetadata> tests{
Azure::Messaging::EventHubs::PerfTest::Batch::BatchTest::GetTestMetadata()}; Azure::Messaging::EventHubs::PerfTest::Batch::BatchTest::GetTestMetadata()};
Azure::Perf::Program::Run(Azure::Core::Context::ApplicationContext, tests, argc, argv); Azure::Perf::Program::Run(Azure::Core::Context{}, tests, argc, argv);
return 0; return 0;
} }

Просмотреть файл

@ -385,13 +385,10 @@ namespace Azure { namespace Messaging { namespace EventHubs { namespace Test {
EXPECT_EQ(totalReceived, numberOfEvents); EXPECT_EQ(totalReceived, numberOfEvents);
// We have consumed all the events. Attempting to consume one more should block. // We have consumed all the events. Attempting to consume one more should block.
{ Azure::Core::Context timeout{Azure::DateTime::clock::now() + std::chrono::seconds(3)};
Azure::Core::Context timeout = Azure::Core::Context::ApplicationContext.WithDeadline(
Azure::DateTime::clock::now() + std::chrono::seconds(3));
EXPECT_THROW( EXPECT_THROW(
partitionClient.ReceiveEvents(50, timeout), Azure::Core::OperationCancelledException); partitionClient.ReceiveEvents(50, timeout), Azure::Core::OperationCancelledException);
} }
}
eventhubNamespace.DeleteEventHub(eventHubName); eventhubNamespace.DeleteEventHub(eventHubName);
} }

Просмотреть файл

@ -86,8 +86,8 @@ namespace Azure { namespace Messaging { namespace EventHubs { namespace Test {
void TestWithLoadBalancer(Models::ProcessorStrategy processorStrategy) void TestWithLoadBalancer(Models::ProcessorStrategy processorStrategy)
{ {
Azure::Core::Context context = Azure::Core::Context::ApplicationContext.WithDeadline( Azure::Core::Context context
Azure::DateTime::clock::now() + std::chrono::minutes(5)); = Azure::Core::Context{Azure::DateTime::clock::now() + std::chrono::minutes(5)};
std::string eventHubName{GetEnv("EVENTHUB_NAME")}; std::string eventHubName{GetEnv("EVENTHUB_NAME")};
@ -163,8 +163,7 @@ namespace Azure { namespace Messaging { namespace EventHubs { namespace Test {
void TestWithLoadBalancerSingleThreaded(Models::ProcessorStrategy processorStrategy) void TestWithLoadBalancerSingleThreaded(Models::ProcessorStrategy processorStrategy)
{ {
Azure::Core::Context context = Azure::Core::Context::ApplicationContext.WithDeadline( Azure::Core::Context context{Azure::DateTime::clock::now() + std::chrono::minutes(5)};
Azure::DateTime::clock::now() + std::chrono::minutes(5));
Azure::Messaging::EventHubs::ConsumerClientOptions consumerClientOptions; Azure::Messaging::EventHubs::ConsumerClientOptions consumerClientOptions;
consumerClientOptions.ApplicationID consumerClientOptions.ApplicationID
@ -217,8 +216,7 @@ namespace Azure { namespace Messaging { namespace EventHubs { namespace Test {
void TestPartitionAcquisition(Models::ProcessorStrategy processorStrategy) void TestPartitionAcquisition(Models::ProcessorStrategy processorStrategy)
{ {
Azure::Core::Context context = Azure::Core::Context::ApplicationContext.WithDeadline( Azure::Core::Context context{Azure::DateTime::clock::now() + std::chrono::minutes(5)};
Azure::DateTime::clock::now() + std::chrono::minutes(5));
Azure::Messaging::EventHubs::ConsumerClientOptions consumerClientOptions; Azure::Messaging::EventHubs::ConsumerClientOptions consumerClientOptions;
consumerClientOptions.ApplicationID consumerClientOptions.ApplicationID
@ -579,8 +577,7 @@ namespace Azure { namespace Messaging { namespace EventHubs { namespace Test {
} }
// Attempts to retrieve a partition client should throw because there are no clients available. // Attempts to retrieve a partition client should throw because there are no clients available.
auto context = Azure::Core::Context::ApplicationContext.WithDeadline( Azure::Core::Context context{Azure::DateTime::clock::now() + std::chrono::milliseconds(50)};
Azure::DateTime::clock::now() + std::chrono::milliseconds(50));
EXPECT_ANY_THROW(processor.NextPartitionClient(context)); EXPECT_ANY_THROW(processor.NextPartitionClient(context));
while (!partitionClients.empty()) while (!partitionClients.empty())

Просмотреть файл

@ -17,7 +17,7 @@ int main()
Azure::Service::Client azureServiceClient("serviceUrl", azureCliCredential); Azure::Service::Client azureServiceClient("serviceUrl", azureCliCredential);
// Step 3: Start using the Azure Service Client. // Step 3: Start using the Azure Service Client.
azureServiceClient.DoSomething(Azure::Core::Context::ApplicationContext); azureServiceClient.DoSomething(Azure::Core::Context{});
std::cout << "Success!" << std::endl; std::cout << "Success!" << std::endl;
} }

Просмотреть файл

@ -27,7 +27,7 @@ int main()
Azure::Service::Client azureServiceClient("serviceUrl", chainedTokenCredential); Azure::Service::Client azureServiceClient("serviceUrl", chainedTokenCredential);
// Step 3: Start using the Azure Service Client. // Step 3: Start using the Azure Service Client.
azureServiceClient.DoSomething(Azure::Core::Context::ApplicationContext); azureServiceClient.DoSomething();
std::cout << "Success!" << std::endl; std::cout << "Success!" << std::endl;
} }

Просмотреть файл

@ -27,7 +27,7 @@ int main()
Azure::Service::Client azureServiceClient("serviceUrl", clientCertificateCredential); Azure::Service::Client azureServiceClient("serviceUrl", clientCertificateCredential);
// Step 3: Start using the Azure Service Client. // Step 3: Start using the Azure Service Client.
azureServiceClient.DoSomething(Azure::Core::Context::ApplicationContext); azureServiceClient.DoSomething();
std::cout << "Success!" << std::endl; std::cout << "Success!" << std::endl;
} }

Просмотреть файл

@ -26,7 +26,7 @@ int main()
Azure::Service::Client azureServiceClient("serviceUrl", clientSecretCredential); Azure::Service::Client azureServiceClient("serviceUrl", clientSecretCredential);
// Step 3: Start using the Azure Service Client. // Step 3: Start using the Azure Service Client.
azureServiceClient.DoSomething(Azure::Core::Context::ApplicationContext); azureServiceClient.DoSomething();
std::cout << "Success!" << std::endl; std::cout << "Success!" << std::endl;
} }

Просмотреть файл

@ -21,7 +21,7 @@ int main()
Azure::Service::Client azureServiceClient("serviceUrl", defaultAzureCredential); Azure::Service::Client azureServiceClient("serviceUrl", defaultAzureCredential);
// Step 3: Start using the Azure Service Client. // Step 3: Start using the Azure Service Client.
azureServiceClient.DoSomething(Azure::Core::Context::ApplicationContext); azureServiceClient.DoSomething();
std::cout << "Success!" << std::endl; std::cout << "Success!" << std::endl;
} }

Просмотреть файл

@ -19,7 +19,7 @@ int main()
Azure::Service::Client azureServiceClient("serviceUrl", environmentCredential); Azure::Service::Client azureServiceClient("serviceUrl", environmentCredential);
// Step 3: Start using the Azure Service Client. // Step 3: Start using the Azure Service Client.
azureServiceClient.DoSomething(Azure::Core::Context::ApplicationContext); azureServiceClient.DoSomething();
std::cout << "Success!" << std::endl; std::cout << "Success!" << std::endl;
} }

Просмотреть файл

@ -19,7 +19,7 @@ int main()
Azure::Service::Client azureServiceClient("serviceUrl", managedIdentityCredential); Azure::Service::Client azureServiceClient("serviceUrl", managedIdentityCredential);
// Step 3: Start using the Azure Service Client. // Step 3: Start using the Azure Service Client.
azureServiceClient.DoSomething(Azure::Core::Context::ApplicationContext); azureServiceClient.DoSomething();
std::cout << "Success!" << std::endl; std::cout << "Success!" << std::endl;
} }

Просмотреть файл

@ -23,7 +23,7 @@ int main()
Azure::Service::Client azureServiceClient("serviceUrl", workloadIdentityCredential); Azure::Service::Client azureServiceClient("serviceUrl", workloadIdentityCredential);
// Step 3: Start using the Azure Service Client. // Step 3: Start using the Azure Service Client.
azureServiceClient.DoSomething(Azure::Core::Context::ApplicationContext); azureServiceClient.DoSomething();
std::cout << "Success!" << std::endl; std::cout << "Success!" << std::endl;
} }

Просмотреть файл

@ -16,7 +16,7 @@ int main(int argc, char** argv)
Azure::Identity::Test::EnvironmentCredentialTest::GetTestMetadata(), Azure::Identity::Test::EnvironmentCredentialTest::GetTestMetadata(),
Azure::Identity::Test::SecretCredentialTest::GetTestMetadata()}; Azure::Identity::Test::SecretCredentialTest::GetTestMetadata()};
Azure::Perf::Program::Run(Azure::Core::Context::ApplicationContext, tests, argc, argv); Azure::Perf::Program::Run(Azure::Core::Context{}, tests, argc, argv);
return 0; return 0;
} }

Просмотреть файл

@ -297,8 +297,7 @@ TEST(AzureCliCredential, ContextCancelled)
TokenRequestContext trc; TokenRequestContext trc;
trc.Scopes.push_back("https://storage.azure.com/.default"); trc.Scopes.push_back("https://storage.azure.com/.default");
auto context = Context::ApplicationContext.WithDeadline( Context context{std::chrono::system_clock::now() + std::chrono::hours(24)};
std::chrono::system_clock::now() + std::chrono::hours(24));
std::atomic<bool> thread1Started(false); std::atomic<bool> thread1Started(false);

Просмотреть файл

@ -68,8 +68,7 @@ TEST_F(TokenCredentialTest, ClientSecret)
tokenRequestContext.Scopes = {"https://vault.azure.net/.default"}; tokenRequestContext.Scopes = {"https://vault.azure.net/.default"};
tokenRequestContext.MinimumExpiration = std::chrono::hours(1000000); tokenRequestContext.MinimumExpiration = std::chrono::hours(1000000);
auto const token = clientSecretCredential->GetToken( auto const token = clientSecretCredential->GetToken(tokenRequestContext, Azure::Core::Context{});
tokenRequestContext, Azure::Core::Context::ApplicationContext);
EXPECT_FALSE(token.Token.empty()); EXPECT_FALSE(token.Token.empty());
EXPECT_GE(token.ExpiresOn, std::chrono::system_clock::now()); EXPECT_GE(token.ExpiresOn, std::chrono::system_clock::now());
@ -90,8 +89,7 @@ TEST_F(TokenCredentialTest, EnvironmentCredential)
tokenRequestContext.Scopes = {"https://vault.azure.net/.default"}; tokenRequestContext.Scopes = {"https://vault.azure.net/.default"};
tokenRequestContext.MinimumExpiration = std::chrono::hours(1000000); tokenRequestContext.MinimumExpiration = std::chrono::hours(1000000);
auto const token = clientSecretCredential->GetToken( auto const token = clientSecretCredential->GetToken(tokenRequestContext, Azure::Core::Context{});
tokenRequestContext, Azure::Core::Context::ApplicationContext);
EXPECT_FALSE(token.Token.empty()); EXPECT_FALSE(token.Token.empty());
EXPECT_GE(token.ExpiresOn, std::chrono::system_clock::now()); EXPECT_GE(token.ExpiresOn, std::chrono::system_clock::now());

Просмотреть файл

@ -18,7 +18,7 @@
{ {
"name": "azure-core-cpp", "name": "azure-core-cpp",
"default-features": false, "default-features": false,
"version>=": "1.9.0" "version>=": "1.14.0-beta.1"
}, },
{ {
"name": "openssl", "name": "openssl",

Просмотреть файл

@ -12,7 +12,7 @@ int main(int argc, char** argv)
std::vector<Azure::Perf::TestMetadata> tests{ std::vector<Azure::Perf::TestMetadata> tests{
Azure::Security::KeyVault::Certificates::Test::GetCertificate::GetTestMetadata()}; Azure::Security::KeyVault::Certificates::Test::GetCertificate::GetTestMetadata()};
Azure::Perf::Program::Run(Azure::Core::Context::ApplicationContext, tests, argc, argv); Azure::Perf::Program::Run(Azure::Core::Context{}, tests, argc, argv);
return 0; return 0;
} }

Просмотреть файл

@ -12,7 +12,7 @@ int main(int argc, char** argv)
std::vector<Azure::Perf::TestMetadata> tests{ std::vector<Azure::Perf::TestMetadata> tests{
Azure::Security::KeyVault::Keys::Test::GetKey::GetTestMetadata()}; Azure::Security::KeyVault::Keys::Test::GetKey::GetTestMetadata()};
Azure::Perf::Program::Run(Azure::Core::Context::ApplicationContext, tests, argc, argv); Azure::Perf::Program::Run(Azure::Core::Context{}, tests, argc, argv);
return 0; return 0;
} }

Просмотреть файл

@ -49,7 +49,7 @@ TEST_F(KeyVaultKeyClient, DeleteKey)
// for so long if something happens and no exception is thrown (paranoid scenario) // for so long if something happens and no exception is thrown (paranoid scenario)
auto duration auto duration
= std::chrono::system_clock::now() + std::chrono::minutes(m_testPollingTimeOutMinutes); = std::chrono::system_clock::now() + std::chrono::minutes(m_testPollingTimeOutMinutes);
auto cancelToken = Azure::Core::Context::ApplicationContext.WithDeadline(duration); Azure::Core::Context cancelToken{duration};
auto keyResponseLRO = client.StartDeleteKey(keyName); auto keyResponseLRO = client.StartDeleteKey(keyName);
auto expectedStatusToken = keyName; auto expectedStatusToken = keyName;
@ -124,7 +124,7 @@ TEST_F(KeyVaultKeyClient, DoubleDelete)
{ {
auto duration auto duration
= std::chrono::system_clock::now() + std::chrono::minutes(m_testPollingTimeOutMinutes); = std::chrono::system_clock::now() + std::chrono::minutes(m_testPollingTimeOutMinutes);
auto cancelToken = Azure::Core::Context::ApplicationContext.WithDeadline(duration); Azure::Core::Context cancelToken{duration};
auto keyResponseLRO = client.StartDeleteKey(keyName); auto keyResponseLRO = client.StartDeleteKey(keyName);
auto keyResponse = keyResponseLRO.PollUntilDone(m_testPollingIntervalMs, cancelToken); auto keyResponse = keyResponseLRO.PollUntilDone(m_testPollingIntervalMs, cancelToken);
} }
@ -197,7 +197,7 @@ TEST_F(KeyVaultKeyClient, CreateDeletedKey)
{ {
auto duration auto duration
= std::chrono::system_clock::now() + std::chrono::minutes(m_testPollingTimeOutMinutes); = std::chrono::system_clock::now() + std::chrono::minutes(m_testPollingTimeOutMinutes);
auto cancelToken = Azure::Core::Context::ApplicationContext.WithDeadline(duration); Azure::Core::Context cancelToken{duration};
auto keyResponseLRO = client.StartDeleteKey(keyName); auto keyResponseLRO = client.StartDeleteKey(keyName);
auto keyResponse = keyResponseLRO.PollUntilDone(m_testPollingIntervalMs, cancelToken); auto keyResponse = keyResponseLRO.PollUntilDone(m_testPollingIntervalMs, cancelToken);
} }
@ -281,7 +281,7 @@ TEST_F(KeyVaultKeyClient, GetDeletedKey)
// Wait until key is deleted // Wait until key is deleted
auto duration auto duration
= std::chrono::system_clock::now() + std::chrono::minutes(m_testPollingTimeOutMinutes); = std::chrono::system_clock::now() + std::chrono::minutes(m_testPollingTimeOutMinutes);
auto cancelToken = Azure::Core::Context::ApplicationContext.WithDeadline(duration); Azure::Core::Context cancelToken{duration};
auto keyResponseLRO = client.StartDeleteKey(keyName); auto keyResponseLRO = client.StartDeleteKey(keyName);
auto expectedStatusToken = m_keyVaultUrl auto expectedStatusToken = m_keyVaultUrl

Просмотреть файл

@ -18,7 +18,7 @@
{ {
"name": "azure-core-cpp", "name": "azure-core-cpp",
"default-features": false, "default-features": false,
"version>=": "1.9.0" "version>=": "1.14.0-beta.1"
}, },
{ {
"name": "vcpkg-cmake", "name": "vcpkg-cmake",

Просмотреть файл

@ -12,7 +12,7 @@ int main(int argc, char** argv)
std::vector<Azure::Perf::TestMetadata> tests{ std::vector<Azure::Perf::TestMetadata> tests{
Azure::Security::KeyVault::Secrets::Test::GetSecret::GetTestMetadata()}; Azure::Security::KeyVault::Secrets::Test::GetSecret::GetTestMetadata()};
Azure::Perf::Program::Run(Azure::Core::Context::ApplicationContext, tests, argc, argv); Azure::Perf::Program::Run(Azure::Core::Context{}, tests, argc, argv);
return 0; return 0;
} }

Просмотреть файл

@ -26,3 +26,7 @@ create_per_service_target_build_for_sample(storage transactional-checksum)
add_executable(blob-query blob_query.cpp) add_executable(blob-query blob_query.cpp)
target_link_libraries(blob-query PRIVATE azure-storage-blobs get-env-helper) target_link_libraries(blob-query PRIVATE azure-storage-blobs get-env-helper)
create_per_service_target_build_for_sample(storage blob-query) create_per_service_target_build_for_sample(storage blob-query)
add_executable(blob_list_operation_with_timeout blob_list_operation_with_timeout.cpp)
target_link_libraries(blob_list_operation_with_timeout PRIVATE azure-storage-blobs get-env-helper)
create_per_service_target_build_for_sample(storage blob_list_operation_with_timeout)

Просмотреть файл

@ -0,0 +1,82 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include <azure/core/context.hpp>
#include <azure/storage/blobs.hpp>
#include <iostream>
#include <stdexcept>
std::string GetConnectionString()
{
const static std::string ConnectionString = "";
if (!ConnectionString.empty())
{
return ConnectionString;
}
const static std::string envConnectionString = std::getenv("AZURE_STORAGE_CONNECTION_STRING");
if (!envConnectionString.empty())
{
return envConnectionString;
}
throw std::runtime_error("Cannot find connection string.");
}
int main()
{
using namespace Azure::Storage::Blobs;
const std::string containerName = "sample-container";
const std::string blobName = "sample-blob";
const std::string blobContent = "Hello Azure!";
{
// Create some containers and blobs for test
for (int i = 0; i < 2; ++i)
{
// @begin_snippet: CreateBlobContext
Azure::Core::Context cancelledIn5s{
std::chrono::system_clock::now() + std::chrono::seconds(5)};
auto containerClient = BlobContainerClient::CreateFromConnectionString(
GetConnectionString(), containerName + std::to_string(i));
containerClient.CreateIfNotExists({}, cancelledIn5s);
for (int j = 0; j < 3; ++j)
{
BlockBlobClient blobClient
= containerClient.GetBlockBlobClient(blobName + std::to_string(j));
blobClient.UploadFrom(
reinterpret_cast<const uint8_t*>(blobContent.data()),
blobContent.size(),
{},
cancelledIn5s);
}
// @end_snippet: CreateBlobContext
}
}
auto serviceClient = BlobServiceClient::CreateFromConnectionString(GetConnectionString());
for (auto containerPage = serviceClient.ListBlobContainers(); containerPage.HasPage();
containerPage.MoveToNextPage())
{
for (auto& container : containerPage.BlobContainers)
{
// Below is what you want to do with each container
std::cout << "blob container: " << container.Name << std::endl;
for (auto blobPage = serviceClient.GetBlobContainerClient(container.Name).ListBlobs();
blobPage.HasPage();
blobPage.MoveToNextPage())
{
for (auto& blob : blobPage.Blobs)
{
// Below is what you want to do with each blob
std::cout << " blob: " << blob.Name << std::endl;
}
}
}
}
return 0;
}

Просмотреть файл

@ -46,11 +46,6 @@ target_include_directories(
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/inc> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/inc>
) )
if (MSVC)
# allow msvc to use getenv()
target_compile_options(azure-storage-blobs-perf PUBLIC /wd4996)
endif()
# link the `azure-perf` lib together with any other library which will be used for the tests. # link the `azure-perf` lib together with any other library which will be used for the tests.
target_link_libraries(azure-storage-blobs-perf PRIVATE Azure::azure-storage-blobs azure-perf) target_link_libraries(azure-storage-blobs-perf PRIVATE Azure::azure-storage-blobs azure-perf)

Просмотреть файл

@ -48,8 +48,7 @@ namespace Azure { namespace Storage { namespace Blobs { namespace Test {
BlobsTest::Setup(); BlobsTest::Setup();
long size = m_options.GetMandatoryOption<long>("Size"); long size = m_options.GetMandatoryOption<long>("Size");
m_uploadBuffer = Azure::Perf::RandomStream::Create(size)->ReadToEnd( m_uploadBuffer = Azure::Perf::RandomStream::Create(size)->ReadToEnd(Azure::Core::Context{});
Azure::Core::Context::ApplicationContext);
} }
/** /**

Просмотреть файл

@ -31,7 +31,7 @@ int main(int argc, char** argv)
Azure::Storage::Blobs::Test::DownloadBlobWithPipelineOnly::GetTestMetadata() Azure::Storage::Blobs::Test::DownloadBlobWithPipelineOnly::GetTestMetadata()
}; };
Azure::Perf::Program::Run(Azure::Core::Context::ApplicationContext, tests, argc, argv); Azure::Perf::Program::Run(Azure::Core::Context{}, tests, argc, argv);
return 0; return 0;
} }

Просмотреть файл

@ -18,7 +18,7 @@
{ {
"name": "azure-core-cpp", "name": "azure-core-cpp",
"default-features": false, "default-features": false,
"version>=": "1.12.0" "version>=": "1.14.0-beta.1"
}, },
{ {
"name": "libxml2", "name": "libxml2",