Skip to content

Commit 6c51999

Browse files
authored
Move ExecuteOrSchedule function to TaskScheduler (#1279)
Move ExecuteOrSchedule function to TaskScheduler Remove ExecuteOrSchedule in other places Add unit tests to cover usage of ExecuteOrSchedule without network Add unit test for ExecuteOrSchedule method Resolves: OLPEDGE-1171 Signed-off-by: Yevhenii Dudnyk <[email protected]>
1 parent 0078be8 commit 6c51999

File tree

9 files changed

+170
-52
lines changed

9 files changed

+170
-52
lines changed

olp-cpp-sdk-authentication/src/AuthenticationClientImpl.cpp

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -551,7 +551,7 @@ client::CancellationToken AuthenticationClientImpl::SignUpHereUser(
551551
const AuthenticationCredentials& credentials,
552552
const SignUpProperties& properties, const SignUpCallback& callback) {
553553
if (!settings_.network_request_handler) {
554-
ExecuteOrSchedule(settings_.task_scheduler, [callback] {
554+
thread::ExecuteOrSchedule(settings_.task_scheduler, [callback] {
555555
callback(
556556
client::ApiError::NetworkConnection("Cannot sign up while offline"));
557557
});
@@ -606,7 +606,8 @@ client::CancellationToken AuthenticationClientImpl::SignUpHereUser(
606606
});
607607

608608
if (!send_outcome.IsSuccessful()) {
609-
ExecuteOrSchedule(settings_.task_scheduler, [send_outcome, callback] {
609+
thread::ExecuteOrSchedule(settings_.task_scheduler, [send_outcome,
610+
callback] {
610611
std::string error_message =
611612
ErrorCodeToString(send_outcome.GetErrorCode());
612613
AuthenticationError result({static_cast<int>(send_outcome.GetErrorCode()),
@@ -630,7 +631,7 @@ client::CancellationToken AuthenticationClientImpl::SignOut(
630631
const AuthenticationCredentials& credentials,
631632
const std::string& access_token, const SignOutUserCallback& callback) {
632633
if (!settings_.network_request_handler) {
633-
ExecuteOrSchedule(settings_.task_scheduler, [callback] {
634+
thread::ExecuteOrSchedule(settings_.task_scheduler, [callback] {
634635
callback(
635636
client::ApiError::NetworkConnection("Cannot sign out while offline"));
636637
});
@@ -680,7 +681,8 @@ client::CancellationToken AuthenticationClientImpl::SignOut(
680681
});
681682

682683
if (!send_outcome.IsSuccessful()) {
683-
ExecuteOrSchedule(settings_.task_scheduler, [send_outcome, callback] {
684+
thread::ExecuteOrSchedule(settings_.task_scheduler, [send_outcome,
685+
callback] {
684686
std::string error_message =
685687
ErrorCodeToString(send_outcome.GetErrorCode());
686688
AuthenticationError result({static_cast<int>(send_outcome.GetErrorCode()),

olp-cpp-sdk-authentication/src/AuthenticationClientUtils.cpp

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -119,19 +119,6 @@ boost::optional<std::time_t> GetTimestampFromHeaders(
119119
return boost::none;
120120
}
121121

122-
void ExecuteOrSchedule(
123-
const std::shared_ptr<olp::thread::TaskScheduler>& task_scheduler,
124-
olp::thread::TaskScheduler::CallFuncType&& func) {
125-
if (!task_scheduler) {
126-
// User didn't specify a TaskScheduler, execute sync
127-
func();
128-
return;
129-
}
130-
131-
// Schedule for async execution
132-
task_scheduler->ScheduleTask(std::move(func));
133-
}
134-
135122
IntrospectAppResult GetIntrospectAppResult(const rapidjson::Document& doc) {
136123
return ResponseFromJsonBuilder<IntrospectAppResult>::Build(doc)
137124
.Value(Constants::CLIENT_ID, &IntrospectAppResult::SetClientId)

olp-cpp-sdk-authentication/src/AuthenticationClientUtils.h

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (C) 2020 HERE Europe B.V.
2+
* Copyright (C) 2020-2021 HERE Europe B.V.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -36,16 +36,6 @@
3636
namespace olp {
3737
namespace authentication {
3838

39-
/*
40-
* @brief Common function used to add a lambda function and schedule this to a
41-
* task scheduler.
42-
* @param task_scheduler Task scheduler instance.
43-
* @param func Function that will be executed.
44-
*/
45-
void ExecuteOrSchedule(
46-
const std::shared_ptr<thread::TaskScheduler>& task_scheduler,
47-
thread::TaskScheduler::CallFuncType&& func);
48-
4939
/*
5040
* @brief Common function used to wrap a lambda function and a callback that
5141
* consumes the function result with a TaskContext class and schedule this to a
@@ -67,7 +57,7 @@ inline client::CancellationToken AddTask(
6757
std::move(task), std::move(callback), std::forward<Args>(args)...);
6858
pending_requests->Insert(context);
6959

70-
ExecuteOrSchedule(task_scheduler, [=] {
60+
thread::ExecuteOrSchedule(task_scheduler, [=] {
7161
context.Execute();
7262
pending_requests->Remove(context);
7363
});

olp-cpp-sdk-authentication/tests/AuthenticationClientTest.cpp

Lines changed: 83 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (C) 2020 HERE Europe B.V.
2+
* Copyright (C) 2020-2021 HERE Europe B.V.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -18,14 +18,14 @@
1818
*/
1919

2020
#include <cstdio>
21-
#include <fstream>
21+
#include <memory>
22+
#include <string>
2223

2324
#include <gmock/gmock.h>
2425

25-
#include "../src/AuthenticationClientImpl.h"
26-
#include "../src/AuthenticationClientUtils.h"
26+
#include "AuthenticationClientImpl.h"
27+
#include "AuthenticationClientUtils.h"
2728
#include "mocks/NetworkMock.h"
28-
#include "olp/core/http/HttpStatusCode.h"
2929

3030
namespace {
3131
constexpr auto kTime = "Fri, 29 May 2020 11:07:45 GMT";
@@ -55,6 +55,84 @@ class AuthenticationClientImplTestable : public auth::AuthenticationClientImpl {
5555

5656
ACTION_P(Wait, time) { std::this_thread::sleep_for(time); }
5757

58+
TEST(AuthenticationClientTest, AuthenticationWithoutNetwork) {
59+
auth::AuthenticationSettings settings;
60+
settings.network_request_handler = nullptr;
61+
62+
AuthenticationClientImplTestable auth_impl(settings);
63+
64+
const auth::AuthenticationCredentials credentials("", "");
65+
66+
{
67+
SCOPED_TRACE("SignUpHereUser, Offline");
68+
69+
auth_impl.SignUpHereUser(
70+
credentials, {},
71+
[=](const auth::AuthenticationClient::SignUpResponse& response) {
72+
EXPECT_FALSE(response.IsSuccessful());
73+
EXPECT_EQ(response.GetError().GetErrorCode(),
74+
client::ErrorCode::NetworkConnection);
75+
});
76+
}
77+
78+
{
79+
SCOPED_TRACE("SignOut, Offline");
80+
81+
auth_impl.SignOut(
82+
credentials, {},
83+
[=](const auth::AuthenticationClient::SignOutUserResponse& response) {
84+
EXPECT_FALSE(response.IsSuccessful());
85+
EXPECT_EQ(response.GetError().GetErrorCode(),
86+
client::ErrorCode::NetworkConnection);
87+
});
88+
}
89+
}
90+
91+
TEST(AuthenticationClientTest, AuthenticationWithUnsuccessfulSend) {
92+
using testing::_;
93+
94+
auth::AuthenticationSettings settings;
95+
auto networkMock = std::make_shared<NetworkMock>();
96+
97+
ON_CALL(*networkMock, Send(_, _, _, _, _))
98+
.WillByDefault([](olp::http::NetworkRequest, olp::http::Network::Payload,
99+
olp::http::Network::Callback,
100+
olp::http::Network::HeaderCallback,
101+
olp::http::Network::DataCallback) {
102+
return olp::http::SendOutcome(olp::http::ErrorCode::UNKNOWN_ERROR);
103+
});
104+
105+
settings.network_request_handler = networkMock;
106+
107+
AuthenticationClientImplTestable auth_impl(settings);
108+
109+
const auth::AuthenticationCredentials credentials("", "");
110+
111+
{
112+
SCOPED_TRACE("SignUpHereUser, Unsuccessful send");
113+
114+
auth_impl.SignUpHereUser(
115+
credentials, {},
116+
[=](const auth::AuthenticationClient::SignUpResponse& response) {
117+
EXPECT_FALSE(response.IsSuccessful());
118+
EXPECT_EQ(response.GetError().GetErrorCode(),
119+
client::ErrorCode::Unknown);
120+
});
121+
}
122+
123+
{
124+
SCOPED_TRACE("SignOut, Unsuccessful send");
125+
126+
auth_impl.SignOut(
127+
credentials, {},
128+
[=](const auth::AuthenticationClient::SignOutUserResponse& response) {
129+
EXPECT_FALSE(response.IsSuccessful());
130+
EXPECT_EQ(response.GetError().GetErrorCode(),
131+
client::ErrorCode::Unknown);
132+
});
133+
}
134+
}
135+
58136
TEST(AuthenticationClientTest, Timestamp) {
59137
using testing::_;
60138

olp-cpp-sdk-core/include/olp/core/thread/TaskScheduler.h

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ class CORE_API TaskScheduler {
9696
auto task = [func, context]() {
9797
if (!context.IsCancelled()) {
9898
func(context);
99-
};
99+
}
100100
};
101101
EnqueueTask(std::move(task));
102102
return context;
@@ -138,5 +138,25 @@ class CORE_API TaskScheduler {
138138
}
139139
};
140140

141+
/**
142+
* @brief Common function used to add a lambda function and schedule this to a
143+
* task scheduler.
144+
*
145+
* @param task_scheduler Task scheduler instance.
146+
* @param func Function that will be executed.
147+
*/
148+
inline CORE_API void ExecuteOrSchedule(
149+
const std::shared_ptr<TaskScheduler>& scheduler,
150+
TaskScheduler::CallFuncType&& func) {
151+
if (!scheduler) {
152+
// User didn't specify a TaskScheduler, execute sync
153+
func();
154+
return;
155+
}
156+
157+
// Schedule for async execution
158+
scheduler->ScheduleTask(std::move(func));
159+
}
160+
141161
} // namespace thread
142162
} // namespace olp

olp-cpp-sdk-core/tests/thread/ThreadPoolTaskSchedulerTest.cpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525

2626
#include <olp/core/client/CancellationContext.h>
2727
#include <olp/core/thread/ThreadPoolTaskScheduler.h>
28+
#include "mocks/TaskSchedulerMock.h"
2829

2930
using SyncTaskType = std::function<void()>;
3031
using CancellationContext = olp::client::CancellationContext;
@@ -280,3 +281,23 @@ TEST(ThreadPoolTaskSchedulerTest, Move) {
280281
thread_pool.reset();
281282
testing::Mock::VerifyAndClearExpectations(&mockop);
282283
}
284+
285+
TEST(ThreadPoolTaskSchedulerTest, ExecuteOrSchedule) {
286+
{
287+
using testing::_;
288+
SCOPED_TRACE("Schedule Task, ExecuteOrSchedule");
289+
290+
auto scheduler = std::make_shared<TaskSchedulerMock>();
291+
EXPECT_CALL(*scheduler, EnqueueTask(_)).Times(1);
292+
293+
olp::thread::ExecuteOrSchedule(scheduler, []() {});
294+
}
295+
296+
{
297+
SCOPED_TRACE("Execute task immediately, ExecuteOrSchedule");
298+
299+
auto counter(0u);
300+
olp::thread::ExecuteOrSchedule(nullptr, [&counter]() { counter++; });
301+
EXPECT_EQ(counter, 1);
302+
}
303+
}

olp-cpp-sdk-dataservice-write/src/StreamLayerClientImpl.cpp

Lines changed: 4 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (C) 2019-2020 HERE Europe B.V.
2+
* Copyright (C) 2019-2021 HERE Europe B.V.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -57,18 +57,6 @@ namespace write {
5757
namespace {
5858
constexpr auto kLogTag = "StreamLayerClientImpl";
5959
constexpr int64_t kTwentyMib = 20971520; // 20 MiB
60-
61-
void ExecuteOrSchedule(const std::shared_ptr<thread::TaskScheduler>& scheduler,
62-
thread::TaskScheduler::CallFuncType&& func) {
63-
if (!scheduler) {
64-
// User didn't specify a TaskScheduler, execute sync
65-
func();
66-
return;
67-
}
68-
69-
// Schedule for async execution
70-
scheduler->ScheduleTask(std::move(func));
71-
}
7260
} // namespace
7361

7462
StreamLayerClientImpl::StreamLayerClientImpl(
@@ -268,7 +256,7 @@ olp::client::CancellationToken StreamLayerClientImpl::Flush(
268256
auto pending_requests = pending_requests_;
269257
pending_requests->Insert(task_context);
270258

271-
ExecuteOrSchedule(task_scheduler_, [=]() {
259+
thread::ExecuteOrSchedule(task_scheduler_, [=]() {
272260
task_context.Execute();
273261
pending_requests->Remove(task_context);
274262
});
@@ -302,7 +290,7 @@ client::CancellationToken StreamLayerClientImpl::PublishData(
302290
auto pending_requests = pending_requests_;
303291
pending_requests->Insert(task_context);
304292

305-
ExecuteOrSchedule(task_scheduler_, [=]() {
293+
thread::ExecuteOrSchedule(task_scheduler_, [=]() {
306294
task_context.Execute();
307295
pending_requests->Remove(task_context);
308296
});
@@ -491,7 +479,7 @@ client::CancellationToken StreamLayerClientImpl::PublishSdii(
491479
auto pending_requests = pending_requests_;
492480
pending_requests->Insert(context);
493481

494-
ExecuteOrSchedule(task_scheduler_, [=]() {
482+
thread::ExecuteOrSchedule(task_scheduler_, [=]() {
495483
context.Execute();
496484
pending_requests->Remove(context);
497485
});

tests/common/CMakeLists.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@
1717

1818
set(OLP_SDK_TESTS_COMMON_HEADERS
1919
${CMAKE_CURRENT_SOURCE_DIR}/matchers/NetworkUrlMatchers.h
20-
${CMAKE_CURRENT_SOURCE_DIR}/mocks/NetworkMock.h
2120
${CMAKE_CURRENT_SOURCE_DIR}/mocks/CacheMock.h
21+
${CMAKE_CURRENT_SOURCE_DIR}/mocks/NetworkMock.h
22+
${CMAKE_CURRENT_SOURCE_DIR}/mocks/TaskSchedulerMock.h
2223
${CMAKE_CURRENT_SOURCE_DIR}/ApiDefaultResponses.h
2324
${CMAKE_CURRENT_SOURCE_DIR}/KeyValueCacheTestable.h
2425
${CMAKE_CURRENT_SOURCE_DIR}/PlatformUrlsGenerator.h
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
* Copyright (C) 2021 HERE Europe B.V.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*
16+
* SPDX-License-Identifier: Apache-2.0
17+
* License-Filename: LICENSE
18+
*/
19+
20+
#pragma once
21+
22+
#include <gmock/gmock.h>
23+
#include <olp/core/thread/TaskScheduler.h>
24+
25+
class TaskSchedulerMock : public olp::thread::TaskScheduler {
26+
public:
27+
MOCK_METHOD(void, EnqueueTask, (olp::thread::TaskScheduler::CallFuncType &&),
28+
(override));
29+
30+
MOCK_METHOD(void, EnqueueTask, (CallFuncType&&, uint32_t), (override));
31+
};

0 commit comments

Comments
 (0)