core: téléchargement avec reprise, archives tar et persistance
- Downloader : HEAD + Range avec reprise, re-probe à chaque essai (URL CDN signées), retries bornés, fichier partiel conservé, repli sans Range, annulation, progression et ETA - licence : fichier temporaire renommé à la fin ; le placeholder vide « licenses_<id>_<ts>.tar » renvoyé par Majestic pendant la génération de la licence est jeté et la requête relancée (cause du bug ENOENT de l'app officielle) - archives (libarchive) : vérification complète, extraction qui ignore UpdateInfo.xml, refus des chemins absolus/.., liens ignorés (FAT32) - persistance : vehicles.json compatible avec l'app officielle (BOM inclus), réglages + téléchargement en attente, chemins XDG / Haiku, écriture atomique - CLI : download, verify, extract ; Ctrl-C annule proprement - tests : faux CDN (coupures, sans Range, 4xx, annulation), tar ustar/gnu/pax/v7, corruption, traversal (42 cas, 322 assertions) - validé en réel : firmware RCC 8,39 Go téléchargé, interrompu, repris et vérifié (ustar, 16 entrées) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WDASLCiN764v685boRVYar
This commit is contained in:
1 parent
95704f9882
commit
543347a1e6
17 files changed
+2168
-40
No files matched your search
@@ -6,8 +6,12 @@ add_executable(openpu_tests
|
||||
test_models.cpp
|
||||
test_http.cpp
|
||||
test_api_client.cpp
|
||||
test_download.cpp
|
||||
test_archive.cpp
|
||||
test_storage.cpp
|
||||
)
|
||||
target_link_libraries(openpu_tests PRIVATE openpu_core openpu_warnings)
|
||||
find_package(LibArchive REQUIRED)
|
||||
target_link_libraries(openpu_tests PRIVATE openpu_core openpu_warnings LibArchive::LibArchive)
|
||||
if(TARGET doctest::doctest)
|
||||
target_link_libraries(openpu_tests PRIVATE doctest::doctest)
|
||||
endif()
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
#include "openpu/archive.hpp"
|
||||
|
||||
#include "test_util.hpp"
|
||||
|
||||
#include <archive.h>
|
||||
#include <archive_entry.h>
|
||||
#include <cstdio>
|
||||
#include <doctest/doctest.h>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
using namespace openpu;
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace {
|
||||
|
||||
struct Entry {
|
||||
std::string path;
|
||||
std::string content;
|
||||
bool directory = false;
|
||||
std::string symlinkTarget;
|
||||
};
|
||||
|
||||
/// Writes a tar with libarchive. `format` is an ARCHIVE_FORMAT_TAR_* value.
|
||||
void makeTar(const fs::path& file, const std::vector<Entry>& entries, int format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED)
|
||||
{
|
||||
archive* a = archive_write_new();
|
||||
archive_write_set_format(a, format);
|
||||
REQUIRE(archive_write_open_filename(a, file.c_str()) == ARCHIVE_OK);
|
||||
for (const auto& e : entries) {
|
||||
archive_entry* entry = archive_entry_new();
|
||||
archive_entry_set_pathname(entry, e.path.c_str());
|
||||
if (e.directory) {
|
||||
archive_entry_set_filetype(entry, AE_IFDIR);
|
||||
archive_entry_set_perm(entry, 0755);
|
||||
} else if (!e.symlinkTarget.empty()) {
|
||||
archive_entry_set_filetype(entry, AE_IFLNK);
|
||||
archive_entry_set_symlink(entry, e.symlinkTarget.c_str());
|
||||
} else {
|
||||
archive_entry_set_filetype(entry, AE_IFREG);
|
||||
archive_entry_set_perm(entry, 0600);
|
||||
archive_entry_set_size(entry, static_cast<la_int64_t>(e.content.size()));
|
||||
}
|
||||
REQUIRE(archive_write_header(a, entry) == ARCHIVE_OK);
|
||||
if (!e.content.empty())
|
||||
archive_write_data(a, e.content.data(), e.content.size());
|
||||
archive_entry_free(entry);
|
||||
}
|
||||
archive_write_close(a);
|
||||
archive_write_free(a);
|
||||
}
|
||||
|
||||
std::vector<Entry> rccLike()
|
||||
{
|
||||
return {
|
||||
{"rcc_update/", "", true, ""},
|
||||
{"rcc_update/UpdateInfo.xml", "<info/>", false, ""},
|
||||
{"rcc_update/pkg/a.bin", std::string(300000, 'x'), false, ""},
|
||||
{"rcc_update/pkg/b.txt", "hello", false, ""},
|
||||
{"./UpdateInfo.xml", "<root/>", false, ""},
|
||||
};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("extraction skips UpdateInfo.xml and keeps the tree")
|
||||
{
|
||||
TempDir tmp;
|
||||
const fs::path tar = tmp.path() / "fw.tar";
|
||||
makeTar(tar, rccLike());
|
||||
const fs::path usb = tmp.path() / "usb";
|
||||
|
||||
ArchiveProgress last;
|
||||
extractTar(tar, usb, [&](const ArchiveProgress& p) { last = p; });
|
||||
CHECK(readAll(usb / "rcc_update/pkg/b.txt") == "hello");
|
||||
CHECK(fs::file_size(usb / "rcc_update/pkg/a.bin") == 300000);
|
||||
CHECK_FALSE(fs::exists(usb / "rcc_update/UpdateInfo.xml"));
|
||||
CHECK_FALSE(fs::exists(usb / "UpdateInfo.xml"));
|
||||
CHECK(last.entries == 5);
|
||||
CHECK(last.processed == last.total);
|
||||
}
|
||||
|
||||
TEST_CASE("payload size excludes skipped entries")
|
||||
{
|
||||
TempDir tmp;
|
||||
const fs::path tar = tmp.path() / "fw.tar";
|
||||
makeTar(tar, rccLike());
|
||||
CHECK(tarPayloadSize(tar) == 300000 + 5);
|
||||
}
|
||||
|
||||
TEST_CASE("verify accepts ustar, gnu, pax and v7 (no magic) archives")
|
||||
{
|
||||
TempDir tmp;
|
||||
for (int format : {ARCHIVE_FORMAT_TAR_USTAR, ARCHIVE_FORMAT_TAR_GNUTAR, ARCHIVE_FORMAT_TAR_PAX_RESTRICTED}) {
|
||||
const fs::path tar = tmp.path() / ("f" + std::to_string(format) + ".tar");
|
||||
makeTar(tar, rccLike(), format);
|
||||
CHECK_NOTHROW(verifyTar(tar));
|
||||
}
|
||||
// V7: ustar header with the magic field blanked out (seen in some PSA archives).
|
||||
const fs::path v7 = tmp.path() / "v7.tar";
|
||||
makeTar(v7, {{"file.bin", "data", false, ""}}, ARCHIVE_FORMAT_TAR_USTAR);
|
||||
std::string raw = readAll(v7);
|
||||
raw.replace(257, 8, std::string(8, '\0')); // magic + version
|
||||
unsigned sum = 0;
|
||||
raw.replace(148, 8, std::string(8, ' '));
|
||||
for (std::size_t i = 0; i < 512; ++i)
|
||||
sum += static_cast<unsigned char>(raw[i]);
|
||||
char chk[8];
|
||||
std::snprintf(chk, sizeof chk, "%06o", sum);
|
||||
raw.replace(148, 7, std::string(chk, 6) + '\0');
|
||||
writeAll(v7, raw);
|
||||
CHECK_NOTHROW(verifyTar(v7));
|
||||
extractTar(v7, tmp.path() / "out");
|
||||
CHECK(readAll(tmp.path() / "out/file.bin") == "data");
|
||||
}
|
||||
|
||||
TEST_CASE("corrupt archives are reported as Corrupt")
|
||||
{
|
||||
TempDir tmp;
|
||||
const fs::path tar = tmp.path() / "fw.tar";
|
||||
makeTar(tar, rccLike());
|
||||
|
||||
SUBCASE("truncated")
|
||||
{
|
||||
std::string raw = readAll(tar);
|
||||
writeAll(tar, raw.substr(0, 100000));
|
||||
try {
|
||||
verifyTar(tar);
|
||||
FAIL("expected ArchiveError");
|
||||
} catch (const ArchiveError& e) {
|
||||
CHECK(e.kind() == ArchiveError::Kind::Corrupt);
|
||||
}
|
||||
}
|
||||
SUBCASE("garbage")
|
||||
{
|
||||
writeAll(tar, std::string(4096, '\x5a'));
|
||||
try {
|
||||
verifyTar(tar);
|
||||
FAIL("expected ArchiveError");
|
||||
} catch (const ArchiveError& e) {
|
||||
CHECK(e.kind() == ArchiveError::Kind::Corrupt);
|
||||
}
|
||||
}
|
||||
SUBCASE("empty file")
|
||||
{
|
||||
writeAll(tar, "");
|
||||
CHECK_THROWS_AS(verifyTar(tar), ArchiveError);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("missing archive is an I/O error")
|
||||
{
|
||||
TempDir tmp;
|
||||
try {
|
||||
verifyTar(tmp.path() / "nope.tar");
|
||||
FAIL("expected ArchiveError");
|
||||
} catch (const ArchiveError& e) {
|
||||
CHECK(e.kind() == ArchiveError::Kind::Io);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("path traversal and links are refused")
|
||||
{
|
||||
TempDir tmp;
|
||||
const fs::path usb = tmp.path() / "usb";
|
||||
|
||||
SUBCASE("dot-dot")
|
||||
{
|
||||
const fs::path tar = tmp.path() / "evil.tar";
|
||||
makeTar(tar, {{"ok.txt", "1", false, ""}, {"../escape.txt", "x", false, ""}});
|
||||
CHECK_THROWS_AS(extractTar(tar, usb), ArchiveError);
|
||||
CHECK_FALSE(fs::exists(tmp.path() / "escape.txt"));
|
||||
}
|
||||
SUBCASE("absolute")
|
||||
{
|
||||
const fs::path tar = tmp.path() / "abs.tar";
|
||||
makeTar(tar, {{(tmp.path() / "abs.txt").string(), "x", false, ""}});
|
||||
CHECK_THROWS_AS(extractTar(tar, usb), ArchiveError);
|
||||
CHECK_FALSE(fs::exists(tmp.path() / "abs.txt"));
|
||||
}
|
||||
SUBCASE("symlinks are skipped")
|
||||
{
|
||||
const fs::path tar = tmp.path() / "link.tar";
|
||||
makeTar(tar, {{"link", "", false, "/etc/passwd"}, {"link2", "", false, "../.."}, {"f.txt", "ok", false, ""}});
|
||||
extractTar(tar, usb);
|
||||
CHECK_FALSE(fs::exists(fs::symlink_status(usb / "link")));
|
||||
CHECK(readAll(usb / "f.txt") == "ok");
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("cancellation")
|
||||
{
|
||||
TempDir tmp;
|
||||
const fs::path tar = tmp.path() / "fw.tar";
|
||||
makeTar(tar, rccLike());
|
||||
CancelToken cancel;
|
||||
cancel.cancel();
|
||||
CHECK_THROWS_AS(extractTar(tar, tmp.path() / "usb", {}, &cancel), Cancelled);
|
||||
CHECK_THROWS_AS(verifyTar(tar, {}, &cancel), Cancelled);
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
#include "openpu/download.hpp"
|
||||
|
||||
#include "test_util.hpp"
|
||||
|
||||
#include <doctest/doctest.h>
|
||||
#include <fstream>
|
||||
|
||||
using namespace openpu;
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace {
|
||||
|
||||
/// In-memory HTTP server emulating Majestic (redirect) + CDN (Range) behaviour.
|
||||
class FakeCdn final : public Transport {
|
||||
public:
|
||||
std::string blob;
|
||||
bool supportsRange = true;
|
||||
/// For each of the first N GET requests, drop the connection after this many body bytes.
|
||||
std::vector<std::size_t> dropAfter;
|
||||
long headStatus = 200;
|
||||
long getStatus = 0; ///< forced status for GET (0 = normal behaviour)
|
||||
std::string licenseBody = "LICENSE-DATA";
|
||||
std::size_t chunk = 1000;
|
||||
int heads = 0;
|
||||
int gets = 0;
|
||||
std::vector<std::string> ranges;
|
||||
|
||||
static constexpr const char* entryUrl = "https://majestic.test/rest/UpdateDownload?updateId=1&uin=0";
|
||||
static constexpr const char* finalUrl = "https://cdn.test/BOSCH/RCC_EU/rcc-firmware/PSA_fw.tar?sig=abc";
|
||||
static constexpr const char* licenseUrl = "https://majestic.test/rest/LicenseDownload?mediaVersion=1&uin=0";
|
||||
|
||||
HttpResponse perform(const HttpRequest& req) override
|
||||
{
|
||||
HttpResponse r;
|
||||
if (req.url == licenseUrl) {
|
||||
r.status = 200;
|
||||
r.headers["content-disposition"] = "attachment; filename=license_0000.key";
|
||||
r.effectiveUrl = req.url;
|
||||
deliver(req, r, licenseBody);
|
||||
return r;
|
||||
}
|
||||
if (req.method == HttpMethod::Head) {
|
||||
++heads;
|
||||
REQUIRE(req.url == entryUrl);
|
||||
r.status = headStatus;
|
||||
r.effectiveUrl = finalUrl;
|
||||
r.headers["content-length"] = std::to_string(blob.size());
|
||||
if (req.onHeaders)
|
||||
req.onHeaders(r.status, r.headers);
|
||||
return r;
|
||||
}
|
||||
REQUIRE(req.url == finalUrl);
|
||||
const int index = gets++;
|
||||
std::size_t from = 0;
|
||||
std::string range;
|
||||
for (const auto& [k, v] : req.headers)
|
||||
if (k == "Range")
|
||||
range = v;
|
||||
ranges.push_back(range);
|
||||
if (getStatus != 0) {
|
||||
r.status = getStatus;
|
||||
deliver(req, r, "error page");
|
||||
return r;
|
||||
}
|
||||
if (!range.empty() && supportsRange) {
|
||||
from = std::stoull(range.substr(6, range.find('-') - 6));
|
||||
r.status = 206;
|
||||
r.headers["content-range"] = "bytes " + std::to_string(from) + "-" + std::to_string(blob.size() - 1) + "/" +
|
||||
std::to_string(blob.size());
|
||||
} else {
|
||||
r.status = 200;
|
||||
}
|
||||
const std::string body = blob.substr(from);
|
||||
r.headers["content-length"] = std::to_string(body.size());
|
||||
const std::size_t limit =
|
||||
index < static_cast<int>(dropAfter.size()) ? dropAfter[static_cast<std::size_t>(index)] : body.size();
|
||||
deliver(req, r, body, limit);
|
||||
return r;
|
||||
}
|
||||
|
||||
private:
|
||||
void deliver(const HttpRequest& req, HttpResponse& r, const std::string& body, std::size_t limit = std::string::npos)
|
||||
{
|
||||
if (req.onHeaders && !req.onHeaders(r.status, r.headers))
|
||||
throw TransferAborted("aborted");
|
||||
const std::size_t end = std::min(limit, body.size());
|
||||
for (std::size_t pos = 0; pos < end; pos += chunk) {
|
||||
const std::size_t n = std::min(chunk, end - pos);
|
||||
if (req.onData) {
|
||||
if (!req.onData(body.data() + pos, n))
|
||||
throw TransferAborted("aborted");
|
||||
} else {
|
||||
r.body.append(body, pos, n);
|
||||
}
|
||||
}
|
||||
if (end < body.size())
|
||||
throw NetworkError("connection reset");
|
||||
}
|
||||
};
|
||||
|
||||
DownloadOptions fastOptions()
|
||||
{
|
||||
DownloadOptions o;
|
||||
o.retryDelay = std::chrono::milliseconds(0);
|
||||
o.progressInterval = std::chrono::milliseconds(0);
|
||||
return o;
|
||||
}
|
||||
|
||||
std::string makeBlob(std::size_t n)
|
||||
{
|
||||
std::string s(n, '\0');
|
||||
for (std::size_t i = 0; i < n; ++i)
|
||||
s[i] = static_cast<char>('a' + (i * 7) % 26);
|
||||
return s;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("fresh download follows the redirect and names the file after the final URL")
|
||||
{
|
||||
TempDir dir;
|
||||
FakeCdn cdn;
|
||||
cdn.blob = makeBlob(10000);
|
||||
Downloader dl(cdn, fastOptions());
|
||||
|
||||
std::vector<DownloadProgress> seen;
|
||||
const auto r = dl.downloadResumable(FakeCdn::entryUrl, dir.path(), [&](const DownloadProgress& p) { seen.push_back(p); });
|
||||
CHECK(r.file == dir.path() / "PSA_fw.tar");
|
||||
CHECK(r.size == 10000);
|
||||
CHECK_FALSE(r.alreadyComplete);
|
||||
CHECK(readAll(r.file) == cdn.blob);
|
||||
CHECK(cdn.ranges.front().empty()); // no Range header for a fresh file
|
||||
REQUIRE_FALSE(seen.empty());
|
||||
CHECK(seen.back().done == 10000);
|
||||
CHECK(seen.back().total == 10000);
|
||||
}
|
||||
|
||||
TEST_CASE("interrupted download is resumed with a Range request")
|
||||
{
|
||||
TempDir dir;
|
||||
FakeCdn cdn;
|
||||
cdn.blob = makeBlob(10000);
|
||||
cdn.dropAfter = {3000, 2000};
|
||||
Downloader dl(cdn, fastOptions());
|
||||
|
||||
const auto r = dl.downloadResumable(FakeCdn::entryUrl, dir.path());
|
||||
CHECK(readAll(r.file) == cdn.blob);
|
||||
REQUIRE(cdn.gets == 3);
|
||||
CHECK(cdn.ranges[0].empty());
|
||||
CHECK(cdn.ranges[1] == "bytes=3000-9999");
|
||||
CHECK(cdn.ranges[2] == "bytes=5000-9999");
|
||||
CHECK(cdn.heads == 3); // re-probed each attempt (signed CDN URLs may expire)
|
||||
}
|
||||
|
||||
TEST_CASE("existing partial file from a previous session is continued")
|
||||
{
|
||||
TempDir dir;
|
||||
FakeCdn cdn;
|
||||
cdn.blob = makeBlob(5000);
|
||||
writeAll(dir.path() / "PSA_fw.tar", cdn.blob.substr(0, 1234));
|
||||
Downloader dl(cdn, fastOptions());
|
||||
|
||||
DownloadProgress last;
|
||||
dl.downloadResumable(FakeCdn::entryUrl, dir.path(), [&](const DownloadProgress& p) { last = p; });
|
||||
CHECK(readAll(dir.path() / "PSA_fw.tar") == cdn.blob);
|
||||
CHECK(cdn.ranges[0] == "bytes=1234-4999");
|
||||
CHECK(last.resumedFrom == 1234);
|
||||
}
|
||||
|
||||
TEST_CASE("complete file is not downloaded again")
|
||||
{
|
||||
TempDir dir;
|
||||
FakeCdn cdn;
|
||||
cdn.blob = makeBlob(100);
|
||||
writeAll(dir.path() / "PSA_fw.tar", cdn.blob);
|
||||
Downloader dl(cdn, fastOptions());
|
||||
const auto r = dl.downloadResumable(FakeCdn::entryUrl, dir.path());
|
||||
CHECK(r.alreadyComplete);
|
||||
CHECK(cdn.gets == 0);
|
||||
}
|
||||
|
||||
TEST_CASE("server without Range support: file rewritten from the start")
|
||||
{
|
||||
TempDir dir;
|
||||
FakeCdn cdn;
|
||||
cdn.blob = makeBlob(4000);
|
||||
cdn.supportsRange = false;
|
||||
writeAll(dir.path() / "PSA_fw.tar", std::string(1500, 'Z')); // garbage partial
|
||||
Downloader dl(cdn, fastOptions());
|
||||
dl.downloadResumable(FakeCdn::entryUrl, dir.path());
|
||||
CHECK(readAll(dir.path() / "PSA_fw.tar") == cdn.blob);
|
||||
}
|
||||
|
||||
TEST_CASE("larger local file than announced is discarded")
|
||||
{
|
||||
TempDir dir;
|
||||
FakeCdn cdn;
|
||||
cdn.blob = makeBlob(100);
|
||||
writeAll(dir.path() / "PSA_fw.tar", std::string(500, 'Z'));
|
||||
Downloader dl(cdn, fastOptions());
|
||||
dl.downloadResumable(FakeCdn::entryUrl, dir.path());
|
||||
CHECK(readAll(dir.path() / "PSA_fw.tar") == cdn.blob);
|
||||
}
|
||||
|
||||
TEST_CASE("retries are bounded and the partial file is kept")
|
||||
{
|
||||
TempDir dir;
|
||||
FakeCdn cdn;
|
||||
cdn.blob = makeBlob(10000);
|
||||
cdn.dropAfter = std::vector<std::size_t>(10, 1000); // never completes... but makes progress
|
||||
auto o = fastOptions();
|
||||
o.maxRetries = 2;
|
||||
Downloader dl(cdn, o);
|
||||
try {
|
||||
dl.downloadResumable(FakeCdn::entryUrl, dir.path());
|
||||
FAIL("expected DownloadError");
|
||||
} catch (const DownloadError& e) {
|
||||
CHECK(e.kind() == DownloadError::Kind::Network);
|
||||
}
|
||||
CHECK(cdn.gets == 3);
|
||||
CHECK(fs::file_size(dir.path() / "PSA_fw.tar") == 3000);
|
||||
}
|
||||
|
||||
TEST_CASE("HTTP 4xx is fatal, no retry")
|
||||
{
|
||||
TempDir dir;
|
||||
FakeCdn cdn;
|
||||
cdn.blob = makeBlob(10);
|
||||
cdn.headStatus = 403;
|
||||
Downloader dl(cdn, fastOptions());
|
||||
try {
|
||||
dl.downloadResumable(FakeCdn::entryUrl, dir.path());
|
||||
FAIL("expected DownloadError");
|
||||
} catch (const DownloadError& e) {
|
||||
CHECK(e.kind() == DownloadError::Kind::Http);
|
||||
}
|
||||
CHECK(cdn.heads == 1);
|
||||
}
|
||||
|
||||
TEST_CASE("cancellation stops the transfer and keeps the partial file")
|
||||
{
|
||||
TempDir dir;
|
||||
FakeCdn cdn;
|
||||
cdn.blob = makeBlob(10000);
|
||||
Downloader dl(cdn, fastOptions());
|
||||
CancelToken cancel;
|
||||
CHECK_THROWS_AS(dl.downloadResumable(
|
||||
FakeCdn::entryUrl, dir.path(),
|
||||
[&](const DownloadProgress& p) {
|
||||
if (p.done >= 4000)
|
||||
cancel.cancel();
|
||||
},
|
||||
&cancel),
|
||||
Cancelled);
|
||||
const auto size = fs::file_size(dir.path() / "PSA_fw.tar");
|
||||
CHECK(size >= 4000);
|
||||
CHECK(size < 10000);
|
||||
}
|
||||
|
||||
TEST_CASE("small download uses Content-Disposition and a temporary file")
|
||||
{
|
||||
TempDir dir;
|
||||
FakeCdn cdn;
|
||||
Downloader dl(cdn, fastOptions());
|
||||
const auto r = dl.downloadSmall(FakeCdn::licenseUrl, dir.path());
|
||||
CHECK(r.file == dir.path() / "license_0000.key");
|
||||
CHECK(readAll(r.file) == "LICENSE-DATA");
|
||||
std::size_t count = 0;
|
||||
for ([[maybe_unused]] const auto& e : fs::directory_iterator(dir.path()))
|
||||
++count;
|
||||
CHECK(count == 1); // no leftover .part
|
||||
|
||||
SUBCASE("known existing file is reused without request")
|
||||
{
|
||||
cdn.licenseBody = "CHANGED";
|
||||
const auto again = dl.downloadSmall(FakeCdn::licenseUrl, dir.path(), std::string("license_0000.key"));
|
||||
CHECK(again.alreadyComplete);
|
||||
CHECK(readAll(again.file) == "LICENSE-DATA");
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/// LicenseDownload that first answers with an empty placeholder, like the real backend.
|
||||
class LazyLicense final : public Transport {
|
||||
public:
|
||||
int calls = 0;
|
||||
int emptyAnswers = 1;
|
||||
HttpResponse perform(const HttpRequest& req) override
|
||||
{
|
||||
++calls;
|
||||
HttpResponse r;
|
||||
r.status = 200;
|
||||
const bool empty = calls <= emptyAnswers;
|
||||
r.headers["content-disposition"] =
|
||||
empty ? "attachment; filename=licenses_1_20261128185520.tar" : "attachment; filename=license_ABC.key";
|
||||
if (req.onHeaders && !req.onHeaders(r.status, r.headers))
|
||||
throw TransferAborted("aborted");
|
||||
if (!empty) {
|
||||
const std::string body = "KEY";
|
||||
if (req.onData && !req.onData(body.data(), body.size()))
|
||||
throw TransferAborted("aborted");
|
||||
}
|
||||
return r;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("empty license placeholder is discarded and the request repeated")
|
||||
{
|
||||
TempDir dir;
|
||||
LazyLicense server;
|
||||
Downloader dl(server, fastOptions());
|
||||
const auto r = dl.downloadSmall("https://majestic.test/rest/LicenseDownload?x", dir.path());
|
||||
CHECK(server.calls == 2);
|
||||
CHECK(r.file.filename() == "license_ABC.key");
|
||||
CHECK(readAll(r.file) == "KEY");
|
||||
CHECK_FALSE(fs::exists(dir.path() / "licenses_1_20261128185520.tar"));
|
||||
|
||||
SUBCASE("gives up when it never arrives")
|
||||
{
|
||||
LazyLicense never;
|
||||
never.emptyAnswers = 100;
|
||||
auto o = fastOptions();
|
||||
o.maxRetries = 3;
|
||||
Downloader dl2(never, o);
|
||||
CHECK_THROWS_AS(dl2.downloadSmall("https://majestic.test/rest/LicenseDownload?x", dir.path()), DownloadError);
|
||||
CHECK(never.calls == 4);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("remaining time estimate")
|
||||
{
|
||||
DownloadProgress p;
|
||||
p.total = 1000;
|
||||
p.resumedFrom = 200;
|
||||
p.done = 600;
|
||||
p.elapsed = std::chrono::seconds(4); // 400 bytes in 4 s -> 100 B/s, 400 left
|
||||
REQUIRE(p.remaining().has_value());
|
||||
CHECK(p.remaining()->count() == 4);
|
||||
p.done = 200;
|
||||
CHECK_FALSE(p.remaining().has_value());
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
#include "openpu/storage.hpp"
|
||||
|
||||
#include "test_util.hpp"
|
||||
|
||||
#include <doctest/doctest.h>
|
||||
|
||||
using namespace openpu;
|
||||
|
||||
TEST_CASE("official vehicles.json (with BOM) is understood")
|
||||
{
|
||||
const std::string official = "\xEF\xBB\xBF"
|
||||
R"({"VF3AAAAAAAAAAAAA1":{"name":"5008","type":"nac","wave":"path_guide_wave_4"},)"
|
||||
R"("VR3AAAAAAAAAAAAA2":{"name":"e208","type":"rcc","wave":"path_guide_rcc",)"
|
||||
R"("undeletedFiles":{"fw":"C:\\dl\\PSA_rcc.tar","license":"C:\\dl\\license_X.key"}}})";
|
||||
const auto v = VehicleStore::parse(official);
|
||||
REQUIRE(v.size() == 2);
|
||||
CHECK(v[0].vin == "VF3AAAAAAAAAAAAA1");
|
||||
CHECK(v[0].type == HeadUnitType::Nac);
|
||||
CHECK(v[0].guideKey == "path_guide_wave_4");
|
||||
CHECK(v[1].type == HeadUnitType::Rcc);
|
||||
CHECK(v[1].pendingFirmware == "C:\\dl\\PSA_rcc.tar");
|
||||
CHECK(v[1].pendingLicense == "C:\\dl\\license_X.key");
|
||||
CHECK(v[1].pendingMap.empty());
|
||||
}
|
||||
|
||||
TEST_CASE("vehicle store round trip")
|
||||
{
|
||||
TempDir tmp;
|
||||
VehicleStore store(tmp.path() / "sub" / "vehicles.json");
|
||||
store.load(); // missing file
|
||||
CHECK(store.all().empty());
|
||||
|
||||
Vehicle a;
|
||||
a.vin = "VF3AAAAAAAAAAAAA1";
|
||||
a.name = "Ma 208";
|
||||
a.type = HeadUnitType::Nac;
|
||||
a.guideKey = "path_guide_wave_2";
|
||||
store.upsert(a);
|
||||
Vehicle b = a;
|
||||
b.vin = "VR3AAAAAAAAAAAAA2";
|
||||
b.type = HeadUnitType::CronyNonav;
|
||||
b.pendingMap = "/dl/map.tar";
|
||||
store.upsert(b);
|
||||
a.name = "renamed";
|
||||
store.upsert(a);
|
||||
store.save();
|
||||
|
||||
VehicleStore again(store.file());
|
||||
again.load();
|
||||
REQUIRE(again.all().size() == 2);
|
||||
REQUIRE(again.find("VF3AAAAAAAAAAAAA1") != nullptr);
|
||||
CHECK(again.find("VF3AAAAAAAAAAAAA1")->name == "renamed");
|
||||
CHECK(again.find("VR3AAAAAAAAAAAAA2")->type == HeadUnitType::CronyNonav);
|
||||
CHECK(again.find("VR3AAAAAAAAAAAAA2")->pendingMap == "/dl/map.tar");
|
||||
CHECK(again.remove("VF3AAAAAAAAAAAAA1"));
|
||||
CHECK_FALSE(again.remove("VF3AAAAAAAAAAAAA1"));
|
||||
CHECK(again.all().size() == 1);
|
||||
}
|
||||
|
||||
TEST_CASE("corrupt vehicles file is an error, not silently emptied")
|
||||
{
|
||||
TempDir tmp;
|
||||
writeAll(tmp.path() / "vehicles.json", "{broken");
|
||||
VehicleStore store(tmp.path() / "vehicles.json");
|
||||
CHECK_THROWS_AS(store.load(), StorageError);
|
||||
}
|
||||
|
||||
TEST_CASE("settings round trip")
|
||||
{
|
||||
TempDir tmp;
|
||||
const auto file = tmp.path() / "config.json";
|
||||
Settings s = Settings::load(file);
|
||||
CHECK(s.language.empty());
|
||||
CHECK_FALSE(s.pending.has_value());
|
||||
CHECK_FALSE(s.effectiveDownloadDir().empty());
|
||||
|
||||
s.language = "fr";
|
||||
s.downloadDir = "/data/dl";
|
||||
PendingDownload p;
|
||||
p.vin = "VR3AAAAAAAAAAAAA2";
|
||||
p.firmware = true;
|
||||
p.firmwareFile = "PSA_rcc.tar";
|
||||
p.licenseFile = "license_X.key";
|
||||
s.pending = p;
|
||||
s.save(file);
|
||||
|
||||
const Settings r = Settings::load(file);
|
||||
CHECK(r.language == "fr");
|
||||
CHECK(r.effectiveDownloadDir() == "/data/dl");
|
||||
REQUIRE(r.pending.has_value());
|
||||
CHECK(r.pending->firmware);
|
||||
CHECK_FALSE(r.pending->map);
|
||||
CHECK(r.pending->licenseFile == "license_X.key");
|
||||
}
|
||||
|
||||
TEST_CASE("XDG paths")
|
||||
{
|
||||
// Only checks the shape: paths end with our application directory.
|
||||
#ifdef __HAIKU__
|
||||
CHECK(paths::configDir().filename() == "OpenPU");
|
||||
CHECK(paths::defaultDownloadDir().filename() == "OpenPU downloads");
|
||||
#else
|
||||
CHECK(paths::configDir().filename() == "openpu");
|
||||
CHECK(paths::defaultDownloadDir().filename() == "OpenPU");
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
/// Self-deleting temporary directory.
|
||||
class TempDir {
|
||||
public:
|
||||
TempDir()
|
||||
{
|
||||
static std::atomic<int> counter{0};
|
||||
path_ = std::filesystem::temp_directory_path() /
|
||||
("openpu-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) + "-" +
|
||||
std::to_string(counter++));
|
||||
std::filesystem::create_directories(path_);
|
||||
}
|
||||
TempDir(const TempDir&) = delete;
|
||||
TempDir& operator=(const TempDir&) = delete;
|
||||
~TempDir()
|
||||
{
|
||||
std::error_code ec;
|
||||
std::filesystem::remove_all(path_, ec);
|
||||
}
|
||||
const std::filesystem::path& path() const { return path_; }
|
||||
|
||||
private:
|
||||
std::filesystem::path path_;
|
||||
};
|
||||
|
||||
inline std::string readAll(const std::filesystem::path& p)
|
||||
{
|
||||
std::ifstream in(p, std::ios::binary);
|
||||
std::stringstream ss;
|
||||
ss << in.rdbuf();
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
inline void writeAll(const std::filesystem::path& p, const std::string& content)
|
||||
{
|
||||
std::filesystem::create_directories(p.parent_path());
|
||||
std::ofstream out(p, std::ios::binary | std::ios::trunc);
|
||||
out << content;
|
||||
}
|
||||
Reference in new issue
Block a user