Files
hrynco-kswitcher/tests/drive_snapshot.cpp
T

210 lines
11 KiB
C++

#include "google_drive.h"
#include "google_drive_oauth.h"
#include "sync.h"
#include "mouse_buttons.h"
#include "json.hpp"
#include <iostream>
#include <string_view>
namespace
{
using namespace ks;
using Json = nlohmann::json;
void check(bool condition, const char *message)
{
if (!condition) throw std::runtime_error(message);
}
Bytes bytes(std::string_view text) { return {text.begin(), text.end()}; }
const std::vector<Layout> Layouts{{{}, L"win:04090409"}, {{}, L"win:04220422"}};
void oauthProtocol()
{
using namespace google_drive_oauth;
check(challengeFor("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk") ==
"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", "PKCE challenge differs from the RFC 7636 vector");
check(callbackCode("GET /oauth/callback?state=right&code=a%2Bb HTTP/1.1", "right") == "a+b",
"loopback rejected a correctly encoded authorization code");
check(callbackCode("GET /oauth/callback?state=right&error=access_denied HTTP/1.1", "right") == "",
"loopback did not report denied consent");
for (const auto *request : {"GET /oauth/callback?state=other&code=x HTTP/1.1",
"GET /oauth/callback?state=right&state=right&code=x HTTP/1.1",
"GET /oauth/callback?state=right&code=%X1 HTTP/1.1",
"GET /favicon.ico?state=right&code=x HTTP/1.1"})
check(!callbackCode(request, "right"), "loopback accepted an unrelated or malformed request");
}
void nativeBackup()
{
auto saved = decodeSettings({}, Layouts);
saved.toggle = L"Ctrl+Alt+F10";
saved.filesHotkey = L"";
saved.direct[0] = L"Ctrl+F9";
saved.snippets = {{L";hi", L"Hello", L"restored-snippet", {L"notepad"}}};
saved.autoWords[L"en"] = {L"foobar"};
saved.appLanguageSets[L"Editor"] = {{L"win:04220422"}, {L"notepad"}};
saved.mouseBindings[GlobalMouseProfile][L"XButton1"] = {MouseActionType::Back};
saved.mouseBindings[L"edge"][L"XButton1"] = {MouseActionType::Launch, {}, L"C:\\source-private\\secret.exe"};
saved.mouseBindings[L"edge"][L"XButton2"] = {MouseActionType::Launch, {}, L"calc.exe"};
saved.tesseractPath = L"C:\\private\\ocr.exe";
saved.snippetTombstones = {L"source-tombstone"};
saved.autostart = saved.elevatedAutostart = saved.writeLog = true;
auto destination = decodeSettings({}, Layouts);
destination.toggle = L"Ctrl+Alt+F11";
destination.tesseractPath = L"D:\\local\\ocr.exe";
destination.writeLog = true;
destination.snippetTombstones = {L"restored-snippet", L"destination-tombstone"};
destination.mouseBindings[L"edge"][L"XButton1"] = {MouseActionType::Launch, {}, L"D:\\local\\tool.exe"};
const auto backup = encodeDriveBackup(saved);
auto envelope = Json::parse(backup);
const auto &stored = envelope.at("settings");
for (auto key : {"writeLog", "startWithSystem", "autostartAsAdministrator", "tesseractPath", "snippetTombstones"})
check(!stored.contains(key), "machine-specific field in native backup");
check(!stored.at("mouseBindings").at("edge").contains("XButton1"), "local executable path in native backup");
envelope["settings"]["openBaoPassword"] = "fake-provider-password";
envelope["settings"]["tesseractPath"] = "C:\\injected\\ocr.exe";
envelope["settings"]["mouseBindings"]["edge"]["XButton1"] = {{"action", "Launch application"},
{"executable", "C:\\injected\\other.exe"}};
const auto restored = restoreDriveBackup(bytes(envelope.dump()), destination, Layouts);
check(restored.toggle == saved.toggle && restored.filesHotkey == L"" && restored.direct == saved.direct,
"saved shortcuts failed to restore");
check(restored.snippets.size() == 1 && restored.snippets[0].id == L"restored-snippet" &&
restored.snippets[0].apps == std::vector<std::wstring>{L"notepad"}, "saved snippet failed to restore");
check(restored.snippetTombstones == std::vector<std::wstring>{L"destination-tombstone"},
"restore did not resurrect the snippet while preserving unrelated tombstones");
check(restored.autoWords == saved.autoWords && restored.appLanguageSets == saved.appLanguageSets,
"saved dictionary or language profile failed to restore");
const auto &mouse = restored.mouseBindings.at(L"edge");
check(mouse.at(L"XButton1").executable == L"D:\\local\\tool.exe" && mouse.at(L"XButton2").executable == L"calc.exe",
"local mouse action or portable executable name failed to survive restore");
check(restored.tesseractPath == destination.tesseractPath && restored.writeLog &&
!restored.autostart && !restored.elevatedAutostart, "restore overwrote local preferences");
check(destination.toggle == L"Ctrl+Alt+F11" && destination.snippets.empty(), "restore mutated its input draft");
}
void automaticDriveProfile()
{
auto saved = decodeSettings({}, Layouts);
saved.autostart = saved.writeLog = true;
saved.tesseractPath = L"C:\\private\\ocr.exe";
saved.mouseBindings[L"edge"][L"XButton1"] = {MouseActionType::Launch, {}, L"C:\\private\\tool.exe"};
saved.snippetTombstones = {L"deleted-fixture"};
auto local = saved, remote = saved;
local.toggle = L"Ctrl+Alt+F10";
local.autoWords[L"en"] = {L"localword"};
remote.toggle = L"Ctrl+Alt+F11";
remote.snippets = {{L";remote", L"Remote text", L"remote-id", {}}};
const auto base = sharedDriveSettings(saved);
const auto profile = Json::parse(base);
check(!profile.contains("startWithSystem") && !profile.contains("writeLog") &&
!profile.contains("tesseractPath") && profile.at("mouseBindings").empty(), "local data in Drive sync profile");
const auto result = mergeSyncProfile(base, sharedDriveSettings(local), sharedDriveSettings(remote));
check(result.conflicts.size() == 1 && result.conflicts.front().key == "/toggleHotkey",
"Drive sync did not preserve concurrent changes to the same preference");
for (const auto &payload : {result.local, result.remote})
{
const auto merged = restoreSharedDriveSettings(payload, saved, Layouts);
check(merged.autostart && merged.writeLog && merged.tesseractPath == saved.tesseractPath &&
merged.mouseBindings == saved.mouseBindings, "Drive sync overwrote local settings");
check(merged.snippets.size() == 1 && merged.autoWords.at(L"en") == std::vector<std::wstring>{L"localword"} &&
merged.snippetTombstones == saved.snippetTombstones, "Drive sync did not merge portable changes");
}
}
// Envelope and profile fields emitted by KSwitcher-New at 6a8d71d.
constexpr auto PreviewSample = R"json({
"format": "kswitcher-drive-backup-v1",
"profile": {
"settings": {
"autocorrect": true,
"mouse": {"enabled": false, "default_action": "Unassigned", "application": "", "application_action": "Unassigned"},
"snippet": {"enabled": false, "trigger": "", "replacement": ""},
"snippets": [{"enabled": true, "trigger": ";mail", "replacement": "Hello {cursor}", "apps": ["notepad"], "template": true}],
"personal_dictionary": {"english": ["foobar"], "ukrainian": [], "never": ["skip"]}
},
"options": {
"layouts": [{"id": "us", "layout": "English", "included": true, "shortcut": "Ctrl+F9"},
{"id": "ua", "layout": "win:04220422", "included": true, "shortcut": ""}],
"appLanguages": [{"id": "editor", "app": "notepad.exe", "languages": "win:04220422\nEnglish"}],
"chatLanguages": [{"id": "chat", "app": "telegram.exe", "contact": "Example", "languages": "English"}],
"snippets": [{"id": "preview-uuid", "enabled": true, "trigger": ";mail", "replacement": "Hello {cursor}", "scoped": true, "apps": "notePAD.exe"}],
"mouseProfiles": [{"id": "*", "name": "Global", "enabled": true, "apps": ""},
{"id": "editor", "name": "Editor mouse", "enabled": true, "apps": "notepad.exe"},
{"id": "chrome", "name": "chrome", "enabled": true, "apps": ""}],
"mouseActions": [{"id": "wheel", "profile": "editor", "event": "Wheel up", "action": "VolumeUp", "step": 7},
{"id": "back", "profile": "chrome", "event": "First side button", "action": "Back"}],
"mouseEvents": [{"id": "wheel-up", "name": "Scroll up", "signal": "Wheel up"}],
"shortcuts.key-bindings.toggle": "Ctrl+Alt+F10",
"general.correction.autoReplacements": "teh=the",
"appearance.color-scheme.scheme": "dark"
}
}
})json";
void previewBackup()
{
auto destination = decodeSettings({}, Layouts);
destination.clipboard = L"Ctrl+F8";
destination.tesseractPath = L"D:\\local\\ocr.exe";
destination.autoWords[L"ru"] = {L"слово"};
auto restored = restoreDriveBackup(bytes(PreviewSample), destination, Layouts);
check(restored.autoCorrect && restored.toggle == L"Ctrl+Alt+F10" && restored.direct[0] == L"Ctrl+F9",
"preview layout or shortcut mapping failed");
check(restored.snippets.size() == 1 && restored.snippets[0].id == L"preview-uuid" &&
restored.snippets[0].apps == std::vector<std::wstring>{L"notepad"} &&
restored.snippets[0].text == L"Hello {cursor}", "preview snippet mapping failed");
check(restored.autoWords.at(L"en").front() == L"foobar" && restored.autoNever.front() == L"skip" &&
restored.autoReplacements.at(L"teh") == L"the" && restored.autoWords.at(L"ru") == destination.autoWords.at(L"ru"),
"preview personal dictionary mapping or retention failed");
check(restored.appLanguageSets.at(L"notepad").languages.size() == 2 &&
restored.chatCycles.at(L"telegram\nExample").front() == L"win:04090409", "preview language profiles failed");
check(restored.mouseProfileApplications.at(L"name:Editor mouse").contains(L"notepad") &&
restored.mouseBindings.at(L"name:Editor mouse").at(L"Wheel up").volumeStep == 7 &&
restored.customMouseEvents.at(L"Wheel up") == L"Scroll up" &&
restored.mouseBindings.at(L"chrome").at(L"XButton1").type == MouseActionType::Back, "preview mouse mapping failed");
check(restored.clipboard == destination.clipboard && restored.tesseractPath == destination.tesseractPath,
"preview settings overwritten despite being absent from backup");
}
void rejects(const Bytes &backup, std::string_view expected, const std::vector<Layout> &layouts = Layouts)
{
try { restoreDriveBackup(backup, decodeSettings({}, layouts), layouts); }
catch (const std::runtime_error &error)
{
check(std::string_view(error.what()).find(expected) != std::string_view::npos, "unexpected restore error");
return;
}
throw std::runtime_error("invalid backup was accepted");
}
}
int main()
{
try
{
oauthProtocol();
nativeBackup();
automaticDriveProfile();
previewBackup();
rejects(bytes("not json"), "corrupt");
rejects(bytes(R"({"format":"other"})"), "unsupported");
rejects(bytes(R"({"format":"kswitcher-win32-drive-backup-v1","settings":{}})"), "invalid");
rejects(Bytes(GoogleDriveBackupLimit + 1, 'a'), "2 MiB");
rejects(bytes(PreviewSample), "Install the keyboard layouts", {});
auto malformed = Json::parse(PreviewSample);
malformed["profile"]["options"]["shortcuts.key-bindings.toggle"] = "not a shortcut";
rejects(bytes(malformed.dump()), "invalid or conflict");
std::cout << "Google Drive backup tests passed\n";
return 0;
}
catch (const std::exception &error)
{
std::cerr << error.what() << '\n';
return 1;
}
}