* Copyright (c) 2025-2026 IB-Robot Group & openEuler Embedded SIG & openharmony-robot sig_RoboFrame.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ibmw_selfdev/coro/task.h"
#include <gtest/gtest.h>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <coroutine>
#include <exception>
#include <memory>
#include <mutex>
#include <optional>
#include <stdexcept>
#include <string>
#include <thread>
#include <utility>
#include "ibmw_selfdev/coro/export.h"
#include "ibmw_selfdev/coro/on.h"
#include "ibmw_selfdev/coro/sync_wait.h"
#include "ibmw_selfdev/coro/then.h"
#include "thread_pool_scheduler.h"
namespace ibmw::selfdev::coro {
namespace {
Task<int> Value(int v)
{
co_return v;
}
Task<int> Add(int a, int b)
{
co_return co_await Value(a) + co_await Value(b);
}
Task<int> Outer()
{
co_return co_await Add(20, 22);
}
Task<void> Throws()
{
throw std::runtime_error("boom");
co_return;
}
TEST(CoroTask, IsLazy)
{
int ran = 0;
auto body = [&ran]() -> Task<void> {
++ran;
co_return;
};
auto t = body();
EXPECT_EQ(ran, 0);
SyncWait(std::move(t));
EXPECT_EQ(ran, 1);
}
TEST(CoroTask, ReturnsValue)
{
auto r = SyncWait(Value(42));
ASSERT_TRUE(r.has_value());
EXPECT_EQ(*r, 42);
}
TEST(CoroTask, VoidTaskYieldsUnit)
{
auto body = []() -> Task<void> { co_return; };
std::optional<Unit> r = SyncWait(body());
EXPECT_TRUE(r.has_value());
}
TEST(CoroTask, NestedAwait)
{
EXPECT_EQ(*SyncWait(Outer()), 42);
}
TEST(CoroTask, ExceptionPropagates)
{
auto catcher = []() -> Task<int> {
try {
co_await Throws();
} catch (const std::runtime_error& e) {
co_return std::string(e.what()) == "boom" ? 1 : 0;
}
co_return -1;
};
EXPECT_EQ(*SyncWait(catcher()), 1);
EXPECT_THROW(SyncWait(Throws()), std::runtime_error);
}
TEST(CoroTask, MoveOnlyResult)
{
auto body = []() -> Task<std::unique_ptr<int>> { co_return std::make_unique<int>(7); };
auto r = SyncWait(body());
ASSERT_TRUE(r.has_value());
ASSERT_NE(*r, nullptr);
EXPECT_EQ(**r, 7);
}
struct DtorCounter {
explicit DtorCounter(int* c) : count(c) {}
DtorCounter(DtorCounter&& o) noexcept : count(std::exchange(o.count, nullptr)) {}
~DtorCounter()
{
if (count) {
++*count;
}
}
int* count;
};
TEST(CoroTask, UnstartedTaskDestroysFrame)
{
int destroyed = 0;
int ran = 0;
{
auto body = [](DtorCounter, int* r) -> Task<void> {
++*r;
co_return;
};
auto t = body(DtorCounter(&destroyed), &ran);
EXPECT_EQ(destroyed, 0);
}
EXPECT_EQ(ran, 0);
EXPECT_EQ(destroyed, 1);
}
Task<int> One()
{
co_return 1;
}
TEST(CoroTask, DeepSynchronousLoopDoesNotOverflow)
{
auto loop = []() -> Task<long> {
long sum = 0;
for (int i = 0; i < 1000000; ++i) {
sum += co_await One();
}
co_return sum;
};
EXPECT_EQ(*SyncWait(loop()), 1000000);
}
struct OtherThreadAwaitable {
explicit OtherThreadAwaitable(int v) noexcept : value(v) {}
int value;
bool await_ready() const noexcept { return false; }
IBMW_SELFDEV_CORO_NOINLINE void await_suspend(std::coroutine_handle<> h) const
{
std::thread([h] { h.resume(); }).detach();
}
int await_resume() const noexcept { return value; }
};
TEST(CoroTask, AwaitsCustomAwaitable)
{
auto body = []() -> Task<int> {
int a = co_await OtherThreadAwaitable(40);
int b = co_await OtherThreadAwaitable(2);
co_return a + b;
};
EXPECT_EQ(*SyncWait(body()), 42);
}
TEST(CoroTask, MoveConstructAndAssign)
{
int destroyed = 0;
auto body = [](DtorCounter) -> Task<int> { co_return 5; };
Task<int> a = body(DtorCounter(&destroyed));
Task<int> b(std::move(a));
EXPECT_FALSE(a.Valid());
EXPECT_TRUE(b.Valid());
Task<int> c = body(DtorCounter(&destroyed));
c = std::move(b);
EXPECT_EQ(destroyed, 1);
EXPECT_FALSE(b.Valid());
EXPECT_EQ(*SyncWait(std::move(c)), 5);
EXPECT_EQ(destroyed, 2);
}
struct LateStartAwaitable {
explicit LateStartAwaitable(std::thread::id* r) noexcept : resumer(r) {}
std::thread::id* resumer;
bool await_ready() const noexcept { return false; }
IBMW_SELFDEV_CORO_NOINLINE void await_suspend(std::coroutine_handle<> h) const
{
std::thread([h] { h.resume(); }).detach();
std::this_thread::sleep_for(std::chrono::milliseconds(2));
}
void await_resume() const noexcept { *resumer = detail::CurrentThreadId(); }
};
TEST(CoroTask, AsyncCompletionDuringStartResumesOnCompletingThread)
{
for (int i = 0; i < 50; ++i) {
std::thread::id childThread;
std::thread::id parentThread;
auto child = [&childThread]() -> Task<int> {
co_await LateStartAwaitable(&childThread);
co_return 7;
};
auto parent = [&child, &parentThread]() -> Task<int> {
int v = co_await child();
parentThread = detail::CurrentThreadId();
co_return v;
};
EXPECT_EQ(*SyncWait(parent()), 7);
EXPECT_NE(childThread, detail::CurrentThreadId());
EXPECT_EQ(parentThread, childThread);
}
}
TEST(CoroTask, OnThenAlwaysContinuesOnPool)
{
test::ThreadPool pool(2);
for (int i = 0; i < 20000; ++i) {
bool onWorker = false;
auto syncChild = []() -> Task<int> { co_return 1; };
auto markOnWorker = [&onWorker, &pool](int x) {
onWorker = pool.IsWorkerThread();
return x;
};
auto chained = On(pool.GetScheduler(), syncChild()) | Then(markOnWorker);
ASSERT_EQ(*SyncWait(std::move(chained)), 1);
ASSERT_TRUE(onWorker) << "iteration " << i;
}
}
struct EagerDriver {
struct promise_type {
EagerDriver get_return_object() const noexcept { return {}; }
std::suspend_never initial_suspend() const noexcept { return {}; }
std::suspend_never final_suspend() const noexcept { return {}; }
void return_void() const noexcept {}
void unhandled_exception() const noexcept { std::terminate(); }
};
};
struct ParkAwaitable {
explicit ParkAwaitable(std::coroutine_handle<>* p) noexcept : parked(p) {}
std::coroutine_handle<>* parked;
bool await_ready() const noexcept { return false; }
IBMW_SELFDEV_CORO_NOINLINE void await_suspend(std::coroutine_handle<> h) const noexcept { *parked = h; }
void await_resume() const noexcept {}
};
TEST(CoroTask, HandoffParentSuspendsFirst)
{
for (int i = 0; i < 20; ++i) {
std::coroutine_handle<> parked;
std::thread::id parentThread;
std::atomic<bool> done{false};
auto child = [&parked]() -> Task<int> {
co_await ParkAwaitable(&parked);
co_return 7;
};
auto parent = [&child, &parentThread]() -> Task<int> {
int v = co_await child();
parentThread = detail::CurrentThreadId();
co_return v;
};
int result = 0;
auto drive = [&result, &parent, &done]() -> EagerDriver {
result = co_await parent();
done.store(true);
};
drive();
ASSERT_TRUE(parked);
EXPECT_FALSE(done.load());
std::thread::id resumer;
std::thread t([&resumer, &parked] {
resumer = detail::CurrentThreadId();
parked.resume();
});
t.join();
EXPECT_TRUE(done.load());
EXPECT_EQ(result, 7);
EXPECT_EQ(parentThread, resumer);
}
}
struct ResumeInlineAwaitable {
ResumeInlineAwaitable() noexcept {}
bool await_ready() const noexcept { return false; }
IBMW_SELFDEV_CORO_NOINLINE void await_suspend(std::coroutine_handle<> h) const { h.resume(); }
void await_resume() const noexcept {}
};
TEST(CoroTask, ReentrantInlineResumeDoesNotOverflow)
{
auto child = []() -> Task<int> {
co_await ResumeInlineAwaitable();
co_return 1;
};
auto loop = [&child]() -> Task<long> {
long sum = 0;
for (int i = 0; i < 1000000; ++i) {
sum += co_await child();
}
co_return sum;
};
EXPECT_EQ(*SyncWait(loop()), 1000000);
}
TEST(CoroTask, LaterCompletionOnStartingThread)
{
test::ThreadPool pool(1);
auto child = [&pool]() -> Task<std::thread::id> {
co_await pool.GetScheduler().schedule();
co_return detail::CurrentThreadId();
};
auto parent = [&pool, &child]() -> Task<bool> {
co_await pool.GetScheduler().schedule();
const std::thread::id worker = detail::CurrentThreadId();
bool ok = true;
for (int i = 0; i < 10000; ++i) {
ok = ok && (co_await child()) == worker;
ok = ok && detail::CurrentThreadId() == worker;
}
co_return ok;
};
EXPECT_TRUE(*SyncWait(parent()));
}
class HandleMailbox {
public:
void Put(std::coroutine_handle<> h)
{
std::lock_guard<std::mutex> lock(mu_);
h_ = h;
cv_.notify_one();
}
std::coroutine_handle<> Take()
{
std::unique_lock<std::mutex> lock(mu_);
cv_.wait(lock, [this] { return static_cast<bool>(h_); });
return std::exchange(h_, {});
}
private:
std::mutex mu_;
std::condition_variable cv_;
std::coroutine_handle<> h_;
};
struct HandoffAwaitable {
HandoffAwaitable(HandleMailbox* m, void** f, bool n) noexcept : mb(m), frame(f), nested(n) {}
HandleMailbox* mb;
void** frame;
bool nested;
bool await_ready() const noexcept { return false; }
IBMW_SELFDEV_CORO_NOINLINE void await_suspend(std::coroutine_handle<> h) const
{
*frame = h.address();
if (!nested) {
mb->Put(h);
return;
}
HandleMailbox* const box = mb;
std::thread([h] { h.resume(); }).detach();
box->Take().resume();
}
void await_resume() const noexcept {}
};
Task<int> HandoffChild(HandleMailbox* mb, void** frame, bool nested)
{
co_await HandoffAwaitable(mb, frame, nested);
co_return nested ? 1 : 2;
}
TEST(CoroTask, ReusedFrameAddressIsNotInlineCompletion)
{
int reused = 0;
for (int i = 0; i < 200; ++i) {
HandleMailbox mb;
void* first = nullptr;
void* second = nullptr;
auto parent = [&mb, &first, &second]() -> Task<int> {
int a = co_await HandoffChild(&mb, &first, true);
int b = co_await HandoffChild(&mb, &second, false);
co_return a * 10 + b;
};
ASSERT_EQ(*SyncWait(parent()), 12) << "iteration " << i;
if (first == second) {
++reused;
}
}
RecordProperty("reused_frames", reused);
}
TEST(CoroTaskDeathTest, AwaitInvalidTaskTerminates)
{
EXPECT_DEATH(
{
Task<int> a = Value(1);
Task<int> b = std::move(a);
auto body = [&a]() -> Task<int> { co_return co_await std::move(a); };
(void)SyncWait(body());
},
"");
}
}
}