Files
Echoion/tests/DatabaseTests.cpp
T
faumaray a3715201e1 Release 1.0.0
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-04 01:50:44 +03:00

286 lines
8.1 KiB
C++

#include <doctest/doctest.h>
#include <Database.hpp>
#include <chrono>
#include <filesystem>
#include <string>
using Echoion::Api::Database;
using Echoion::Api::DatabaseConfig;
namespace
{
// Fresh on-disk database per test (":memory:" would also work but the
// file path exercises the real open/migrate path).
struct TempDb {
std::filesystem::path path;
Database db;
TempDb()
{
path = std::filesystem::temp_directory_path() /
("echoion-test-" +
std::to_string(
std::chrono::steady_clock::now()
.time_since_epoch()
.count()) +
".db");
REQUIRE(db.initialize(DatabaseConfig{.path = path.string()})
.has_value());
}
~TempDb()
{
db.shutdown();
std::error_code ec;
std::filesystem::remove(path, ec);
std::filesystem::remove(path.string() + "-wal", ec);
std::filesystem::remove(path.string() + "-shm", ec);
}
};
Echoion::Api::TrackInfo track(const std::string& url,
const std::string& title)
{
Echoion::Api::TrackInfo t;
t.originalUrl = url;
t.title = title;
t.artist = "Artist";
return t;
}
} // namespace
TEST_CASE("Database playlist CRUD round-trip")
{
TempDb tdb;
auto& db = tdb.db;
auto id = db.createPlaylist("Mix", "desc", 1);
REQUIRE(id.has_value());
REQUIRE(db.addTrackToPlaylist(*id, track("u1", "One"), 0).has_value());
REQUIRE(db.addTrackToPlaylist(*id, track("u2", "Two"), 1).has_value());
REQUIRE(db.addTrackToPlaylist(*id, track("u3", "Three"), 2).has_value());
auto loaded = db.getPlaylist(*id);
REQUIRE(loaded.has_value());
REQUIRE(loaded->has_value());
CHECK((*loaded)->name == "Mix");
REQUIRE((*loaded)->tracks.size() == 3);
CHECK((*loaded)->tracks[0].title == "One");
CHECK((*loaded)->tracks[2].title == "Three");
REQUIRE(db.updatePlaylist(*id, "Renamed", std::nullopt, true)
.has_value());
auto renamed = db.getPlaylist(*id);
REQUIRE(renamed.has_value());
REQUIRE(renamed->has_value());
CHECK((*renamed)->name == "Renamed");
CHECK((*renamed)->description == "desc"); // untouched via COALESCE
CHECK((*renamed)->isPublic);
}
TEST_CASE("Database getKv/setKv round-trip")
{
TempDb tdb;
auto& db = tdb.db;
auto missing = db.getKv("nope");
REQUIRE(missing.has_value());
CHECK_FALSE(missing->has_value());
REQUIRE(db.setKv("instances.invidious", "[\"https://a\"]").has_value());
auto value = db.getKv("instances.invidious");
REQUIRE(value.has_value());
REQUIRE(value->has_value());
CHECK(**value == "[\"https://a\"]");
// Overwrite
REQUIRE(db.setKv("instances.invidious", "[]").has_value());
auto updated = db.getKv("instances.invidious");
REQUIRE(updated.has_value());
CHECK(**updated == "[]");
}
// Mirrors MusicManager's announcement persistence: id bumped per post,
// per-uid seen-id gate delivers exactly once and survives a "restart"
// (reopening the same DB). This locks the kv contract the delivery code
// relies on.
namespace
{
int64_t kvInt(Database& db, const std::string& key, int64_t def)
{
if (auto v = db.getKv(key); v && *v) {
try {
return std::stoll(**v);
} catch (...) {
return def;
}
}
return def;
}
// Returns true if a "send" would occur for this uid, applying the gate.
bool wouldDeliver(Database& db, const std::string& uid)
{
const int64_t id = kvInt(db, "announcement.id", 0);
auto text = db.getKv("announcement.text");
if (id == 0 || !text || !*text || (*text)->empty()) {
return false;
}
const std::string seenKey = "announcement.seen." + uid;
if (kvInt(db, seenKey, 0) >= id) {
return false;
}
(void)db.setKv(seenKey, std::to_string(id)); // mark delivered
return true;
}
void postAnnouncement(Database& db, const std::string& text)
{
const int64_t id = kvInt(db, "announcement.id", 0) + 1;
(void)db.setKv("announcement.text", text);
(void)db.setKv("announcement.id", std::to_string(id));
}
} // namespace
TEST_CASE("Announcement delivery is once-per-subscriber and restart-safe")
{
TempDb tdb;
auto& db = tdb.db;
// No announcement yet → nothing delivers.
CHECK_FALSE(wouldDeliver(db, "uidA"));
postAnnouncement(db, "v1");
CHECK(wouldDeliver(db, "uidA")); // first delivery
CHECK_FALSE(wouldDeliver(db, "uidA")); // never twice
CHECK(wouldDeliver(db, "uidB")); // a different subscriber still gets it
// Simulate a bot restart: reopen the same database file.
db.shutdown();
REQUIRE(db.initialize(DatabaseConfig{.path = tdb.path.string()})
.has_value());
CHECK_FALSE(wouldDeliver(db, "uidA")); // seen-id persisted, no resend
// A fresh announcement bumps the id and reaches everyone once more.
postAnnouncement(db, "v2");
CHECK(wouldDeliver(db, "uidA"));
CHECK_FALSE(wouldDeliver(db, "uidA"));
}
TEST_CASE("Database history: recently played dedupes, stats add up, trim caps")
{
TempDb tdb;
auto& db = tdb.db;
using std::chrono::milliseconds;
// "a" played twice, "b" once.
REQUIRE(db.recordPlayback(track("a", "A"), 1, milliseconds(1000), true)
.has_value());
REQUIRE(db.recordPlayback(track("b", "B"), 1, milliseconds(2000), true)
.has_value());
REQUIRE(db.recordPlayback(track("a", "A"), 2, milliseconds(3000), true)
.has_value());
auto recent = db.getRecentlyPlayed(0, 10);
REQUIRE(recent.has_value());
CHECK(recent->size() == 2); // deduped by url
auto stats = db.getStatistics(0);
REQUIRE(stats.has_value());
CHECK(stats->totalPlays == 3);
CHECK(stats->totalTracks == 2);
CHECK(stats->totalPlaytimeMs == 6000);
REQUIRE(stats->mostPlayedTrack.has_value());
CHECK(stats->mostPlayedTrack->originalUrl == "a");
CHECK(stats->mostPlayedCount == 2);
auto top = db.getMostPlayed(0, 5);
REQUIRE(top.has_value());
REQUIRE(top->size() == 2);
CHECK(top->front().second == 2);
// Trim to 1 entry.
REQUIRE(db.trimHistory(1).has_value());
auto after = db.getPlaybackHistory(2, 100);
REQUIRE(after.has_value());
auto global = db.getRecentlyPlayed(0, 10);
REQUIRE(global.has_value());
CHECK(global->size() == 1);
}
TEST_CASE("Database persists the shortened track URL across history and favorites")
{
TempDb tdb;
auto& db = tdb.db;
using std::chrono::milliseconds;
auto yt = track("https://www.youtube.com/watch?v=abc", "Shorty");
yt.shortenedUrl = "https://faumaray.ru/x1";
REQUIRE(db.recordPlayback(yt, 7, milliseconds(1000), true).has_value());
REQUIRE(db.addFavorite(7, yt).has_value());
auto history = db.getPlaybackHistory(7, 10);
REQUIRE(history.has_value());
REQUIRE(history->size() == 1);
REQUIRE(history->front().track.shortenedUrl.has_value());
CHECK(*history->front().track.shortenedUrl == "https://faumaray.ru/x1");
auto favs = db.getFavorites(7);
REQUIRE(favs.has_value());
REQUIRE(favs->size() == 1);
REQUIRE(favs->front().track.shortenedUrl.has_value());
CHECK(*favs->front().track.shortenedUrl == "https://faumaray.ru/x1");
auto recent = db.getRecentlyPlayed(0, 10);
REQUIRE(recent.has_value());
REQUIRE(recent->size() == 1);
REQUIRE(recent->front().shortenedUrl.has_value());
CHECK(*recent->front().shortenedUrl == "https://faumaray.ru/x1");
}
TEST_CASE("Database playlist remove and reorder keep positions dense")
{
TempDb tdb;
auto& db = tdb.db;
auto id = db.createPlaylist("Order", "", 1);
REQUIRE(id.has_value());
for (int i = 0; i < 4; ++i) {
REQUIRE(db.addTrackToPlaylist(
*id, track("u" + std::to_string(i),
"T" + std::to_string(i)),
static_cast<uint32_t>(i))
.has_value());
}
// Track db ids are their playlist_tracks rowids (1-based insert order
// in a fresh database).
// Remove the second track (T1): T0,T2,T3 remain in that order.
REQUIRE(db.removeTrackFromPlaylist(*id, 2).has_value());
{
auto loaded = db.getPlaylist(*id);
REQUIRE(loaded.has_value());
REQUIRE(loaded->has_value());
REQUIRE((*loaded)->tracks.size() == 3);
CHECK((*loaded)->tracks[0].title == "T0");
CHECK((*loaded)->tracks[1].title == "T2");
CHECK((*loaded)->tracks[2].title == "T3");
}
// Move T3 (rowid 4) to the front.
REQUIRE(db.reorderPlaylistTrack(*id, 4, 0).has_value());
{
auto loaded = db.getPlaylist(*id);
REQUIRE(loaded.has_value());
REQUIRE(loaded->has_value());
REQUIRE((*loaded)->tracks.size() == 3);
CHECK((*loaded)->tracks[0].title == "T3");
CHECK((*loaded)->tracks[1].title == "T0");
CHECK((*loaded)->tracks[2].title == "T2");
}
}