Skip to content

Commit

Permalink
impl(oauth2): make MapCredentials() unit testable (#10426)
Browse files Browse the repository at this point in the history
Add a variant of `rest_internal::MapCredentials()` that can be unit
tested.  Use this to test all interesting code paths in the function.
  • Loading branch information
coryan committed Dec 13, 2022
1 parent 4c59584 commit a65f43f
Show file tree
Hide file tree
Showing 3 changed files with 326 additions and 42 deletions.
12 changes: 9 additions & 3 deletions google/cloud/internal/unified_rest_credentials.cc
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,14 @@ CreateServiceAccountCredentialsFromJsonContents(

std::shared_ptr<oauth2_internal::Credentials> MapCredentials(
std::shared_ptr<google::cloud::Credentials> const& credentials) {
return MapCredentials(std::move(credentials), [](Options const& options) {
return MakeDefaultRestClient("", options);
});
}

std::shared_ptr<oauth2_internal::Credentials> MapCredentials(
std::shared_ptr<google::cloud::Credentials> const& credentials,
oauth2_internal::HttpClientFactory client_factory) {
class Visitor : public CredentialsVisitor {
public:
explicit Visitor(oauth2_internal::HttpClientFactory client_factory)
Expand Down Expand Up @@ -126,9 +134,7 @@ std::shared_ptr<oauth2_internal::Credentials> MapCredentials(
oauth2_internal::HttpClientFactory client_factory_;
};

Visitor visitor([](Options options) {
return MakeDefaultRestClient(std::string{}, std::move(options));
});
Visitor visitor(std::move(client_factory));
CredentialsVisitor::dispatch(*credentials, visitor);
return std::move(visitor.result);
}
Expand Down
10 changes: 10 additions & 0 deletions google/cloud/internal/unified_rest_credentials.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

#include "google/cloud/credentials.h"
#include "google/cloud/internal/oauth2_credentials.h"
#include "google/cloud/internal/oauth2_http_client_factory.h"
#include "google/cloud/version.h"
#include <memory>

Expand All @@ -32,6 +33,15 @@ GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
std::shared_ptr<oauth2_internal::Credentials> MapCredentials(
std::shared_ptr<google::cloud::Credentials> const& credentials);

/**
* @copydoc MapCredentials(std::shared_ptr<google::cloud::Credentials> const&)
*
* This is used in tests, where the HTTP client needs to be mocked.
*/
std::shared_ptr<oauth2_internal::Credentials> MapCredentials(
std::shared_ptr<google::cloud::Credentials> const& credentials,
oauth2_internal::HttpClientFactory client_factory);

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace rest_internal
} // namespace cloud
Expand Down
Loading

0 comments on commit a65f43f

Please sign in to comment.