feat: implement AI schedule app with multi-device sync
- Qt 6 desktop client with day/month/year views, AI scheduling, and TOML settings\n- Go sync server with SQLite change stream, WebSocket notifications, and Docker deployment\n- Client outbox/LWW sync, offline retry, and dual-client integration tests\n- Linux fcitx5 setup, validation reports, and Windows MinGW preset
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
add_executable(test_storage test_storage.cpp)
|
||||
target_link_libraries(test_storage PRIVATE schedule_core Qt6::Test schedule_warnings)
|
||||
add_test(NAME storage COMMAND test_storage)
|
||||
|
||||
add_executable(test_services test_services.cpp)
|
||||
target_link_libraries(test_services PRIVATE schedule_services Qt6::Test schedule_warnings)
|
||||
add_test(NAME services COMMAND test_services)
|
||||
|
||||
add_executable(test_grid test_grid.cpp)
|
||||
target_link_libraries(test_grid PRIVATE schedule_ui Qt6::Test schedule_warnings)
|
||||
add_test(NAME grid COMMAND test_grid)
|
||||
|
||||
add_executable(test_mainwindow test_mainwindow.cpp)
|
||||
target_link_libraries(test_mainwindow PRIVATE schedule_ui Qt6::Test schedule_warnings)
|
||||
add_test(NAME mainwindow COMMAND test_mainwindow)
|
||||
|
||||
add_executable(test_compactwindow test_compactwindow.cpp)
|
||||
target_link_libraries(test_compactwindow PRIVATE schedule_ui Qt6::Test schedule_warnings)
|
||||
add_test(NAME compactwindow COMMAND test_compactwindow)
|
||||
|
||||
add_executable(test_config test_config.cpp)
|
||||
target_link_libraries(test_config PRIVATE schedule_services Qt6::Test schedule_warnings)
|
||||
add_test(NAME config COMMAND test_config)
|
||||
|
||||
add_executable(test_scheduler test_scheduler.cpp)
|
||||
target_link_libraries(test_scheduler PRIVATE schedule_core Qt6::Test schedule_warnings)
|
||||
add_test(NAME scheduler COMMAND test_scheduler)
|
||||
|
||||
add_executable(test_ai test_ai.cpp)
|
||||
target_link_libraries(test_ai PRIVATE schedule_ai Qt6::Test schedule_warnings)
|
||||
add_test(NAME ai COMMAND test_ai)
|
||||
|
||||
add_executable(test_openai_provider test_openai_provider.cpp)
|
||||
target_link_libraries(test_openai_provider PRIVATE schedule_ai Qt6::Test schedule_warnings)
|
||||
add_test(NAME openai_provider COMMAND test_openai_provider)
|
||||
|
||||
add_executable(test_sync_integration test_sync_integration.cpp)
|
||||
target_link_libraries(test_sync_integration PRIVATE schedule_sync Qt6::Test schedule_warnings)
|
||||
add_test(NAME sync_integration COMMAND test_sync_integration)
|
||||
if(TARGET schedule-sync-server)
|
||||
add_dependencies(test_sync_integration schedule-sync-server)
|
||||
set_tests_properties(sync_integration PROPERTIES
|
||||
ENVIRONMENT "SCHEDULE_SYNC_SERVER_BIN=${CMAKE_BINARY_DIR}/bin/schedule-sync-server${CMAKE_EXECUTABLE_SUFFIX}"
|
||||
)
|
||||
endif()
|
||||
@@ -0,0 +1,746 @@
|
||||
#include <QFile>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonObject>
|
||||
#include <QSignalSpy>
|
||||
#include <QTemporaryDir>
|
||||
#include <QtTest>
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "ai/AIService.h"
|
||||
#include "ai/IAIProvider.h"
|
||||
#include "core/DateTimeUtils.h"
|
||||
#include "services/ScheduleService.h"
|
||||
#include "storage/SqliteStore.h"
|
||||
#include "utils/AppSettings.h"
|
||||
|
||||
class MockProvider : public ai::IAIProvider
|
||||
{
|
||||
public:
|
||||
QStringList responses;
|
||||
int calls = 0;
|
||||
QJsonArray lastMessages;
|
||||
AiConfig lastConfig;
|
||||
|
||||
QString name() const override
|
||||
{
|
||||
return QStringLiteral("mock");
|
||||
}
|
||||
|
||||
void cancel() override
|
||||
{
|
||||
}
|
||||
|
||||
void streamCompletion(const AiConfig& config,
|
||||
const QJsonArray& messages,
|
||||
ai::CompletionCallbacks callbacks) override
|
||||
{
|
||||
lastConfig = config;
|
||||
lastMessages = messages;
|
||||
const QString response = responses.value(calls);
|
||||
++calls;
|
||||
|
||||
if (response.startsWith(QStringLiteral("ERROR:")))
|
||||
{
|
||||
if (callbacks.onError)
|
||||
{
|
||||
callbacks.onError(response.mid(6).trimmed());
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 小分片模拟流式响应,同时验证标记跨分片解析。
|
||||
for (int i = 0; i < response.size(); i += 5)
|
||||
{
|
||||
if (callbacks.onDelta)
|
||||
{
|
||||
callbacks.onDelta(response.mid(i, 5));
|
||||
}
|
||||
}
|
||||
if (callbacks.onFinished)
|
||||
{
|
||||
callbacks.onFinished();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
class TestAI : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
private slots:
|
||||
void streamsReplyAndAppliesProposal();
|
||||
void repairsInvalidJsonOnce();
|
||||
void chatWithoutDiffDoesNotCreateProposal();
|
||||
void rejectsProposal();
|
||||
void includesAttachedTextFile();
|
||||
void keepsConversationHistory();
|
||||
void operationsUpdateCreateDelete();
|
||||
void rippleMovesConflictingBlock();
|
||||
void partialAcceptanceCannotCreateOverlap();
|
||||
void splitsLongTaskWhenNoSingleSlot();
|
||||
void forcesSplitWhenUserAllowsIt();
|
||||
void localDeleteAllMeetingsFallback();
|
||||
void retriesNoDiffActionableRequest();
|
||||
};
|
||||
|
||||
namespace
|
||||
{
|
||||
struct Context
|
||||
{
|
||||
QTemporaryDir dir;
|
||||
std::unique_ptr<SqliteStore> store;
|
||||
std::unique_ptr<ScheduleService> service;
|
||||
std::unique_ptr<AppSettings> settings;
|
||||
MockProvider* mock = nullptr;
|
||||
std::unique_ptr<AIService> ai;
|
||||
|
||||
bool initialize()
|
||||
{
|
||||
if (!dir.isValid())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
store = std::make_unique<SqliteStore>(dir.filePath(QStringLiteral("schedule.db")));
|
||||
QString error;
|
||||
if (!store->open(&error))
|
||||
{
|
||||
qWarning() << error;
|
||||
return false;
|
||||
}
|
||||
service = std::make_unique<ScheduleService>(*store, QStringLiteral("ai-test-device"));
|
||||
settings = std::make_unique<AppSettings>(dir.filePath(QStringLiteral("config.toml")));
|
||||
AiConfig config;
|
||||
config.baseUrl = QStringLiteral("http://localhost/v1");
|
||||
config.apiKey = QStringLiteral("test-key");
|
||||
config.model = QStringLiteral("test-model");
|
||||
settings->setAiConfig(config);
|
||||
|
||||
auto provider = std::make_unique<MockProvider>();
|
||||
mock = provider.get();
|
||||
ai = std::make_unique<AIService>(*service, *store, *settings, std::move(provider));
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
QString diffResponse(const QString& reply, const QString& tasksJson)
|
||||
{
|
||||
return reply + QStringLiteral("\n@@DIFF@@\n") + tasksJson;
|
||||
}
|
||||
|
||||
QString taskJson(const QString& title,
|
||||
int minutes,
|
||||
const QDateTime& preferredStart,
|
||||
const QDateTime& preferredEnd)
|
||||
{
|
||||
return QStringLiteral(
|
||||
"{\"tasks\":[{\"title\":\"%1\",\"duration_min\":%2,\"priority\":2,"
|
||||
"\"preferred_start\":\"%3\",\"preferred_end\":\"%4\"}]}")
|
||||
.arg(title)
|
||||
.arg(minutes)
|
||||
.arg(preferredStart.toString(QStringLiteral("yyyy-MM-ddTHH:mm:ss")),
|
||||
preferredEnd.toString(QStringLiteral("yyyy-MM-ddTHH:mm:ss")));
|
||||
}
|
||||
|
||||
QString joinDeltas(const QSignalSpy& spy)
|
||||
{
|
||||
QString text;
|
||||
for (const QList<QVariant>& args : spy)
|
||||
{
|
||||
text += args.at(0).toString();
|
||||
}
|
||||
return text;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void TestAI::streamsReplyAndAppliesProposal()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.initialize());
|
||||
|
||||
const QDate tomorrow = QDate::currentDate().addDays(1);
|
||||
const QDateTime preferredStart(tomorrow, QTime(14, 0), Qt::LocalTime);
|
||||
const QDateTime preferredEnd(tomorrow, QTime(16, 0), Qt::LocalTime);
|
||||
context.mock->responses = {
|
||||
diffResponse(QStringLiteral("好的,我来安排。"),
|
||||
taskJson(QStringLiteral("写周报"), 120, preferredStart, preferredEnd))};
|
||||
|
||||
QSignalSpy deltaSpy(context.ai.get(), &AIService::streamDelta);
|
||||
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
|
||||
QSignalSpy finishedSpy(context.ai.get(), &AIService::requestFinished);
|
||||
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
|
||||
QSignalSpy appliedSpy(context.ai.get(), &AIService::diffApplied);
|
||||
QSignalSpy noticeSpy(context.ai.get(), &AIService::notice);
|
||||
|
||||
context.ai->request(QStringLiteral("明天下午写周报 2 小时"));
|
||||
QCOMPARE(failedSpy.count(), 0);
|
||||
QCOMPARE(noticeSpy.count(), 0);
|
||||
QCOMPARE(finishedSpy.count(), 1);
|
||||
QCOMPARE(proposalSpy.count(), 1);
|
||||
QVERIFY(joinDeltas(deltaSpy).contains(QStringLiteral("好的")));
|
||||
QVERIFY(!joinDeltas(deltaSpy).contains(QStringLiteral("@@DIFF@@")));
|
||||
|
||||
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
|
||||
QCOMPARE(proposal.entries.size(), 1);
|
||||
QCOMPARE(proposal.entries.first().title, QStringLiteral("写周报"));
|
||||
QCOMPARE(proposal.entries.first().startAt, preferredStart);
|
||||
QCOMPARE(proposal.entries.first().endAt, preferredEnd);
|
||||
|
||||
const auto stored = context.store->proposedDiffById(proposal.diffId);
|
||||
QVERIFY(stored.has_value());
|
||||
QCOMPARE(stored->state, QStringLiteral("pending"));
|
||||
|
||||
context.ai->applyDiff(proposal.diffId, {proposal.entries.first().tempId});
|
||||
QCOMPARE(appliedSpy.count(), 1);
|
||||
const auto applied = context.store->proposedDiffById(proposal.diffId);
|
||||
QVERIFY(applied.has_value());
|
||||
QCOMPARE(applied->state, QStringLiteral("applied"));
|
||||
|
||||
const QVector<ScheduleItem> items = context.service->itemsForDay(tomorrow);
|
||||
QCOMPARE(items.size(), 1);
|
||||
QCOMPARE(items.first().task.title, QStringLiteral("写周报"));
|
||||
QCOMPARE(items.first().task.source, QStringLiteral("ai_chat"));
|
||||
QCOMPARE(items.first().block.startAt, preferredStart);
|
||||
}
|
||||
|
||||
void TestAI::repairsInvalidJsonOnce()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.initialize());
|
||||
|
||||
const QDate tomorrow = QDate::currentDate().addDays(1);
|
||||
const QDateTime preferredStart(tomorrow, QTime(10, 0), Qt::LocalTime);
|
||||
const QDateTime preferredEnd(tomorrow, QTime(11, 0), Qt::LocalTime);
|
||||
context.mock->responses = {
|
||||
diffResponse(QStringLiteral("我先安排一下。"), QStringLiteral("{not valid json")),
|
||||
taskJson(QStringLiteral("复习"), 60, preferredStart, preferredEnd)};
|
||||
|
||||
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
|
||||
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
|
||||
|
||||
context.ai->request(QStringLiteral("明天上午复习一小时"));
|
||||
QTRY_COMPARE_WITH_TIMEOUT(proposalSpy.count(), 1, 3000);
|
||||
QCOMPARE(failedSpy.count(), 0);
|
||||
QCOMPARE(context.mock->calls, 2);
|
||||
|
||||
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
|
||||
QCOMPARE(proposal.entries.size(), 1);
|
||||
QCOMPARE(proposal.entries.first().title, QStringLiteral("复习"));
|
||||
QCOMPARE(proposal.entries.first().startAt, preferredStart);
|
||||
}
|
||||
|
||||
void TestAI::chatWithoutDiffDoesNotCreateProposal()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.initialize());
|
||||
context.mock->responses = {QStringLiteral("你好,我是日程助手。")};
|
||||
|
||||
QSignalSpy deltaSpy(context.ai.get(), &AIService::streamDelta);
|
||||
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
|
||||
QSignalSpy finishedSpy(context.ai.get(), &AIService::requestFinished);
|
||||
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
|
||||
|
||||
context.ai->request(QStringLiteral("你能做什么?"));
|
||||
QCOMPARE(failedSpy.count(), 0);
|
||||
QCOMPARE(finishedSpy.count(), 1);
|
||||
QCOMPARE(proposalSpy.count(), 0);
|
||||
QVERIFY(joinDeltas(deltaSpy).contains(QStringLiteral("日程助手")));
|
||||
}
|
||||
|
||||
void TestAI::rejectsProposal()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.initialize());
|
||||
|
||||
const QDate tomorrow = QDate::currentDate().addDays(1);
|
||||
const QDateTime preferredStart(tomorrow, QTime(9, 0), Qt::LocalTime);
|
||||
const QDateTime preferredEnd(tomorrow, QTime(10, 0), Qt::LocalTime);
|
||||
context.mock->responses = {
|
||||
diffResponse(QStringLiteral("建议如下。"),
|
||||
taskJson(QStringLiteral("整理资料"), 60, preferredStart, preferredEnd))};
|
||||
|
||||
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
|
||||
QSignalSpy rejectedSpy(context.ai.get(), &AIService::diffRejected);
|
||||
context.ai->request(QStringLiteral("明天上午整理资料"));
|
||||
QCOMPARE(proposalSpy.count(), 1);
|
||||
|
||||
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
|
||||
context.ai->rejectDiff(proposal.diffId);
|
||||
QCOMPARE(rejectedSpy.count(), 1);
|
||||
QVERIFY(context.service->itemsForDay(tomorrow).isEmpty());
|
||||
const auto stored = context.store->proposedDiffById(proposal.diffId);
|
||||
QVERIFY(stored.has_value());
|
||||
QCOMPARE(stored->state, QStringLiteral("rejected"));
|
||||
}
|
||||
|
||||
void TestAI::includesAttachedTextFile()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.initialize());
|
||||
|
||||
const QString filePath = context.dir.filePath(QStringLiteral("需求.txt"));
|
||||
QFile file(filePath);
|
||||
QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
|
||||
file.write("下周准备产品发布会材料,需要两小时。");
|
||||
file.close();
|
||||
|
||||
context.mock->responses = {QStringLiteral("已收到附件内容。")};
|
||||
QSignalSpy finishedSpy(context.ai.get(), &AIService::requestFinished);
|
||||
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
|
||||
|
||||
context.ai->request(QStringLiteral("请分析附件"), {filePath});
|
||||
QTRY_COMPARE_WITH_TIMEOUT(context.mock->calls, 1, 5000);
|
||||
QTRY_COMPARE_WITH_TIMEOUT(finishedSpy.count(), 1, 5000);
|
||||
QCOMPARE(failedSpy.count(), 0);
|
||||
|
||||
QCOMPARE(context.mock->lastMessages.size(), 2);
|
||||
const QString userContent =
|
||||
context.mock->lastMessages.at(1).toObject().value(QStringLiteral("content")).toString();
|
||||
QVERIFY(userContent.contains(QStringLiteral("产品发布会材料")));
|
||||
}
|
||||
|
||||
void TestAI::keepsConversationHistory()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.initialize());
|
||||
context.mock->responses = {QStringLiteral("你好,我在。"), QStringLiteral("当然可以。")};
|
||||
|
||||
QSignalSpy finishedSpy(context.ai.get(), &AIService::requestFinished);
|
||||
context.ai->request(QStringLiteral("第一句"));
|
||||
QCOMPARE(finishedSpy.count(), 1);
|
||||
context.ai->request(QStringLiteral("第二句"));
|
||||
QCOMPARE(finishedSpy.count(), 2);
|
||||
QCOMPARE(context.mock->calls, 2);
|
||||
|
||||
const QJsonArray messages = context.mock->lastMessages;
|
||||
QVERIFY(messages.size() >= 4);
|
||||
bool sawFirstUser = false;
|
||||
bool sawFirstAssistant = false;
|
||||
for (const QJsonValue& value : messages)
|
||||
{
|
||||
const QJsonObject message = value.toObject();
|
||||
if (message.value(QStringLiteral("content")).toString() == QStringLiteral("第一句"))
|
||||
{
|
||||
sawFirstUser = true;
|
||||
}
|
||||
if (message.value(QStringLiteral("content")).toString() == QStringLiteral("你好,我在。"))
|
||||
{
|
||||
sawFirstAssistant = true;
|
||||
}
|
||||
}
|
||||
QVERIFY(sawFirstUser);
|
||||
QVERIFY(sawFirstAssistant);
|
||||
}
|
||||
|
||||
void TestAI::operationsUpdateCreateDelete()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.initialize());
|
||||
|
||||
const QDate tomorrow = QDate::currentDate().addDays(1);
|
||||
const QDateTime oldStart(tomorrow, QTime(9, 0), Qt::LocalTime);
|
||||
const QDateTime oldEnd(tomorrow, QTime(10, 0), Qt::LocalTime);
|
||||
const QDateTime deleteStart(tomorrow, QTime(11, 0), Qt::LocalTime);
|
||||
const QDateTime deleteEnd(tomorrow, QTime(12, 0), Qt::LocalTime);
|
||||
QString error;
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("旧任务"), oldStart, oldEnd, &error));
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("删除任务"), deleteStart, deleteEnd, &error));
|
||||
|
||||
const QDateTime updateStart(tomorrow, QTime(14, 0), Qt::LocalTime);
|
||||
const QDateTime updateEnd(tomorrow, QTime(15, 0), Qt::LocalTime);
|
||||
const QDateTime createStart(tomorrow, QTime(16, 0), Qt::LocalTime);
|
||||
const QDateTime createEnd(tomorrow, QTime(17, 0), Qt::LocalTime);
|
||||
context.mock->responses = {
|
||||
QStringLiteral(
|
||||
"好的,我调整一下。\n@@DIFF@@\n"
|
||||
"{\"operations\":["
|
||||
"{\"type\":\"update\",\"target_ref\":\"b1\",\"title\":\"新任务\","
|
||||
"\"preferred_start\":\"%1T14:00:00\",\"preferred_end\":\"%1T15:00:00\"},"
|
||||
"{\"type\":\"create\",\"title\":\"新安排\",\"duration_min\":60,"
|
||||
"\"preferred_start\":\"%1T16:00:00\",\"preferred_end\":\"%1T17:00:00\"},"
|
||||
"{\"type\":\"delete\",\"target_ref\":\"b2\"}]}")
|
||||
.arg(tomorrow.toString(QStringLiteral("yyyy-MM-dd"))),
|
||||
};
|
||||
|
||||
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
|
||||
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
|
||||
QSignalSpy appliedSpy(context.ai.get(), &AIService::diffApplied);
|
||||
QSignalSpy applyFailedSpy(context.ai.get(), &AIService::diffApplyFailed);
|
||||
context.ai->request(QStringLiteral("把旧任务改到下午两点,四点新增安排,删掉十一点的会议"));
|
||||
QCOMPARE(failedSpy.count(), 0);
|
||||
QCOMPARE(proposalSpy.count(), 1);
|
||||
|
||||
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
|
||||
QStringList tempIds;
|
||||
bool sawUpdate = false;
|
||||
bool sawCreate = false;
|
||||
bool sawDelete = false;
|
||||
for (const ProposedScheduleEntry& entry : proposal.entries)
|
||||
{
|
||||
tempIds.append(entry.tempId);
|
||||
if (entry.operation == ProposedOperation::Update)
|
||||
{
|
||||
sawUpdate = true;
|
||||
QCOMPARE(entry.oldTitle, QStringLiteral("旧任务"));
|
||||
QCOMPARE(entry.title, QStringLiteral("新任务"));
|
||||
QCOMPARE(entry.oldStartAt, oldStart);
|
||||
QCOMPARE(entry.startAt, updateStart);
|
||||
}
|
||||
else if (entry.operation == ProposedOperation::Create)
|
||||
{
|
||||
sawCreate = true;
|
||||
QCOMPARE(entry.title, QStringLiteral("新安排"));
|
||||
QCOMPARE(entry.startAt, createStart);
|
||||
}
|
||||
else if (entry.operation == ProposedOperation::Delete)
|
||||
{
|
||||
sawDelete = true;
|
||||
QCOMPARE(entry.oldTitle, QStringLiteral("删除任务"));
|
||||
}
|
||||
}
|
||||
QVERIFY(sawUpdate);
|
||||
QVERIFY(sawCreate);
|
||||
QVERIFY(sawDelete);
|
||||
|
||||
context.ai->applyDiff(proposal.diffId, tempIds);
|
||||
QCOMPARE(applyFailedSpy.count(), 0);
|
||||
QCOMPARE(appliedSpy.count(), 1);
|
||||
|
||||
const QVector<ScheduleItem> items = context.service->itemsForDay(tomorrow);
|
||||
QCOMPARE(items.size(), 2);
|
||||
bool foundUpdated = false;
|
||||
bool foundCreated = false;
|
||||
for (const ScheduleItem& item : items)
|
||||
{
|
||||
if (item.task.title == QStringLiteral("新任务"))
|
||||
{
|
||||
foundUpdated = true;
|
||||
QCOMPARE(item.block.startAt, updateStart);
|
||||
QCOMPARE(item.block.endAt, updateEnd);
|
||||
}
|
||||
if (item.task.title == QStringLiteral("新安排"))
|
||||
{
|
||||
foundCreated = true;
|
||||
QCOMPARE(item.block.startAt, createStart);
|
||||
QCOMPARE(item.block.endAt, createEnd);
|
||||
}
|
||||
QVERIFY(item.task.title != QStringLiteral("删除任务"));
|
||||
}
|
||||
QVERIFY(foundUpdated);
|
||||
QVERIFY(foundCreated);
|
||||
}
|
||||
|
||||
void TestAI::rippleMovesConflictingBlock()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.initialize());
|
||||
|
||||
const QDate tomorrow = QDate::currentDate().addDays(1);
|
||||
const QDateTime existingStart(tomorrow, QTime(14, 0), Qt::LocalTime);
|
||||
const QDateTime existingEnd(tomorrow, QTime(15, 0), Qt::LocalTime);
|
||||
QString error;
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("已有日程"), existingStart, existingEnd, &error));
|
||||
|
||||
context.mock->responses = {
|
||||
QStringLiteral(
|
||||
"好的,我把它插进去。\n@@DIFF@@\n"
|
||||
"{\"operations\":[{\"type\":\"create\",\"title\":\"插入任务\","
|
||||
"\"duration_min\":60,\"preferred_start\":\"%1T14:00:00\","
|
||||
"\"preferred_end\":\"%1T15:00:00\"}]}")
|
||||
.arg(tomorrow.toString(QStringLiteral("yyyy-MM-dd"))),
|
||||
};
|
||||
|
||||
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
|
||||
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
|
||||
context.ai->request(QStringLiteral("明天下午两点插入一个一小时任务"));
|
||||
QCOMPARE(failedSpy.count(), 0);
|
||||
QCOMPARE(proposalSpy.count(), 1);
|
||||
|
||||
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
|
||||
QCOMPARE(proposal.entries.size(), 2);
|
||||
bool sawCreate = false;
|
||||
bool sawMove = false;
|
||||
QStringList tempIds;
|
||||
for (const ProposedScheduleEntry& entry : proposal.entries)
|
||||
{
|
||||
tempIds.append(entry.tempId);
|
||||
if (entry.operation == ProposedOperation::Create &&
|
||||
entry.title == QStringLiteral("插入任务"))
|
||||
{
|
||||
sawCreate = true;
|
||||
QCOMPARE(entry.startAt, existingStart);
|
||||
}
|
||||
if (entry.operation == ProposedOperation::Update &&
|
||||
entry.oldTitle == QStringLiteral("已有日程"))
|
||||
{
|
||||
sawMove = true;
|
||||
QCOMPARE(entry.startAt, existingEnd);
|
||||
QCOMPARE(entry.endAt, existingEnd.addSecs(3600));
|
||||
}
|
||||
}
|
||||
QVERIFY(sawCreate);
|
||||
QVERIFY(sawMove);
|
||||
|
||||
context.ai->applyDiff(proposal.diffId, tempIds);
|
||||
const QVector<ScheduleItem> items = context.service->itemsForDay(tomorrow);
|
||||
QCOMPARE(items.size(), 2);
|
||||
for (const ScheduleItem& item : items)
|
||||
{
|
||||
if (item.task.title == QStringLiteral("插入任务"))
|
||||
{
|
||||
QCOMPARE(item.block.startAt, existingStart);
|
||||
}
|
||||
if (item.task.title == QStringLiteral("已有日程"))
|
||||
{
|
||||
QCOMPARE(item.block.startAt, existingEnd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void TestAI::partialAcceptanceCannotCreateOverlap()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.initialize());
|
||||
|
||||
const QDate tomorrow = QDate::currentDate().addDays(1);
|
||||
const QDateTime existingStart(tomorrow, QTime(14, 0), Qt::LocalTime);
|
||||
const QDateTime existingEnd(tomorrow, QTime(15, 0), Qt::LocalTime);
|
||||
QString error;
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("已有日程"), existingStart, existingEnd, &error));
|
||||
|
||||
context.mock->responses = {
|
||||
QStringLiteral(
|
||||
"好的。\n@@DIFF@@\n"
|
||||
"{\"operations\":[{\"type\":\"create\",\"title\":\"插入任务\","
|
||||
"\"duration_min\":60,\"preferred_start\":\"%1T14:00:00\","
|
||||
"\"preferred_end\":\"%1T15:00:00\"}]}")
|
||||
.arg(tomorrow.toString(QStringLiteral("yyyy-MM-dd"))),
|
||||
};
|
||||
|
||||
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
|
||||
QSignalSpy applyFailedSpy(context.ai.get(), &AIService::diffApplyFailed);
|
||||
context.ai->request(QStringLiteral("明天下午两点插入一个一小时任务"));
|
||||
QCOMPARE(proposalSpy.count(), 1);
|
||||
|
||||
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
|
||||
QString createTempId;
|
||||
for (const ProposedScheduleEntry& entry : proposal.entries)
|
||||
{
|
||||
if (entry.operation == ProposedOperation::Create)
|
||||
{
|
||||
createTempId = entry.tempId;
|
||||
}
|
||||
}
|
||||
QVERIFY(!createTempId.isEmpty());
|
||||
|
||||
// 只接受新增、不接受涟漪移动,应被服务层冲突检查拒绝。
|
||||
context.ai->applyDiff(proposal.diffId, {createTempId});
|
||||
QCOMPARE(applyFailedSpy.count(), 1);
|
||||
const QVector<ScheduleItem> items = context.service->itemsForDay(tomorrow);
|
||||
QCOMPARE(items.size(), 1);
|
||||
QCOMPARE(items.first().task.title, QStringLiteral("已有日程"));
|
||||
}
|
||||
|
||||
void TestAI::splitsLongTaskWhenNoSingleSlot()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.initialize());
|
||||
|
||||
const QDate today = QDate::currentDate();
|
||||
const QDate tomorrow = today.addDays(1);
|
||||
QString error;
|
||||
for (const QDate& day : {today, tomorrow})
|
||||
{
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("占用一"),
|
||||
QDateTime(day, QTime(8, 0), Qt::LocalTime),
|
||||
QDateTime(day, QTime(12, 0), Qt::LocalTime),
|
||||
&error));
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("占用二"),
|
||||
QDateTime(day, QTime(13, 0), Qt::LocalTime),
|
||||
QDateTime(day, QTime(17, 0), Qt::LocalTime),
|
||||
&error));
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("占用三"),
|
||||
QDateTime(day, QTime(18, 0), Qt::LocalTime),
|
||||
QDateTime(day, QTime(22, 0), Qt::LocalTime),
|
||||
&error));
|
||||
}
|
||||
|
||||
context.mock->responses = {
|
||||
QStringLiteral(
|
||||
"好的,我拆分安排。\n@@DIFF@@\n"
|
||||
"{\"operations\":[{\"type\":\"create\",\"title\":\"长任务\","
|
||||
"\"duration_min\":120,\"splittable\":true,"
|
||||
"\"deadline\":\"%1T22:00:00\"}]}")
|
||||
.arg(tomorrow.toString(QStringLiteral("yyyy-MM-dd"))),
|
||||
};
|
||||
|
||||
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
|
||||
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
|
||||
QSignalSpy noticeSpy(context.ai.get(), &AIService::notice);
|
||||
context.ai->request(QStringLiteral("明天之前找时间做两小时长任务,可以拆开"));
|
||||
QCOMPARE(failedSpy.count(), 0);
|
||||
QCOMPARE(proposalSpy.count(), 1);
|
||||
|
||||
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
|
||||
QCOMPARE(proposal.entries.size(), 1);
|
||||
const ProposedScheduleEntry entry = proposal.entries.first();
|
||||
QCOMPARE(entry.operation, ProposedOperation::Create);
|
||||
QCOMPARE(entry.title, QStringLiteral("长任务"));
|
||||
QCOMPARE(entry.segments.size(), 2);
|
||||
QVERIFY(!noticeSpy.isEmpty());
|
||||
|
||||
QStringList tempIds{entry.tempId};
|
||||
QSignalSpy appliedSpy(context.ai.get(), &AIService::diffApplied);
|
||||
context.ai->applyDiff(proposal.diffId, tempIds);
|
||||
QCOMPARE(appliedSpy.count(), 1);
|
||||
|
||||
QVector<ScheduleItem> splitBlocks;
|
||||
for (const QDate& day : {today, tomorrow})
|
||||
{
|
||||
for (const ScheduleItem& item : context.service->itemsForDay(day))
|
||||
{
|
||||
if (item.task.title == QStringLiteral("长任务"))
|
||||
{
|
||||
splitBlocks.append(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
QCOMPARE(splitBlocks.size(), 2);
|
||||
QCOMPARE(splitBlocks.first().task.id, splitBlocks.last().task.id);
|
||||
int totalMinutes = 0;
|
||||
for (const ScheduleItem& item : splitBlocks)
|
||||
{
|
||||
totalMinutes += DateTimeUtils::minutesBetween(item.block.startAt, item.block.endAt);
|
||||
}
|
||||
QCOMPARE(totalMinutes, 120);
|
||||
}
|
||||
|
||||
void TestAI::forcesSplitWhenUserAllowsIt()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.initialize());
|
||||
|
||||
const QDate today = QDate::currentDate();
|
||||
const QDate tomorrow = today.addDays(1);
|
||||
QString error;
|
||||
for (const QDate& day : {today, tomorrow})
|
||||
{
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("占用一"),
|
||||
QDateTime(day, QTime(8, 0), Qt::LocalTime),
|
||||
QDateTime(day, QTime(12, 0), Qt::LocalTime),
|
||||
&error));
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("占用二"),
|
||||
QDateTime(day, QTime(13, 0), Qt::LocalTime),
|
||||
QDateTime(day, QTime(17, 0), Qt::LocalTime),
|
||||
&error));
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("占用三"),
|
||||
QDateTime(day, QTime(18, 0), Qt::LocalTime),
|
||||
QDateTime(day, QTime(22, 0), Qt::LocalTime),
|
||||
&error));
|
||||
}
|
||||
|
||||
// 模型没有设置 splittable,但用户明确说“可以拆开”,AIService 应主动强制拆分。
|
||||
context.mock->responses = {
|
||||
QStringLiteral(
|
||||
"好的,我拆分安排。\n@@DIFF@@\n"
|
||||
"{\"operations\":[{\"type\":\"create\",\"title\":\"长任务\","
|
||||
"\"duration_min\":120,\"deadline\":\"%1T22:00:00\"}]}")
|
||||
.arg(tomorrow.toString(QStringLiteral("yyyy-MM-dd"))),
|
||||
};
|
||||
|
||||
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
|
||||
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
|
||||
context.ai->request(QStringLiteral("明天之前找时间做两小时长任务,可以拆开"));
|
||||
QCOMPARE(failedSpy.count(), 0);
|
||||
QCOMPARE(proposalSpy.count(), 1);
|
||||
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
|
||||
QCOMPARE(proposal.entries.size(), 1);
|
||||
QCOMPARE(proposal.entries.first().operation, ProposedOperation::Create);
|
||||
QCOMPARE(proposal.entries.first().segments.size(), 2);
|
||||
}
|
||||
|
||||
void TestAI::localDeleteAllMeetingsFallback()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.initialize());
|
||||
|
||||
const QDate tomorrow = QDate::currentDate().addDays(1);
|
||||
QString error;
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("写周报"),
|
||||
QDateTime(tomorrow, QTime(9, 0), Qt::LocalTime),
|
||||
QDateTime(tomorrow, QTime(10, 0), Qt::LocalTime),
|
||||
&error));
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("团队同步"),
|
||||
QDateTime(tomorrow, QTime(11, 0), Qt::LocalTime),
|
||||
QDateTime(tomorrow, QTime(12, 0), Qt::LocalTime),
|
||||
&error));
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("健身"),
|
||||
QDateTime(tomorrow, QTime(15, 0), Qt::LocalTime),
|
||||
QDateTime(tomorrow, QTime(16, 0), Qt::LocalTime),
|
||||
&error));
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("项目会议"),
|
||||
QDateTime(tomorrow, QTime(13, 0), Qt::LocalTime),
|
||||
QDateTime(tomorrow, QTime(14, 0), Qt::LocalTime),
|
||||
&error));
|
||||
|
||||
// 模型没有给出 diff,只追问;AIService 对“删除所有会议”做确定性兜底。
|
||||
context.mock->responses = {QStringLiteral("请确认要删除哪些会议?")};
|
||||
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
|
||||
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
|
||||
QSignalSpy appliedSpy(context.ai.get(), &AIService::diffApplied);
|
||||
context.ai->request(QStringLiteral("删除明天所有会议"));
|
||||
QCOMPARE(failedSpy.count(), 0);
|
||||
QCOMPARE(proposalSpy.count(), 1);
|
||||
|
||||
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
|
||||
QCOMPARE(proposal.entries.size(), 2);
|
||||
QStringList tempIds;
|
||||
QStringList titles;
|
||||
for (const ProposedScheduleEntry& entry : proposal.entries)
|
||||
{
|
||||
QCOMPARE(entry.operation, ProposedOperation::Delete);
|
||||
tempIds.append(entry.tempId);
|
||||
titles.append(entry.oldTitle);
|
||||
}
|
||||
QVERIFY(titles.contains(QStringLiteral("团队同步")));
|
||||
QVERIFY(titles.contains(QStringLiteral("项目会议")));
|
||||
|
||||
context.ai->applyDiff(proposal.diffId, tempIds);
|
||||
QCOMPARE(appliedSpy.count(), 1);
|
||||
const QVector<ScheduleItem> items = context.service->itemsForDay(tomorrow);
|
||||
QCOMPARE(items.size(), 2);
|
||||
for (const ScheduleItem& item : items)
|
||||
{
|
||||
QVERIFY(item.task.title != QStringLiteral("团队同步"));
|
||||
QVERIFY(item.task.title != QStringLiteral("项目会议"));
|
||||
}
|
||||
}
|
||||
|
||||
void TestAI::retriesNoDiffActionableRequest()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.initialize());
|
||||
|
||||
const QDate tomorrow = QDate::currentDate().addDays(1);
|
||||
context.mock->responses = {
|
||||
QStringLiteral("抱歉,我暂时无法安排。"),
|
||||
QStringLiteral(
|
||||
"重新整理完成。\n@@DIFF@@\n"
|
||||
"{\"operations\":[{\"type\":\"create\",\"title\":\"深度工作\","
|
||||
"\"duration_min\":180,\"deadline\":\"%1T22:00:00\"}]}")
|
||||
.arg(tomorrow.toString(QStringLiteral("yyyy-MM-dd"))),
|
||||
};
|
||||
|
||||
QSignalSpy proposalSpy(context.ai.get(), &AIService::proposalReady);
|
||||
QSignalSpy failedSpy(context.ai.get(), &AIService::requestFailed);
|
||||
context.ai->request(QStringLiteral("明天之前找时间做 3 小时深度工作,可以拆开"));
|
||||
QTRY_COMPARE_WITH_TIMEOUT(proposalSpy.count(), 1, 3000);
|
||||
QCOMPARE(failedSpy.count(), 0);
|
||||
QCOMPARE(context.mock->calls, 2);
|
||||
const ScheduleProposal proposal = proposalSpy.at(0).at(0).value<ScheduleProposal>();
|
||||
QCOMPARE(proposal.entries.size(), 1);
|
||||
QVERIFY(proposal.entries.first().title == QStringLiteral("深度工作"));
|
||||
}
|
||||
|
||||
QTEST_GUILESS_MAIN(TestAI)
|
||||
#include "test_ai.moc"
|
||||
@@ -0,0 +1,447 @@
|
||||
#include <QApplication>
|
||||
#include <QDir>
|
||||
#include <QTemporaryDir>
|
||||
#include <QTimer>
|
||||
#include <QtTest>
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "ElaApplication.h"
|
||||
#include "ElaLineEdit.h"
|
||||
#include "ElaPushButton.h"
|
||||
#include "ElaToolButton.h"
|
||||
#include "ai/AIService.h"
|
||||
#include "services/NotificationService.h"
|
||||
#include "services/ScheduleService.h"
|
||||
#include "storage/SqliteStore.h"
|
||||
#include "ui/CompactWindow.h"
|
||||
#include "ui/MainWindow.h"
|
||||
#include "ui/dialogs/SettingsDialog.h"
|
||||
#include "ui/panels/DiffPreviewCard.h"
|
||||
#include "ui/theme/ThemeManager.h"
|
||||
#include "ui/views/ScheduleGridView.h"
|
||||
#include "ui/theme/WindowEffects.h"
|
||||
#include "utils/AppSettings.h"
|
||||
|
||||
class MockChatProvider : public ai::IAIProvider
|
||||
{
|
||||
public:
|
||||
QString response;
|
||||
|
||||
QString name() const override
|
||||
{
|
||||
return QStringLiteral("mock");
|
||||
}
|
||||
void cancel() override
|
||||
{
|
||||
}
|
||||
void streamCompletion(const AiConfig&,
|
||||
const QJsonArray&,
|
||||
ai::CompletionCallbacks callbacks) override
|
||||
{
|
||||
for (int i = 0; i < response.size(); i += 7)
|
||||
{
|
||||
if (callbacks.onDelta)
|
||||
{
|
||||
callbacks.onDelta(response.mid(i, 7));
|
||||
}
|
||||
}
|
||||
if (callbacks.onFinished)
|
||||
{
|
||||
callbacks.onFinished();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
class TestCompactWindow : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
private slots:
|
||||
void initTestCase();
|
||||
void compactOpensScheduleAndReturns();
|
||||
void aiChatShowsDiffAndAccepts();
|
||||
void aiChatShowsMultiOperationDiff();
|
||||
|
||||
private:
|
||||
void createSampleData(ScheduleService& service, const QDate& today);
|
||||
static void saveWindow(QWidget* widget, const QString& name);
|
||||
|
||||
QTemporaryDir m_tempDir;
|
||||
std::unique_ptr<AppSettings> m_settings;
|
||||
bool m_mica = false;
|
||||
};
|
||||
|
||||
void TestCompactWindow::initTestCase()
|
||||
{
|
||||
QVERIFY(m_tempDir.isValid());
|
||||
QCoreApplication::setOrganizationName(QStringLiteral("ScheduleTest"));
|
||||
QCoreApplication::setApplicationName(QStringLiteral("ScheduleTest"));
|
||||
QApplication::setStyle(QStringLiteral("Fusion"));
|
||||
eApp->init();
|
||||
m_settings = std::make_unique<AppSettings>(m_tempDir.filePath(QStringLiteral("config.toml")));
|
||||
m_settings->setThemePreference(qEnvironmentVariable("SCHEDULE_TEST_THEME", QStringLiteral("system")));
|
||||
m_mica = qEnvironmentVariableIsSet("SCHEDULE_TEST_MICA");
|
||||
m_settings->setMicaEnabled(m_mica);
|
||||
}
|
||||
|
||||
void TestCompactWindow::createSampleData(ScheduleService& service, const QDate& today)
|
||||
{
|
||||
const auto create = [&service](const QString& title,
|
||||
const QDateTime& start,
|
||||
const QDateTime& end,
|
||||
const QString& status = QStringLiteral("scheduled")) {
|
||||
QString error;
|
||||
if (!service.createBlock(title, start, end, &error))
|
||||
{
|
||||
qWarning() << error;
|
||||
return false;
|
||||
}
|
||||
if (status != QStringLiteral("scheduled"))
|
||||
{
|
||||
const QVector<ScheduleItem> items = service.itemsForDay(start.date());
|
||||
for (const ScheduleItem& item : items)
|
||||
{
|
||||
if (item.task.title == title)
|
||||
{
|
||||
service.setBlockStatus(item.block.id, status, &error);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
QVERIFY(create(QStringLiteral("写周报"),
|
||||
QDateTime(today, QTime(9, 0), Qt::LocalTime),
|
||||
QDateTime(today, QTime(10, 30), Qt::LocalTime)));
|
||||
QVERIFY(create(QStringLiteral("团队同步"),
|
||||
QDateTime(today, QTime(10, 0), Qt::LocalTime),
|
||||
QDateTime(today, QTime(11, 0), Qt::LocalTime)));
|
||||
QVERIFY(create(QStringLiteral("设计评审"),
|
||||
QDateTime(today, QTime(14, 0), Qt::LocalTime),
|
||||
QDateTime(today, QTime(15, 0), Qt::LocalTime),
|
||||
QStringLiteral("done")));
|
||||
QVERIFY(create(QStringLiteral("整理邮件"),
|
||||
QDateTime(today, QTime(16, 0), Qt::LocalTime),
|
||||
QDateTime(today, QTime(16, 30), Qt::LocalTime),
|
||||
QStringLiteral("dropped")));
|
||||
QVERIFY(create(QStringLiteral("项目周会"),
|
||||
QDateTime(today.addDays(-2), QTime(10, 0), Qt::LocalTime),
|
||||
QDateTime(today.addDays(-2), QTime(11, 0), Qt::LocalTime)));
|
||||
QVERIFY(create(QStringLiteral("深度阅读"),
|
||||
QDateTime(today.addDays(3), QTime(15, 0), Qt::LocalTime),
|
||||
QDateTime(today.addDays(3), QTime(16, 30), Qt::LocalTime)));
|
||||
const QDate nextMonth = QDate(today.year(), today.month(), 1).addMonths(1);
|
||||
QVERIFY(create(QStringLiteral("月度复盘"),
|
||||
QDateTime(nextMonth.addDays(4), QTime(9, 0), Qt::LocalTime),
|
||||
QDateTime(nextMonth.addDays(4), QTime(10, 30), Qt::LocalTime)));
|
||||
const QDate earlier = QDate(today.year(), today.month(), 1).addMonths(-2);
|
||||
QVERIFY(create(QStringLiteral("季度目标"),
|
||||
QDateTime(earlier.addDays(9), QTime(13, 0), Qt::LocalTime),
|
||||
QDateTime(earlier.addDays(9), QTime(15, 0), Qt::LocalTime)));
|
||||
}
|
||||
|
||||
void TestCompactWindow::saveWindow(QWidget* widget, const QString& name)
|
||||
{
|
||||
const QString directory = qEnvironmentVariable("SCHEDULE_TEST_SCREENSHOTS");
|
||||
if (directory.isEmpty() || !widget)
|
||||
{
|
||||
return;
|
||||
}
|
||||
QDir().mkpath(directory);
|
||||
widget->grab().save(directory + QLatin1Char('/') + name);
|
||||
}
|
||||
|
||||
void TestCompactWindow::compactOpensScheduleAndReturns()
|
||||
{
|
||||
QTemporaryDir databaseDir;
|
||||
QVERIFY(databaseDir.isValid());
|
||||
SqliteStore store(databaseDir.filePath(QStringLiteral("schedule.db")));
|
||||
QString error;
|
||||
QVERIFY2(store.open(&error), qPrintable(error));
|
||||
|
||||
ThemeManager theme(*m_settings);
|
||||
theme.initialize();
|
||||
ScheduleService service(store, QStringLiteral("compact-test"));
|
||||
NotificationService notifications(service);
|
||||
AIService aiService(service, store, *m_settings);
|
||||
|
||||
const QDate today = QDate::currentDate();
|
||||
createSampleData(service, today);
|
||||
|
||||
CompactWindow compact(service, notifications, aiService, theme, *m_settings);
|
||||
compact.show();
|
||||
QVERIFY(QTest::qWaitForWindowExposed(&compact));
|
||||
if (m_mica)
|
||||
{
|
||||
WindowEffects::applyMica(true);
|
||||
QTest::qWait(4500);
|
||||
}
|
||||
else
|
||||
{
|
||||
QTest::qWait(300);
|
||||
}
|
||||
saveWindow(&compact, QStringLiteral("compact.png"));
|
||||
|
||||
ElaPushButton* openButton = nullptr;
|
||||
for (ElaPushButton* button : compact.findChildren<ElaPushButton*>())
|
||||
{
|
||||
if (button->text() == QStringLiteral("详细日程"))
|
||||
{
|
||||
openButton = button;
|
||||
break;
|
||||
}
|
||||
}
|
||||
QVERIFY(openButton);
|
||||
|
||||
QTest::mouseClick(openButton, Qt::LeftButton);
|
||||
QTest::qWait(300);
|
||||
|
||||
MainWindow* scheduleWindow = nullptr;
|
||||
for (QWidget* widget : QApplication::topLevelWidgets())
|
||||
{
|
||||
if (auto* candidate = qobject_cast<MainWindow*>(widget))
|
||||
{
|
||||
scheduleWindow = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
QVERIFY(scheduleWindow);
|
||||
QVERIFY(scheduleWindow->isVisible());
|
||||
QVERIFY(!compact.isVisible());
|
||||
if (auto* grid = scheduleWindow->findChild<ScheduleGridView*>())
|
||||
{
|
||||
grid->scrollToHour(8);
|
||||
QTest::qWait(80);
|
||||
}
|
||||
saveWindow(scheduleWindow, QStringLiteral("schedule-day.png"));
|
||||
|
||||
scheduleWindow->setView(MainWindow::View::Month);
|
||||
QTest::qWait(200);
|
||||
QCOMPARE(scheduleWindow->view(), MainWindow::View::Month);
|
||||
saveWindow(scheduleWindow, QStringLiteral("schedule-month.png"));
|
||||
|
||||
scheduleWindow->setView(MainWindow::View::Year);
|
||||
QTest::qWait(200);
|
||||
QCOMPARE(scheduleWindow->view(), MainWindow::View::Year);
|
||||
saveWindow(scheduleWindow, QStringLiteral("schedule-year.png"));
|
||||
|
||||
scheduleWindow->setView(MainWindow::View::Day);
|
||||
QTest::qWait(120);
|
||||
scheduleWindow->close();
|
||||
QTest::qWait(200);
|
||||
QVERIFY(compact.isVisible());
|
||||
|
||||
ElaToolButton* settingsButton = nullptr;
|
||||
for (ElaToolButton* button : compact.findChildren<ElaToolButton*>())
|
||||
{
|
||||
if (button->toolTip().startsWith(QStringLiteral("设置")))
|
||||
{
|
||||
settingsButton = button;
|
||||
break;
|
||||
}
|
||||
}
|
||||
QVERIFY(settingsButton);
|
||||
|
||||
QTimer::singleShot(400, []() {
|
||||
for (QWidget* widget : QApplication::topLevelWidgets())
|
||||
{
|
||||
if (auto* dialog = qobject_cast<SettingsDialog*>(widget))
|
||||
{
|
||||
saveWindow(dialog, QStringLiteral("settings.png"));
|
||||
dialog->reject();
|
||||
}
|
||||
}
|
||||
});
|
||||
QTimer::singleShot(2000, []() {
|
||||
for (QWidget* widget : QApplication::topLevelWidgets())
|
||||
{
|
||||
if (auto* dialog = qobject_cast<SettingsDialog*>(widget))
|
||||
{
|
||||
dialog->reject();
|
||||
}
|
||||
}
|
||||
});
|
||||
QTest::mouseClick(settingsButton, Qt::LeftButton);
|
||||
}
|
||||
|
||||
void TestCompactWindow::aiChatShowsDiffAndAccepts()
|
||||
{
|
||||
QTemporaryDir databaseDir;
|
||||
QVERIFY(databaseDir.isValid());
|
||||
SqliteStore store(databaseDir.filePath(QStringLiteral("schedule.db")));
|
||||
QString error;
|
||||
QVERIFY2(store.open(&error), qPrintable(error));
|
||||
|
||||
AiConfig config;
|
||||
config.baseUrl = QStringLiteral("http://localhost/v1");
|
||||
config.apiKey = QStringLiteral("test-key");
|
||||
config.model = QStringLiteral("test-model");
|
||||
m_settings->setAiConfig(config);
|
||||
|
||||
auto provider = std::make_unique<MockChatProvider>();
|
||||
MockChatProvider* mock = provider.get();
|
||||
const QDate tomorrow = QDate::currentDate().addDays(1);
|
||||
mock->response = QStringLiteral(
|
||||
"好的,我为你安排。\n@@DIFF@@\n"
|
||||
"{\"tasks\":[{\"title\":\"写周报\",\"duration_min\":120,"
|
||||
"\"priority\":2,\"preferred_start\":\"%1T14:00:00\","
|
||||
"\"preferred_end\":\"%1T16:00:00\"}]}")
|
||||
.arg(tomorrow.toString(QStringLiteral("yyyy-MM-dd")));
|
||||
|
||||
ThemeManager theme(*m_settings);
|
||||
theme.initialize();
|
||||
ScheduleService service(store, QStringLiteral("chat-ui-test"));
|
||||
NotificationService notifications(service);
|
||||
AIService aiService(service, store, *m_settings, std::move(provider));
|
||||
|
||||
CompactWindow compact(service, notifications, aiService, theme, *m_settings);
|
||||
compact.show();
|
||||
QVERIFY(QTest::qWaitForWindowExposed(&compact));
|
||||
QTest::qWait(100);
|
||||
|
||||
ElaLineEdit* input = compact.findChild<ElaLineEdit*>();
|
||||
QVERIFY(input);
|
||||
input->setText(QStringLiteral("明天下午写周报 2 小时"));
|
||||
|
||||
ElaPushButton* sendButton = nullptr;
|
||||
for (ElaPushButton* button : compact.findChildren<ElaPushButton*>())
|
||||
{
|
||||
if (button->text() == QStringLiteral("发送"))
|
||||
{
|
||||
sendButton = button;
|
||||
break;
|
||||
}
|
||||
}
|
||||
QVERIFY(sendButton);
|
||||
QTest::mouseClick(sendButton, Qt::LeftButton);
|
||||
QTest::qWait(150);
|
||||
|
||||
auto* card = compact.findChild<DiffPreviewCard*>();
|
||||
QVERIFY(card);
|
||||
saveWindow(&compact, QStringLiteral("chat-diff.png"));
|
||||
|
||||
ElaPushButton* acceptButton = nullptr;
|
||||
for (ElaPushButton* button : card->findChildren<ElaPushButton*>())
|
||||
{
|
||||
if (button->text() == QStringLiteral("接受选中"))
|
||||
{
|
||||
acceptButton = button;
|
||||
break;
|
||||
}
|
||||
}
|
||||
QVERIFY(acceptButton);
|
||||
QTest::mouseClick(acceptButton, Qt::LeftButton);
|
||||
QTest::qWait(150);
|
||||
|
||||
const QVector<ScheduleItem> items = service.itemsForDay(tomorrow);
|
||||
QCOMPARE(items.size(), 1);
|
||||
QCOMPARE(items.first().task.title, QStringLiteral("写周报"));
|
||||
QCOMPARE(items.first().task.source, QStringLiteral("ai_chat"));
|
||||
saveWindow(&compact, QStringLiteral("chat-applied.png"));
|
||||
}
|
||||
|
||||
void TestCompactWindow::aiChatShowsMultiOperationDiff()
|
||||
{
|
||||
QTemporaryDir databaseDir;
|
||||
QVERIFY(databaseDir.isValid());
|
||||
SqliteStore store(databaseDir.filePath(QStringLiteral("schedule.db")));
|
||||
QString error;
|
||||
QVERIFY2(store.open(&error), qPrintable(error));
|
||||
|
||||
AiConfig config;
|
||||
config.baseUrl = QStringLiteral("http://localhost/v1");
|
||||
config.apiKey = QStringLiteral("test-key");
|
||||
config.model = QStringLiteral("test-model");
|
||||
m_settings->setAiConfig(config);
|
||||
|
||||
ThemeManager theme(*m_settings);
|
||||
theme.initialize();
|
||||
ScheduleService service(store, QStringLiteral("chat-multi-test"));
|
||||
NotificationService notifications(service);
|
||||
const QDate tomorrow = QDate::currentDate().addDays(1);
|
||||
QVERIFY(service.createBlock(QStringLiteral("已有日程"),
|
||||
QDateTime(tomorrow, QTime(14, 0), Qt::LocalTime),
|
||||
QDateTime(tomorrow, QTime(15, 0), Qt::LocalTime),
|
||||
&error));
|
||||
QVERIFY(service.createBlock(QStringLiteral("待删除"),
|
||||
QDateTime(tomorrow, QTime(16, 0), Qt::LocalTime),
|
||||
QDateTime(tomorrow, QTime(17, 0), Qt::LocalTime),
|
||||
&error));
|
||||
|
||||
auto provider = std::make_unique<MockChatProvider>();
|
||||
MockChatProvider* mock = provider.get();
|
||||
mock->response = QStringLiteral(
|
||||
"好的,我插入并清理一下。\n@@DIFF@@\n"
|
||||
"{\"operations\":["
|
||||
"{\"type\":\"create\",\"title\":\"插入任务\","
|
||||
"\"duration_min\":60,\"preferred_start\":\"%1T14:00:00\","
|
||||
"\"preferred_end\":\"%1T15:00:00\"},"
|
||||
"{\"type\":\"delete\",\"target_ref\":\"b2\"}]}")
|
||||
.arg(tomorrow.toString(QStringLiteral("yyyy-MM-dd")));
|
||||
AIService aiService(service, store, *m_settings, std::move(provider));
|
||||
|
||||
CompactWindow compact(service, notifications, aiService, theme, *m_settings);
|
||||
compact.show();
|
||||
QVERIFY(QTest::qWaitForWindowExposed(&compact));
|
||||
QTest::qWait(100);
|
||||
|
||||
ElaLineEdit* input = compact.findChild<ElaLineEdit*>();
|
||||
QVERIFY(input);
|
||||
input->setText(QStringLiteral("明天下午两点插入一小时任务,并删掉四点的会议"));
|
||||
ElaPushButton* sendButton = nullptr;
|
||||
for (ElaPushButton* button : compact.findChildren<ElaPushButton*>())
|
||||
{
|
||||
if (button->text() == QStringLiteral("发送"))
|
||||
{
|
||||
sendButton = button;
|
||||
break;
|
||||
}
|
||||
}
|
||||
QVERIFY(sendButton);
|
||||
QTest::mouseClick(sendButton, Qt::LeftButton);
|
||||
QTest::qWait(180);
|
||||
|
||||
auto* card = compact.findChild<DiffPreviewCard*>();
|
||||
QVERIFY(card);
|
||||
saveWindow(&compact, QStringLiteral("chat-multi-diff.png"));
|
||||
|
||||
ElaPushButton* acceptButton = nullptr;
|
||||
for (ElaPushButton* button : card->findChildren<ElaPushButton*>())
|
||||
{
|
||||
if (button->text() == QStringLiteral("接受选中"))
|
||||
{
|
||||
acceptButton = button;
|
||||
break;
|
||||
}
|
||||
}
|
||||
QVERIFY(acceptButton);
|
||||
QTest::mouseClick(acceptButton, Qt::LeftButton);
|
||||
QTest::qWait(150);
|
||||
saveWindow(&compact, QStringLiteral("chat-multi-applied.png"));
|
||||
|
||||
const QVector<ScheduleItem> items = service.itemsForDay(tomorrow);
|
||||
QCOMPARE(items.size(), 2);
|
||||
bool sawInsert = false;
|
||||
bool sawMoved = false;
|
||||
for (const ScheduleItem& item : items)
|
||||
{
|
||||
QVERIFY(item.task.title != QStringLiteral("待删除"));
|
||||
if (item.task.title == QStringLiteral("插入任务"))
|
||||
{
|
||||
sawInsert = true;
|
||||
QCOMPARE(item.block.startAt, QDateTime(tomorrow, QTime(14, 0), Qt::LocalTime));
|
||||
}
|
||||
if (item.task.title == QStringLiteral("已有日程"))
|
||||
{
|
||||
sawMoved = true;
|
||||
QCOMPARE(item.block.startAt, QDateTime(tomorrow, QTime(15, 0), Qt::LocalTime));
|
||||
}
|
||||
}
|
||||
QVERIFY(sawInsert);
|
||||
QVERIFY(sawMoved);
|
||||
}
|
||||
|
||||
QTEST_MAIN(TestCompactWindow)
|
||||
#include "test_compactwindow.moc"
|
||||
@@ -0,0 +1,107 @@
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
#include <QTemporaryDir>
|
||||
#include <QtTest>
|
||||
|
||||
#include "utils/AppSettings.h"
|
||||
|
||||
class TestConfig : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
private slots:
|
||||
void defaultsAndRoundTrip();
|
||||
void invalidFileFallsBack();
|
||||
};
|
||||
|
||||
void TestConfig::defaultsAndRoundTrip()
|
||||
{
|
||||
QTemporaryDir dir;
|
||||
QVERIFY(dir.isValid());
|
||||
const QString path = dir.filePath(QStringLiteral("config.toml"));
|
||||
|
||||
QString deviceId;
|
||||
{
|
||||
AppSettings settings(path);
|
||||
QVERIFY(QFileInfo::exists(path));
|
||||
QCOMPARE(settings.configPath(), path);
|
||||
QCOMPARE(settings.themePreference(), QStringLiteral("system"));
|
||||
QCOMPARE(settings.micaEnabled(), false);
|
||||
QCOMPARE(settings.snapMinutes(), 15);
|
||||
QCOMPARE(settings.trayHintShown(), false);
|
||||
QCOMPARE(settings.aiConfig().baseUrl, QStringLiteral("https://api.openai.com/v1"));
|
||||
QCOMPARE(settings.aiConfig().model, QStringLiteral("gpt-4o-mini"));
|
||||
QVERIFY(settings.aiConfig().apiKey.isEmpty());
|
||||
|
||||
deviceId = settings.deviceId();
|
||||
QVERIFY(!deviceId.isEmpty());
|
||||
|
||||
settings.setThemePreference(QStringLiteral("dark"));
|
||||
settings.setMicaEnabled(true);
|
||||
settings.setSnapMinutes(30);
|
||||
settings.setTrayHintShown(true);
|
||||
settings.setCompactGeometry(QByteArray("compact-geometry"));
|
||||
settings.setScheduleGeometry(QByteArray("schedule-geometry"));
|
||||
settings.setScheduleSplitter(QByteArray("splitter-state"));
|
||||
|
||||
SyncConfig syncConfig;
|
||||
syncConfig.enabled = true;
|
||||
syncConfig.serverUrl = QStringLiteral("http://sync.test:8787");
|
||||
syncConfig.token = QStringLiteral("sync-token");
|
||||
settings.setSyncConfig(syncConfig);
|
||||
|
||||
AiConfig ai;
|
||||
ai.baseUrl = QStringLiteral("https://example.test/v1");
|
||||
ai.apiKey = QStringLiteral("test-secret-key");
|
||||
ai.model = QStringLiteral("test-model");
|
||||
ai.temperature = 0.7;
|
||||
settings.setAiConfig(ai);
|
||||
}
|
||||
|
||||
AppSettings reloaded(path);
|
||||
QCOMPARE(reloaded.deviceId(), deviceId);
|
||||
QCOMPARE(reloaded.themePreference(), QStringLiteral("dark"));
|
||||
QCOMPARE(reloaded.micaEnabled(), true);
|
||||
QCOMPARE(reloaded.snapMinutes(), 30);
|
||||
QCOMPARE(reloaded.trayHintShown(), true);
|
||||
QCOMPARE(reloaded.compactGeometry(), QByteArray("compact-geometry"));
|
||||
QCOMPARE(reloaded.scheduleGeometry(), QByteArray("schedule-geometry"));
|
||||
QCOMPARE(reloaded.scheduleSplitter(), QByteArray("splitter-state"));
|
||||
QCOMPARE(reloaded.aiConfig().baseUrl, QStringLiteral("https://example.test/v1"));
|
||||
QCOMPARE(reloaded.aiConfig().apiKey, QStringLiteral("test-secret-key"));
|
||||
QCOMPARE(reloaded.aiConfig().model, QStringLiteral("test-model"));
|
||||
QCOMPARE(reloaded.aiConfig().temperature, 0.7);
|
||||
QCOMPARE(reloaded.syncConfig().enabled, true);
|
||||
QCOMPARE(reloaded.syncConfig().serverUrl, QStringLiteral("http://sync.test:8787"));
|
||||
QCOMPARE(reloaded.syncConfig().token, QStringLiteral("sync-token"));
|
||||
|
||||
#ifndef Q_OS_WIN
|
||||
const auto permissions = QFileInfo(path).permissions();
|
||||
QVERIFY(permissions.testFlag(QFileDevice::ReadOwner));
|
||||
QVERIFY(permissions.testFlag(QFileDevice::WriteOwner));
|
||||
QVERIFY(!permissions.testFlag(QFileDevice::ReadGroup));
|
||||
QVERIFY(!permissions.testFlag(QFileDevice::ReadOther));
|
||||
#endif
|
||||
}
|
||||
|
||||
void TestConfig::invalidFileFallsBack()
|
||||
{
|
||||
QTemporaryDir dir;
|
||||
QVERIFY(dir.isValid());
|
||||
const QString path = dir.filePath(QStringLiteral("config.toml"));
|
||||
|
||||
QFile file(path);
|
||||
QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
|
||||
file.write("this is not valid toml = [");
|
||||
file.close();
|
||||
|
||||
AppSettings settings(path);
|
||||
QCOMPARE(settings.themePreference(), QStringLiteral("system"));
|
||||
QCOMPARE(settings.micaEnabled(), false);
|
||||
QCOMPARE(settings.snapMinutes(), 15);
|
||||
QVERIFY(!settings.deviceId().isEmpty());
|
||||
QVERIFY(QFileInfo::exists(path + QStringLiteral(".bak")));
|
||||
}
|
||||
|
||||
QTEST_GUILESS_MAIN(TestConfig)
|
||||
#include "test_config.moc"
|
||||
@@ -0,0 +1,163 @@
|
||||
#include <QSignalSpy>
|
||||
#include <QTemporaryDir>
|
||||
#include <QtTest>
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "core/DateTimeUtils.h"
|
||||
#include "ui/theme/ThemeManager.h"
|
||||
#include "ui/views/ScheduleGridView.h"
|
||||
#include "utils/AppSettings.h"
|
||||
|
||||
class TestGrid : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
private slots:
|
||||
void initTestCase();
|
||||
void createByDoubleClick();
|
||||
void dragMovesBlock();
|
||||
void resizeBottomEdge();
|
||||
void doubleClickEditsBlock();
|
||||
|
||||
private:
|
||||
ScheduleItem makeItem(const QString& id,
|
||||
const QString& title,
|
||||
const QDateTime& start,
|
||||
const QDateTime& end) const;
|
||||
void prepareView(ScheduleGridView& view, int hour);
|
||||
|
||||
QTemporaryDir m_tempDir;
|
||||
std::unique_ptr<AppSettings> m_settings;
|
||||
std::unique_ptr<ThemeManager> m_theme;
|
||||
};
|
||||
|
||||
void TestGrid::initTestCase()
|
||||
{
|
||||
QVERIFY(m_tempDir.isValid());
|
||||
QCoreApplication::setOrganizationName(QStringLiteral("ScheduleTest"));
|
||||
QCoreApplication::setApplicationName(QStringLiteral("ScheduleTest"));
|
||||
m_settings = std::make_unique<AppSettings>(m_tempDir.filePath(QStringLiteral("config.toml")));
|
||||
m_theme = std::make_unique<ThemeManager>(*m_settings);
|
||||
m_theme->initialize();
|
||||
}
|
||||
|
||||
ScheduleItem TestGrid::makeItem(const QString& id,
|
||||
const QString& title,
|
||||
const QDateTime& start,
|
||||
const QDateTime& end) const
|
||||
{
|
||||
ScheduleItem item;
|
||||
item.task.id = QStringLiteral("task-") + id;
|
||||
item.task.title = title;
|
||||
item.block.id = id;
|
||||
item.block.taskId = item.task.id;
|
||||
item.block.startAt = start;
|
||||
item.block.endAt = end;
|
||||
return item;
|
||||
}
|
||||
|
||||
void TestGrid::prepareView(ScheduleGridView& view, int hour)
|
||||
{
|
||||
view.resize(900, 600);
|
||||
view.setDate(QDate::currentDate());
|
||||
view.setTokens(m_theme->tokens());
|
||||
view.show();
|
||||
QVERIFY(QTest::qWaitForWindowExposed(&view));
|
||||
QTest::qWait(30);
|
||||
view.scrollToHour(hour);
|
||||
QTest::qWait(20);
|
||||
}
|
||||
|
||||
void TestGrid::createByDoubleClick()
|
||||
{
|
||||
ScheduleGridView view;
|
||||
prepareView(view, 8);
|
||||
|
||||
QSignalSpy createSpy(&view, &ScheduleGridView::createRequested);
|
||||
QTest::mouseDClick(view.viewport(), Qt::LeftButton, Qt::NoModifier, QPoint(300, 200), 10);
|
||||
QTest::qWait(10);
|
||||
|
||||
QCOMPARE(createSpy.count(), 1);
|
||||
const QDateTime start = createSpy.at(0).at(0).toDateTime();
|
||||
const QDateTime end = createSpy.at(0).at(1).toDateTime();
|
||||
QCOMPARE(start, QDateTime(QDate::currentDate(), QTime(8, 0), Qt::LocalTime));
|
||||
QCOMPARE(end, start.addSecs(60 * 60));
|
||||
}
|
||||
|
||||
void TestGrid::dragMovesBlock()
|
||||
{
|
||||
ScheduleGridView view;
|
||||
prepareView(view, 8);
|
||||
|
||||
const QDate today = QDate::currentDate();
|
||||
view.setBlocks({makeItem(QStringLiteral("block-1"),
|
||||
QStringLiteral("写周报"),
|
||||
QDateTime(today, QTime(9, 0), Qt::LocalTime),
|
||||
QDateTime(today, QTime(10, 0), Qt::LocalTime))});
|
||||
QTest::qWait(20);
|
||||
|
||||
QSignalSpy moveSpy(&view, &ScheduleGridView::moveRequested);
|
||||
const QPoint startPoint(300, 380);
|
||||
const QPoint endPoint(300, 500);
|
||||
QTest::mousePress(view.viewport(), Qt::LeftButton, Qt::NoModifier, startPoint, 10);
|
||||
QTest::mouseMove(view.viewport(), endPoint, 20);
|
||||
QTest::mouseRelease(view.viewport(), Qt::LeftButton, Qt::NoModifier, endPoint, 10);
|
||||
QTest::qWait(10);
|
||||
|
||||
QCOMPARE(moveSpy.count(), 1);
|
||||
QCOMPARE(moveSpy.at(0).at(0).toString(), QStringLiteral("block-1"));
|
||||
QCOMPARE(moveSpy.at(0).at(1).toDateTime(),
|
||||
QDateTime(today, QTime(10, 0), Qt::LocalTime));
|
||||
QCOMPARE(moveSpy.at(0).at(2).toDateTime(),
|
||||
QDateTime(today, QTime(11, 0), Qt::LocalTime));
|
||||
}
|
||||
|
||||
void TestGrid::resizeBottomEdge()
|
||||
{
|
||||
ScheduleGridView view;
|
||||
prepareView(view, 8);
|
||||
|
||||
const QDate today = QDate::currentDate();
|
||||
view.setBlocks({makeItem(QStringLiteral("block-2"),
|
||||
QStringLiteral("写文档"),
|
||||
QDateTime(today, QTime(9, 0), Qt::LocalTime),
|
||||
QDateTime(today, QTime(10, 0), Qt::LocalTime))});
|
||||
QTest::qWait(20);
|
||||
|
||||
QSignalSpy moveSpy(&view, &ScheduleGridView::moveRequested);
|
||||
const QPoint edgePoint(300, 434);
|
||||
const QPoint targetPoint(300, 470);
|
||||
QTest::mousePress(view.viewport(), Qt::LeftButton, Qt::NoModifier, edgePoint, 10);
|
||||
QTest::mouseMove(view.viewport(), targetPoint, 20);
|
||||
QTest::mouseRelease(view.viewport(), Qt::LeftButton, Qt::NoModifier, targetPoint, 10);
|
||||
QTest::qWait(10);
|
||||
|
||||
QCOMPARE(moveSpy.count(), 1);
|
||||
QCOMPARE(moveSpy.at(0).at(1).toDateTime(),
|
||||
QDateTime(today, QTime(9, 0), Qt::LocalTime));
|
||||
QVERIFY(moveSpy.at(0).at(2).toDateTime() > QDateTime(today, QTime(10, 0), Qt::LocalTime));
|
||||
}
|
||||
|
||||
void TestGrid::doubleClickEditsBlock()
|
||||
{
|
||||
ScheduleGridView view;
|
||||
prepareView(view, 8);
|
||||
|
||||
const QDate today = QDate::currentDate();
|
||||
view.setBlocks({makeItem(QStringLiteral("block-3"),
|
||||
QStringLiteral("复盘"),
|
||||
QDateTime(today, QTime(9, 0), Qt::LocalTime),
|
||||
QDateTime(today, QTime(10, 0), Qt::LocalTime))});
|
||||
QTest::qWait(20);
|
||||
|
||||
QSignalSpy editSpy(&view, &ScheduleGridView::editRequested);
|
||||
QTest::mouseDClick(view.viewport(), Qt::LeftButton, Qt::NoModifier, QPoint(300, 350), 10);
|
||||
QTest::qWait(10);
|
||||
|
||||
QCOMPARE(editSpy.count(), 1);
|
||||
QCOMPARE(editSpy.at(0).at(0).toString(), QStringLiteral("block-3"));
|
||||
}
|
||||
|
||||
QTEST_MAIN(TestGrid)
|
||||
#include "test_grid.moc"
|
||||
@@ -0,0 +1,132 @@
|
||||
#include <QApplication>
|
||||
#include <QScrollBar>
|
||||
#include <QTemporaryDir>
|
||||
#include <QTimer>
|
||||
#include <QtTest>
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "core/ScheduleItem.h"
|
||||
#include "services/NotificationService.h"
|
||||
#include "services/ScheduleService.h"
|
||||
#include "storage/SqliteStore.h"
|
||||
#include "ui/MainWindow.h"
|
||||
#include "ui/dialogs/BlockEditDialog.h"
|
||||
#include "ui/theme/ThemeManager.h"
|
||||
#include "ui/views/ScheduleGridView.h"
|
||||
#include "utils/AppSettings.h"
|
||||
|
||||
#include "ElaLineEdit.h"
|
||||
|
||||
class TestMainWindow : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
private slots:
|
||||
void initTestCase();
|
||||
void createEditAndDeleteThroughUi();
|
||||
|
||||
private:
|
||||
static void fillDialogAndAccept(const QString& title, bool accept);
|
||||
|
||||
QTemporaryDir m_tempDir;
|
||||
std::unique_ptr<AppSettings> m_settings;
|
||||
};
|
||||
|
||||
void TestMainWindow::initTestCase()
|
||||
{
|
||||
QVERIFY(m_tempDir.isValid());
|
||||
QCoreApplication::setOrganizationName(QStringLiteral("ScheduleTest"));
|
||||
QCoreApplication::setApplicationName(QStringLiteral("ScheduleTest"));
|
||||
m_settings = std::make_unique<AppSettings>(m_tempDir.filePath(QStringLiteral("config.toml")));
|
||||
}
|
||||
|
||||
void TestMainWindow::fillDialogAndAccept(const QString& title, bool accept)
|
||||
{
|
||||
QTimer::singleShot(400, [title, accept]() {
|
||||
for (QWidget* widget : QApplication::topLevelWidgets())
|
||||
{
|
||||
auto* dialog = qobject_cast<BlockEditDialog*>(widget);
|
||||
if (!dialog)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
const auto edits = dialog->findChildren<ElaLineEdit*>();
|
||||
if (!edits.isEmpty())
|
||||
{
|
||||
edits.first()->setText(title);
|
||||
}
|
||||
if (accept)
|
||||
{
|
||||
dialog->accept();
|
||||
}
|
||||
else
|
||||
{
|
||||
dialog->reject();
|
||||
}
|
||||
return;
|
||||
}
|
||||
});
|
||||
QTimer::singleShot(2000, []() {
|
||||
for (QWidget* widget : QApplication::topLevelWidgets())
|
||||
{
|
||||
if (auto* dialog = qobject_cast<BlockEditDialog*>(widget))
|
||||
{
|
||||
dialog->reject();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void TestMainWindow::createEditAndDeleteThroughUi()
|
||||
{
|
||||
QTemporaryDir databaseDir;
|
||||
QVERIFY(databaseDir.isValid());
|
||||
SqliteStore store(databaseDir.filePath(QStringLiteral("schedule.db")));
|
||||
QString error;
|
||||
QVERIFY2(store.open(&error), qPrintable(error));
|
||||
|
||||
ThemeManager theme(*m_settings);
|
||||
theme.initialize();
|
||||
ScheduleService service(store, QStringLiteral("ui-test-device"));
|
||||
NotificationService notifications(service);
|
||||
|
||||
MainWindow window(service, notifications, theme, *m_settings);
|
||||
window.show();
|
||||
QVERIFY(QTest::qWaitForWindowExposed(&window));
|
||||
QTest::qWait(60);
|
||||
|
||||
auto* grid = window.findChild<ScheduleGridView*>();
|
||||
QVERIFY(grid);
|
||||
grid->scrollToHour(8);
|
||||
QTest::qWait(20);
|
||||
const int scroll = grid->verticalScrollBar()->value();
|
||||
const QPoint createPoint(300, 8 * 120 - scroll + 5);
|
||||
|
||||
fillDialogAndAccept(QStringLiteral("自动测试日程"), true);
|
||||
QTest::mouseDClick(grid->viewport(), Qt::LeftButton, Qt::NoModifier, createPoint, 10);
|
||||
QTest::qWait(80);
|
||||
|
||||
QVector<ScheduleItem> items = service.itemsForDay(QDate::currentDate());
|
||||
QCOMPARE(items.size(), 1);
|
||||
QCOMPARE(items.first().task.title, QStringLiteral("自动测试日程"));
|
||||
const QString blockId = items.first().block.id;
|
||||
|
||||
const QPoint editPoint(300, 8 * 120 - scroll + 40);
|
||||
fillDialogAndAccept(QStringLiteral("改名为复盘"), true);
|
||||
QTest::mouseDClick(grid->viewport(), Qt::LeftButton, Qt::NoModifier, editPoint, 10);
|
||||
QTest::qWait(80);
|
||||
|
||||
items = service.itemsForDay(QDate::currentDate());
|
||||
QCOMPARE(items.size(), 1);
|
||||
QCOMPARE(items.first().task.title, QStringLiteral("改名为复盘"));
|
||||
|
||||
grid->setFocus();
|
||||
grid->setSelectedBlock(blockId);
|
||||
QTest::keyClick(grid, Qt::Key_Delete);
|
||||
QTest::qWait(80);
|
||||
QVERIFY(service.itemsForDay(QDate::currentDate()).isEmpty());
|
||||
}
|
||||
|
||||
QTEST_MAIN(TestMainWindow)
|
||||
#include "test_mainwindow.moc"
|
||||
@@ -0,0 +1,135 @@
|
||||
#include <QJsonArray>
|
||||
#include <QJsonObject>
|
||||
#include <QTcpServer>
|
||||
#include <QTcpSocket>
|
||||
#include <QTimer>
|
||||
#include <QtTest>
|
||||
|
||||
#include "ai/IAIProvider.h"
|
||||
#include "ai/OpenAiProvider.h"
|
||||
|
||||
class FakeSseServer : public QTcpServer
|
||||
{
|
||||
public:
|
||||
QByteArray response;
|
||||
|
||||
FakeSseServer()
|
||||
{
|
||||
connect(this, &QTcpServer::newConnection, this, [this]() {
|
||||
while (hasPendingConnections())
|
||||
{
|
||||
QTcpSocket* socket = nextPendingConnection();
|
||||
connect(socket, &QTcpSocket::readyRead, socket, [this, socket]() {
|
||||
if (socket->property("responded").toBool())
|
||||
{
|
||||
return;
|
||||
}
|
||||
QByteArray buffer = socket->property("buffer").toByteArray();
|
||||
buffer += socket->readAll();
|
||||
socket->setProperty("buffer", buffer);
|
||||
if (!buffer.contains("\r\n\r\n"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
socket->setProperty("responded", true);
|
||||
socket->write(response);
|
||||
socket->flush();
|
||||
QTimer::singleShot(30, socket, [socket]() { socket->disconnectFromHost(); });
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
class TestOpenAiProvider : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
private slots:
|
||||
void streamsSseContent();
|
||||
void reportsHttpError();
|
||||
};
|
||||
|
||||
void TestOpenAiProvider::streamsSseContent()
|
||||
{
|
||||
FakeSseServer server;
|
||||
QVERIFY(server.listen(QHostAddress::LocalHost, 0));
|
||||
server.response =
|
||||
"HTTP/1.1 200 OK\r\n"
|
||||
"Content-Type: text/event-stream\r\n"
|
||||
"Cache-Control: no-cache\r\n"
|
||||
"Connection: close\r\n"
|
||||
"\r\n"
|
||||
"data: {\"choices\":[{\"delta\":{\"content\":\"你好\"}}]}\n\n"
|
||||
"data: {\"choices\":[{\"delta\":{\"content\":\",世界\"}}]}\n\n"
|
||||
"data: [DONE]\n\n";
|
||||
|
||||
AiConfig config;
|
||||
config.baseUrl = QStringLiteral("http://127.0.0.1:%1/v1").arg(server.serverPort());
|
||||
config.apiKey = QStringLiteral("test-key");
|
||||
config.model = QStringLiteral("test-model");
|
||||
|
||||
QJsonArray messages;
|
||||
QJsonObject message;
|
||||
message.insert(QStringLiteral("role"), QStringLiteral("user"));
|
||||
message.insert(QStringLiteral("content"), QStringLiteral("hi"));
|
||||
messages.append(message);
|
||||
|
||||
OpenAiProvider provider;
|
||||
QString text;
|
||||
QString error;
|
||||
bool finished = false;
|
||||
provider.streamCompletion(
|
||||
config,
|
||||
messages,
|
||||
{
|
||||
[&text](const QString& delta) { text += delta; },
|
||||
[&error](const QString& message) { error = message; },
|
||||
[&finished]() { finished = true; },
|
||||
});
|
||||
QTRY_VERIFY_WITH_TIMEOUT(finished, 5000);
|
||||
QCOMPARE(error, QString());
|
||||
QCOMPARE(text, QStringLiteral("你好,世界"));
|
||||
}
|
||||
|
||||
void TestOpenAiProvider::reportsHttpError()
|
||||
{
|
||||
FakeSseServer server;
|
||||
QVERIFY(server.listen(QHostAddress::LocalHost, 0));
|
||||
server.response =
|
||||
"HTTP/1.1 401 Unauthorized\r\n"
|
||||
"Content-Type: application/json\r\n"
|
||||
"Connection: close\r\n"
|
||||
"\r\n"
|
||||
"{\"error\":{\"message\":\"Invalid API key\"}}";
|
||||
|
||||
AiConfig config;
|
||||
config.baseUrl = QStringLiteral("http://127.0.0.1:%1/v1").arg(server.serverPort());
|
||||
config.apiKey = QStringLiteral("bad-key");
|
||||
config.model = QStringLiteral("test-model");
|
||||
|
||||
QJsonArray messages;
|
||||
QJsonObject message;
|
||||
message.insert(QStringLiteral("role"), QStringLiteral("user"));
|
||||
message.insert(QStringLiteral("content"), QStringLiteral("hi"));
|
||||
messages.append(message);
|
||||
|
||||
OpenAiProvider provider;
|
||||
QString error;
|
||||
bool finished = false;
|
||||
provider.streamCompletion(
|
||||
config,
|
||||
messages,
|
||||
{
|
||||
[](const QString&) {},
|
||||
[&error](const QString& message) { error = message; },
|
||||
[&finished]() { finished = true; },
|
||||
});
|
||||
QTRY_VERIFY_WITH_TIMEOUT(!error.isEmpty(), 5000);
|
||||
QVERIFY(!finished);
|
||||
QVERIFY(error.contains(QStringLiteral("Invalid API key")));
|
||||
QVERIFY(error.contains(QStringLiteral("401")));
|
||||
}
|
||||
|
||||
QTEST_GUILESS_MAIN(TestOpenAiProvider)
|
||||
#include "test_openai_provider.moc"
|
||||
@@ -0,0 +1,161 @@
|
||||
#include <QtTest>
|
||||
|
||||
#include <chrono>
|
||||
|
||||
#include "core/SchedulerEngine.h"
|
||||
|
||||
using namespace std::chrono;
|
||||
using namespace std::chrono_literals;
|
||||
using scheduler::SysTime;
|
||||
|
||||
namespace
|
||||
{
|
||||
SysTime at(int day, int hour, int minute = 0)
|
||||
{
|
||||
return SysTime{sys_days{year{2026} / January / 5} + days{day} + hours{hour} + minutes{minute}};
|
||||
}
|
||||
|
||||
std::vector<scheduler::TimeRange> workWindows(int days = 2)
|
||||
{
|
||||
std::vector<scheduler::TimeRange> windows;
|
||||
for (int day = 0; day < days; ++day)
|
||||
{
|
||||
windows.push_back({at(day, 8), at(day, 22)});
|
||||
}
|
||||
return windows;
|
||||
}
|
||||
|
||||
scheduler::TaskInput task(const std::string& id,
|
||||
int minutes,
|
||||
int priority = 1,
|
||||
std::optional<SysTime> deadline = std::nullopt,
|
||||
std::optional<SysTime> preferredStart = std::nullopt,
|
||||
std::optional<SysTime> preferredEnd = std::nullopt)
|
||||
{
|
||||
scheduler::TaskInput input;
|
||||
input.id = id;
|
||||
input.title = id;
|
||||
input.durationMinutes = minutes;
|
||||
input.priority = priority;
|
||||
input.deadline = deadline;
|
||||
input.preferredStart = preferredStart;
|
||||
input.preferredEnd = preferredEnd;
|
||||
return input;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
class TestScheduler : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
private slots:
|
||||
void skipsBusyIntervals();
|
||||
void honorsPreferredWindow();
|
||||
void alignsToGranularity();
|
||||
void respectsDeadline();
|
||||
void prioritizesHigherPriorityFirst();
|
||||
void fallsBackWhenPreferredIsFull();
|
||||
void preferredWindowCanOverrideDefaultHours();
|
||||
void reportsFailureWhenNoRoom();
|
||||
};
|
||||
|
||||
void TestScheduler::skipsBusyIntervals()
|
||||
{
|
||||
const auto result = scheduler::schedule({task("a", 60)},
|
||||
{{at(0, 8), at(0, 10)}},
|
||||
workWindows(),
|
||||
at(0, 8),
|
||||
at(1, 22));
|
||||
QCOMPARE(result.placements.size(), std::size_t(1));
|
||||
QVERIFY(result.placements[0].start == at(0, 10));
|
||||
QVERIFY(result.placements[0].end == at(0, 11));
|
||||
QVERIFY(result.failures.empty());
|
||||
}
|
||||
|
||||
void TestScheduler::honorsPreferredWindow()
|
||||
{
|
||||
const auto result = scheduler::schedule({task("a", 60, 1, std::nullopt, at(0, 14), at(0, 17))},
|
||||
{},
|
||||
workWindows(),
|
||||
at(0, 8),
|
||||
at(1, 22));
|
||||
QCOMPARE(result.placements.size(), std::size_t(1));
|
||||
QVERIFY(result.placements[0].start == at(0, 14));
|
||||
QVERIFY(result.placements[0].end == at(0, 15));
|
||||
}
|
||||
|
||||
void TestScheduler::alignsToGranularity()
|
||||
{
|
||||
const auto result = scheduler::schedule({task("a", 30)},
|
||||
{},
|
||||
workWindows(),
|
||||
at(0, 8, 7),
|
||||
at(0, 22));
|
||||
QCOMPARE(result.placements.size(), std::size_t(1));
|
||||
QVERIFY(result.placements[0].start == at(0, 8, 15));
|
||||
QVERIFY(result.placements[0].end == at(0, 8, 45));
|
||||
}
|
||||
|
||||
void TestScheduler::respectsDeadline()
|
||||
{
|
||||
const auto result = scheduler::schedule({task("a", 60, 1, at(0, 9))},
|
||||
{{at(0, 8), at(0, 10)}},
|
||||
workWindows(),
|
||||
at(0, 8),
|
||||
at(1, 22));
|
||||
QVERIFY(result.placements.empty());
|
||||
QCOMPARE(result.failures.size(), std::size_t(1));
|
||||
QCOMPARE(QString::fromStdString(result.failures[0].taskId), QStringLiteral("a"));
|
||||
}
|
||||
|
||||
void TestScheduler::prioritizesHigherPriorityFirst()
|
||||
{
|
||||
const auto result = scheduler::schedule({task("low", 60, 1), task("high", 60, 3)},
|
||||
{},
|
||||
workWindows(1),
|
||||
at(0, 8),
|
||||
at(0, 22));
|
||||
QCOMPARE(result.placements.size(), std::size_t(2));
|
||||
QCOMPARE(QString::fromStdString(result.placements[0].taskId), QStringLiteral("high"));
|
||||
QVERIFY(result.placements[0].start == at(0, 8));
|
||||
QCOMPARE(QString::fromStdString(result.placements[1].taskId), QStringLiteral("low"));
|
||||
QVERIFY(result.placements[1].start == at(0, 9));
|
||||
}
|
||||
|
||||
void TestScheduler::fallsBackWhenPreferredIsFull()
|
||||
{
|
||||
const auto result = scheduler::schedule({task("a", 60, 1, std::nullopt, at(0, 14), at(0, 16))},
|
||||
{{at(0, 14), at(0, 16)}},
|
||||
workWindows(),
|
||||
at(0, 8),
|
||||
at(1, 22));
|
||||
QCOMPARE(result.placements.size(), std::size_t(1));
|
||||
QVERIFY(result.placements[0].start == at(0, 8));
|
||||
QVERIFY(result.placements[0].end == at(0, 9));
|
||||
}
|
||||
|
||||
void TestScheduler::preferredWindowCanOverrideDefaultHours()
|
||||
{
|
||||
const auto result = scheduler::schedule({task("late", 60, 1, std::nullopt, at(0, 23), at(1, 1))},
|
||||
{},
|
||||
workWindows(),
|
||||
at(0, 8),
|
||||
at(1, 22));
|
||||
QCOMPARE(result.placements.size(), std::size_t(1));
|
||||
QVERIFY(result.placements[0].start == at(0, 23));
|
||||
QVERIFY(result.placements[0].end == at(1, 0));
|
||||
}
|
||||
|
||||
void TestScheduler::reportsFailureWhenNoRoom()
|
||||
{
|
||||
const auto result = scheduler::schedule({task("a", 120)},
|
||||
{{at(0, 8), at(0, 22)}},
|
||||
workWindows(1),
|
||||
at(0, 8),
|
||||
at(0, 22));
|
||||
QVERIFY(result.placements.empty());
|
||||
QCOMPARE(result.failures.size(), std::size_t(1));
|
||||
}
|
||||
|
||||
QTEST_GUILESS_MAIN(TestScheduler)
|
||||
#include "test_scheduler.moc"
|
||||
@@ -0,0 +1,317 @@
|
||||
#include <QJsonArray>
|
||||
#include <QJsonObject>
|
||||
#include <QSignalSpy>
|
||||
#include <QTemporaryDir>
|
||||
#include <QtTest>
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "core/DateTimeUtils.h"
|
||||
#include "core/ProposedDiff.h"
|
||||
#include "services/NotificationService.h"
|
||||
#include "services/ScheduleService.h"
|
||||
#include "storage/SqliteStore.h"
|
||||
|
||||
class TestServices : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
private slots:
|
||||
void createAndQueryDay();
|
||||
void queryMonthAndYearRange();
|
||||
void updateAndMove();
|
||||
void statusAndPostpone();
|
||||
void deleteCascadesTask();
|
||||
void overdueAndNotificationDedup();
|
||||
void invalidRangeRejected();
|
||||
void applyProposedCreatesOnlySelected();
|
||||
};
|
||||
|
||||
namespace
|
||||
{
|
||||
struct Context
|
||||
{
|
||||
QTemporaryDir dir;
|
||||
std::unique_ptr<SqliteStore> store;
|
||||
std::unique_ptr<ScheduleService> service;
|
||||
|
||||
bool open()
|
||||
{
|
||||
if (!dir.isValid())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
store = std::make_unique<SqliteStore>(dir.filePath(QStringLiteral("schedule.db")));
|
||||
QString error;
|
||||
if (!store->open(&error))
|
||||
{
|
||||
qWarning() << error;
|
||||
return false;
|
||||
}
|
||||
service = std::make_unique<ScheduleService>(*store, QStringLiteral("test-device"));
|
||||
return true;
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
void TestServices::createAndQueryDay()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.open());
|
||||
|
||||
const QDateTime start(QDate::currentDate(), QTime(9, 0), Qt::LocalTime);
|
||||
const QDateTime end = start.addSecs(90 * 60);
|
||||
QString error;
|
||||
QVERIFY2(context.service->createBlock(QStringLiteral("写周报"), start, end, &error), qPrintable(error));
|
||||
|
||||
const QVector<ScheduleItem> items = context.service->itemsForDay(QDate::currentDate());
|
||||
QCOMPARE(items.size(), 1);
|
||||
QCOMPARE(items.first().task.title, QStringLiteral("写周报"));
|
||||
QCOMPARE(items.first().block.startAt, start);
|
||||
QCOMPARE(items.first().block.endAt, end);
|
||||
QCOMPARE(items.first().task.source, QStringLiteral("manual"));
|
||||
}
|
||||
|
||||
void TestServices::queryMonthAndYearRange()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.open());
|
||||
|
||||
const QDate today = QDate::currentDate();
|
||||
const QDate first = QDate(today.year(), today.month(), 1);
|
||||
const QDate last = QDate(today.year(), today.month(), first.daysInMonth());
|
||||
|
||||
QString error;
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("月初"),
|
||||
QDateTime(first, QTime(9, 0), Qt::LocalTime),
|
||||
QDateTime(first, QTime(10, 0), Qt::LocalTime),
|
||||
&error));
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("月末"),
|
||||
QDateTime(last, QTime(9, 0), Qt::LocalTime),
|
||||
QDateTime(last, QTime(10, 0), Qt::LocalTime),
|
||||
&error));
|
||||
const QDate outside = QDate(today.year() + 1, 6, 15);
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("范围外"),
|
||||
QDateTime(outside, QTime(9, 0), Qt::LocalTime),
|
||||
QDateTime(outside, QTime(10, 0), Qt::LocalTime),
|
||||
&error));
|
||||
|
||||
const QVector<ScheduleItem> monthItems = context.service->itemsForRange(first, last);
|
||||
QCOMPARE(monthItems.size(), 2);
|
||||
QCOMPARE(monthItems.first().task.title, QStringLiteral("月初"));
|
||||
QCOMPARE(monthItems.last().task.title, QStringLiteral("月末"));
|
||||
|
||||
const QVector<ScheduleItem> yearItems = context.service->itemsForRange(
|
||||
QDate(today.year(), 1, 1), QDate(today.year(), 12, 31));
|
||||
QCOMPARE(yearItems.size(), 2);
|
||||
|
||||
QVERIFY(context.service->itemsForRange(last, first).isEmpty());
|
||||
}
|
||||
|
||||
void TestServices::updateAndMove()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.open());
|
||||
|
||||
const QDateTime start(QDate::currentDate(), QTime(9, 0), Qt::LocalTime);
|
||||
QString error;
|
||||
QVERIFY2(context.service->createBlock(QStringLiteral("旧标题"),
|
||||
start,
|
||||
start.addSecs(60 * 60),
|
||||
&error),
|
||||
qPrintable(error));
|
||||
|
||||
QVector<ScheduleItem> items = context.service->itemsForDay(QDate::currentDate());
|
||||
QCOMPARE(items.size(), 1);
|
||||
const QString blockId = items.first().block.id;
|
||||
|
||||
const QDateTime newStart = start.addSecs(2 * 60 * 60);
|
||||
const QDateTime newEnd = newStart.addSecs(45 * 60);
|
||||
QVERIFY2(context.service->updateBlock(blockId,
|
||||
QStringLiteral("新标题"),
|
||||
newStart,
|
||||
newEnd,
|
||||
&error),
|
||||
qPrintable(error));
|
||||
|
||||
items = context.service->itemsForDay(QDate::currentDate());
|
||||
QCOMPARE(items.size(), 1);
|
||||
QCOMPARE(items.first().task.title, QStringLiteral("新标题"));
|
||||
QCOMPARE(items.first().block.startAt, newStart);
|
||||
QCOMPARE(items.first().block.endAt, newEnd);
|
||||
QVERIFY(items.first().block.version >= 1);
|
||||
QCOMPARE(items.first().block.deviceId, QStringLiteral("test-device"));
|
||||
|
||||
const QDateTime movedStart = newStart.addSecs(15 * 60);
|
||||
const QDateTime movedEnd = newEnd.addSecs(15 * 60);
|
||||
QVERIFY2(context.service->moveBlock(blockId, movedStart, movedEnd, &error), qPrintable(error));
|
||||
items = context.service->itemsForDay(QDate::currentDate());
|
||||
QCOMPARE(items.first().block.startAt, movedStart);
|
||||
QCOMPARE(items.first().block.endAt, movedEnd);
|
||||
}
|
||||
|
||||
void TestServices::statusAndPostpone()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.open());
|
||||
|
||||
const QDateTime start(QDate::currentDate(), QTime(9, 0), Qt::LocalTime);
|
||||
QString error;
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("任务"),
|
||||
start,
|
||||
start.addSecs(60 * 60),
|
||||
&error));
|
||||
QVector<ScheduleItem> items = context.service->itemsForDay(QDate::currentDate());
|
||||
const QString blockId = items.first().block.id;
|
||||
|
||||
QVERIFY2(context.service->setBlockStatus(blockId, QStringLiteral("done"), &error), qPrintable(error));
|
||||
items = context.service->itemsForDay(QDate::currentDate());
|
||||
QCOMPARE(items.first().block.status, QStringLiteral("done"));
|
||||
QVERIFY(items.first().block.doneAt.has_value());
|
||||
|
||||
QVERIFY2(context.service->postponeBlock(blockId, 15, &error), qPrintable(error));
|
||||
items = context.service->itemsForDay(QDate::currentDate());
|
||||
QCOMPARE(items.first().block.status, QStringLiteral("scheduled"));
|
||||
QVERIFY(!items.first().block.doneAt.has_value());
|
||||
QCOMPARE(items.first().block.startAt, start.addSecs(15 * 60));
|
||||
QCOMPARE(items.first().block.endAt, start.addSecs(75 * 60));
|
||||
|
||||
QVERIFY(!context.service->setBlockStatus(blockId, QStringLiteral("unknown"), &error));
|
||||
QVERIFY(!error.isEmpty());
|
||||
}
|
||||
|
||||
void TestServices::deleteCascadesTask()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.open());
|
||||
|
||||
const QDateTime start(QDate::currentDate(), QTime(9, 0), Qt::LocalTime);
|
||||
QString error;
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("待删除"),
|
||||
start,
|
||||
start.addSecs(60 * 60),
|
||||
&error));
|
||||
QVector<ScheduleItem> items = context.service->itemsForDay(QDate::currentDate());
|
||||
const QString blockId = items.first().block.id;
|
||||
const QString taskId = items.first().task.id;
|
||||
QVERIFY(context.store->taskById(taskId).has_value());
|
||||
|
||||
QVERIFY2(context.service->deleteBlock(blockId, &error), qPrintable(error));
|
||||
QVERIFY(context.service->itemsForDay(QDate::currentDate()).isEmpty());
|
||||
QVERIFY(!context.store->taskById(taskId).has_value());
|
||||
}
|
||||
|
||||
void TestServices::overdueAndNotificationDedup()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.open());
|
||||
|
||||
const QDateTime now = QDateTime::currentDateTime();
|
||||
const QDateTime start = now.addSecs(-2 * 60 * 60);
|
||||
const QDateTime end = now.addSecs(-60 * 60);
|
||||
QString error;
|
||||
QVERIFY(context.service->createBlock(QStringLiteral("已超时"), start, end, &error));
|
||||
|
||||
const QVector<ScheduleItem> overdue = context.service->overdueItems(now);
|
||||
QCOMPARE(overdue.size(), 1);
|
||||
const QString overdueId = overdue.first().block.id;
|
||||
|
||||
NotificationService notifications(*context.service);
|
||||
QSignalSpy detectedSpy(¬ifications, &NotificationService::overdueDetected);
|
||||
QSignalSpy listSpy(¬ifications, &NotificationService::overdueListChanged);
|
||||
notifications.checkNow();
|
||||
QCOMPARE(detectedSpy.count(), 1);
|
||||
QCOMPARE(listSpy.count(), 1);
|
||||
QCOMPARE(notifications.overdueItems().size(), 1);
|
||||
|
||||
notifications.checkNow();
|
||||
QCOMPARE(detectedSpy.count(), 1);
|
||||
|
||||
QVERIFY(context.service->setBlockStatus(overdueId, QStringLiteral("done"), &error));
|
||||
QCOMPARE(context.service->overdueItems(QDateTime::currentDateTime()).size(), 0);
|
||||
QCOMPARE(notifications.overdueItems().size(), 0);
|
||||
}
|
||||
|
||||
void TestServices::invalidRangeRejected()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.open());
|
||||
|
||||
const QDateTime start(QDate::currentDate(), QTime(9, 0), Qt::LocalTime);
|
||||
QString error;
|
||||
QVERIFY(!context.service->createBlock(QStringLiteral("倒序"),
|
||||
start,
|
||||
start.addSecs(-60 * 60),
|
||||
&error));
|
||||
QVERIFY(!error.isEmpty());
|
||||
|
||||
error.clear();
|
||||
QVERIFY(!context.service->createBlock(QStringLiteral("太短"),
|
||||
start,
|
||||
start.addSecs(60),
|
||||
&error));
|
||||
QVERIFY(!error.isEmpty());
|
||||
QVERIFY(context.service->itemsForDay(QDate::currentDate()).isEmpty());
|
||||
}
|
||||
|
||||
void TestServices::applyProposedCreatesOnlySelected()
|
||||
{
|
||||
Context context;
|
||||
QVERIFY(context.open());
|
||||
|
||||
const QDate today = QDate::currentDate();
|
||||
const QDateTime startA(today, QTime(9, 0), Qt::LocalTime);
|
||||
const QDateTime endA = startA.addSecs(60 * 60);
|
||||
const QDateTime startB(today, QTime(11, 0), Qt::LocalTime);
|
||||
const QDateTime endB = startB.addSecs(30 * 60);
|
||||
|
||||
const auto makeCreate = [](const QString& tempId,
|
||||
const QString& title,
|
||||
const QDateTime& start,
|
||||
const QDateTime& end) {
|
||||
QJsonObject task;
|
||||
task.insert(QStringLiteral("title"), title);
|
||||
task.insert(QStringLiteral("description"), QStringLiteral("AI 生成"));
|
||||
task.insert(QStringLiteral("priority"), 2);
|
||||
task.insert(QStringLiteral("energy_req"), 1);
|
||||
QJsonObject block;
|
||||
block.insert(QStringLiteral("start_at"), DateTimeUtils::toDb(start));
|
||||
block.insert(QStringLiteral("end_at"), DateTimeUtils::toDb(end));
|
||||
block.insert(QStringLiteral("granularity"), 15);
|
||||
QJsonObject create;
|
||||
create.insert(QStringLiteral("temp_id"), tempId);
|
||||
create.insert(QStringLiteral("task"), task);
|
||||
create.insert(QStringLiteral("block"), block);
|
||||
return create;
|
||||
};
|
||||
|
||||
ProposedDiff diff;
|
||||
diff.id = QStringLiteral("diff-2");
|
||||
diff.createdAt = DateTimeUtils::toDb(QDateTime::currentDateTimeUtc());
|
||||
diff.explanation = QStringLiteral("新增两个日程");
|
||||
diff.state = QStringLiteral("pending");
|
||||
diff.payload = QJsonObject{
|
||||
{QStringLiteral("creates"),
|
||||
QJsonArray{makeCreate(QStringLiteral("a"), QStringLiteral("AI 任务 A"), startA, endA),
|
||||
makeCreate(QStringLiteral("b"), QStringLiteral("AI 任务 B"), startB, endB)}},
|
||||
{QStringLiteral("updates"), QJsonArray{}},
|
||||
{QStringLiteral("deletes"), QJsonArray{}}};
|
||||
|
||||
QString error;
|
||||
QVERIFY2(context.service->applyProposedCreates(diff, {QStringLiteral("a")}, &error), qPrintable(error));
|
||||
QVector<ScheduleItem> items = context.service->itemsForDay(today);
|
||||
QCOMPARE(items.size(), 1);
|
||||
QCOMPARE(items.first().task.title, QStringLiteral("AI 任务 A"));
|
||||
QCOMPARE(items.first().task.source, QStringLiteral("ai_chat"));
|
||||
QCOMPARE(items.first().block.startAt, startA);
|
||||
QCOMPARE(items.first().block.endAt, endA);
|
||||
|
||||
QVERIFY2(context.service->applyProposedCreates(diff, {QStringLiteral("b")}, &error), qPrintable(error));
|
||||
items = context.service->itemsForDay(today);
|
||||
QCOMPARE(items.size(), 2);
|
||||
|
||||
QVERIFY(!context.service->applyProposedCreates(diff, {}, &error));
|
||||
}
|
||||
|
||||
QTEST_GUILESS_MAIN(TestServices)
|
||||
#include "test_services.moc"
|
||||
@@ -0,0 +1,264 @@
|
||||
#include <QJsonObject>
|
||||
#include <QTemporaryDir>
|
||||
#include <QtTest>
|
||||
|
||||
#include "core/DateTimeUtils.h"
|
||||
#include "core/ProposedDiff.h"
|
||||
#include "storage/SqliteStore.h"
|
||||
|
||||
class TestStorage : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
private slots:
|
||||
void migrationCreatesSchema();
|
||||
void taskAndBlockRoundTrip();
|
||||
void blockRangeIncludesOverlap();
|
||||
void proposedDiffRoundTrip();
|
||||
void outboxCapturesLocalChanges();
|
||||
void remoteApplySuppressesOutboxAndUsesLww();
|
||||
};
|
||||
|
||||
void TestStorage::migrationCreatesSchema()
|
||||
{
|
||||
QTemporaryDir dir;
|
||||
QVERIFY(dir.isValid());
|
||||
SqliteStore store(dir.filePath(QStringLiteral("schedule.db")));
|
||||
QString error;
|
||||
QVERIFY2(store.open(&error), qPrintable(error));
|
||||
QCOMPARE(store.schemaVersion(), 3);
|
||||
store.close();
|
||||
QVERIFY2(store.open(&error), qPrintable(error));
|
||||
QCOMPARE(store.schemaVersion(), 3);
|
||||
}
|
||||
|
||||
void TestStorage::taskAndBlockRoundTrip()
|
||||
{
|
||||
QTemporaryDir dir;
|
||||
QVERIFY(dir.isValid());
|
||||
SqliteStore store(dir.filePath(QStringLiteral("schedule.db")));
|
||||
QString error;
|
||||
QVERIFY2(store.open(&error), qPrintable(error));
|
||||
|
||||
const QDateTime now = QDateTime::currentDateTime();
|
||||
Task task;
|
||||
task.id = QStringLiteral("task-1");
|
||||
task.title = QStringLiteral("写周报");
|
||||
task.createdAt = now;
|
||||
task.updatedAt = now;
|
||||
task.deviceId = QStringLiteral("device-1");
|
||||
QVERIFY2(store.insertTask(task), qPrintable(store.lastError()));
|
||||
|
||||
TimeBlock block;
|
||||
block.id = QStringLiteral("block-1");
|
||||
block.taskId = task.id;
|
||||
block.startAt = QDateTime(QDate::currentDate(), QTime(9, 0), Qt::LocalTime);
|
||||
block.endAt = block.startAt.addSecs(90 * 60);
|
||||
block.createdAt = now;
|
||||
block.updatedAt = now;
|
||||
block.deviceId = QStringLiteral("device-1");
|
||||
QVERIFY2(store.insertTimeBlock(block), qPrintable(store.lastError()));
|
||||
|
||||
const QVector<ScheduleItem> items = store.blocksInRange(
|
||||
DateTimeUtils::localDayStartUtc(QDate::currentDate()),
|
||||
DateTimeUtils::localDayEndUtc(QDate::currentDate()));
|
||||
QCOMPARE(items.size(), 1);
|
||||
QCOMPARE(items.first().task.title, QStringLiteral("写周报"));
|
||||
QCOMPARE(items.first().block.startAt, block.startAt);
|
||||
QCOMPARE(items.first().block.endAt, block.endAt);
|
||||
QCOMPARE(items.first().block.granularity, 15);
|
||||
QVERIFY(items.first().block.splittable);
|
||||
QVERIFY(items.first().block.breakable);
|
||||
|
||||
const auto loadedTask = store.taskById(task.id);
|
||||
QVERIFY(loadedTask.has_value());
|
||||
QCOMPARE(loadedTask->title, task.title);
|
||||
|
||||
QVERIFY2(store.deleteTimeBlock(block.id), qPrintable(store.lastError()));
|
||||
QVERIFY(store.blocksInRange(DateTimeUtils::localDayStartUtc(QDate::currentDate()),
|
||||
DateTimeUtils::localDayEndUtc(QDate::currentDate()))
|
||||
.isEmpty());
|
||||
}
|
||||
|
||||
void TestStorage::blockRangeIncludesOverlap()
|
||||
{
|
||||
QTemporaryDir dir;
|
||||
QVERIFY(dir.isValid());
|
||||
SqliteStore store(dir.filePath(QStringLiteral("schedule.db")));
|
||||
QString error;
|
||||
QVERIFY2(store.open(&error), qPrintable(error));
|
||||
|
||||
const QDate today = QDate::currentDate();
|
||||
const QDateTime now = QDateTime::currentDateTime();
|
||||
|
||||
Task task;
|
||||
task.id = QStringLiteral("task-2");
|
||||
task.title = QStringLiteral("跨午夜");
|
||||
task.createdAt = now;
|
||||
task.updatedAt = now;
|
||||
task.deviceId = QStringLiteral("device-1");
|
||||
QVERIFY(store.insertTask(task));
|
||||
|
||||
TimeBlock block;
|
||||
block.id = QStringLiteral("block-2");
|
||||
block.taskId = task.id;
|
||||
block.startAt = QDateTime(today.addDays(-1), QTime(23, 30), Qt::LocalTime);
|
||||
block.endAt = QDateTime(today, QTime(0, 30), Qt::LocalTime);
|
||||
block.createdAt = now;
|
||||
block.updatedAt = now;
|
||||
block.deviceId = QStringLiteral("device-1");
|
||||
QVERIFY(store.insertTimeBlock(block));
|
||||
|
||||
const QVector<ScheduleItem> items =
|
||||
store.blocksInRange(DateTimeUtils::localDayStartUtc(today), DateTimeUtils::localDayEndUtc(today));
|
||||
QCOMPARE(items.size(), 1);
|
||||
QCOMPARE(items.first().block.id, block.id);
|
||||
}
|
||||
|
||||
void TestStorage::proposedDiffRoundTrip()
|
||||
{
|
||||
QTemporaryDir dir;
|
||||
QVERIFY(dir.isValid());
|
||||
SqliteStore store(dir.filePath(QStringLiteral("schedule.db")));
|
||||
QString error;
|
||||
QVERIFY2(store.open(&error), qPrintable(error));
|
||||
|
||||
ProposedDiff diff;
|
||||
diff.id = QStringLiteral("diff-1");
|
||||
diff.createdAt = QStringLiteral("2026-10-26T00:00:00Z");
|
||||
diff.explanation = QStringLiteral("新增一个日程");
|
||||
diff.state = QStringLiteral("pending");
|
||||
diff.payload = QJsonObject{{QStringLiteral("creates"), QJsonArray{}}};
|
||||
|
||||
QVERIFY2(store.insertProposedDiff(diff), qPrintable(store.lastError()));
|
||||
const auto loaded = store.proposedDiffById(diff.id);
|
||||
QVERIFY(loaded.has_value());
|
||||
QCOMPARE(loaded->explanation, diff.explanation);
|
||||
QCOMPARE(loaded->state, QStringLiteral("pending"));
|
||||
QVERIFY(loaded->payload.contains(QStringLiteral("creates")));
|
||||
|
||||
QVERIFY2(store.updateProposedDiffState(diff.id, QStringLiteral("applied"), QStringLiteral("2026-10-26T01:00:00Z")),
|
||||
qPrintable(store.lastError()));
|
||||
const auto updated = store.proposedDiffById(diff.id);
|
||||
QVERIFY(updated.has_value());
|
||||
QCOMPARE(updated->state, QStringLiteral("applied"));
|
||||
QCOMPARE(updated->resolvedAt, QStringLiteral("2026-10-26T01:00:00Z"));
|
||||
}
|
||||
|
||||
void TestStorage::outboxCapturesLocalChanges()
|
||||
{
|
||||
QTemporaryDir dir;
|
||||
QVERIFY(dir.isValid());
|
||||
SqliteStore store(dir.filePath(QStringLiteral("schedule.db")));
|
||||
QString error;
|
||||
QVERIFY2(store.open(&error), qPrintable(error));
|
||||
QCOMPARE(store.outboxCount(), 0);
|
||||
|
||||
const QDateTime now = QDateTime::currentDateTime();
|
||||
Task task;
|
||||
task.id = QStringLiteral("sync-task");
|
||||
task.title = QStringLiteral("同步任务");
|
||||
task.createdAt = now;
|
||||
task.updatedAt = now;
|
||||
task.deviceId = QStringLiteral("device-1");
|
||||
QVERIFY(store.insertTask(task));
|
||||
|
||||
TimeBlock block;
|
||||
block.id = QStringLiteral("sync-block");
|
||||
block.taskId = task.id;
|
||||
block.startAt = QDateTime(QDate::currentDate(), QTime(10, 0), Qt::LocalTime);
|
||||
block.endAt = block.startAt.addSecs(3600);
|
||||
block.createdAt = now;
|
||||
block.updatedAt = now;
|
||||
block.deviceId = QStringLiteral("device-1");
|
||||
QVERIFY(store.insertTimeBlock(block));
|
||||
QCOMPARE(store.outboxCount(), 2);
|
||||
|
||||
const QVector<SyncOutboxItem> items = store.outboxBatch(10);
|
||||
QCOMPARE(items.size(), 2);
|
||||
QCOMPARE(items.first().entityType, QStringLiteral("task"));
|
||||
QCOMPARE(items.first().op, QStringLiteral("upsert"));
|
||||
QCOMPARE(items.first().payload.value(QStringLiteral("title")).toString(), QStringLiteral("同步任务"));
|
||||
|
||||
task.title = QStringLiteral("同步任务 v2");
|
||||
task.updatedAt = now.addSecs(1);
|
||||
task.version = 1;
|
||||
QVERIFY(store.updateTask(task));
|
||||
QCOMPARE(store.outboxCount(), 3);
|
||||
|
||||
QVERIFY(store.deleteTimeBlock(block.id));
|
||||
QVERIFY(store.deleteTask(task.id));
|
||||
QCOMPARE(store.outboxCount(), 5);
|
||||
const qint64 maxId = store.outboxBatch(100).last().id;
|
||||
QVERIFY(store.clearOutboxThrough(maxId));
|
||||
QCOMPARE(store.outboxCount(), 0);
|
||||
}
|
||||
|
||||
void TestStorage::remoteApplySuppressesOutboxAndUsesLww()
|
||||
{
|
||||
QTemporaryDir dir;
|
||||
QVERIFY(dir.isValid());
|
||||
SqliteStore store(dir.filePath(QStringLiteral("schedule.db")));
|
||||
QString error;
|
||||
QVERIFY2(store.open(&error), qPrintable(error));
|
||||
QVERIFY(store.setSyncCursor(QStringLiteral("device-1"), 42));
|
||||
QCOMPARE(store.syncCursor(QStringLiteral("device-1")), 42);
|
||||
|
||||
QVERIFY(store.beginTransaction());
|
||||
QVERIFY(store.setRemoteApplySuppressed(true));
|
||||
RemoteChange taskChange;
|
||||
taskChange.seq = 1;
|
||||
taskChange.deviceId = QStringLiteral("remote-device");
|
||||
taskChange.entityType = QStringLiteral("task");
|
||||
taskChange.entityId = QStringLiteral("remote-task");
|
||||
taskChange.op = QStringLiteral("upsert");
|
||||
taskChange.version = 1;
|
||||
taskChange.updatedAt = QStringLiteral("2026-10-26T10:00:00Z");
|
||||
taskChange.payload = QJsonObject{
|
||||
{QStringLiteral("id"), QStringLiteral("remote-task")},
|
||||
{QStringLiteral("title"), QStringLiteral("远程任务")},
|
||||
{QStringLiteral("status"), QStringLiteral("active")},
|
||||
{QStringLiteral("priority"), 1},
|
||||
{QStringLiteral("created_at"), QStringLiteral("2026-10-26T09:00:00Z")},
|
||||
{QStringLiteral("updated_at"), QStringLiteral("2026-10-26T10:00:00Z")},
|
||||
};
|
||||
QVERIFY(store.applyRemoteChange(taskChange));
|
||||
QVERIFY(store.setRemoteApplySuppressed(false));
|
||||
QVERIFY(store.commit());
|
||||
QCOMPARE(store.outboxCount(), 0);
|
||||
QVERIFY(store.taskById(QStringLiteral("remote-task")).has_value());
|
||||
|
||||
// 较旧的远程版本应被 LWW 忽略。
|
||||
taskChange.updatedAt = QStringLiteral("2026-10-26T09:30:00Z");
|
||||
taskChange.payload.insert(QStringLiteral("title"), QStringLiteral("旧标题"));
|
||||
QVERIFY(store.beginTransaction());
|
||||
QVERIFY(store.setRemoteApplySuppressed(true));
|
||||
QVERIFY(store.applyRemoteChange(taskChange));
|
||||
QVERIFY(store.setRemoteApplySuppressed(false));
|
||||
QVERIFY(store.commit());
|
||||
QCOMPARE(store.taskById(QStringLiteral("remote-task"))->title, QStringLiteral("远程任务"));
|
||||
|
||||
// 毫秒级时间戳必须可比较,且能覆盖同秒的无毫秒旧时间戳。
|
||||
taskChange.updatedAt = QStringLiteral("2026-10-26T10:00:00.500Z");
|
||||
taskChange.payload.insert(QStringLiteral("title"), QStringLiteral("毫秒版本"));
|
||||
QVERIFY(store.beginTransaction());
|
||||
QVERIFY(store.setRemoteApplySuppressed(true));
|
||||
QVERIFY(store.applyRemoteChange(taskChange));
|
||||
QVERIFY(store.setRemoteApplySuppressed(false));
|
||||
QVERIFY(store.commit());
|
||||
QCOMPARE(store.taskById(QStringLiteral("remote-task"))->title, QStringLiteral("毫秒版本"));
|
||||
|
||||
// 同时间戳删除优先,避免墓碑被等时间戳的 upsert 覆盖。
|
||||
taskChange.op = QStringLiteral("delete");
|
||||
taskChange.updatedAt = QStringLiteral("2026-10-26T10:00:00.500Z");
|
||||
QVERIFY(store.beginTransaction());
|
||||
QVERIFY(store.setRemoteApplySuppressed(true));
|
||||
QVERIFY(store.applyRemoteChange(taskChange));
|
||||
QVERIFY(store.setRemoteApplySuppressed(false));
|
||||
QVERIFY(store.commit());
|
||||
QVERIFY(!store.taskById(QStringLiteral("remote-task")).has_value());
|
||||
QCOMPARE(store.outboxCount(), 0);
|
||||
}
|
||||
|
||||
QTEST_GUILESS_MAIN(TestStorage)
|
||||
#include "test_storage.moc"
|
||||
@@ -0,0 +1,186 @@
|
||||
#include <QCoreApplication>
|
||||
#include <QElapsedTimer>
|
||||
#include <QFileInfo>
|
||||
#include <QProcess>
|
||||
#include <QTcpServer>
|
||||
#include <QTcpSocket>
|
||||
#include <QTemporaryDir>
|
||||
#include <QThread>
|
||||
#include <QtTest>
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "services/ScheduleService.h"
|
||||
#include "storage/SqliteStore.h"
|
||||
#include "sync/SyncService.h"
|
||||
#include "utils/AppSettings.h"
|
||||
|
||||
namespace
|
||||
{
|
||||
int freePort()
|
||||
{
|
||||
QTcpServer probe;
|
||||
if (!probe.listen(QHostAddress::LocalHost, 0))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
const int port = probe.serverPort();
|
||||
probe.close();
|
||||
return port;
|
||||
}
|
||||
|
||||
bool waitForServer(int port, int timeoutMs)
|
||||
{
|
||||
QElapsedTimer timer;
|
||||
timer.start();
|
||||
while (timer.elapsed() < timeoutMs)
|
||||
{
|
||||
QTcpSocket socket;
|
||||
socket.connectToHost(QHostAddress::LocalHost, static_cast<quint16>(port));
|
||||
if (socket.waitForConnected(150))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
QCoreApplication::processEvents();
|
||||
QThread::msleep(50);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
class TestSyncIntegration : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
private slots:
|
||||
void twoClientsConverge();
|
||||
};
|
||||
|
||||
void TestSyncIntegration::twoClientsConverge()
|
||||
{
|
||||
const QString serverBinary = qEnvironmentVariable("SCHEDULE_SYNC_SERVER_BIN");
|
||||
if (serverBinary.isEmpty() || !QFileInfo::exists(serverBinary))
|
||||
{
|
||||
QSKIP("sync server binary is not available");
|
||||
}
|
||||
const int port = freePort();
|
||||
QVERIFY(port > 0);
|
||||
QTemporaryDir serverDir;
|
||||
QVERIFY(serverDir.isValid());
|
||||
QProcess serverProcess;
|
||||
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
|
||||
env.insert(QStringLiteral("SYNC_LISTEN_ADDR"), QStringLiteral("127.0.0.1:%1").arg(port));
|
||||
env.insert(QStringLiteral("SYNC_DB_PATH"), serverDir.filePath(QStringLiteral("sync.db")));
|
||||
env.insert(QStringLiteral("SYNC_TOKEN_PEPPER"), QStringLiteral("integration-pepper"));
|
||||
serverProcess.setProcessEnvironment(env);
|
||||
serverProcess.setProcessChannelMode(QProcess::MergedChannels);
|
||||
serverProcess.setStandardOutputFile(serverDir.filePath(QStringLiteral("server.log")));
|
||||
serverProcess.start(serverBinary, {});
|
||||
QVERIFY2(serverProcess.waitForStarted(5000), qPrintable(serverProcess.errorString()));
|
||||
QVERIFY(waitForServer(port, 10000));
|
||||
|
||||
QTemporaryDir clientADir;
|
||||
QTemporaryDir clientBDir;
|
||||
QVERIFY(clientADir.isValid());
|
||||
QVERIFY(clientBDir.isValid());
|
||||
AppSettings settingsA(clientADir.filePath(QStringLiteral("config.toml")));
|
||||
AppSettings settingsB(clientBDir.filePath(QStringLiteral("config.toml")));
|
||||
SyncConfig syncConfig;
|
||||
syncConfig.enabled = true;
|
||||
syncConfig.serverUrl = QStringLiteral("http://127.0.0.1:%1").arg(port);
|
||||
settingsA.setSyncConfig(syncConfig);
|
||||
settingsB.setSyncConfig(syncConfig);
|
||||
|
||||
SqliteStore storeA(clientADir.filePath(QStringLiteral("schedule.db")));
|
||||
SqliteStore storeB(clientBDir.filePath(QStringLiteral("schedule.db")));
|
||||
QString error;
|
||||
QVERIFY2(storeA.open(&error), qPrintable(error));
|
||||
QVERIFY2(storeB.open(&error), qPrintable(error));
|
||||
ScheduleService serviceA(storeA, settingsA.deviceId());
|
||||
ScheduleService serviceB(storeB, settingsB.deviceId());
|
||||
SyncService syncA(serviceA, storeA, settingsA);
|
||||
SyncService syncB(serviceB, storeB, settingsB);
|
||||
syncA.start();
|
||||
syncB.start();
|
||||
QTRY_VERIFY_WITH_TIMEOUT(syncA.statusText().contains(QStringLiteral("同步")) ||
|
||||
syncA.statusText().contains(QStringLiteral("已连接")), 12000);
|
||||
QTRY_VERIFY_WITH_TIMEOUT(syncB.statusText().contains(QStringLiteral("同步")) ||
|
||||
syncB.statusText().contains(QStringLiteral("已连接")), 12000);
|
||||
|
||||
const QDate tomorrow = QDate::currentDate().addDays(1);
|
||||
const QDateTime start(tomorrow, QTime(9, 0), Qt::LocalTime);
|
||||
const QDateTime end(tomorrow, QTime(10, 0), Qt::LocalTime);
|
||||
QVERIFY2(serviceA.createBlock(QStringLiteral("跨设备任务"), start, end, &error), qPrintable(error));
|
||||
|
||||
QTRY_VERIFY_WITH_TIMEOUT(serviceB.itemsForDay(tomorrow).size() == 1, 20000);
|
||||
QCOMPARE(serviceB.itemsForDay(tomorrow).first().task.title, QStringLiteral("跨设备任务"));
|
||||
|
||||
QVERIFY2(serviceA.updateBlock(serviceA.itemsForDay(tomorrow).first().block.id,
|
||||
QStringLiteral("跨设备任务 v2"),
|
||||
start.addSecs(3600),
|
||||
end.addSecs(3600),
|
||||
&error),
|
||||
qPrintable(error));
|
||||
QTRY_VERIFY_WITH_TIMEOUT(!serviceB.itemsForDay(tomorrow).isEmpty() &&
|
||||
serviceB.itemsForDay(tomorrow).first().task.title ==
|
||||
QStringLiteral("跨设备任务 v2"),
|
||||
20000);
|
||||
|
||||
QVERIFY2(serviceB.createBlock(QStringLiteral("反向任务"),
|
||||
start.addSecs(2 * 3600),
|
||||
end.addSecs(2 * 3600),
|
||||
&error),
|
||||
qPrintable(error));
|
||||
QTRY_VERIFY_WITH_TIMEOUT(serviceA.itemsForDay(tomorrow).size() == 2, 20000);
|
||||
bool sawReverse = false;
|
||||
for (const ScheduleItem& item : serviceA.itemsForDay(tomorrow))
|
||||
{
|
||||
if (item.task.title == QStringLiteral("反向任务"))
|
||||
{
|
||||
sawReverse = true;
|
||||
}
|
||||
}
|
||||
QVERIFY(sawReverse);
|
||||
|
||||
for (const ScheduleItem& item : serviceA.itemsForDay(tomorrow))
|
||||
{
|
||||
if (item.task.title == QStringLiteral("跨设备任务 v2"))
|
||||
{
|
||||
QVERIFY2(serviceA.deleteBlock(item.block.id, &error), qPrintable(error));
|
||||
break;
|
||||
}
|
||||
}
|
||||
QTRY_VERIFY_WITH_TIMEOUT(serviceB.itemsForDay(tomorrow).size() == 1, 20000);
|
||||
QCOMPARE(serviceB.itemsForDay(tomorrow).first().task.title, QStringLiteral("反向任务"));
|
||||
|
||||
serverProcess.terminate();
|
||||
QVERIFY(serverProcess.waitForFinished(5000));
|
||||
QVERIFY2(serviceA.createBlock(QStringLiteral("离线任务"),
|
||||
start.addSecs(4 * 3600),
|
||||
end.addSecs(4 * 3600),
|
||||
&error),
|
||||
qPrintable(error));
|
||||
QTest::qWait(1000);
|
||||
|
||||
serverProcess.start(serverBinary, {});
|
||||
QVERIFY2(serverProcess.waitForStarted(5000), qPrintable(serverProcess.errorString()));
|
||||
QVERIFY(waitForServer(port, 10000));
|
||||
QTRY_VERIFY_WITH_TIMEOUT(serviceB.itemsForDay(tomorrow).size() == 2, 30000);
|
||||
bool sawOffline = false;
|
||||
for (const ScheduleItem& item : serviceB.itemsForDay(tomorrow))
|
||||
{
|
||||
if (item.task.title == QStringLiteral("离线任务"))
|
||||
{
|
||||
sawOffline = true;
|
||||
}
|
||||
}
|
||||
QVERIFY(sawOffline);
|
||||
|
||||
syncA.stop();
|
||||
syncB.stop();
|
||||
serverProcess.terminate();
|
||||
serverProcess.waitForFinished(5000);
|
||||
}
|
||||
|
||||
QTEST_GUILESS_MAIN(TestSyncIntegration)
|
||||
#include "test_sync_integration.moc"
|
||||
Reference in New Issue
Block a user