feat(app): add the Nostro app, a window for phones and desktops
Linux phones have no banking apps, and a command line is no answer on a phone. The app does everything the nostro command does and, like it, only talks to nostrod: it holds no key and no token. - Nostro.Ui, a toolkit whose screens are functions that fill a frame, ported from imsd-messages ca5cd72d; Nostro.App, the app's state, forms and screens; Nostro.Ui.Shell, which puts them on a Wayland window with Crafter.Graphics; nostro-app; and Nostro.DebugCommands for the --debug-api build. - Client: every method also in an asynchronous form for an sd-event loop, with DaemonMissing and OutcomeUnknown. - nostrod's Flatpak is net.catcrafts.Nostrod now and the app takes net.catcrafts.Nostro; install.sh moves the state. The app's Flatpak, both Flatpaks cross-built for aarch64, and the licence texts they carry. - nostro-fake-system, a made-up bus and bank with a real nostrod on them, to look at the app against. The README's screenshots are taken on it. - The nostro command: an API key's environment is the key's own to say, so --sandbox is for bunq-oauth alone, and a virtual card is listed as VIRTUAL. The published contract changes in three places, before any release (design rule 10): - Transactions' query takes `stored`: answered from what nostrod has stored, without asking the bank. The app searches with it; before, every search was a call to bunq. - AddBunq's `environment` no longer chooses over what the key says of itself: a key of the other environment is refused. - SetCardStatus refuses to freeze or unfreeze a virtual card. bunq reports one as DEACTIVATED however well it pays, and leaves it as it is when asked, without an error. The app is GPL-3.0-only, the library stays LGPL-3.0-only, and no code moved from one to the other (design rule 13). Transaction's schema is unchanged. Verified: the 17 tests pass with every line, function and region of what they link run, and the five lint runs are clean. Every screen was looked at on the made-up system, at a phone's and a desktop's sizes in the light and the dark look, on Plasma under Wayland. What is said of bunq's cards comes from its sandbox, with throwaway users, and from one real virtual card. Known to have been used against production: connecting, and reading accounts, payments and cards. Not known to have been tried: a payment from the app against bunq, OAuth against bunq, and anything on a phone. Building the app takes --graphics=, a Crafter.Graphics checkout on its branch claude/nostro-app, until that branch is merged and pinned here. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
1ea50c50bc
commit
5b4037955b
106 changed files with 17804 additions and 289 deletions
266
tests/FakeSystem/main.cpp
Normal file
266
tests/FakeSystem/main.cpp
Normal file
|
|
@ -0,0 +1,266 @@
|
|||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// nostro-fake-system: a whole system for the app to be looked at against, with no bank, no real bus and nobody's
|
||||
// money in it. It runs the tests' fake system bus and fake bunq (tests/Support), starts nostrod on them (this
|
||||
// executable again, with nostrod's main compiled in), fills the bank with a made-up user, and then runs a program
|
||||
// with DBUS_SYSTEM_BUS_ADDRESS pointing at the fake bus, or waits for one to be started by hand.
|
||||
// nostro-fake-system [--dir <directory>] [--port <port>] [--polkit allow|password|deny|dismiss|absent|silent|slow]
|
||||
// [--bank-delay <milliseconds>] [--empty] [--run <program> <arguments…>]
|
||||
// --dir is where the bus's socket and nostrod's state go (a temporary directory by default). --polkit is what every
|
||||
// request for a password is answered with: allow by default, as if the user typed it at once. --bank-delay is how
|
||||
// long the made-up bank takes over each answer: none by default, where a real bank is a network away and takes a few
|
||||
// hundred milliseconds, which is what shows whether a screen waits for the bank more than it has to. --empty leaves
|
||||
// the user without a bank connection, to start from the welcome; the made-up bank's API key is printed, to add it by
|
||||
// hand. Everything after --run is the program and its arguments.
|
||||
|
||||
#include "../../lib/json.hpp"
|
||||
#include <poll.h>
|
||||
#include <signal.h>
|
||||
#include <spawn.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/resource.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/un.h>
|
||||
#include <sys/wait.h>
|
||||
#include <systemd/sd-bus.h>
|
||||
#include <systemd/sd-event.h>
|
||||
#include <systemd/sd-id128.h>
|
||||
#include <unistd.h>
|
||||
|
||||
import std;
|
||||
import Nostro;
|
||||
import Crafter.Network;
|
||||
|
||||
#define main NostrodMain
|
||||
#include "../../implementations/nostrod.cpp"
|
||||
#undef main
|
||||
|
||||
#include "../Support/FakeBunq.inc"
|
||||
#include "../Support/FakeBus.inc"
|
||||
|
||||
using namespace Nostro;
|
||||
using json = nlohmann::json;
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace {
|
||||
constexpr std::string_view busName = "net.catcrafts.Nostro1";
|
||||
// A key of the sandbox's kind: the app's own guard against real keys in a build open to a debugger lets it by.
|
||||
const std::string demoKey = "sandbox_demo_0123456789abcdef0123456789abcdef";
|
||||
const std::string currentIban = "NL54BUNQ2100000011";
|
||||
const std::string savingsIban = "NL48BUNQ2100000022";
|
||||
const std::string holidayIban = "NL42BUNQ2100000033";
|
||||
const std::string friendIban = "NL36BUNQ2100000044";
|
||||
const std::string sharedIban = "NL06BUNQ2100000099";
|
||||
|
||||
// The made-up user's bank: three accounts, three months of payments, three cards, and one of everything else. All of
|
||||
// it is in English, as the app is: the README's pictures are of this (docs/screenshots/take.sh).
|
||||
void Fill(Fake::Bunq& bunq) {
|
||||
const std::uint64_t robin = bunq.AddPerson("Robin Walker", demoKey);
|
||||
const std::uint64_t current = bunq.AddAccount(robin, currentIban, "Current account", 84210);
|
||||
bunq.AddAccount(robin, savingsIban, "Savings", 1250000, "MonetaryAccountSavings");
|
||||
bunq.AddAccount(robin, holidayIban, "Holiday", 43050, "MonetaryAccountSavings");
|
||||
const std::uint64_t nora = bunq.AddPerson("Nora White", "sandbox_demo_friend");
|
||||
bunq.AddAccount(nora, friendIban, "Nora", 150000);
|
||||
const std::uint64_t sam = bunq.AddPerson("Sam Johnson", "sandbox_demo_shared");
|
||||
bunq.AddAccount(sam, sharedIban, "Household", 96400);
|
||||
bunq.AddGrant(sam, "demo-code", "sandbox_demo_token");
|
||||
|
||||
struct Regular {
|
||||
std::string_view name;
|
||||
std::string_view iban;
|
||||
std::string_view description;
|
||||
std::int64_t amount;
|
||||
std::int32_t every; // days between two of them
|
||||
std::string_view type;
|
||||
std::string_view subType;
|
||||
};
|
||||
static constexpr std::array<Regular, 9> regulars = {{
|
||||
{"Maple Court Housing", "NL35RABO0300000055", "Rent", -98500, 30, "EBA_SDD", "SDD"},
|
||||
{"Employer Ltd", "NL20INGB0001234567", "Salary", 285000, 30, "EBA_SCT", "SCT"},
|
||||
{"Northern Energy", "NL69ABNA0500000077", "Monthly instalment", -14200, 30, "EBA_SDD", "SDD"},
|
||||
{"Corner Supermarket", "", "", -4350, 3, "MASTERCARD", "PAYMENT"},
|
||||
{"Sunflower Bakery", "", "", -685, 4, "MASTERCARD", "PAYMENT"},
|
||||
{"Nora White", "NL36BUNQ2100000044", "Groceries", -2250, 11, "BUNQ", "PAYMENT"},
|
||||
{"Swift Cycles", "NL96TRIO0200000088", "Repair", -6500, 41, "IDEAL", "PAYMENT"},
|
||||
{"Eastside Sports Club", "NL43KNAB0600000100", "Membership", -2750, 30, "EBA_SDD", "SDD"},
|
||||
{"Nora White", "NL36BUNQ2100000044", "Dinner, paid back", 3100, 17, "BUNQ", "PAYMENT"},
|
||||
}};
|
||||
// Oldest first, as a bank makes them: ninety days up to an hour ago.
|
||||
const std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
|
||||
std::vector<std::pair<std::chrono::system_clock::time_point, const Regular*>> made;
|
||||
for(std::size_t r = 0; r < regulars.size(); r++) {
|
||||
for(std::int32_t day = 90 - static_cast<std::int32_t>(r) % 5; day >= 0; day -= regulars[r].every) {
|
||||
made.emplace_back(now - std::chrono::hours(24 * day + 1 + static_cast<std::int32_t>(r) * 2), ®ulars[r]);
|
||||
}
|
||||
}
|
||||
std::ranges::sort(made, {}, [](const auto& entry) { return entry.first; });
|
||||
for(const auto& [at, regular] : made) {
|
||||
bunq.AddPayment(current, regular->amount, regular->name, regular->iban, regular->description, json{{"created", FormatTimestamp(at)}, {"type", regular->type}, {"sub_type", regular->subType}});
|
||||
}
|
||||
{
|
||||
// What the bank makes from here on is made now, after all of that.
|
||||
std::lock_guard lock(bunq.mutex);
|
||||
bunq.clock = static_cast<std::uint32_t>(std::chrono::duration_cast<std::chrono::minutes>(now - ParseTimestamp("2026-10-01 10:00:00")).count());
|
||||
}
|
||||
bunq.AddCard(robin, "ACTIVE", json{{"name_on_card", "R. Walker"}, {"second_line", ""}, {"label_monetary_account_current", json{{"iban", currentIban}}}});
|
||||
bunq.AddCard(robin, "DEACTIVATED", json{{"name_on_card", "R. Walker"}, {"second_line", "Travel"}, {"product_type", "MAESTRO_DEBIT"}, {"primary_account_numbers", json::array({json{{"four_digit", "8841"}}})}, {"label_monetary_account_current", json{{"iban", holidayIban}}}});
|
||||
// And a virtual one, which bunq has as deactivated however well it pays.
|
||||
bunq.AddCard(robin, "DEACTIVATED", json{{"order_status", "VIRTUAL_DELIVERY"}, {"name_on_card", "R. Walker"}, {"second_line", "Online"}, {"primary_account_numbers", json::array({json{{"four_digit", "5512"}}})}, {"label_monetary_account_current", json{{"iban", currentIban}}}});
|
||||
}
|
||||
|
||||
// What a connected user has besides payments: a request sent, one received, a schedule and a draft.
|
||||
void Furnish(Client& robin) {
|
||||
robin.AddBunq("sandbox_demo_friend", "*", "");
|
||||
robin.Request(friendIban, currentIban, "Robin Walker", 1875, "Concert tickets");
|
||||
robin.RemoveConnector("Nora White");
|
||||
robin.Request(currentIban, friendIban, "Nora White", 1250, "Lunch");
|
||||
robin.Schedule(currentIban, savingsIban, "Robin Walker", 20000, "Savings", BunqSchedule{.start = std::chrono::system_clock::now() + std::chrono::hours(24 * 5), .unit = "MONTHLY"});
|
||||
robin.Draft(currentIban, "NL70ASNB0700000111", "Millbrook Dental", 8900, "Check-up");
|
||||
robin.AddBunqOAuth("sandbox", "fake-client", "fake-secret", "http://127.0.0.1/cb", "demo-code");
|
||||
}
|
||||
}
|
||||
|
||||
// main's signature is C's; past it the arguments are string views.
|
||||
// lint-disable-next-line no-char-pointer
|
||||
int main(int argc, char* argv[]) {
|
||||
// nostrod, and each of its workers, is this executable again.
|
||||
if(Fake::IsNostrod()) {
|
||||
Fake::Bunq::RedirectFromEnvironment();
|
||||
return NostrodMain(argc, argv);
|
||||
}
|
||||
|
||||
const std::vector<std::string_view> args(argv + 1, argv + argc);
|
||||
try {
|
||||
fs::path directory = fs::temp_directory_path() / std::format("nostro-fake-system-{}", getpid());
|
||||
std::uint16_t port = 47390;
|
||||
Fake::Polkit polkit = Fake::Polkit::Allow;
|
||||
std::uint32_t bankDelay = 0;
|
||||
bool empty = false;
|
||||
std::vector<std::string> run;
|
||||
const auto value = [&args](std::size_t index) {
|
||||
if(index >= args.size()) {
|
||||
throw std::invalid_argument(std::format("{} needs a value", args[index - 1]));
|
||||
}
|
||||
return args[index];
|
||||
};
|
||||
for(std::size_t i = 0; i < args.size(); i++) {
|
||||
if(args[i] == "--dir") {
|
||||
directory = value(++i);
|
||||
} else if(args[i] == "--port") {
|
||||
const std::string_view text = value(++i);
|
||||
if(std::from_chars(text.data(), text.data() + text.size(), port).ec != std::errc()) {
|
||||
throw std::invalid_argument(std::format("'{}' is not a port", text));
|
||||
}
|
||||
} else if(args[i] == "--polkit") {
|
||||
static constexpr std::array<std::pair<std::string_view, Fake::Polkit>, 7> answers = {{
|
||||
{"allow", Fake::Polkit::Allow}, {"password", Fake::Polkit::Password}, {"deny", Fake::Polkit::Deny}, {"dismiss", Fake::Polkit::Dismiss},
|
||||
{"absent", Fake::Polkit::Absent}, {"silent", Fake::Polkit::Silent}, {"slow", Fake::Polkit::Slow},
|
||||
}};
|
||||
const auto found = std::ranges::find(answers, value(++i), &std::pair<std::string_view, Fake::Polkit>::first);
|
||||
if(found == answers.end()) {
|
||||
throw std::invalid_argument(std::format("unknown answer '{}' in --polkit", args[i]));
|
||||
}
|
||||
polkit = found->second;
|
||||
} else if(args[i] == "--bank-delay") {
|
||||
const std::string_view text = value(++i);
|
||||
if(std::from_chars(text.data(), text.data() + text.size(), bankDelay).ec != std::errc()) {
|
||||
throw std::invalid_argument(std::format("'{}' is not a number of milliseconds", text));
|
||||
}
|
||||
} else if(args[i] == "--empty") {
|
||||
empty = true;
|
||||
} else if(args[i] == "--run") {
|
||||
run.assign(args.begin() + static_cast<std::ptrdiff_t>(i) + 1, args.end());
|
||||
if(run.empty()) {
|
||||
throw std::invalid_argument("--run needs a program");
|
||||
}
|
||||
break;
|
||||
} else {
|
||||
throw std::invalid_argument(std::format("unknown argument '{}'", args[i]));
|
||||
}
|
||||
}
|
||||
|
||||
fs::create_directories(directory);
|
||||
const fs::path socket = directory / "bus";
|
||||
fs::remove(socket);
|
||||
// What nostrod and the program read from the environment, and the signals this waits for, are set before any
|
||||
// thread starts.
|
||||
setenv("XDG_DATA_HOME", (directory / "data").c_str(), 1);
|
||||
Fake::Bunq::ExportRedirect(port, directory / "bunq.pem");
|
||||
setenv("DBUS_SYSTEM_BUS_ADDRESS", Fake::Bus::Address(socket).c_str(), 1);
|
||||
sigset_t ending{};
|
||||
sigemptyset(&ending);
|
||||
sigaddset(&ending, SIGINT);
|
||||
sigaddset(&ending, SIGTERM);
|
||||
sigprocmask(SIG_BLOCK, &ending, nullptr);
|
||||
|
||||
std::int32_t status = 0;
|
||||
{
|
||||
Fake::Bus bus(socket);
|
||||
{
|
||||
// Whoever runs this is the one user of the fake system, under the name "you".
|
||||
std::lock_guard lock(bus.mutex);
|
||||
bus.clientUid = getuid();
|
||||
bus.logindNames = {{getuid(), "you"}};
|
||||
}
|
||||
Fake::Bunq bunq(port);
|
||||
Fill(bunq);
|
||||
const pid_t nostrod = Fake::StartNostrod({"--state", (directory / "state").string(), "--idle", "3600", "--prompt-timeout", "120"});
|
||||
if(!bus.WaitForName(busName)) {
|
||||
throw std::runtime_error("nostrod did not come up on the fake bus");
|
||||
}
|
||||
if(!empty) {
|
||||
Client robin = Client::System();
|
||||
robin.AddBunq(demoKey, "*", "");
|
||||
Furnish(robin);
|
||||
}
|
||||
{
|
||||
std::lock_guard lock(bus.mutex);
|
||||
bus.polkit = polkit;
|
||||
}
|
||||
{
|
||||
// From here on, once the user is furnished: the bank takes its time.
|
||||
std::lock_guard lock(bunq.mutex);
|
||||
bunq.latency = std::chrono::milliseconds(bankDelay);
|
||||
}
|
||||
std::println("nostro-fake-system: DBUS_SYSTEM_BUS_ADDRESS={}", Fake::Bus::Address(socket));
|
||||
if(empty) {
|
||||
std::println("nostro-fake-system: nothing is connected; the made-up bank's API key is {}", demoKey);
|
||||
}
|
||||
std::fflush(stdout);
|
||||
|
||||
if(run.empty()) {
|
||||
std::int32_t signal = 0;
|
||||
sigwait(&ending, &signal);
|
||||
} else {
|
||||
// posix_spawn takes C strings.
|
||||
// lint-disable-next-line no-char-pointer
|
||||
std::vector<char*> arguments;
|
||||
for(std::string& argument : run) {
|
||||
arguments.push_back(argument.data());
|
||||
}
|
||||
arguments.push_back(nullptr);
|
||||
// The program ends on the signals this waits for, by itself.
|
||||
posix_spawnattr_t attributes{};
|
||||
posix_spawnattr_init(&attributes);
|
||||
sigset_t none{};
|
||||
sigemptyset(&none);
|
||||
posix_spawnattr_setsigmask(&attributes, &none);
|
||||
posix_spawnattr_setflags(&attributes, POSIX_SPAWN_SETSIGMASK);
|
||||
pid_t program = -1;
|
||||
const std::int32_t spawned = posix_spawnp(&program, arguments.front(), nullptr, &attributes, arguments.data(), environ);
|
||||
posix_spawnattr_destroy(&attributes);
|
||||
if(spawned != 0) {
|
||||
throw std::system_error(spawned, std::generic_category(), std::format("cannot run {}", run.front()));
|
||||
}
|
||||
status = Fake::Wait(program);
|
||||
}
|
||||
bus.Disconnect(busName);
|
||||
Fake::Wait(nostrod);
|
||||
}
|
||||
return status;
|
||||
} catch(const std::exception& e) {
|
||||
std::println(std::cerr, "nostro-fake-system: {}", e.what());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
398
tests/ShouldAnswerAsynchronously/main.cpp
Normal file
398
tests/ShouldAnswerAsynchronously/main.cpp
Normal file
|
|
@ -0,0 +1,398 @@
|
|||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// Nostro::Client's asynchronous calls, as a program with an event loop makes them: each method once, every way an answer
|
||||
// fails, and what a Pending does. nostrod is this executable again (nostrod's main is compiled in), on a fake system bus
|
||||
// (tests/Support/FakeBus.inc) in front of a fake bunq (tests/Support/FakeBunq.inc), and every answer arrives through an
|
||||
// sd-event loop.
|
||||
|
||||
#include "../../lib/json.hpp"
|
||||
#include <poll.h>
|
||||
#include <signal.h>
|
||||
#include <spawn.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/resource.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/un.h>
|
||||
#include <sys/wait.h>
|
||||
#include <systemd/sd-bus.h>
|
||||
#include <systemd/sd-event.h>
|
||||
#include <systemd/sd-id128.h>
|
||||
#include <unistd.h>
|
||||
|
||||
import std;
|
||||
import Nostro;
|
||||
import Crafter.Network;
|
||||
|
||||
#define main NostrodMain
|
||||
#include "../../implementations/nostrod.cpp"
|
||||
#undef main
|
||||
|
||||
#include "../Support/Check.inc"
|
||||
#include "../Support/FakeBunq.inc"
|
||||
#include "../Support/FakeBus.inc"
|
||||
|
||||
using namespace Nostro;
|
||||
using Test::Check;
|
||||
using Test::Equal;
|
||||
using Test::Throws;
|
||||
using json = nlohmann::json;
|
||||
using Fault = Fake::Fault;
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace {
|
||||
constexpr std::uint16_t port = 47306;
|
||||
constexpr std::uint32_t aliceUid = 4242;
|
||||
constexpr std::uint32_t bobUid = 4343;
|
||||
constexpr std::string_view name = "net.catcrafts.Nostro1";
|
||||
const std::string aliceMain = "NL23BUNQ2025123456";
|
||||
const std::string bobIban = "NL67BUNQ2025654321";
|
||||
const std::string carolIban = "NL65BUNQ2025222222";
|
||||
|
||||
using Summaries = std::vector<ConnectorSummary>;
|
||||
|
||||
// A client for user `uid`: the fake bus gives each new connection the uid it is set to.
|
||||
Client As(Fake::Bus& bus, std::uint32_t uid, std::chrono::seconds timeout = std::chrono::minutes(10)) {
|
||||
{
|
||||
std::lock_guard lock(bus.mutex);
|
||||
bus.clientUid = uid;
|
||||
}
|
||||
return Client::System(timeout);
|
||||
}
|
||||
|
||||
void SetPolkit(Fake::Bus& bus, Fake::Polkit outcome, std::string_view action = {}) {
|
||||
std::lock_guard lock(bus.mutex);
|
||||
if(action.empty()) {
|
||||
bus.polkit = outcome;
|
||||
bus.polkitByAction.clear();
|
||||
} else {
|
||||
bus.polkitByAction[std::string(action)] = outcome;
|
||||
}
|
||||
}
|
||||
|
||||
// Runs the loop until `done` says so, for at most `limit`; whether it did.
|
||||
template<typename Done>
|
||||
bool RunUntil(sd_event* loop, Done&& done, std::chrono::seconds limit = std::chrono::seconds(60)) {
|
||||
const std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::now() + limit;
|
||||
while(!done()) {
|
||||
if(std::chrono::steady_clock::now() >= deadline) {
|
||||
return false;
|
||||
}
|
||||
sd_event_run(loop, 100000);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// What the call `start` makes (given its `then`, it returns its Pending) answers, once the loop has delivered it.
|
||||
template<typename T, typename Start>
|
||||
Answer<T> Await(sd_event* loop, Start&& start, std::source_location where = std::source_location::current()) {
|
||||
std::optional<Answer<T>> answer;
|
||||
const Client::Pending pending = start([&answer](Answer<T> got) { answer = std::move(got); });
|
||||
Check(pending.Active(), "a call waits for its answer", where);
|
||||
Check(RunUntil(loop, [&answer] { return answer.has_value(); }), "and gets it", where);
|
||||
Check(!pending.Active(), "and waits no more once it has", where);
|
||||
if(!answer) {
|
||||
std::exit(Test::Result());
|
||||
}
|
||||
return std::move(*answer);
|
||||
}
|
||||
|
||||
// The result of the call `start` makes, which must work.
|
||||
template<typename T, typename Start>
|
||||
T Result(sd_event* loop, Start&& start, std::source_location where = std::source_location::current()) {
|
||||
Answer<T> answer = Await<T>(loop, std::forward<Start>(start), where);
|
||||
Check(!answer.Failed() && answer.Error() == nullptr, "the call works", where);
|
||||
try {
|
||||
return std::move(answer.Get());
|
||||
} catch(const std::exception& e) {
|
||||
Check(false, e.what(), where);
|
||||
std::exit(Test::Result());
|
||||
}
|
||||
}
|
||||
|
||||
// The D-Bus name of the DaemonError an answer failed with; "other" for another exception, "none" when it worked.
|
||||
template<typename T>
|
||||
std::string NameOf(Answer<T>& answer) {
|
||||
try {
|
||||
answer.Get();
|
||||
} catch(const DaemonError& e) {
|
||||
return e.name;
|
||||
} catch(const std::exception&) {
|
||||
return "other";
|
||||
}
|
||||
return "none";
|
||||
}
|
||||
|
||||
// A stand-in for nostrod that answers every call with a string, an answer of another shape than any method's. A
|
||||
// plain object rather than a vtable, whose answers sd-bus would hold to their signature.
|
||||
class StandIn {
|
||||
public:
|
||||
StandIn() {
|
||||
sd_bus_open_system(&bus);
|
||||
sd_bus_add_object(bus, nullptr, "/net/catcrafts/Nostro1", OnCall, nullptr);
|
||||
sd_bus_request_name(bus, "net.catcrafts.Nostro1", 0);
|
||||
thread = std::thread([this] {
|
||||
while(!stop) {
|
||||
while(sd_bus_process(bus, nullptr) > 0) {
|
||||
}
|
||||
sd_bus_wait(bus, 20000);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
StandIn(const StandIn&) = delete;
|
||||
StandIn& operator=(const StandIn&) = delete;
|
||||
|
||||
~StandIn() {
|
||||
stop = true;
|
||||
thread.join();
|
||||
sd_bus_flush_close_unref(bus);
|
||||
}
|
||||
|
||||
private:
|
||||
static std::int32_t OnCall(sd_bus_message* call, void*, sd_bus_error*) {
|
||||
return sd_bus_reply_method_return(call, "s", "not what was asked");
|
||||
}
|
||||
|
||||
sd_bus* bus = nullptr;
|
||||
std::atomic<bool> stop = false;
|
||||
std::thread thread;
|
||||
};
|
||||
|
||||
// Before nostrod runs: calls the client refuses itself, no daemon, and an answer that cannot be read.
|
||||
void WithoutNostrod(Fake::Bus& bus, sd_event* loop) {
|
||||
Client unattached = As(bus, aliceUid);
|
||||
Throws<std::logic_error>([&unattached] { const Client::Pending pending = unattached.Connectors([](Answer<Summaries>) {}); }, "attached to no event loop", "an answer to wait for needs a loop to wait in");
|
||||
|
||||
Client client = As(bus, aliceUid);
|
||||
client.Attach(loop);
|
||||
Check(client.Connected(), "a new client is connected");
|
||||
Throws<std::system_error>([&client, loop] { client.Attach(loop); }, "attach to an event loop", "and attached once");
|
||||
|
||||
Answer<Summaries> missing = Await<Summaries>(loop, [&client](auto then) { return client.Connectors(std::move(then)); });
|
||||
Throws<DaemonMissing>([&missing] { missing.Get(); }, "nostrod is not running", "nostrod not on the bus");
|
||||
|
||||
{
|
||||
const StandIn stand;
|
||||
Check(bus.WaitForName(name), "a stand-in owns nostrod's name");
|
||||
Answer<Summaries> odd = Await<Summaries>(loop, [&client](auto then) { return client.Connectors(std::move(then)); });
|
||||
Check(odd.Failed() && odd.notes.empty(), "an answer that cannot be read fails");
|
||||
Throws<std::system_error>([&odd] { odd.Get(); }, "cannot read", "with what reading it threw");
|
||||
}
|
||||
Check(bus.WaitForName(name, false), "the stand-in lets go of the name");
|
||||
}
|
||||
|
||||
// Each method once, with what it answers.
|
||||
void EveryMethod(Fake::Bus& bus, Fake::Bunq& bunq, std::uint64_t alice, sd_event* loop) {
|
||||
Client client = As(bus, aliceUid);
|
||||
client.Attach(loop);
|
||||
Check(Result<Summaries>(loop, [&client](auto then) { return client.Connectors(std::move(then)); }).empty(), "a new user has no connectors");
|
||||
const AddedConnector added = Result<AddedConnector>(loop, [&client](auto then) { return client.AddBunq("key-alice", "*", "", std::move(then)); });
|
||||
Check(added.name == "Alice" && added.environment == "production" && added.accounts == 1, "a connector added");
|
||||
Equal(Result<Summaries>(loop, [&client](auto then) { return client.Connectors(std::move(then)); }).size(), std::size_t{1}, "and listed");
|
||||
const std::vector<ConnectorAccounts> accounts = Result<std::vector<ConnectorAccounts>>(loop, [&client](auto then) { return client.Accounts(std::move(then)); });
|
||||
Check(accounts.size() == 1 && accounts.at(0).accounts.at(0).iban == aliceMain, "its accounts");
|
||||
Check(Result<std::vector<Transaction>>(loop, [&client](auto then) { return client.Transactions(aliceMain, TransactionQuery{}, std::move(then)); }).empty(), "no transactions yet");
|
||||
|
||||
const Created sent = Result<Created>(loop, [&client](auto then) { return client.Send(aliceMain, bobIban, "Bob", 1250, "lunch", std::move(then)); });
|
||||
Check(sent.id != 0 && sent.currency == Currency::Euro, "a payment");
|
||||
const BunqSchedule schedule{.start = std::chrono::sys_days(std::chrono::year(2027) / 1 / 1), .unit = "MONTHLY"};
|
||||
Check(Result<Created>(loop, [&client, &schedule](auto then) { return client.Schedule(aliceMain, bobIban, "Bob", 300, "rent", schedule, std::move(then)); }).id != 0, "a schedule");
|
||||
Check(Result<Created>(loop, [&client](auto then) { return client.Draft(aliceMain, bobIban, "Bob", 200, "", std::move(then)); }).id != 0, "a draft");
|
||||
const BunqPaymentRequest asked = Result<BunqPaymentRequest>(loop, [&client](auto then) { return client.Request(aliceMain, bobIban, "Bob", 500, "back", std::move(then)); });
|
||||
Check(asked.id != 0 && asked.amount == 500, "a request");
|
||||
Equal(Result<std::vector<BunqPaymentRequest>>(loop, [&client](auto then) { return client.Requests(aliceMain, std::move(then)); }).size(), std::size_t{1}, "the request listed");
|
||||
Result<std::monostate>(loop, [&client, &asked](auto then) { return client.RevokeRequest(aliceMain, asked.id, std::move(then)); });
|
||||
|
||||
Client bob = As(bus, bobUid);
|
||||
bob.AddBunq("key-bob", "*", "");
|
||||
bob.Request(bobIban, aliceMain, "Alice", 700, "rent");
|
||||
const std::vector<BunqIncomingRequest> owed = Result<std::vector<BunqIncomingRequest>>(loop, [&client](auto then) { return client.IncomingRequests(aliceMain, std::move(then)); });
|
||||
Check(!owed.empty() && owed.at(0).amount == 700, "a request received");
|
||||
Result<std::monostate>(loop, [&client, &owed](auto then) { return client.RespondToRequest(aliceMain, owed.at(0).id, false, std::move(then)); });
|
||||
|
||||
const std::vector<BunqScheduledPayment> scheduled = Result<std::vector<BunqScheduledPayment>>(loop, [&client](auto then) { return client.ScheduledPayments(aliceMain, std::move(then)); });
|
||||
Check(!scheduled.empty() && scheduled.at(0).schedule.unit == "MONTHLY", "the schedule listed");
|
||||
Result<std::monostate>(loop, [&client, &scheduled](auto then) { return client.CancelScheduledPayment(aliceMain, scheduled.at(0).id, std::move(then)); });
|
||||
const std::vector<BunqDraftPayment> drafts = Result<std::vector<BunqDraftPayment>>(loop, [&client](auto then) { return client.DraftPayments(aliceMain, std::move(then)); });
|
||||
Check(!drafts.empty(), "the draft listed");
|
||||
Result<std::monostate>(loop, [&client, &drafts](auto then) { return client.RespondToDraftPayment(aliceMain, drafts.at(0).id, false, std::move(then)); });
|
||||
|
||||
const std::uint64_t card = bunq.AddCard(alice, "ACTIVE");
|
||||
Check(!Result<std::vector<ConnectorCards>>(loop, [&client](auto then) { return client.Cards(std::move(then)); }).at(0).cards.empty(), "the cards");
|
||||
Equal(Result<BunqCard>(loop, [&client, card](auto then) { return client.SetCardStatus(card, "DEACTIVATED", std::move(then)); }).status, std::string("DEACTIVATED"), "a card frozen");
|
||||
|
||||
Check(!Result<std::optional<Account>>(loop, [&client](auto then) { return client.DefaultCheckoutAccount(std::move(then)); }).has_value(), "no account pays checkouts yet");
|
||||
Equal(Result<Account>(loop, [&client](auto then) { return client.SetDefaultCheckoutAccount(aliceMain, std::move(then)); }).iban, aliceMain, "until one is chosen");
|
||||
|
||||
const AddedConnector oauth = Result<AddedConnector>(loop, [&client, &bunq](auto then) { return client.AddBunqOAuth("production", bunq.clientId, bunq.clientSecret, "http://127.0.0.1/cb", "code-carol", std::move(then)); });
|
||||
Equal(oauth.name, std::string("Carol"), "a connector through OAuth");
|
||||
}
|
||||
|
||||
// Every way an answer fails, as the blocking calls throw it.
|
||||
void Failures(Fake::Bus& bus, Fake::Bunq& bunq, sd_event* loop) {
|
||||
Client client = As(bus, aliceUid);
|
||||
client.Attach(loop);
|
||||
Answer<Created> unknown = Await<Created>(loop, [&client](auto then) { return client.Send("Nope", bobIban, "Bob", 100, "", std::move(then)); });
|
||||
Check(unknown.Failed() && unknown.Error() != nullptr && unknown.notes.empty(), "a refusal is a failed answer, without notes");
|
||||
Throws<std::invalid_argument>([&unknown] { unknown.Get(); }, "no account is called or has IBAN 'Nope'", "input nostrod refuses");
|
||||
|
||||
SetPolkit(bus, Fake::Polkit::Dismiss, Bus::actionPay);
|
||||
Answer<Created> dismissed = Await<Created>(loop, [&client](auto then) { return client.Send(aliceMain, bobIban, "Bob", 100, "", std::move(then)); });
|
||||
Equal(NameOf(dismissed), std::string(Bus::errorCancelled), "a dialog closed without a password");
|
||||
SetPolkit(bus, Fake::Polkit::Allow);
|
||||
|
||||
bunq.Fail(Fault{.method = "POST", .path = "/user/", .status = 400, .body = R"({"Error":[{"error_description":"Not enough money."}]})"});
|
||||
Answer<Created> poor = Await<Created>(loop, [&client](auto then) { return client.Send(aliceMain, bobIban, "Bob", 100, "", std::move(then)); });
|
||||
Equal(NameOf(poor), std::string(Bus::errorBank), "bunq's refusal");
|
||||
|
||||
// bunq's 5xx to a payment leaves open whether it was made, which the Bank error's message says at its end.
|
||||
bunq.Fail(Fault{.method = "POST", .path = "/user/", .status = 500, .body = R"({"Error":[{"error_description":"Hiccup."}]})"});
|
||||
Answer<Created> hiccup = Await<Created>(loop, [&client](auto then) { return client.Send(aliceMain, bobIban, "Bob", 100, "", std::move(then)); });
|
||||
Throws<OutcomeUnknown>([&hiccup] { hiccup.Get(); }, "Hiccup. (500); the request may have been carried out", "a payment bunq answered with a 5xx may have been made");
|
||||
|
||||
bunq.Fail(Fault{.method = "POST", .path = "/user/", .status = 403, .body = R"({"Error":[{"error_description":"Not allowed for this user."}]})"});
|
||||
Answer<Created> oauth = Await<Created>(loop, [&client](auto then) { return client.Send(carolIban, bobIban, "Bob", 100, "", std::move(then)); });
|
||||
Equal(NameOf(oauth), std::string(Bus::errorOAuthCannotPay), "an OAuth connector paying someone else");
|
||||
|
||||
// No answer in time: a payment may have been made, a listing is only late.
|
||||
Client hurried = As(bus, aliceUid, std::chrono::seconds(1));
|
||||
hurried.Attach(loop);
|
||||
SetPolkit(bus, Fake::Polkit::Silent);
|
||||
Answer<Created> lost = Await<Created>(loop, [&hurried](auto then) { return hurried.Send(aliceMain, bobIban, "Bob", 100, "", std::move(then)); });
|
||||
Throws<OutcomeUnknown>([&lost] { lost.Get(); }, "may have been carried out", "a payment without an answer");
|
||||
Answer<Summaries> late = Await<Summaries>(loop, [&hurried](auto then) { return hurried.Connectors(std::move(then)); });
|
||||
const std::string lateName = NameOf(late);
|
||||
Check(lateName == SD_BUS_ERROR_NO_REPLY || lateName == SD_BUS_ERROR_TIMEOUT, std::format("a listing without an answer is only that: {}", lateName));
|
||||
SetPolkit(bus, Fake::Polkit::Allow);
|
||||
}
|
||||
|
||||
// A Pending dropped, cancelled, moved or assigned over: only the one that still waits gets the answer.
|
||||
void Pendings(Fake::Bus& bus, sd_event* loop) {
|
||||
Client client = As(bus, aliceUid);
|
||||
client.Attach(loop);
|
||||
// Authorized a second later, so each call is still waiting while this looks at it.
|
||||
SetPolkit(bus, Fake::Polkit::Slow, Bus::actionView);
|
||||
bool dropped = false;
|
||||
Client::Pending cancelled = client.Connectors([&dropped](Answer<Summaries>) { dropped = true; });
|
||||
Check(cancelled.Active(), "a call waits");
|
||||
cancelled.Cancel();
|
||||
Check(!cancelled.Active(), "until it is cancelled");
|
||||
cancelled.Cancel();
|
||||
{
|
||||
const Client::Pending forgotten = client.Connectors([&dropped](Answer<Summaries>) { dropped = true; });
|
||||
}
|
||||
|
||||
bool delivered = false;
|
||||
Client::Pending first = client.Connectors([&delivered](Answer<Summaries>) { delivered = true; });
|
||||
Client::Pending second(std::move(first));
|
||||
Check(!first.Active() && second.Active(), "a moved Pending waits in its new place");
|
||||
Client::Pending third;
|
||||
Check(!third.Active(), "an empty one waits for nothing");
|
||||
third = std::move(second);
|
||||
Client::Pending overwritten = client.Connectors([&dropped](Answer<Summaries>) { dropped = true; });
|
||||
overwritten = std::move(third);
|
||||
Check(overwritten.Active(), "assigned over, it waits for what it was given");
|
||||
Check(RunUntil(loop, [&delivered] { return delivered; }), "which is delivered");
|
||||
// The others would have been answered by now, had they not been dropped.
|
||||
RunUntil(loop, [] { return false; }, std::chrono::seconds(2));
|
||||
Check(!dropped, "and nothing that was dropped is");
|
||||
SetPolkit(bus, Fake::Polkit::Allow);
|
||||
}
|
||||
|
||||
struct NotAnException {
|
||||
};
|
||||
|
||||
// A `then` that throws: what it threw goes to the notes, never into sd-bus.
|
||||
void Throwing(Fake::Bus& bus, sd_event* loop) {
|
||||
std::vector<std::string> notes;
|
||||
const std::function<void(std::string_view)> sink = noteSink;
|
||||
noteSink = [¬es](std::string_view note) { notes.emplace_back(note); };
|
||||
Client client = As(bus, aliceUid);
|
||||
client.Attach(loop);
|
||||
bool reached = false;
|
||||
{
|
||||
const Client::Pending pending = client.Connectors([&reached](Answer<Summaries>) {
|
||||
reached = true;
|
||||
throw std::runtime_error("the handler broke");
|
||||
});
|
||||
Check(RunUntil(loop, [&reached] { return reached; }), "a then that throws is called");
|
||||
}
|
||||
reached = false;
|
||||
{
|
||||
const Client::Pending pending = client.Connectors([&reached](Answer<Summaries>) {
|
||||
reached = true;
|
||||
throw NotAnException();
|
||||
});
|
||||
Check(RunUntil(loop, [&reached] { return reached; }), "and one that throws something else");
|
||||
}
|
||||
noteSink = sink;
|
||||
Check(notes.size() == 2 && notes.at(0) == "nostrod's answer to Connectors could not be handled: the handler broke" && notes.at(1) == "nostrod's answer to Connectors could not be handled", "what they threw is noted");
|
||||
}
|
||||
|
||||
void Remove(Fake::Bus& bus, sd_event* loop) {
|
||||
Client client = As(bus, aliceUid);
|
||||
client.Attach(loop);
|
||||
Equal(Result<std::string>(loop, [&client](auto then) { return client.RemoveConnector("Carol", std::move(then)); }), std::string("Carol"), "a connector removed");
|
||||
}
|
||||
|
||||
// The library's warnings come with the answer of the call they were given during, not into the client's own notes.
|
||||
void Notes(Fake::Bus& bus, Fake::Bunq& bunq, sd_event* loop) {
|
||||
Client bob = As(bus, bobUid);
|
||||
bob.Attach(loop);
|
||||
{
|
||||
std::lock_guard lock(bunq.mutex);
|
||||
bunq.keys.erase("key-bob");
|
||||
}
|
||||
bunq.ExpireSessions();
|
||||
const Answer<std::vector<ConnectorAccounts>> answer = Await<std::vector<ConnectorAccounts>>(loop, [&bob](auto then) { return bob.Accounts(std::move(then)); });
|
||||
Check(!answer.Failed() && !answer.notes.empty() && std::ranges::all_of(answer.notes, [](const std::string& note) { return note.contains("bunq connector 'Bob' is unavailable"); }), "a connector that cannot be reached comes with the answer as a note");
|
||||
Check(bob.TakeNotes().empty(), "and not into the client's notes");
|
||||
}
|
||||
}
|
||||
|
||||
// main's signature is C's.
|
||||
// lint-disable-next-line no-char-pointer
|
||||
int main(int argc, char* argv[]) {
|
||||
// nostrod, and each of its workers, is this executable again.
|
||||
if(Fake::IsNostrod()) {
|
||||
Fake::Bunq::RedirectFromEnvironment();
|
||||
return NostrodMain(argc, argv);
|
||||
}
|
||||
|
||||
const Test::Directory directory("async");
|
||||
const fs::path state = directory.path / "state";
|
||||
// What nostrod reads from the environment is set before any thread starts.
|
||||
setenv("XDG_DATA_HOME", (directory.path / "data").c_str(), 1);
|
||||
Fake::Bunq::ExportRedirect(port, directory.path / "bunq.pem");
|
||||
setenv("DBUS_SYSTEM_BUS_ADDRESS", Fake::Bus::Address(directory.path / "bus").c_str(), 1);
|
||||
Fake::Bus bus(directory.path / "bus");
|
||||
{
|
||||
std::lock_guard lock(bus.mutex);
|
||||
bus.logindNames = {{aliceUid, "alice"}, {bobUid, "bob"}};
|
||||
}
|
||||
|
||||
Fake::Bunq bunq(port);
|
||||
const std::uint64_t alice = bunq.AddPerson("Alice", "key-alice");
|
||||
bunq.AddAccount(alice, aliceMain, "Main", 100000);
|
||||
bunq.AddAccount(bunq.AddPerson("Bob", "key-bob"), bobIban, "Bob's", 0);
|
||||
const std::uint64_t carol = bunq.AddPerson("Carol", "key-carol");
|
||||
bunq.AddAccount(carol, carolIban, "Shared", 500);
|
||||
bunq.AddGrant(carol, "code-carol", "token-carol");
|
||||
|
||||
sd_event* loop = nullptr;
|
||||
sd_event_new(&loop);
|
||||
WithoutNostrod(bus, loop);
|
||||
const pid_t nostrod = Fake::StartNostrod({"--state", state.string(), "--idle", "60", "--prompt-timeout", "2"});
|
||||
Check(bus.WaitForName(name), "nostrod owns its name");
|
||||
EveryMethod(bus, bunq, alice, loop);
|
||||
Failures(bus, bunq, loop);
|
||||
Pendings(bus, loop);
|
||||
Throwing(bus, loop);
|
||||
Remove(bus, loop);
|
||||
Notes(bus, bunq, loop);
|
||||
bus.Disconnect(name);
|
||||
Equal(Fake::Wait(nostrod), 0, "nostrod ends when the bus goes");
|
||||
sd_event_unref(loop);
|
||||
return Test::Result();
|
||||
}
|
||||
1236
tests/ShouldBuildFrames/main.cpp
Normal file
1236
tests/ShouldBuildFrames/main.cpp
Normal file
File diff suppressed because it is too large
Load diff
1870
tests/ShouldDriveTheApp/main.cpp
Normal file
1870
tests/ShouldDriveTheApp/main.cpp
Normal file
File diff suppressed because it is too large
Load diff
195
tests/ShouldEditText/main.cpp
Normal file
195
tests/ShouldEditText/main.cpp
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// A text field's editing by code point: one to four bytes of UTF-8, the selection, what each kind of field takes,
|
||||
// the input method's composing text and its deletions, and a secret that is wiped when it goes.
|
||||
|
||||
import std;
|
||||
import Nostro.Ui;
|
||||
|
||||
#include "../Support/Check.inc"
|
||||
|
||||
using namespace Nostro::Ui;
|
||||
using Test::Check;
|
||||
using Test::Equal;
|
||||
|
||||
namespace {
|
||||
// a, é, € and 😀: one, two, three and four bytes; boundaries 0 1 3 6 10.
|
||||
const std::string mixed = "aé€\U0001F600";
|
||||
|
||||
void Put(EditState& field, std::string_view value, std::size_t cursor) {
|
||||
field.Set(value);
|
||||
field.MoveTo(cursor);
|
||||
}
|
||||
|
||||
void Keys() {
|
||||
EditState field;
|
||||
Check(field.Empty() && field.kind == FieldKind::Text, "a new field is empty, and takes prose");
|
||||
Put(field, mixed, 10);
|
||||
Check(field.Apply(EditKey::Backspace) && field.cursor == 6 && field.value == "aé€", "Backspace takes the four-byte emoji");
|
||||
Put(field, mixed, 1);
|
||||
Check(field.Apply(EditKey::Delete) && field.cursor == 1 && field.value == "a€\U0001F600", "Delete takes the two-byte é");
|
||||
Put(field, "abc", 0);
|
||||
Check(!field.Apply(EditKey::Backspace) && field.value == "abc" && field.cursor == 0, "Backspace at the start deletes nothing and says so");
|
||||
Put(field, "abc", 3);
|
||||
Check(!field.Apply(EditKey::Delete) && field.value == "abc" && field.cursor == 3, "Delete at the end deletes nothing and says so");
|
||||
|
||||
Put(field, mixed, 6);
|
||||
Check(field.Apply(EditKey::Left) && field.cursor == 3, "Left moves back over the three-byte €");
|
||||
Check(field.Apply(EditKey::Right) && field.cursor == 6, "Right moves over it again");
|
||||
Put(field, "ab", 0);
|
||||
Check(field.Apply(EditKey::Left) && field.cursor == 0, "Left at the start stays, and is still a move");
|
||||
Put(field, "ab", 2);
|
||||
Check(field.Apply(EditKey::Right) && field.cursor == 2, "Right at the end stays, and is still a move");
|
||||
Put(field, "hello", 2);
|
||||
Check(field.Apply(EditKey::Home) && field.cursor == 0 && field.Apply(EditKey::End) && field.cursor == 5, "Home and End go to the line's ends");
|
||||
|
||||
Put(field, mixed, 2);
|
||||
Equal(field.cursor, std::size_t{1}, "a cursor asked for inside a character goes to its start");
|
||||
Put(field, mixed, 99);
|
||||
Equal(field.cursor, std::size_t{10}, "and one past the end to the end");
|
||||
}
|
||||
|
||||
void Selecting() {
|
||||
EditState field;
|
||||
Put(field, "hello world", 5);
|
||||
Check(!field.HasSelection() && field.Selected().empty(), "a cursor alone selects nothing");
|
||||
field.Apply(EditKey::Right, true);
|
||||
field.Apply(EditKey::End, true);
|
||||
Check(field.HasSelection() && field.Selected() == " world" && field.SelectionBegin() == 5 && field.SelectionEnd() == 11, "Shift with a move stretches the selection from where it began");
|
||||
field.Apply(EditKey::Home, true);
|
||||
Check(field.Selected() == "hello" && field.cursor == 0 && field.anchor == 5, "back past where it began, it selects the other way");
|
||||
field.Apply(EditKey::Left);
|
||||
Check(!field.HasSelection() && field.cursor == 0, "Left without Shift ends a selection at its start");
|
||||
field.SelectAll();
|
||||
Check(field.Selected() == "hello world" && field.cursor == 11, "everything selected, the cursor at the end");
|
||||
field.Apply(EditKey::Right);
|
||||
Check(!field.HasSelection() && field.cursor == 11, "Right ends a selection at its end");
|
||||
field.SelectAll();
|
||||
field.Apply(EditKey::Left);
|
||||
Equal(field.cursor, std::size_t{0}, "and Left at its start, wherever the cursor was");
|
||||
field.SelectAll();
|
||||
field.Apply(EditKey::Home);
|
||||
Check(!field.HasSelection() && field.cursor == 0, "Home ends it at the start of the line");
|
||||
|
||||
Put(field, "hello world", 5);
|
||||
field.Apply(EditKey::End, true);
|
||||
Check(field.Apply(EditKey::Backspace) && field.value == "hello" && field.cursor == 5 && !field.HasSelection(), "Backspace deletes what is selected, and only that");
|
||||
field.SelectAll();
|
||||
Check(field.Apply(EditKey::Delete) && field.Empty(), "so does Delete");
|
||||
Check(!field.DeleteSelection(), "with nothing selected there is nothing to delete");
|
||||
Put(field, "hello world", 0);
|
||||
field.Apply(EditKey::End, true);
|
||||
field.Commit("x");
|
||||
Check(field.value == "x" && field.cursor == 1, "what is typed takes the place of the selection");
|
||||
field.SelectAll();
|
||||
field.MoveTo(0);
|
||||
Check(!field.HasSelection(), "a tap ends a selection");
|
||||
}
|
||||
|
||||
void Kinds() {
|
||||
EditState prose;
|
||||
prose.Commit("a\tb\nc d\x01\x7f");
|
||||
Equal(prose.value, std::string("a b c d"), "a line of prose: a tab or a line break is a space, a control character nothing");
|
||||
prose.Set("\xff" "ok\xe2\x82");
|
||||
Equal(prose.value, std::string("ok"), "malformed UTF-8 is dropped");
|
||||
prose.Set("a\xEF\xBF\xBD" "b");
|
||||
Equal(prose.value, std::string("a\xEF\xBF\xBD" "b"), "a replacement character that is one is kept");
|
||||
|
||||
EditState plain(FieldKind::Plain);
|
||||
plain.Paste("NL23 BUNQ 2025\n");
|
||||
Equal(plain.value, std::string("NL23 BUNQ 2025"), "a line taken as typed keeps its spaces and drops a line break around it");
|
||||
|
||||
EditState decimal(FieldKind::Decimal);
|
||||
decimal.Paste("€ 1.234,50 EUR");
|
||||
Equal(decimal.value, std::string("1.234,50"), "an amount takes digits and separators");
|
||||
|
||||
EditState digits(FieldKind::Digits);
|
||||
digits.Commit("12,5 x");
|
||||
Equal(digits.value, std::string("125"), "a whole number takes digits");
|
||||
|
||||
EditState secret(FieldKind::Secret);
|
||||
secret.Paste(" sandbox_abc 123\n");
|
||||
Equal(secret.value, std::string("sandbox_abc123"), "a key has no space in it");
|
||||
|
||||
EditState full;
|
||||
full.Set(std::string(EditState::limit - 1, 'a'));
|
||||
full.Commit("é!");
|
||||
Check(full.value.size() == EditState::limit - 1 && full.cursor == full.value.size(), "a field takes no more than it holds, and no half character");
|
||||
full.Commit("b");
|
||||
Equal(full.value.size(), EditState::limit, "what still fits is taken");
|
||||
full.Commit("c");
|
||||
Equal(full.value.size(), EditState::limit, "and nothing after that");
|
||||
}
|
||||
|
||||
void Composing() {
|
||||
EditState field;
|
||||
Put(field, "hello", 2);
|
||||
field.preedit = "XY";
|
||||
Check(field.Shown() == "heXYllo" && field.ShownCursor() == 4 && !field.Empty(), "the composing text shows at the cursor");
|
||||
field.Commit("Z");
|
||||
Check(field.value == "heZllo" && field.preedit.empty() && field.cursor == 3, "what the input method commits takes the place of what it composed");
|
||||
field.preedit = "W";
|
||||
field.Paste("!");
|
||||
Check(field.value == "heZW!llo" && field.preedit.empty(), "what is pasted follows the composing word, which is kept");
|
||||
|
||||
// The input method's deletions: byte counts around the cursor, rounded out to code points.
|
||||
Put(field, mixed, 6);
|
||||
field.preedit = "z";
|
||||
field.DeleteAround(1, 1);
|
||||
Check(field.cursor == 3 && field.preedit == "z" && field.value == "aé", "one byte each side takes the € before and the 😀 after; the composing text stays");
|
||||
Put(field, "abc", 1);
|
||||
field.DeleteAround(5, 0);
|
||||
Check(field.cursor == 0 && field.value == "bc", "a deletion past the start stops at the start");
|
||||
Put(field, "abc", 2);
|
||||
field.DeleteAround(0, 9);
|
||||
Check(field.cursor == 2 && field.value == "ab", "and one past the end at the end");
|
||||
field.DeleteAround(0, 0);
|
||||
Check(field.cursor == 2 && field.value == "ab", "a deletion of nothing leaves the text");
|
||||
|
||||
Put(field, "hello wor", 9);
|
||||
field.preedit = "ld";
|
||||
field.CommitPreedit();
|
||||
Check(field.cursor == 11 && field.preedit.empty() && field.value == "hello world", "the composing text taken into the value, the cursor past it");
|
||||
field.CommitPreedit();
|
||||
Equal(field.value, std::string("hello world"), "with no composing text nothing changes");
|
||||
|
||||
EditState empty;
|
||||
empty.preedit = "x";
|
||||
Check(!empty.Empty(), "a field with only a composing text is not empty");
|
||||
empty.Clear();
|
||||
Check(empty.Empty() && empty.cursor == 0 && empty.anchor == 0, "cleared, nothing is left");
|
||||
}
|
||||
|
||||
void Secrets() {
|
||||
EditState secret(FieldKind::Secret);
|
||||
Check(secret.value.capacity() >= EditState::secretLimit, "a secret's buffer is its full size from the start");
|
||||
// libc++'s string keeps its buffer when it is cleared, so its address can still be read: the bytes of the key
|
||||
// must be gone from it.
|
||||
const std::string_view buffer(secret.value.data(), EditState::secretLimit);
|
||||
secret.Commit("sandbox_0123456789abcdef");
|
||||
Check(secret.value.data() == buffer.data(), "typing into it moves nothing");
|
||||
secret.Apply(EditKey::Backspace);
|
||||
secret.preedit = "composing";
|
||||
secret.CommitPreedit();
|
||||
Check(secret.value == "sandbox_0123456789abcdecomposing" && secret.value.data() == buffer.data(), "nor does an edit");
|
||||
secret.Commit(std::string(600, 'k'));
|
||||
Check(secret.value.size() == EditState::secretLimit && secret.value.data() == buffer.data(), "it takes no more than its buffer holds");
|
||||
secret.Clear();
|
||||
Check(secret.Empty() && buffer.find_first_not_of('\0') == std::string_view::npos, "cleared, no byte of it is left in memory");
|
||||
{
|
||||
EditState gone(FieldKind::Secret);
|
||||
gone.Commit("another-key");
|
||||
}
|
||||
Check(true, "a secret that goes out of scope is cleared first");
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
Keys();
|
||||
Selecting();
|
||||
Kinds();
|
||||
Composing();
|
||||
Secrets();
|
||||
return Test::Result();
|
||||
}
|
||||
466
tests/ShouldLayOutWidgets/main.cpp
Normal file
466
tests/ShouldLayOutWidgets/main.cpp
Normal file
|
|
@ -0,0 +1,466 @@
|
|||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// Nostro.Ui's layout cursors and its widgets, each in every state it has: what it draws, where, in which colours, and
|
||||
// what a press on it does. The font is a fixed one (Ui.inc); the window is 400 by 800 at a scale of one unless a
|
||||
// check says otherwise, so a size of the design is that many pixels.
|
||||
|
||||
import std;
|
||||
import Nostro.Ui;
|
||||
|
||||
#include "../Support/Check.inc"
|
||||
#include "../Support/Ui.inc"
|
||||
|
||||
using namespace Nostro::Ui;
|
||||
using Test::Check;
|
||||
using Test::Equal;
|
||||
using Test::Hides;
|
||||
using Test::Shows;
|
||||
using Test::TapAt;
|
||||
|
||||
namespace {
|
||||
constexpr Box window{0, 0, 400, 800};
|
||||
|
||||
template<typename Scene>
|
||||
void Build(Context& ui, Scene&& scene, Box bounds = window, float scale = 1) {
|
||||
Frame& frame = ui.Begin(bounds, scale, 0);
|
||||
scene(frame);
|
||||
ui.End();
|
||||
}
|
||||
|
||||
// The line of text that reads `text`, or nothing.
|
||||
const TextItem* Line(const Context& ui, std::string_view text) {
|
||||
for(std::size_t layer = 0; layer < layerCount; layer++) {
|
||||
for(const Batch& batch : ui.Shown().draw.Batches(static_cast<Layer>(layer))) {
|
||||
for(const TextItem& item : batch.texts) {
|
||||
if(item.text == text) {
|
||||
return &item;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// The boxes drawn in a colour, in the order they are drawn.
|
||||
std::vector<RectItem> Rects(const Context& ui, Color color) {
|
||||
std::vector<RectItem> rects;
|
||||
for(std::size_t layer = 0; layer < layerCount; layer++) {
|
||||
for(const Batch& batch : ui.Shown().draw.Batches(static_cast<Layer>(layer))) {
|
||||
for(const RectItem& item : batch.rects) {
|
||||
if(item.color == color) {
|
||||
rects.push_back(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return rects;
|
||||
}
|
||||
|
||||
std::size_t Circles(const Context& ui) {
|
||||
std::size_t count = 0;
|
||||
for(std::size_t layer = 0; layer < layerCount; layer++) {
|
||||
for(const Batch& batch : ui.Shown().draw.Batches(static_cast<Layer>(layer))) {
|
||||
count += batch.circles.size();
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
// Whether a line is drawn around a box: the keyboard's focus on it.
|
||||
bool Ringed(const Context& ui, Box box) {
|
||||
const std::vector<RectItem> rings = Rects(ui, ui.theme.accent.WithAlpha(0));
|
||||
return std::ranges::any_of(rings, [box](const RectItem& ring) { return ring.box == box && ring.outline == 2; });
|
||||
}
|
||||
|
||||
void Cursors() {
|
||||
Column column({10, 20, 100, 300}, 8);
|
||||
Check(column.Next() == Box{10, 20, 100, 300} && column.Used() == 0, "a column starts at its area's top, with nothing used");
|
||||
Check(column.Take(40) == Box{10, 20, 100, 40} && column.Take(60) == Box{10, 68, 100, 60}, "each box starts under the one before, the gap between them");
|
||||
Check(column.Next() == Box{10, 136, 100, 184} && column.Used() == 108, "what is used is the boxes and the gaps between them, not the gap after the last");
|
||||
column.Advance(500);
|
||||
Check(column.Next().h == 0 && column.Take(10).y == 644, "a column may run past its area: one that scrolls is as long as its content");
|
||||
|
||||
Row row({10, 20, 300, 40}, 4);
|
||||
Check(row.TakeLeft(50) == Box{10, 20, 50, 40} && row.TakeRight(60) == Box{250, 20, 60, 40} && row.Rest() == Box{64, 20, 182, 40}, "a row gives boxes from its ends, and the rest between them");
|
||||
row.TakeLeft(400);
|
||||
Equal(row.Rest().w, 0.0f, "nothing is left of a row that is taken up");
|
||||
|
||||
Check(Centered({0, 0, 1000, 50}, 640) == Box{180, 0, 640, 50} && Centered({20, 0, 300, 50}, 640) == Box{20, 0, 300, 50}, "a box no wider than asked, in the middle of the area");
|
||||
}
|
||||
|
||||
void Words() {
|
||||
Context ui(Test::FixedMeasure());
|
||||
float tall = 0;
|
||||
float measured = 0;
|
||||
Build(ui, [&](Frame& frame) {
|
||||
Check(Body(frame).sizeDp == 16 && Strong(frame).face == FontFace::Medium && Muted(frame).color == ui.theme.muted && Caption(frame).sizeDp == 12 && Heading(frame).sizeDp == 18, "the styles text is set in");
|
||||
Label(frame, {10, 0, 200, 40}, "left", Body(frame));
|
||||
Label(frame, {10, 40, 200, 40}, "middle", {FontFace::Regular, 16, ui.theme.text, TextAlign::Center});
|
||||
Label(frame, {10, 80, 200, 40}, "right", {FontFace::Regular, 16, ui.theme.text, TextAlign::Right});
|
||||
Label(frame, {10, 120, 64, 40}, "much too long", Body(frame));
|
||||
tall = Paragraph(frame, {10, 200, 80, 0}, "one two three four", Body(frame));
|
||||
Paragraph(frame, {10, 400, 200, 0}, "in the middle", {FontFace::Regular, 16, ui.theme.text, TextAlign::Center});
|
||||
Paragraph(frame, {10, 440, 200, 0}, "at the end", {FontFace::Regular, 16, ui.theme.text, TextAlign::Right});
|
||||
measured = ParagraphHeight(frame, 80, "one two three four", Body(frame));
|
||||
});
|
||||
Check(Line(ui, "left")->x == 10 && Line(ui, "left")->baseline == 10 + 12.8f && Line(ui, "middle")->x == 110 && Line(ui, "right")->x == 210, "a label sits in the middle of its box's height, at the edge its alignment names");
|
||||
Shows(ui, "much to…", "and is cut where it does not fit");
|
||||
Check(Line(ui, "one two") != nullptr && Line(ui, "three four") != nullptr && Line(ui, "three four")->baseline == Line(ui, "one two")->baseline + 20 && tall == 40 && measured == 40, "a paragraph wraps to its box's width, and says how tall it came out");
|
||||
Check(Line(ui, "in the middle")->x == 110 && Line(ui, "at the end")->x == 210, "its lines go by the same alignment");
|
||||
}
|
||||
|
||||
void Buttons() {
|
||||
Context ui(Test::FixedMeasure());
|
||||
std::int32_t taps = 0;
|
||||
const auto scene = [&](Frame& frame) {
|
||||
frame.draw.SetLayer(Layer::Content);
|
||||
Button(frame, {10, 10, 120, 48}, {.key = "filled", .label = "Pay", .onTap = [&taps] { taps++; }});
|
||||
Button(frame, {10, 70, 120, 48}, {.key = "tonal", .label = "Request", .kind = ButtonKind::Tonal});
|
||||
Button(frame, {10, 130, 120, 48}, {.key = "plain", .label = "Cancel", .kind = ButtonKind::Plain});
|
||||
Button(frame, {10, 190, 120, 48}, {.key = "danger", .label = "Remove", .kind = ButtonKind::Danger});
|
||||
Button(frame, {10, 250, 120, 48}, {.key = "off", .label = "Not yet", .enabled = false, .onTap = [&taps] { taps++; }});
|
||||
Button(frame, {10, 328, 120, 32}, {.key = "low", .label = "More", .kind = ButtonKind::Plain, .onTap = [&taps] { taps += 10; }});
|
||||
Check(ButtonWidth(frame, "Pay") == 3 * 8 + 32, "a button is as wide as its label and a gutter each side");
|
||||
};
|
||||
Build(ui, scene);
|
||||
const Theme& theme = ui.theme;
|
||||
Check(Rects(ui, theme.accent).size() == 1 && Rects(ui, theme.accent)[0].box == Box{10, 10, 120, 48} && Line(ui, "Pay")->color == theme.onAccent && Line(ui, "Pay")->face == FontFace::Medium && Line(ui, "Pay")->x == 70, "a filled button: the accent, its label in the middle");
|
||||
Check(Rects(ui, theme.surfaceAlt).size() == 2 && Line(ui, "Request")->color == theme.text && Line(ui, "Not yet")->color == theme.muted, "a tonal button and a disabled one stand on the quiet ground");
|
||||
Check(Rects(ui, theme.surface).empty() && Line(ui, "Cancel")->color == theme.accent, "a plain one is its label alone");
|
||||
Check(Rects(ui, theme.danger).size() == 1 && Line(ui, "Remove")->color == theme.onDanger, "a dangerous one says so by its colour");
|
||||
Check(ui.Find("filled")->focusable && ui.Find("filled")->label == "Pay" && !ui.Find("off")->enabled && ui.Find("filled")->box == Box{10, 10, 120, 48}, "each is a region with its label, as large as it is drawn");
|
||||
|
||||
TapAt(ui, {50, 30});
|
||||
TapAt(ui, {50, 270});
|
||||
Equal(taps, 1, "a tap presses it, unless it is disabled");
|
||||
TapAt(ui, {50, 322});
|
||||
TapAt(ui, {50, 366});
|
||||
TapAt(ui, {50, 370});
|
||||
Check(taps == 21 && ui.Find("low")->box == Box{10, 320, 120, 48}, "a button lower than a finger needs takes a press from as much above and below it as makes up for that");
|
||||
ui.Hover(Point{50, 150});
|
||||
Build(ui, scene);
|
||||
Equal(Rects(ui, theme.Hovered(theme.surface)).size(), std::size_t{1}, "under the pointer a plain button gets a ground");
|
||||
ui.Pointer(PointerPhase::Down, {50, 30}, 0);
|
||||
ui.Hover(Point{50, 270});
|
||||
Build(ui, scene);
|
||||
Check(Rects(ui, theme.Pressed(theme.accent)).size() == 1 && Rects(ui, theme.accent).empty() && Rects(ui, theme.surfaceAlt).size() == 2, "a pressed button is drawn pressed; a disabled one feels nothing");
|
||||
ui.Pointer(PointerPhase::Cancel, {50, 30}, 10);
|
||||
ui.Focus("tonal");
|
||||
Build(ui, scene);
|
||||
Check(Ringed(ui, {10, 70, 120, 48}) && !Ringed(ui, {10, 10, 120, 48}), "the keyboard's focus is a line around it");
|
||||
}
|
||||
|
||||
void Rows() {
|
||||
Context ui(Test::FixedMeasure());
|
||||
std::vector<std::string> seen;
|
||||
const Color green{0, 0.5f, 0};
|
||||
// 43 characters, and room for 37 beside the mark: the row is 368 wide within its gutters, the mark 58 and a gap of 8.
|
||||
const std::string longTitle = "A connection with quite a long name, indeed";
|
||||
const std::string cutTitle = Ellipsize(Test::FixedMeasure(), longTitle, FontFace::Regular, 16, 302);
|
||||
const auto scene = [&](Frame& frame) {
|
||||
frame.draw.SetLayer(Layer::Content);
|
||||
ListRow(frame, {0, 0, 400, 64}, {.key = "main", .title = "Main account", .subtitle = "NL23 BUNQ 2025 1234 56", .trailing = "€12.50", .trailingSub = "today", .chevron = true, .onTap = [&seen] { seen.push_back("main"); }, .onLongPress = [&seen] { seen.push_back("main held"); }});
|
||||
ListRow(frame, {0, 64, 400, 56}, {.key = "plain", .title = "Just a title", .divider = false});
|
||||
ListRow(frame, {0, 120, 400, 64}, {.key = "in", .title = "Bob", .trailing = "+€5.00", .trailingColor = green});
|
||||
ListRow(frame, {0, 184, 400, 64}, {.key = "dated", .title = "Carol", .trailingSub = "1 Nov"});
|
||||
ListRow(frame, {0, 248, 400, 64}, {.key = "sandbox", .title = longTitle, .badge = "Sandbox"});
|
||||
ListRow(frame, {0, 312, 400, 64}, {.key = "chosen", .title = "Savings", .selected = true, .onTap = [&seen] { seen.push_back("chosen"); }});
|
||||
ListRow(frame, {0, 376, 400, 64}, {.key = "other", .title = "Joint", .selected = false, .enabled = false, .onTap = [&seen] { seen.push_back("other"); }});
|
||||
};
|
||||
Build(ui, scene);
|
||||
const Theme& theme = ui.theme;
|
||||
Check(Line(ui, "Main account")->x == 16 && Line(ui, "NL23 BUNQ 2025 1234 56")->color == theme.muted && Line(ui, "NL23 BUNQ 2025 1234 56")->baseline > Line(ui, "Main account")->baseline, "a row's title, and under it its second line");
|
||||
Check(Line(ui, "€12.50")->align == TextAlign::Right && Line(ui, "€12.50")->x == 400 - 16 - 20 && Line(ui, "today")->x == 364 && Line(ui, "today")->baseline > Line(ui, "€12.50")->baseline && Line(ui, "›") != nullptr, "what trails it at the right, before the mark that it leads somewhere");
|
||||
Check(Line(ui, "Just a title")->baseline == 64 + (56 - 20) / 2.0f + 12.8f, "a title alone is in the middle of the row");
|
||||
Check(Line(ui, "+€5.00")->color == green && Line(ui, "+€5.00")->baseline == Line(ui, "Bob")->baseline && Line(ui, "1 Nov")->baseline == 184 + (64 - 15) / 2.0f + 9.6f, "an amount in its own colour; one trailing line alone is in the row's middle");
|
||||
Check(cutTitle != longTitle && Line(ui, cutTitle) != nullptr && Line(ui, "Sandbox") != nullptr && Line(ui, "Sandbox")->bounds.x > Line(ui, cutTitle)->bounds.Right(), "a mark follows the title, which makes room for it");
|
||||
Check(Circles(ui) == 3 && Line(ui, "Savings")->x == 16 + 36 && Line(ui, "Joint")->color == theme.muted, "a choice among rows is a ring, with a dot in the one chosen; a disabled row is muted");
|
||||
Check(Rects(ui, theme.divider).size() == 6 && Rects(ui, theme.divider)[0].box == Box{16, 63, 384, 1}, "a line under every row but the one that asked for none, from its title to the edge of a window as narrow as a phone");
|
||||
Check(ui.Find("main")->role == Role::Row && ui.Find("main")->focusable && !ui.Find("plain")->focusable && ui.Find("main")->label == "Main account", "a row is a region; one that does nothing takes no focus");
|
||||
|
||||
TapAt(ui, {200, 30});
|
||||
TapAt(ui, {200, 400});
|
||||
Check(ui.LongPress("main") && seen == std::vector<std::string>{"main", "main held"}, "a tap and a long press act; a disabled row does not");
|
||||
ui.Hover(Point{200, 30});
|
||||
Build(ui, scene);
|
||||
Check(Rects(ui, theme.Hovered(theme.surface)).size() == 1 && Rects(ui, theme.Hovered(theme.surface))[0].box == Box{0, 0, 400, 64}, "the pointer over a row that acts tints it");
|
||||
ui.Hover(Point{200, 90});
|
||||
ui.Pointer(PointerPhase::Down, {200, 340}, 0);
|
||||
Build(ui, scene);
|
||||
Check(Rects(ui, theme.Hovered(theme.surface)).empty() && Rects(ui, theme.Pressed(theme.surface)).size() == 1, "one that does nothing is not; a pressed one is drawn pressed");
|
||||
ui.Pointer(PointerPhase::Cancel, {200, 340}, 10);
|
||||
ui.Focus("chosen");
|
||||
Build(ui, scene);
|
||||
Check(Ringed(ui, {2, 314, 396, 60}), "the keyboard's focus is a line just inside it");
|
||||
|
||||
Build(ui, scene, {0, 0, 1000, 800});
|
||||
Check(Rects(ui, theme.divider)[0].box == Box{16, 63, 368, 1}, "in a wider window the line under a row ends where the row's text does");
|
||||
}
|
||||
|
||||
// A line of a sheet that says what something is: a label, and beside it a value that a press can copy.
|
||||
void Values() {
|
||||
Context ui(Test::FixedMeasure());
|
||||
std::vector<std::string> seen;
|
||||
std::array<float, 3> heights{};
|
||||
float foretold = 0;
|
||||
// 74 characters, and room for 34 on a line: the row is 400 wide, its text 8 clear of either side, the label 112.
|
||||
const std::string longValue = "A description that is long enough to need a second line in the room it has";
|
||||
const std::string longLabel = "A label that is too long for its room";
|
||||
const auto scene = [&](Frame& frame) {
|
||||
frame.draw.SetLayer(Layer::Content);
|
||||
const ValueOptions iban{.key = "iban", .label = "IBAN", .value = "NL23 BUNQ 2025 1234 56", .onTap = [&seen] { seen.push_back("tap"); }, .onLongPress = [&seen] { seen.push_back("held"); }};
|
||||
foretold = ValueRowHeight(frame, frame.bounds.w, iban);
|
||||
heights[0] = ValueRow(frame, {0, 0, frame.bounds.w, 0}, iban);
|
||||
heights[1] = ValueRow(frame, {0, 100, 400, 0}, {.key = "long", .label = "Description", .value = longValue, .onTap = [&seen] { seen.push_back("long"); }});
|
||||
heights[2] = ValueRow(frame, {0, 300, 400, 0}, {.key = "read", .label = longLabel, .value = "Read only"});
|
||||
};
|
||||
Build(ui, scene);
|
||||
const Theme& theme = ui.theme;
|
||||
Check(heights[0] == 48 && foretold == 48 && heights[2] == 48, "on a phone a line is as tall as a finger needs, which can be asked beforehand");
|
||||
Check(Line(ui, "IBAN")->x == 8 && Line(ui, "IBAN")->px == 14 && Line(ui, "IBAN")->color == theme.muted && Line(ui, "NL23 BUNQ 2025 1234 56")->x == 8 + 112, "the label, and beside it the value, clear of the row's sides");
|
||||
Check(Line(ui, "NL23 BUNQ 2025 1234 56")->baseline == 14 + 12.8f && Line(ui, "IBAN")->baseline == 14 + 12.8f, "the value in the middle of the row's height, the label on its line");
|
||||
Check(heights[1] == 3 * 20 + 12 && Line(ui, "A description that is long enough") != nullptr && Line(ui, "it has")->baseline == 100 + 6 + 40 + 12.8f && Line(ui, "Description")->baseline == 100 + 6 + 12.8f, "a value too long for its room wraps, the row grows with it, and the label stays on its first line");
|
||||
Check(Line(ui, Ellipsize(Test::FixedMeasure(), longLabel, FontFace::Regular, 14, 104)) != nullptr && Line(ui, longLabel) == nullptr, "a label too long for its room is cut");
|
||||
Check(ui.Find("iban")->role == Role::Row && ui.Find("iban")->focusable && ui.Find("iban")->box == Box{0, 0, 400, 48} && ui.Find("iban")->label == "IBAN" && ui.Find("read") == nullptr, "a line with something to do is a region; one that is only read is not");
|
||||
Check(ui.Tap("iban") && ui.LongPress("iban") && ui.Tap("long") && seen == std::vector<std::string>{"tap", "held", "long"}, "a tap and a long press act");
|
||||
|
||||
ui.Hover(Point{200, 20});
|
||||
Build(ui, scene);
|
||||
Check(Rects(ui, theme.Hovered(theme.surface)).size() == 1 && Rects(ui, theme.Hovered(theme.surface))[0].box == Box{0, 0, 400, 48}, "under the pointer the whole row is tinted");
|
||||
ui.Hover(Point{200, 320});
|
||||
ui.Pointer(PointerPhase::Down, {200, 120}, 0);
|
||||
Build(ui, scene);
|
||||
Check(Rects(ui, theme.Hovered(theme.surface)).empty() && Rects(ui, theme.Pressed(theme.surface)).size() == 1, "a line that is only read is not; a pressed one is drawn pressed");
|
||||
ui.Pointer(PointerPhase::Cancel, {200, 120}, 10);
|
||||
ui.Focus("long");
|
||||
Build(ui, scene);
|
||||
Check(Ringed(ui, {0, 100, 400, 72}), "the keyboard's focus is a line around the row");
|
||||
|
||||
Build(ui, scene, {0, 0, 1000, 800});
|
||||
Check(heights[0] == 36 && foretold == 36 && ui.Find("iban")->box == Box{0, 0, 1000, 36}, "in a wider window, under a pointer, the lines are closer together");
|
||||
}
|
||||
|
||||
void Choosing() {
|
||||
Context ui(Test::FixedMeasure());
|
||||
std::vector<std::size_t> picked;
|
||||
std::size_t selected = 1;
|
||||
bool enabled = true;
|
||||
const auto scene = [&](Frame& frame) {
|
||||
frame.draw.SetLayer(Layer::Content);
|
||||
Segmented(frame, {10, 10, 300, 40}, {.key = "when", .labels = {"Now", "Scheduled", "Draft"}, .selected = selected, .enabled = enabled, .onSelect = [&](std::size_t i) { picked.push_back(i); }});
|
||||
Segmented(frame, {10, 60, 300, 40}, {.key = "idle", .labels = {"One", "Two"}});
|
||||
Tabs(frame, {0, 200, 400, 48}, {.key = "tabs", .labels = {"Activity", "Requests", "Incoming", "Scheduled", "Drafts"}, .selected = selected, .enabled = enabled, .onSelect = [&](std::size_t i) { picked.push_back(i); }});
|
||||
Tabs(frame, {0, 300, 300, 48}, {.key = "tight", .labels = {"Activity", "Requests", "Incoming", "Scheduled", "Drafts"}, .selected = 0});
|
||||
Segmented(frame, {10, 400, 300, 40}, {.key = "none"});
|
||||
};
|
||||
Build(ui, scene);
|
||||
const Theme& theme = ui.theme;
|
||||
Check(Line(ui, "Scheduled")->face == FontFace::Medium && Line(ui, "Now")->face == FontFace::Regular && Rects(ui, theme.surface).size() == 2, "of a row of segments the one taken stands out");
|
||||
Check(ui.Find("when.0")->box == Box{10, 10, 100, 40} && ui.Find("when.2")->box == Box{210, 10, 100, 40} && ui.Find("when.1")->label == "Scheduled" && ui.Find("none.0") == nullptr, "each segment is an equal part, and a region");
|
||||
Check(ui.Tap("when.2") && ui.Tap("tabs.4") && picked == std::vector<std::size_t>{2, 4} && ui.Tap("idle.1"), "a tap on one says which; one nobody listens to can still be pressed");
|
||||
|
||||
// The tabs: 80 wide each in the wide strip, 60 in the tight one, where "Scheduled" at 14 pixels wants 71.
|
||||
const std::span<const Batch> content = ui.Shown().draw.Batches(Layer::Content);
|
||||
std::vector<float> sizes;
|
||||
for(const Batch& batch : content) {
|
||||
for(const TextItem& item : batch.texts) {
|
||||
if(item.text == "Scheduled" && item.baseline > 200) {
|
||||
sizes.push_back(item.px);
|
||||
}
|
||||
}
|
||||
}
|
||||
Equal(sizes == std::vector<float>{14, 12}, true, "tabs whose labels do not all fit beside each other are set a size down");
|
||||
Check(Rects(ui, theme.accent).size() == 2 && Rects(ui, theme.accent)[0].box == Box{80 + 8, 245, 64, 3}, "a line under the tab that is shown");
|
||||
|
||||
ui.Hover(Point{50, 30});
|
||||
ui.Pointer(PointerPhase::Down, {40, 220}, 0);
|
||||
Build(ui, scene);
|
||||
Check(Rects(ui, theme.Hovered(theme.surfaceAlt)).size() == 1 && Rects(ui, theme.Pressed(theme.surface)).size() == 1, "a segment under the pointer and a tab that is pressed are drawn so");
|
||||
ui.Pointer(PointerPhase::Cancel, {40, 220}, 10);
|
||||
ui.Hover(Point{160, 30});
|
||||
Build(ui, scene);
|
||||
Check(Rects(ui, theme.Hovered(theme.surfaceAlt)).empty(), "the segment that is taken does not change under the pointer");
|
||||
ui.Focus("when.0");
|
||||
Build(ui, scene);
|
||||
Check(Ringed(ui, {13, 13, 94, 34}), "the focus on a segment");
|
||||
ui.Focus("tabs.2");
|
||||
Build(ui, scene);
|
||||
Check(Ringed(ui, {162, 202, 76, 44}), "and on a tab");
|
||||
|
||||
enabled = false;
|
||||
ui.Hover(Point{50, 30});
|
||||
ui.Pointer(PointerPhase::Down, {40, 220}, 0);
|
||||
Build(ui, scene);
|
||||
Check(Line(ui, "Now")->color == theme.muted && Rects(ui, theme.Hovered(theme.surfaceAlt)).empty() && Rects(ui, theme.Pressed(theme.surface)).empty() && !ui.Tap("when.0"), "disabled, they are muted, feel nothing and take no tap");
|
||||
ui.Pointer(PointerPhase::Cancel, {40, 220}, 10);
|
||||
|
||||
// A dark theme's surface is darker than the ground the segments stand on: the one taken is lighter than both.
|
||||
ui.theme = Theme::Dark();
|
||||
Build(ui, scene);
|
||||
Check(Rects(ui, ui.theme.Taken()).size() == 2 && Rects(ui, ui.theme.surface).empty(), "on a dark theme the segment taken still stands out as the lighter");
|
||||
}
|
||||
|
||||
void Notices() {
|
||||
Context ui(Test::FixedMeasure());
|
||||
std::vector<std::string> seen;
|
||||
std::array<float, 4> heights{};
|
||||
const auto scene = [&](Frame& frame) {
|
||||
frame.draw.SetLayer(Layer::Content);
|
||||
heights[0] = Banner(frame, {10, 0, 380, 0}, {.key = "info", .text = "A connection could not be reached"});
|
||||
heights[1] = Banner(frame, {10, 100, 380, 0}, {.key = "warn", .kind = BannerKind::Warning, .text = "It may have been carried out: check your activity before trying again", .action = "Open activity", .onAction = [&seen] { seen.push_back("action"); }, .onDismiss = [&seen] { seen.push_back("dismiss"); }});
|
||||
heights[2] = Banner(frame, {10, 300, 380, 0}, {.key = "error", .kind = BannerKind::Error, .text = "bunq refused", .onDismiss = [&seen] { seen.push_back("gone"); }});
|
||||
heights[3] = Banner(frame, {10, 400, 380, 0}, {.key = "act", .text = "Nothing is connected yet", .action = "Add a bank"});
|
||||
Chip(frame, {10, 600, ChipWidth(frame, "PENDING"), 20}, "PENDING", ui.theme.surfaceAlt, ui.theme.muted);
|
||||
Divider(frame, {0, 700, 400, 20});
|
||||
Skeleton(frame, {10, 740, 200, 16});
|
||||
Skeleton(frame, {10, 770, 200, 16}, 0.5f);
|
||||
};
|
||||
Build(ui, scene);
|
||||
const Theme& theme = ui.theme;
|
||||
Check(heights[0] == 24 + 17.5f && Rects(ui, theme.surfaceAlt)[0].box == Box{10, 0, 380, 41.5f} && Line(ui, "A connection could not be reached")->color == theme.text, "a notice is as tall as its text and its padding");
|
||||
Check(Rects(ui, theme.warning).size() == 2 && Line(ui, "×") != nullptr && Line(ui, "Open activity")->color == theme.onWarning && heights[1] == 24 + 35 + 40, "a warning in its own colours, wrapped beside the mark that closes it, its action under the text");
|
||||
Check(Rects(ui, theme.danger).size() == 1 && Line(ui, "bunq refused")->color == theme.onDanger && heights[2] == 48, "an error; a notice that can be closed is at least as tall as the mark");
|
||||
Check(ui.Tap("warn.action") && ui.Tap("warn.dismiss") && ui.Tap("error.dismiss") && ui.Tap("act.action") && seen == std::vector<std::string>{"action", "dismiss", "gone"}, "its action and its closing can be pressed");
|
||||
Check(ui.Find("info.dismiss") == nullptr && ui.Find("info.action") == nullptr && ui.Find("warn.dismiss")->label == "Dismiss", "a notice without them has neither");
|
||||
Check(Line(ui, "PENDING")->px == 12 && Rects(ui, theme.surfaceAlt)[3].corners == Corners::All(10) && ChipWidth(ui.Shown(), "PENDING") == 7 * 6 + 16, "a chip is a rounded mark around its text");
|
||||
Check(Rects(ui, theme.divider)[0].box == Box{0, 719, 400, 1}, "a divider is a line along its box's bottom edge");
|
||||
Check(Rects(ui, theme.surfaceAlt)[4].box == Box{10, 740, 200, 16} && Rects(ui, theme.surfaceAlt)[5].box == Box{10, 770, 100, 16}, "a skeleton is a bar, or part of one");
|
||||
|
||||
ui.Focus("warn.action");
|
||||
ui.Hover(Point{50, 170});
|
||||
Build(ui, scene);
|
||||
Check(Ringed(ui, ui.Find("warn.action")->box.Inset(Insets::Symmetric(0, 6))) && ui.Find("warn.action")->box.h == 48 && Rects(ui, theme.Hovered(theme.warning)).size() == 1, "the action takes the focus and feels the pointer, and a press from a little above and below what is drawn: a finger's height");
|
||||
ui.Focus("warn.dismiss");
|
||||
Build(ui, scene);
|
||||
Check(Ringed(ui, ui.Find("warn.dismiss")->box.Inset(Insets::All(6))), "and so does the mark");
|
||||
}
|
||||
|
||||
void Bars() {
|
||||
Context ui(Test::FixedMeasure());
|
||||
std::vector<std::string> seen;
|
||||
bool back = true;
|
||||
Box under;
|
||||
Box above;
|
||||
Box beside;
|
||||
float sideWidth = 240;
|
||||
const std::vector<NavItem> places = {
|
||||
{.key = "nav.accounts", .label = "Accounts", .selected = true, .onTap = [&seen] { seen.push_back("accounts"); }},
|
||||
{.key = "nav.cards", .label = "Cards", .onTap = [&seen] { seen.push_back("cards"); }},
|
||||
{.key = "nav.settings", .label = "Settings", .onTap = [&seen] { seen.push_back("settings"); }},
|
||||
};
|
||||
const std::vector<NavItem> side = {
|
||||
{.key = "side.accounts", .label = "Accounts", .selected = true, .onTap = [&seen] { seen.push_back("side accounts"); }},
|
||||
{.key = "side.head", .label = "Alice at bunq", .header = true},
|
||||
{.key = "side.main", .label = "Main", .detail = "€1,000.00", .onTap = [&seen] { seen.push_back("side main"); }},
|
||||
};
|
||||
const auto scene = [&](Frame& frame) {
|
||||
frame.draw.SetLayer(Layer::Content);
|
||||
under = TopBar(frame, frame.bounds, {.title = "A title that is far too long to fit beside two actions", .onBack = back ? std::function<void()>([&seen] { seen.push_back("back"); }) : nullptr, .actions = {{.key = "bar.refresh", .label = "Refresh", .onTap = [&seen] { seen.push_back("refresh"); }}, {.key = "bar.add", .label = "Add", .enabled = false}}});
|
||||
above = NavBar(frame, under, places);
|
||||
beside = Sidebar(frame, above, sideWidth, side);
|
||||
Check(frame.draw.CurrentLayer() == Layer::Content, "a bar leaves the layer as it found it");
|
||||
};
|
||||
Build(ui, scene);
|
||||
const Theme& theme = ui.theme;
|
||||
Check(under == Box{0, 56, 400, 744} && above == Box{0, 56, 400, 688} && beside == Box{240, 56, 160, 688}, "each bar returns the area it leaves");
|
||||
Check(ui.Find("bar")->role == Role::Panel && ui.Find("bar")->layer == Layer::Chrome && ui.Find("bar.back")->box == Box{4, 0, 48, 56} && Line(ui, "‹") != nullptr, "the top bar, with the way back at its left");
|
||||
Check(ui.Find("bar.add")->box.Right() == 396 && ui.Find("bar.refresh")->box.Right() == ui.Find("bar.add")->box.x - 4 && !ui.Find("bar.add")->enabled, "its actions from the right, in the order they were named");
|
||||
Shows(ui, "…", "and its title in what room is left");
|
||||
Check(ui.Tap("bar.back") && ui.Tap("bar.refresh") && seen == std::vector<std::string>{"back", "refresh"}, "which can be pressed");
|
||||
ui.KeyDown(Key::Escape, {});
|
||||
Equal(seen.back(), std::string("back"), "Escape is the way back");
|
||||
|
||||
Check(ui.Find("nav")->box == Box{0, 744, 400, 56} && ui.Find("nav.cards")->box == Box{400 / 3.0f, 744, 400 / 3.0f, 56}, "the places along the bottom, in equal parts");
|
||||
Check(Line(ui, "Cards")->color == theme.muted && Rects(ui, theme.accent.WithAlpha(0.14f)).size() == 2, "the place the window is at stands out, in each bar");
|
||||
Check(ui.Tap("nav.cards") && seen.back() == "cards", "a place can be pressed");
|
||||
|
||||
Check(ui.Find("side")->box == Box{0, 56, 240, 688} && ui.Find("side.scroll")->role == Role::Scroll && ui.Find("side.head") == nullptr && Line(ui, "Alice at bunq")->px == 12, "the places down the side, a heading among them that is no region");
|
||||
Check(Line(ui, "€1,000.00") != nullptr && Line(ui, "€1,000.00")->align == TextAlign::Right && ui.Tap("side.main") && seen.back() == "side main", "a place with its detail beside it");
|
||||
|
||||
ui.Hover(Point{20, 20});
|
||||
Build(ui, scene);
|
||||
Equal(Rects(ui, theme.Hovered(theme.surface)).size(), std::size_t{1}, "the way back feels the pointer");
|
||||
ui.Hover(Point{200, 770});
|
||||
Build(ui, scene);
|
||||
Equal(Rects(ui, theme.Hovered(theme.surface)).size(), std::size_t{1}, "so does a place along the bottom");
|
||||
ui.Pointer(PointerPhase::Down, {100, 160}, 0);
|
||||
ui.Hover(std::nullopt);
|
||||
Build(ui, scene);
|
||||
Equal(Rects(ui, theme.Pressed(theme.surface)).size(), std::size_t{1}, "and one down the side a press");
|
||||
ui.Pointer(PointerPhase::Cancel, {100, 160}, 10);
|
||||
ui.Focus("bar.back");
|
||||
Build(ui, scene);
|
||||
Check(Ringed(ui, {4, 4, 48, 48}), "the focus on the way back");
|
||||
ui.Focus("nav.cards");
|
||||
Build(ui, scene);
|
||||
Check(Rects(ui, theme.accent.WithAlpha(0)).size() == 1, "on a place along the bottom");
|
||||
ui.Focus("side.main");
|
||||
Build(ui, scene);
|
||||
Check(Rects(ui, theme.accent.WithAlpha(0)).size() == 1, "and on one down the side");
|
||||
|
||||
back = false;
|
||||
sideWidth = 120;
|
||||
Build(ui, scene);
|
||||
Check(ui.Find("bar.back") == nullptr && Line(ui, "‹") == nullptr, "a screen with no way back shows none");
|
||||
Check(Line(ui, "€1,000.00") == nullptr && Line(ui, "Main") != nullptr, "a detail gives way where the side bar is too narrow for both");
|
||||
seen.clear();
|
||||
ui.KeyDown(Key::Escape, {});
|
||||
Check(seen.empty(), "and Escape goes nowhere");
|
||||
|
||||
// The dark theme tints the place the window is at more strongly.
|
||||
ui.theme = Theme::Dark();
|
||||
Build(ui, scene);
|
||||
Equal(Rects(ui, ui.theme.accent.WithAlpha(0.28f)).size(), std::size_t{2}, "on a dark ground it stands out more strongly");
|
||||
}
|
||||
|
||||
void Sheets() {
|
||||
Context ui(Test::FixedMeasure());
|
||||
std::vector<std::string> seen;
|
||||
Box content;
|
||||
std::string title = "Report this card stolen?";
|
||||
bool dismissable = true;
|
||||
float wanted = 200;
|
||||
const auto scene = [&](Frame& frame) {
|
||||
frame.draw.SetLayer(Layer::Content);
|
||||
Button(frame, {10, 10, 100, 48}, {.key = "under", .label = "Under", .onTap = [&seen] { seen.push_back("under"); }});
|
||||
Sheet(frame, {.key = "sheet", .title = title, .contentHeight = wanted, .onDismiss = dismissable ? std::function<void()>([&seen] { seen.push_back("dismissed"); }) : nullptr}, [&](Box box) {
|
||||
content = box;
|
||||
Button(frame, {box.x, box.y, 100, 48}, {.key = "sheet.ok", .label = "Report", .kind = ButtonKind::Danger, .onTap = [&seen] { seen.push_back("ok"); }});
|
||||
});
|
||||
Check(frame.draw.CurrentLayer() == Layer::Content, "a sheet leaves the layer as it found it");
|
||||
};
|
||||
Build(ui, scene);
|
||||
const Theme& theme = ui.theme;
|
||||
Check(ui.Find("sheet.panel")->box == Box{0, 800 - 272, 400, 272} && content == Box{16, 528 + 16 + 40, 368, 200} && ui.Find("sheet.panel")->layer == Layer::Overlay && SheetBodyWidth(ui.Shown()) == 368, "in a narrow window a sheet rises from the bottom edge, as tall as its title and its body");
|
||||
Check(Rects(ui, theme.scrim).size() == 1 && Rects(ui, theme.surface).back().corners == Corners::Top(12), "over a scrim, its top corners rounded");
|
||||
Shows(ui, "Report this card stolen?", "with its title");
|
||||
Check(!ui.Tap("under") && ui.Tap("sheet.ok") && seen.back() == "ok", "what it covers is out of reach; its own button is not");
|
||||
TapAt(ui, {200, 100});
|
||||
ui.KeyDown(Key::Escape, {});
|
||||
Equal(seen == std::vector<std::string>{"ok", "dismissed", "dismissed"}, true, "a tap beside it or Escape dismisses it");
|
||||
|
||||
title.clear();
|
||||
dismissable = false;
|
||||
wanted = 5000;
|
||||
Build(ui, scene, {0, 0, 1000, 700});
|
||||
Check(ui.Find("sheet.panel")->box == Box{260, 24, 480, 652} && content == Box{276, 40, 448, 620} && Rects(ui, theme.surface).back().corners == Corners::All(12), "in a wide window it is a dialog in the middle, no taller than the window leaves room for");
|
||||
Check(SheetBodyWidth(ui.Shown()) == 448, "how wide its body is can be asked beforehand");
|
||||
TapAt(ui, {50, 50});
|
||||
ui.KeyDown(Key::Escape, {});
|
||||
Equal(seen.size(), std::size_t{3}, "one that cannot be dismissed stays");
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
Cursors();
|
||||
Words();
|
||||
Buttons();
|
||||
Rows();
|
||||
Values();
|
||||
Choosing();
|
||||
Notices();
|
||||
Bars();
|
||||
Sheets();
|
||||
return Test::Result();
|
||||
}
|
||||
150
tests/ShouldRecognizeGestures/main.cpp
Normal file
150
tests/ShouldRecognizeGestures/main.cpp
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// What a pointer did, from its phases and their times: taps, long presses, drags and flings; a list's scrolling and
|
||||
// what keeps a field in view; the compositor's event times on the host's clock; and the frames owed to the font atlas.
|
||||
|
||||
import std;
|
||||
import Nostro.Ui;
|
||||
|
||||
#include "../Support/Check.inc"
|
||||
|
||||
using namespace Nostro::Ui;
|
||||
using Test::Check;
|
||||
using Test::Equal;
|
||||
using Kind = GestureEvent::Kind;
|
||||
|
||||
namespace {
|
||||
void Gestures() {
|
||||
GestureDetector g;
|
||||
Check(!g.Pressed() && !g.LongPressDue(), "nothing is pressed at first");
|
||||
Check(g.Feed(PointerPhase::Move, {5, 5}, 0).kind == Kind::None && g.Feed(PointerPhase::Up, {5, 5}, 1).kind == Kind::None, "a move or a release without a press is nothing");
|
||||
g.Feed(PointerPhase::Down, {10, 10}, 0);
|
||||
Check(g.Pressed() && g.LongPressDue() == std::optional<std::int64_t>(500), "a press waits for its long-press time");
|
||||
Check(g.Feed(PointerPhase::Move, {13, 12}, 50).kind == Kind::None, "movement within the slop is not a drag");
|
||||
const GestureEvent tap = g.Feed(PointerPhase::Up, {13, 12}, 120);
|
||||
Check(tap.kind == Kind::Tap && tap.at == Point{10, 10} && !g.Pressed(), "a short press is a tap at the press position");
|
||||
|
||||
g.Feed(PointerPhase::Down, {10, 10}, 1000);
|
||||
Check(g.Timeout(1400).kind == Kind::None, "the timer before the long-press time decides nothing");
|
||||
const GestureEvent held = g.Timeout(1500);
|
||||
Check(held.kind == Kind::LongPress && held.at == Point{10, 10} && !g.LongPressDue(), "the timer at the long-press time is a long press");
|
||||
Check(g.Feed(PointerPhase::Move, {40, 40}, 1600).kind == Kind::None, "movement after a long press is not a drag");
|
||||
Check(g.Feed(PointerPhase::Up, {40, 40}, 1700).kind == Kind::Release, "the release after a long press is a plain release");
|
||||
|
||||
g.Feed(PointerPhase::Down, {100, 100}, 2000);
|
||||
const GestureEvent start = g.Feed(PointerPhase::Move, {100, 120}, 2016);
|
||||
Check(start.kind == Kind::DragStart && start.at == Point{100, 100} && start.delta == Point{0, 20}, "movement past the slop starts a drag with the whole movement as its delta");
|
||||
const GestureEvent drag = g.Feed(PointerPhase::Move, {100, 150}, 2032);
|
||||
Check(drag.kind == Kind::Drag && drag.delta == Point{0, 30} && drag.at == Point{100, 150}, "a drag reports the movement since the event before");
|
||||
Check(g.Dragging() && !g.LongPressDue(), "dragging, and no long press to wait for");
|
||||
const GestureEvent fling = g.Feed(PointerPhase::Up, {100, 200}, 2048);
|
||||
Check(fling.kind == Kind::Fling && fling.velocity.y > 1000 && fling.velocity.x == 0 && fling.at == Point{100, 200}, "a fast release is a fling with a velocity in pixels per second");
|
||||
Check(g.Timeout(2500).kind == Kind::None && !g.Dragging(), "the timer after a drag decides nothing");
|
||||
|
||||
g.Feed(PointerPhase::Down, {100, 100}, 3000);
|
||||
g.Feed(PointerPhase::Move, {100, 150}, 3016);
|
||||
g.Feed(PointerPhase::Move, {100, 200}, 3032);
|
||||
Check(g.Feed(PointerPhase::Up, {100, 200}, 3500).kind == Kind::Release, "a release after the finger was held still is not a fling, however fast it moved before");
|
||||
g.Feed(PointerPhase::Down, {0, 0}, 3000);
|
||||
g.Feed(PointerPhase::Move, {0, 30}, 3100);
|
||||
g.Feed(PointerPhase::Move, {0, 31}, 3900);
|
||||
Check(g.Feed(PointerPhase::Up, {0, 31}, 4000).kind == Kind::Release, "a slow release after a drag is a release, not a fling");
|
||||
g.Feed(PointerPhase::Down, {0, 0}, 4500);
|
||||
g.Feed(PointerPhase::Move, {30, 0}, 4500);
|
||||
Check(g.Feed(PointerPhase::Up, {30, 0}, 4500).kind == Kind::Release, "a drag and its release in one instant have no speed to fling with");
|
||||
|
||||
g.Feed(PointerPhase::Down, {0, 0}, 5000);
|
||||
g.Feed(PointerPhase::Cancel, {0, 0}, 5010);
|
||||
Check(!g.Pressed() && g.Feed(PointerPhase::Up, {0, 0}, 5020).kind == Kind::None, "a cancel forgets the press");
|
||||
g.Feed(PointerPhase::Down, {5, 5}, 6000);
|
||||
const GestureEvent late = g.Feed(PointerPhase::Up, {5, 5}, 6600);
|
||||
Check(late.kind == Kind::LongPress && late.at == Point{5, 5}, "a release past the long-press time with no timer fired, the press and its release dispatched together behind a stall, is the long press");
|
||||
g.Feed(PointerPhase::Down, {5, 5}, 7000);
|
||||
const GestureEvent stalled = g.Feed(PointerPhase::Move, {40, 40}, 7600);
|
||||
Check(stalled.kind == Kind::LongPress && stalled.at == Point{5, 5}, "a move past the long-press time with no timer fired is the long press first: the finger was held that long before it moved");
|
||||
Check(g.Feed(PointerPhase::Up, {40, 40}, 7700).kind == Kind::Release, "and its release a plain release, no drag");
|
||||
|
||||
// A press on what has no long press, the host's word before the Down: held as long, it is still a tap.
|
||||
g.longPress = false;
|
||||
g.Feed(PointerPhase::Down, {5, 5}, 8000);
|
||||
Check(!g.LongPressDue() && g.Timeout(8600).kind == Kind::None, "without a long press the timer past the time gives nothing");
|
||||
Check(g.Feed(PointerPhase::Move, {6, 5}, 8700).kind == Kind::None, "nor does a move within the slop");
|
||||
const GestureEvent slow = g.Feed(PointerPhase::Up, {6, 5}, 9500);
|
||||
Check(slow.kind == Kind::Tap && slow.at == Point{5, 5}, "and the release is the tap, however late");
|
||||
g.Feed(PointerPhase::Down, {5, 5}, 10000);
|
||||
Check(g.Feed(PointerPhase::Move, {5, 40}, 10800).kind == Kind::DragStart, "a finger that slides off past the time drags, as one that slides off before it");
|
||||
Check(g.Feed(PointerPhase::Up, {5, 40}, 11500).kind == Kind::Release, "and its release taps nothing");
|
||||
g.longPress = true;
|
||||
g.Feed(PointerPhase::Down, {5, 5}, 12000);
|
||||
Check(g.Timeout(12500).kind == Kind::LongPress, "a press the host gives a long press has it as before");
|
||||
g.Feed(PointerPhase::Up, {5, 5}, 12600);
|
||||
}
|
||||
|
||||
void Scrolling() {
|
||||
ScrollState s;
|
||||
s.content = 1000;
|
||||
s.viewport = 400;
|
||||
s.ScrollBy(100);
|
||||
Check(s.offset == 100 && s.Max() == 600, "scroll by, and the furthest it goes");
|
||||
s.ScrollBy(5000);
|
||||
Equal(s.offset, 600.0f, "the offset stops at the end");
|
||||
s.ScrollBy(-5000);
|
||||
Equal(s.offset, 0.0f, "and at the start");
|
||||
s.Fling(1000);
|
||||
Check(s.Tick(0.1f) && s.offset > 0 && s.velocity < 1000, "a fling moves the content and slows down");
|
||||
while(s.Tick(0.1f)) {
|
||||
}
|
||||
Check(s.velocity == 0 && s.offset > 0 && s.offset <= 600, "a fling comes to rest within the extent");
|
||||
s.offset = 0;
|
||||
s.Fling(-500);
|
||||
Check(!s.Tick(0.1f) && s.offset == 0, "a fling against the edge stops at once");
|
||||
s.Fling(10);
|
||||
Check(!s.Tick(0.1f) && s.velocity == 0, "one too slow to see is none");
|
||||
s.content = 300;
|
||||
s.offset = 250;
|
||||
s.Clamp();
|
||||
Equal(s.offset, 0.0f, "content shorter than the viewport does not scroll");
|
||||
|
||||
// A field that got the focus, in a form of 1000 pixels shown 400 at a time.
|
||||
s.content = 1000;
|
||||
s.offset = 0;
|
||||
Check(!s.EnsureVisible(100, 148, 16) && s.offset == 0, "what is in view stays where it is");
|
||||
Check(s.EnsureVisible(500, 548, 16) && s.offset == 164, "what is below comes up to the bottom edge, the margin clear of it");
|
||||
s.Fling(900);
|
||||
Check(s.EnsureVisible(100, 148, 16) && s.offset == 84 && s.velocity == 0, "what is above comes down to the top edge, and a fling under it stops");
|
||||
Check(s.EnsureVisible(980, 1000, 16) && s.offset == 600, "the margin gives way at the content's end");
|
||||
Check(s.EnsureVisible(200, 900, 16) && s.offset == 184, "what is taller than the room shows its top");
|
||||
}
|
||||
|
||||
void Clock() {
|
||||
EventClock clock;
|
||||
Equal(clock.At(0, 5000), std::int64_t{5000}, "an event without a time happened now");
|
||||
Equal(clock.At(1000, 5000), std::int64_t{5000}, "the first stamped event too");
|
||||
Equal(clock.At(1016, 5040), std::int64_t{5016}, "the next one when its stamp says, not when it was dispatched: it waited 24 ms");
|
||||
Equal(clock.At(1100, 5095), std::int64_t{5095}, "one dispatched sooner than any before shows the clocks are nearer: the difference is the smallest seen");
|
||||
Equal(clock.At(1200, 5300), std::int64_t{5195}, "and the later ones go by it");
|
||||
EventClock wrapping;
|
||||
wrapping.At(0xFFFFFFF0u, 100);
|
||||
Equal(wrapping.At(0x10u, 132), std::int64_t{132}, "a stamp that wrapped at 2^32 is 32 ms on, not 4 billion back");
|
||||
Equal(wrapping.At(0x8u, 140), std::int64_t{124}, "and one before it is before it");
|
||||
}
|
||||
|
||||
void AtlasFrames() {
|
||||
FrameWait wait{.patience = 4};
|
||||
Check(!wait.Again(0), "no glyph waits: no frame owed");
|
||||
Check(wait.Again(5) && wait.Again(5) && wait.Again(5) && wait.Again(5), "glyphs waiting: a frame is owed at the first sighting and at three gainless ones after it");
|
||||
Check(!wait.Again(5), "the fourth gainless frame ends it: the screen needs more cells than the atlas holds");
|
||||
wait.Reset();
|
||||
Check(wait.Again(5) && wait.Again(3) && wait.Again(3) && wait.Again(1) && !wait.Again(0), "a gain starts the count over; none waiting ends it");
|
||||
Check(wait.Again(2) && wait.Again(7) && wait.Again(7) && wait.Again(7) && wait.Again(7) && !wait.Again(7), "a changed count, as a screen change makes, starts the count over");
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
Gestures();
|
||||
Scrolling();
|
||||
Clock();
|
||||
AtlasFrames();
|
||||
return Test::Result();
|
||||
}
|
||||
|
|
@ -153,9 +153,11 @@ namespace {
|
|||
}
|
||||
|
||||
void Connecting(Fake::Bunq& bunq) {
|
||||
// The key comes from the prompt, here stdin, never from the command line.
|
||||
Works({"connectors", "add", "bunq", "--sandbox"}, "added Ann (sandbox, 2 accounts)", "key-ann\n");
|
||||
// The key comes from the prompt, here stdin, never from the command line. It says itself which environment
|
||||
// it is of, by how it starts: there is no flag for that, and the one OAuth has is refused before a key is read.
|
||||
Works({"connectors", "add", "bunq"}, "added Ann (sandbox, 2 accounts)", "sandbox_key-ann\n");
|
||||
Works({"connectors", "add", "bunq", "*"}, "added Bob (production, 1 accounts)", "key-bob\n");
|
||||
Fails({"connectors", "add", "bunq", "--sandbox"}, "--sandbox goes with bunq-oauth: an API key is a sandbox key when it starts with sandbox_");
|
||||
Fails({"connectors", "add", "bunq"}, "nothing given for 'bunq API key: '");
|
||||
Fails({"connectors", "add"}, "connector type not provided");
|
||||
Fails({"connectors", "add", "unknown"}, "unknown connector type 'unknown'");
|
||||
|
|
@ -246,8 +248,17 @@ namespace {
|
|||
std::lock_guard lock(bunq.mutex);
|
||||
bunq.cardsActivate = false;
|
||||
}
|
||||
Fails({"cards", "unfreeze", card}, std::format("bunq kept card {} DEACTIVATED (its order status is VIRTUAL_DELIVERY)", card));
|
||||
Fails({"cards", "unfreeze", card}, std::format("bunq kept card {} DEACTIVATED (its order status is DELIVERED_TO_CUSTOMER)", card));
|
||||
Works({"cards", "lost", card}, std::format("card {} is now LOST", card));
|
||||
// A virtual card is listed as one, since bunq has it as DEACTIVATED however well it pays. It is not frozen or
|
||||
// unfrozen: bunq would leave it as it is and answer as if it had been done.
|
||||
const std::string number = std::to_string(bunq.AddCard(ann, "DEACTIVATED", json{{"order_status", "VIRTUAL_DELIVERY"}}));
|
||||
Works({"cards"}, std::format("\t{}\tVIRTUAL\tMASTERCARD_DEBIT", number));
|
||||
const std::size_t asked = bunq.Count("PUT", "/user/");
|
||||
Fails({"cards", "freeze", number}, std::format("card {} is a virtual card, which bunq does not freeze or unfreeze when asked", number));
|
||||
Fails({"cards", "unfreeze", number}, "do that in the bunq app");
|
||||
Equal(bunq.Count("PUT", "/user/"), asked, "bunq is not asked to freeze a virtual card");
|
||||
Works({"cards", "stolen", number}, std::format("card {} is now STOLEN", number));
|
||||
Fails({"cards", "melt", card}, "unknown card action 'melt'");
|
||||
Fails({"cards", "freeze", "1"}, "no card has id 1");
|
||||
Fails({"cards", "freeze"}, "card id not provided");
|
||||
|
|
@ -265,7 +276,7 @@ namespace {
|
|||
void Removing(Fake::Bunq& bunq) {
|
||||
bunq.AddAccount(bunq.AddPerson("Ann", "key-ann2"), "NL84BUNQ2025333333", "Other", 0);
|
||||
Works({"connectors", "add", "bunq"}, "added Ann (production", "key-ann2\n");
|
||||
Fails({"connectors", "remove", "Ann"}, "2 connectors are called 'Ann': use the number");
|
||||
Fails({"connectors", "remove", "Ann"}, "2 connectors are called 'Ann': use its number");
|
||||
Fails({"connectors", "remove", "Nobody"}, "no connector is called or numbered 'Nobody'");
|
||||
Works({"connectors", "remove", "4"}, "removed Ann");
|
||||
|
||||
|
|
@ -309,7 +320,7 @@ int main(int argc, char* argv[]) {
|
|||
}
|
||||
|
||||
Fake::Bunq bunq(port);
|
||||
const std::uint64_t ann = bunq.AddPerson("Ann", "key-ann");
|
||||
const std::uint64_t ann = bunq.AddPerson("Ann", "sandbox_key-ann");
|
||||
const std::uint64_t annMain = bunq.AddAccount(ann, annIban, "Main", 100000);
|
||||
bunq.AddAccount(ann, savingsIban, "Savings", 100);
|
||||
bunq.AddAccount(bunq.AddPerson("Bob", "key-bob"), bobIban, "Main", 0);
|
||||
|
|
|
|||
|
|
@ -250,7 +250,17 @@ namespace {
|
|||
|
||||
Client bob = As(bus, bobUid);
|
||||
Check(bob.Connectors().empty(), "another user sees none of them");
|
||||
Equal(bob.AddBunq("key-bob", "", "sandbox").environment, std::string("sandbox"), "an environment named by the caller");
|
||||
// An API key says itself which environment it is of. One the caller names is held to that, before anyone is
|
||||
// asked and before the key goes anywhere: a real key is not shown to the sandbox.
|
||||
const auto prompted = [&bus] {
|
||||
std::lock_guard lock(bus.mutex);
|
||||
return bus.checks.size();
|
||||
};
|
||||
const std::size_t prompts = prompted();
|
||||
Throws<std::invalid_argument>([&bob] { bob.AddBunq("key-bob", "", "sandbox"); }, "that API key is a production key, not a sandbox one", "a key that is not a sandbox key is not sent to the sandbox");
|
||||
Throws<std::invalid_argument>([&bob] { bob.AddBunq("sandbox_key-bob", "", "production"); }, "that API key is a sandbox key, not a production one", "nor a sandbox key taken for a real one");
|
||||
Check(prompted() == prompts && bob.Connectors().empty(), "nobody is asked for a password for either, and nothing is connected");
|
||||
Equal(bob.AddBunq("key-bob", "", "production").environment, std::string("production"), "an environment named by the caller, which the key is of");
|
||||
Equal(alice.Connectors().size(), std::size_t{1}, "each user sees their own connectors");
|
||||
Equal(bob.Connectors().at(0).name, std::string("Bob"), "and only those");
|
||||
Equal(Slurp(state / "users" / std::to_string(aliceUid) / "owner"), std::string("alice\n"), "a user's directory says whose it is");
|
||||
|
|
@ -279,8 +289,16 @@ namespace {
|
|||
|
||||
alice.Accounts();
|
||||
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.View" && Summary(bus) == "see your accounts and balances", "listing is the View action");
|
||||
alice.Transactions(aliceMain, {});
|
||||
const std::size_t listed = alice.Transactions(aliceMain, {}).size();
|
||||
Equal(Summary(bus), std::string("see your transactions"), "so are the transactions");
|
||||
// From what nostrod has stored alone: the bank is not asked, so what it has had since is not among it.
|
||||
bunq.AddPayment(bank.aliceMainId, 4200, "Carol", "NL65BUNQ2025222222", "since the last look");
|
||||
const std::size_t calls = bunq.Count("GET", "/user/");
|
||||
Equal(alice.Transactions(aliceMain, {.stored = true}).size(), listed, "a question about what is stored is answered from it");
|
||||
Check(bunq.Count("GET", "/user/") == calls && Summary(bus) == "see your transactions", "without a call to the bank, and after the same check");
|
||||
Equal(alice.Transactions(aliceMain, {.search = "since the last look", .stored = true}).size(), std::size_t{0}, "so a payment the bank has had since is not found there");
|
||||
Check(alice.Transactions(aliceMain, {.search = "since the last look"}).size() == 1 && bunq.Count("GET", "/user/") == calls + 1, "any other question asks the bank first, and finds it");
|
||||
Equal(alice.Transactions(aliceMain, {.search = "since the last look", .stored = true}).size(), std::size_t{1}, "after which it is stored");
|
||||
|
||||
alice.Request(aliceMain, bobIban, "Bob", 500, "back");
|
||||
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.Change" && Summary(bus) == std::format("ask {} (Bob) for €5.00 into {} (Main)", bobIban, aliceMain), "asking for money is a Change");
|
||||
|
|
@ -337,6 +355,22 @@ namespace {
|
|||
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.UnfreezeCard" && Summary(bus) == "unfreeze card **** 1234", "unfreezing one has an action of its own");
|
||||
alice.SetCardStatus(card, "STOLEN");
|
||||
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.BlockCard" && Summary(bus) == "report card **** 1234 stolen, which blocks it for good", "and so does blocking one for good");
|
||||
|
||||
// A virtual card is not frozen or unfrozen: bunq would leave it as it is and answer as if it had been done. It
|
||||
// is refused before anyone is asked for a password, and bunq is not asked at all.
|
||||
const std::uint64_t number = bunq.AddCard(bank.alice, "DEACTIVATED", json{{"order_status", "VIRTUAL_DELIVERY"}, {"primary_account_numbers", json::array({json{{"four_digit", "4321"}}})}});
|
||||
const auto prompted = [&bus] {
|
||||
std::lock_guard lock(bus.mutex);
|
||||
return bus.checks.size();
|
||||
};
|
||||
const std::size_t prompts = prompted();
|
||||
const std::size_t changes = bunq.Count("PUT", "/user/");
|
||||
for(const std::string_view status : {"DEACTIVATED", "ACTIVE"}) {
|
||||
Throws<std::invalid_argument>([&alice, number, status] { alice.SetCardStatus(number, status); }, std::format("card {} is a virtual card, which bunq does not freeze or unfreeze when asked", number), "a virtual card is not frozen or unfrozen");
|
||||
}
|
||||
Check(prompted() == prompts && bunq.Count("PUT", "/user/") == changes, "nobody is asked for a password for it, and bunq is not asked");
|
||||
Equal(alice.SetCardStatus(number, "LOST").status, std::string("LOST"), "it is reported lost like any card");
|
||||
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.BlockCard" && Summary(bus) == "report card **** 4321 lost, which blocks it for good", "which blocks it for good, after the password for that");
|
||||
}
|
||||
|
||||
void Outcomes(Fake::Bus& bus) {
|
||||
|
|
|
|||
|
|
@ -283,6 +283,29 @@ namespace {
|
|||
Equal(std::format("{}", cards.at(0)), std::format("{}\tACTIVE\tMASTERCARD_DEBIT\t**** 1234\tJ. Tester\tNostro\tNL01BUNQ0000000001\texpires 2030-11-30", active), "a card formats as one line");
|
||||
|
||||
Equal(connector.SetCardStatus(active, "DEACTIVATED").status, std::string("DEACTIVATED"), "freezing a card");
|
||||
Check(!cards.at(0).Virtual() && cards.at(0).State() == "ACTIVE" && cards.at(1).State() == "DEACTIVATED", "plastic stands as bunq says it does");
|
||||
cards.at(0).ExpectStatus("ACTIVE");
|
||||
Throws([&cards] { cards.at(0).ExpectStatus("DEACTIVATED"); }, "a card can only be frozen or unfrozen once it has been activated", "a card bunq kept as it was");
|
||||
|
||||
// A virtual card: bunq has it as DEACTIVATED however well it pays, and leaves it so when it is asked to freeze
|
||||
// or to unfreeze it, without an error. That status says nothing of it, and having it after a freeze does not
|
||||
// show the card was frozen.
|
||||
const std::uint64_t number = bunq.AddCard(connector.id, "DEACTIVATED", json{{"order_status", "VIRTUAL_DELIVERY"}});
|
||||
const std::vector<BunqCard> listed = connector.Cards();
|
||||
const BunqCard& virtualCard = *std::ranges::find(listed, number, &BunqCard::id);
|
||||
Check(virtualCard.Virtual() && virtualCard.status == "DEACTIVATED" && virtualCard.State() == "VIRTUAL", "a virtual card is said to be one, whatever bunq's status for it");
|
||||
Check(std::format("{}", virtualCard).starts_with(std::format("{}\tVIRTUAL\tMASTERCARD_DEBIT", number)), "and listed as one");
|
||||
for(const std::string_view asked : {"DEACTIVATED", "ACTIVE"}) {
|
||||
const BunqCard kept = connector.SetCardStatus(number, asked);
|
||||
Check(kept.status == "DEACTIVATED" && kept.State() == "VIRTUAL", "bunq leaves it as it is when asked to freeze or unfreeze it");
|
||||
Throws([&kept, asked] { kept.ExpectStatus(asked); }, "it is a virtual card, which bunq does not freeze or unfreeze", "which is not taken for having been done");
|
||||
}
|
||||
const BunqCard gone = connector.SetCardStatus(number, "LOST");
|
||||
Check(gone.Virtual() && gone.status == "LOST" && gone.State() == "LOST", "reported lost it is gone for good, as bunq then says");
|
||||
gone.ExpectStatus("LOST");
|
||||
const BunqCard paying{.id = 1, .kind = "CardDebit", .productType = "MASTERCARD_DEBIT", .status = "ACTIVE", .orderStatus = "VIRTUAL_DELIVERY", .nameOnCard = "", .secondLine = "", .lastFour = "", .expiry = "", .iban = ""};
|
||||
Check(paying.State() == "VIRTUAL", "and should bunq ever call one active, that is not taken for more than it is");
|
||||
Throws([&paying] { paying.ExpectStatus("ACTIVE"); }, "it is a virtual card", "nor for an unfreezing that worked");
|
||||
{
|
||||
std::lock_guard lock(bunq.mutex);
|
||||
bunq.cardsActivate = false;
|
||||
|
|
|
|||
426
tests/ShouldValidateForms/main.cpp
Normal file
426
tests/ShouldValidateForms/main.cpp
Normal file
|
|
@ -0,0 +1,426 @@
|
|||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// Nostro.App without nostrod: how money, days and the bank's capitals are worded (in a fixed time zone, so the
|
||||
// expectations hold anywhere), what each form reads from what was typed and what it refuses, what every error
|
||||
// nostrod can answer with is explained as, and what the app knows of each bank it can connect.
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
|
||||
import std;
|
||||
import Nostro;
|
||||
import Nostro.Ui;
|
||||
import Nostro.App;
|
||||
|
||||
#include "../Support/Check.inc"
|
||||
|
||||
using namespace Nostro;
|
||||
using namespace Nostro::App;
|
||||
using Test::Check;
|
||||
using Test::Equal;
|
||||
using Test::Throws;
|
||||
using Moment = std::chrono::system_clock::time_point;
|
||||
|
||||
namespace {
|
||||
constexpr std::string_view iban = "NL91ABNA0417164300";
|
||||
constexpr Currency euro = Currency::Euro;
|
||||
|
||||
void Words() {
|
||||
Equal(GroupIban(iban), std::string("NL91 ABNA 0417 1643 00"), "an IBAN is grouped in fours");
|
||||
for(const std::string_view other : {"", "NL9", "bob@example.org", "nl91abna0417164300", "NL91-ABNA", "N191ABNA", "NLA1ABNA", "NL9AABNA", "Savings"}) {
|
||||
Equal(GroupIban(other), std::string(other), "what is no IBAN is left as it is");
|
||||
}
|
||||
Equal(AccountKey(Account{.name = "Main", .bic = "BUNQNL2A", .iban = std::string(iban), .currency = euro, .balance = 0}), std::string(iban), "an account is found by its IBAN");
|
||||
Equal(AccountKey(Account{.name = "Pocket", .bic = "", .iban = "", .currency = euro, .balance = 0}), std::string("Pocket"), "or by its name where it has none");
|
||||
Equal(PartyName(BunqLabel{.name = "Bob", .iban = std::string(iban)}), std::string("Bob"), "someone is said by name");
|
||||
Equal(PartyName(BunqLabel{.name = "", .iban = std::string(iban)}), std::string("NL91 ABNA 0417 1643 00"), "else by IBAN");
|
||||
Equal(PartyName(BunqLabel{.name = "", .iban = ""}), std::string("Unknown"), "and as unknown where the bank says neither");
|
||||
Equal(PartyName(BunqCounterparty{.type = "IBAN", .value = std::string(iban), .name = "Bob"}), std::string("Bob"), "a payee by the name given");
|
||||
Equal(PartyName(BunqCounterparty{.type = "EMAIL", .value = "bob@example.org", .name = ""}), std::string("bob@example.org"), "else by the address");
|
||||
for(const auto& [minor, said] : std::array<std::pair<std::int64_t, std::string_view>, 7>{{{0, "€0.00"}, {99999, "€999.99"}, {100000, "€1,000.00"}, {-1250000, "-€12,500.00"}, {123456789012, "€1,234,567,890.12"}, {-5, "-€0.05"}, {100000000, "€1,000,000.00"}}}) {
|
||||
Equal(Money(minor, euro), std::string(said), "money has its thousands apart");
|
||||
}
|
||||
Equal(SignedMoney(1250, euro), std::string("+€12.50"), "money that came in has a plus");
|
||||
Equal(SignedMoney(250000, euro), std::string("+€2,500.00"), "and its thousands apart too");
|
||||
Equal(SignedMoney(-300, euro), std::string("-€3.00"), "money that went out a minus");
|
||||
Equal(SignedMoney(0, euro), std::string("€0.00"), "and nothing has neither");
|
||||
|
||||
const Moment now = ParseLocalDate("2026-11-19 15:00");
|
||||
Check(LocalDay(ParseLocalDate("2026-11-19 00:00")) == LocalDay(ParseLocalDate("2026-11-19 23:59")) && LocalDay(ParseLocalDate("2026-11-19 23:59")) != LocalDay(ParseLocalDate("2026-11-20 00:00")), "a day runs from midnight to midnight");
|
||||
Equal(DayLabel(ParseLocalDate("2026-11-19 08:00"), now), std::string("Today"), "today");
|
||||
Equal(DayLabel(ParseLocalDate("2026-11-18 23:59"), now), std::string("Yesterday"), "yesterday");
|
||||
Equal(DayLabel(ParseLocalDate("2026-11-03 12:00"), now), std::string("Tuesday 3 November"), "a day of this year by its name");
|
||||
Equal(DayLabel(ParseLocalDate("2025-12-31 12:00"), now), std::string("Wednesday 31 December 2025"), "one of another year with it");
|
||||
// The night the clocks go back: the day before is 25 hours long.
|
||||
Equal(DayLabel(ParseLocalDate("2026-10-24 23:30"), ParseLocalDate("2026-10-25 00:30")), std::string("Yesterday"), "yesterday across a change of the clocks");
|
||||
Equal(DayLabel(ParseLocalDate("2026-10-25 01:30"), ParseLocalDate("2026-10-26 00:10")), std::string("Yesterday"), "and after it");
|
||||
Equal(ShortDate(ParseLocalDate("2026-11-03"), now), std::string("3 Nov"), "a short date");
|
||||
Equal(ShortDate(ParseLocalDate("2025-12-31"), now), std::string("31 Dec 2025"), "with its year when that is another");
|
||||
Equal(ClockTime(ParseLocalDate("2026-11-03 14:05")), std::string("14:05"), "the time of day");
|
||||
Equal(FullTime(ParseLocalDate("2026-11-03 14:05")), std::string("3 November 2026, 14:05"), "a moment in full");
|
||||
Equal(DateInput(ParseLocalDate("2026-11-03 14:05")), std::string("2026-11-03"), "a day as a field takes it");
|
||||
|
||||
const std::array<std::pair<std::string_view, std::string_view>, 10> kinds = {{
|
||||
{"MASTERCARD/PAYMENT", "Card payment"}, {"EBA_SDD/SDD", "Direct debit"}, {"EBA_SCT/SCT", "Bank transfer"}, {"IDEAL/PAYMENT", "iDEAL"},
|
||||
{"SOFORT/PAYMENT", "Sofort"}, {"SWIFT/PAYMENT", "International transfer"}, {"BUNQ/REQUEST", "Paid request"}, {"BUNQ/PAYMENT", "Payment within the bank"},
|
||||
{"NEW/THING", "NEW/THING"}, {"", ""},
|
||||
}};
|
||||
for(const auto& [kind, label] : kinds) {
|
||||
Equal(KindLabel(kind), std::string(label), "a kind of payment in words");
|
||||
}
|
||||
Equal(StatusLabel("PIN_TRIES_EXCEEDED"), std::string("Pin tries exceeded"), "the bank's capitals as words");
|
||||
Equal(StatusLabel("sandbox"), std::string("Sandbox"), "and its small letters with a capital");
|
||||
Equal(CardProduct("MASTERCARD_DEBIT"), std::string("Mastercard debit"), "a card's product");
|
||||
Equal(CardExpiry("2030-11-30"), std::string("11/30"), "when a card expires, as its face has it");
|
||||
for(const std::string_view other : {"", "11/30", "2030-11-3", "2030/11/30", "2030-11_30", "203O-11-30", "2030-11-30T00"}) {
|
||||
Equal(CardExpiry(other), std::string(other), "what is no day is left as the bank says it");
|
||||
}
|
||||
|
||||
BunqSchedule schedule{.start = ParseLocalDate("2026-11-03")};
|
||||
Equal(ScheduleLabel(schedule, now), std::string("Once on 3 Nov"), "a payment scheduled once");
|
||||
schedule.start = ParseLocalDate("2026-11-03 14:05");
|
||||
Equal(ScheduleLabel(schedule, now), std::string("Once on 3 Nov, 14:05"), "with its time when that is not midnight");
|
||||
schedule.unit = "MONTHLY";
|
||||
schedule.start = ParseLocalDate("2026-11-03");
|
||||
Equal(ScheduleLabel(schedule, now), std::string("Every month from 3 Nov"), "one that repeats");
|
||||
schedule.unit = "WEEKLY";
|
||||
schedule.every = 2;
|
||||
schedule.end = ParseLocalDate("2027-01-01");
|
||||
Equal(ScheduleLabel(schedule, now), std::string("Every 2 weeks from 3 Nov until 1 Jan 2027"), "every so many, until a day");
|
||||
schedule.unit = "FORTNIGHTLY";
|
||||
schedule.end.reset();
|
||||
Equal(ScheduleLabel(schedule, now), std::string("Every 2 Fortnightlys from 3 Nov"), "a unit this does not know is said as bunq says it");
|
||||
for(const auto& [unit, word] : std::array<std::pair<std::string_view, std::string_view>, 3>{{{"HOURLY", "hour"}, {"DAILY", "day"}, {"YEARLY", "year"}}}) {
|
||||
schedule.unit = unit;
|
||||
schedule.every = 1;
|
||||
Equal(ScheduleLabel(schedule, now), std::format("Every {} from 3 Nov", word), "each unit bunq has");
|
||||
}
|
||||
|
||||
Equal(Fingerprint("short"), std::string("••••"), "a short secret shows nothing of itself");
|
||||
Equal(Fingerprint("sandbox_ab12cd34ef56gh78"), std::string("sandbox_…gh78"), "a key shows what it is for and how it ends");
|
||||
Equal(Fingerprint("abcdefghijklmnopqrst"), std::string("abcd…qrst"), "one without a mark its first four");
|
||||
Equal(Fingerprint("abcdefghijklmn_opqrst"), std::string("abcd…qrst"), "and so one whose mark comes late");
|
||||
}
|
||||
|
||||
void Reading() {
|
||||
for(const auto& [text, minor] : std::array<std::pair<std::string_view, std::int64_t>, 6>{{{"12,50", 1250}, {"12.50", 1250}, {" 12 ", 1200}, {"0,05", 5}, {"12.", 1200}, {"999999999999,99", 99999999999999}}}) {
|
||||
const Read<std::int64_t> read = ReadAmount(text, euro);
|
||||
Check(read.value == minor && read.error.empty(), std::format("'{}' is an amount", text));
|
||||
}
|
||||
for(const auto& [text, why] : std::array<std::pair<std::string_view, std::string_view>, 10>{{
|
||||
{"", "Enter an amount"}, {" ", "Enter an amount"}, {"abc", "Not an amount"}, {"-5", "Not an amount"}, {",5", "Not an amount"}, {"1,2,3", "Not an amount"},
|
||||
{"1,234", "At most 2 decimals"}, {"0", "An amount above zero"}, {"0,00", "An amount above zero"}, {"1234567890123", "That is too much"},
|
||||
}}) {
|
||||
const Read<std::int64_t> read = ReadAmount(text, euro);
|
||||
Check(!read.value && read.error.contains(why), std::format("'{}' is refused: {}", text, why));
|
||||
}
|
||||
|
||||
Equal(PartyKind(""), std::string(), "nothing typed is no kind of address yet");
|
||||
Equal(PartyKind(" bob@example.org"), std::string("E-mail address"), "an e-mail address by its @");
|
||||
Equal(PartyKind("+31612345678"), std::string("Phone number"), "a phone number by its +");
|
||||
Equal(PartyKind("NL91"), std::string("IBAN"), "anything else is an IBAN being typed");
|
||||
Read<BunqCounterparty> party = ReadParty(" NL91 ABNA 0417 1643 00 ");
|
||||
Check(party.value && party.value->type == "IBAN" && party.value->value == iban, "an IBAN as it is printed");
|
||||
party = ReadParty("nl91abna0417164300");
|
||||
Check(party.value && party.value->value == iban, "or in small letters");
|
||||
party = ReadParty("bob@example.org");
|
||||
Check(party.value && party.value->type == "EMAIL" && party.value->value == "bob@example.org", "an e-mail address");
|
||||
party = ReadParty("+31 6 1234 5678");
|
||||
Check(party.value && party.value->type == "PHONE_NUMBER" && party.value->value == "+31612345678", "a phone number");
|
||||
for(const auto& [text, why] : std::array<std::pair<std::string_view, std::string_view>, 7>{{
|
||||
{"", "An IBAN, an e-mail address or a phone number"}, {"NL91ABNA0417164301", "Not a valid IBAN"}, {"Bob", "Not a valid IBAN"},
|
||||
{"@example.org", "Not an e-mail address"}, {"bob@", "Not an e-mail address"}, {"bob smith@example.org", "Not an e-mail address"}, {"+31x", "Not a phone number"},
|
||||
}}) {
|
||||
const Read<BunqCounterparty> read = ReadParty(text);
|
||||
Check(!read.value && read.error.contains(why), std::format("'{}' is refused: {}", text, why));
|
||||
}
|
||||
|
||||
Check(ReadDay(" 2026-11-03 ").value == ParseLocalDate("2026-11-03"), "a day is its start");
|
||||
Check(ReadDay("2026-11-03", "14:05").value == ParseLocalDate("2026-11-03 14:05"), "or the time on it");
|
||||
Check(ReadDay("2026-11-03", {}, true).value == ParseLocalDateEnd("2026-11-03"), "or its last moment, for the end of a range");
|
||||
Check(ReadDay("2026-11-03", " 14:05 ", true).value == ParseLocalDate("2026-11-03 14:05"), "a time given is that time either way");
|
||||
for(const auto& [day, time, why] : std::array<std::tuple<std::string_view, std::string_view, std::string_view>, 5>{{
|
||||
{"", "", "A day: YYYY-MM-DD"}, {"2026-13-01", "", "Not a day"}, {"tomorrow", "", "Not a day"}, {"2026-13-01", "10:00", "Not a day"}, {"2026-11-03", "25:00", "Not a time: hh:mm"},
|
||||
}}) {
|
||||
const Read<Moment> read = ReadDay(day, time);
|
||||
Check(!read.value && read.error.contains(why), std::format("'{}' '{}' is refused: {}", day, time, why));
|
||||
}
|
||||
|
||||
Check(ReadCount("3").value == 3u && ReadCount(" 12 ").value == 12u, "a count");
|
||||
for(const std::string_view bad : {"", "0", "x", "1.5", "-1"}) {
|
||||
const Read<std::uint32_t> read = ReadCount(bad);
|
||||
Check(!read.value && read.error == "A whole number, 1 or more", std::format("'{}' is no count", bad));
|
||||
}
|
||||
}
|
||||
|
||||
void Paying() {
|
||||
const Moment now = ParseLocalDate("2026-11-19 15:00");
|
||||
PaymentForm form;
|
||||
PaymentOrder order;
|
||||
PaymentForm::Errors errors = form.Check(euro, now, order);
|
||||
Check(errors.Any() && !errors.to.empty() && !errors.amount.empty() && errors.name.empty(), "an empty form lacks who and how much");
|
||||
Check(!PaymentForm::Errors().Any(), "no errors is none");
|
||||
|
||||
form.to.Set("NL91 ABNA 0417 1643 00");
|
||||
form.amount.Set("12,50");
|
||||
form.description.Set(" lunch ");
|
||||
errors = form.Check(euro, now, order);
|
||||
Check(errors.Any() && errors.to.empty() && errors.amount.empty() && errors.name == "The name of the account's holder", "an IBAN needs its holder's name");
|
||||
Equal(order.amount, std::int64_t{0}, "and a form with an error gives no order");
|
||||
form.name.Set(" Bob ");
|
||||
errors = form.Check(euro, now, order);
|
||||
Check(!errors.Any() && order.to.type == "IBAN" && order.to.value == iban && order.to.name == "Bob" && order.amount == 1250 && order.description == "lunch" && order.when == When::Now, "a form filled in is an order");
|
||||
|
||||
form.to.Set("bob@example.org");
|
||||
form.name.Clear();
|
||||
errors = form.Check(euro, now, order);
|
||||
Check(!errors.Any() && order.to.type == "EMAIL" && order.to.name.empty(), "an e-mail address needs no name");
|
||||
|
||||
// A schedule: a first day, an optional time, and for one that repeats how often and until when.
|
||||
form.when = When::Scheduled;
|
||||
errors = form.Check(euro, now, order);
|
||||
Equal(errors.day, std::string("A day: YYYY-MM-DD"), "a schedule needs its first day");
|
||||
form.day.Set("soon");
|
||||
Equal(form.Check(euro, now, order).day, std::string("Not a day: YYYY-MM-DD"), "which is a day");
|
||||
form.day.Set("2026-11-18");
|
||||
Equal(form.Check(euro, now, order).day, std::string("Today or later"), "not one that has passed");
|
||||
form.day.Set("2026-11-19");
|
||||
Check(!form.Check(euro, now, order).Any() && order.when == When::Scheduled && order.schedule.unit == "ONCE" && order.schedule.start == ParseLocalDate("2026-11-19"), "today will do, once, from the start of the day");
|
||||
form.time.Set("25:00");
|
||||
Equal(form.Check(euro, now, order).time, std::string("Not a time: hh:mm"), "its time is one");
|
||||
form.day.Set("2026-11-20");
|
||||
form.time.Set("09:30");
|
||||
// Once has nothing to repeat: what is left in those fields is not looked at.
|
||||
form.every.Set("0");
|
||||
form.until.Set("never");
|
||||
Check(!form.Check(euro, now, order).Any() && order.schedule.start == ParseLocalDate("2026-11-20 09:30") && order.schedule.every == 1 && !order.schedule.end, "a time on the day, once");
|
||||
form.unit = 3;
|
||||
errors = form.Check(euro, now, order);
|
||||
Check(errors.every == "A whole number, 1 or more" && errors.until == "Not a day: YYYY-MM-DD", "one that repeats checks how often and until when");
|
||||
form.every.Set("2");
|
||||
form.until.Set("2026-11-19");
|
||||
Equal(form.Check(euro, now, order).until, std::string("After the first payment"), "it ends after it starts");
|
||||
form.until.Set("2027-01-01");
|
||||
Check(!form.Check(euro, now, order).Any() && order.schedule.unit == "WEEKLY" && order.schedule.every == 2 && order.schedule.end == ParseLocalDateEnd("2027-01-01"), "every other week until the end of a day");
|
||||
form.every.Clear();
|
||||
form.until.Clear();
|
||||
Check(!form.Check(euro, now, order).Any() && order.schedule.every == 1 && !order.schedule.end, "or every week, for as long as it runs");
|
||||
form.day.Set("nonsense");
|
||||
form.until.Set("2027-01-01");
|
||||
Check(form.Check(euro, now, order).until.empty(), "an end is not held against a start that is not there");
|
||||
|
||||
form.when = When::Draft;
|
||||
form.day.Clear();
|
||||
Check(!form.Check(euro, now, order).Any() && order.when == When::Draft, "a draft needs no day");
|
||||
form.tried = true;
|
||||
form.Clear();
|
||||
Check(form.to.value.empty() && form.amount.value.empty() && form.when == When::Now && form.unit == 0 && form.day.value.empty() && !form.tried, "a cleared form is as new");
|
||||
}
|
||||
|
||||
void Asking() {
|
||||
RequestForm form;
|
||||
RequestOrder order;
|
||||
RequestForm::Errors errors = form.Check(euro, order);
|
||||
Check(errors.Any() && !errors.from.empty() && !errors.amount.empty() && errors.name.empty() && !RequestForm::Errors().Any(), "an empty request lacks who and how much");
|
||||
form.from.Set(iban);
|
||||
form.amount.Set("5");
|
||||
Equal(form.Check(euro, order).name, std::string("The name of the account's holder"), "an IBAN needs its holder's name");
|
||||
form.name.Set("Bob");
|
||||
form.description.Set("back");
|
||||
Check(!form.Check(euro, order).Any() && order.from.value == iban && order.from.name == "Bob" && order.amount == 500 && order.description == "back", "a request filled in is an order");
|
||||
form.from.Set("+31612345678");
|
||||
form.name.Clear();
|
||||
Check(!form.Check(euro, order).Any() && order.from.type == "PHONE_NUMBER", "a phone number needs no name");
|
||||
form.tried = true;
|
||||
form.Clear();
|
||||
Check(form.from.value.empty() && form.amount.value.empty() && form.description.value.empty() && !form.tried, "a cleared request is as new");
|
||||
}
|
||||
|
||||
void Filtering() {
|
||||
const Moment now = ParseLocalDate("2026-11-19 15:00");
|
||||
FilterForm form;
|
||||
TransactionQuery query;
|
||||
query.limit = 300;
|
||||
Check(!form.Check(euro, query).Any() && query.search.empty() && !query.amount && query.from == Moment::min() && query.to == Moment::max() && query.limit == 300, "an empty filter asks for everything, as many as before");
|
||||
Check(form.Chips(euro, now).empty() && !FilterForm::Errors().Any(), "and shows nothing");
|
||||
form.search.Set(" rent ");
|
||||
form.amount.Set("12,50");
|
||||
form.from.Set("2026-11-01");
|
||||
form.to.Set("2026-11-30");
|
||||
Check(!form.Check(euro, query).Any() && query.search == "rent" && query.amount == -1250 && query.from == ParseLocalDate("2026-11-01") && query.to == ParseLocalDateEnd("2026-11-30"), "what went out, between two days, the last one whole");
|
||||
Check(form.Chips(euro, now) == std::vector<std::string>{"Paid €12.50", "From 1 Nov", "Until 30 Nov"}, "said in a few words each");
|
||||
form.received = true;
|
||||
Check(!form.Check(euro, query).Any() && query.amount == 1250 && form.Chips(euro, now).front() == "Received €12.50", "or what came in");
|
||||
|
||||
query = TransactionQuery();
|
||||
form.amount.Set("1,234");
|
||||
form.from.Set("soon");
|
||||
form.to.Set("later");
|
||||
const FilterForm::Errors errors = form.Check(euro, query);
|
||||
Check(errors.Any() && errors.amount.contains("At most 2 decimals") && errors.from.contains("Not a day") && errors.to.contains("Not a day") && query.search.empty(), "a filter with a mistake asks for nothing");
|
||||
Check(form.Chips(euro, now).empty(), "and what cannot be read is no chip");
|
||||
form.amount.Clear();
|
||||
form.from.Set("2026-11-30");
|
||||
form.to.Set("2026-11-01");
|
||||
Equal(form.Check(euro, query).to, std::string("On or after the first day"), "a range ends after it starts");
|
||||
form.to.Set("2026-11-30");
|
||||
Check(!form.Check(euro, query).Any(), "one day is a range");
|
||||
form.Reset();
|
||||
Check(form.amount.value.empty() && form.from.value.empty() && form.to.value.empty() && !form.received && form.search.value == " rent ", "a reset keeps the search and drops the rest");
|
||||
}
|
||||
|
||||
void Connecting() {
|
||||
BunqKeyForm key;
|
||||
Check(key.ips.value == "*" && key.Check() == "The API key, from the bunq app", "a new key form allows any address and lacks its key");
|
||||
key.key.Set("sandbox_0123456789abcdef");
|
||||
key.ips.Set("10.0.0.1");
|
||||
key.advanced = true;
|
||||
key.tried = true;
|
||||
Check(key.Check().empty(), "with a key it can be sent");
|
||||
key.Clear();
|
||||
Check(key.key.value.empty() && key.ips.value == "*" && !key.advanced && !key.tried, "a cleared key form is as new");
|
||||
|
||||
BunqOAuthForm oauth;
|
||||
BunqOAuthForm::Errors errors = oauth.Check();
|
||||
Check(errors.Any() && !errors.clientId.empty() && !errors.redirectUri.empty() && !errors.secret.empty() && !BunqOAuthForm::Errors().Any(), "an empty OAuth form lacks everything");
|
||||
oauth.clientId.Set(" client-1 ");
|
||||
oauth.secret.Set("secret-1");
|
||||
oauth.redirectUri.Set("ftp://example.org/cb");
|
||||
Check(!oauth.Check().redirectUri.empty() && oauth.Check().clientId.empty() && oauth.Check().secret.empty(), "a redirect address is a web address");
|
||||
oauth.redirectUri.Set("http://127.0.0.1/cb");
|
||||
Check(!oauth.Check().Any(), "to this computer itself will do");
|
||||
oauth.redirectUri.Set(" https://example.org/cb ");
|
||||
oauth.Begin("state123");
|
||||
Equal(oauth.address, std::string("https://oauth.bunq.com/auth?response_type=code&client_id=client-1&redirect_uri=https%3A%2F%2Fexample.org%2Fcb&state=state123"), "the address to approve at, with this request's state");
|
||||
oauth.sandbox = true;
|
||||
oauth.Begin("state456");
|
||||
Check(oauth.address.starts_with("https://oauth.sandbox.bunq.com/auth?") && oauth.state == "state456", "the sandbox has its own");
|
||||
oauth.redirected.Set(" https://example.org/cb?code=abc&state=state456 ");
|
||||
Equal(oauth.Code(), std::string("abc"), "the code in the address the browser was sent to");
|
||||
oauth.redirected.Set("https://example.org/cb?code=abc&state=state123");
|
||||
Throws<std::runtime_error>([&oauth] { oauth.Code(); }, "its state differs", "an answer to another request is refused");
|
||||
oauth.redirected.Set("https://example.org/cb?error=access_denied&error_description=No");
|
||||
Throws<std::runtime_error>([&oauth] { oauth.Code(); }, "bunq did not authorize", "and so is bunq's refusal");
|
||||
oauth.tried = true;
|
||||
oauth.Clear();
|
||||
Check(oauth.clientId.value.empty() && oauth.redirectUri.value.empty() && oauth.secret.value.empty() && !oauth.sandbox && oauth.redirected.value.empty() && oauth.state.empty() && oauth.address.empty() && !oauth.tried, "a cleared OAuth form is as new");
|
||||
}
|
||||
|
||||
template<typename E>
|
||||
Guidance Explained(E error, Operation operation) {
|
||||
return Explain(std::make_exception_ptr(std::move(error)), operation);
|
||||
}
|
||||
|
||||
void Explaining() {
|
||||
// What nostrod asks polkit for, per the policy nostro installs.
|
||||
const std::array<std::tuple<Operation, std::string_view, bool, bool>, 17> operations = {{
|
||||
{Operation::Load, Bus::actionView, false, false},
|
||||
{Operation::Send, Bus::actionPay, true, true}, {Operation::Schedule, Bus::actionPay, true, true},
|
||||
{Operation::PayRequest, Bus::actionPay, true, true}, {Operation::AcceptDraft, Bus::actionPay, true, true},
|
||||
{Operation::Draft, Bus::actionChange, false, false}, {Operation::Request, Bus::actionChange, false, false},
|
||||
{Operation::RevokeRequest, Bus::actionChange, false, false}, {Operation::RejectRequest, Bus::actionChange, false, false},
|
||||
{Operation::CancelSchedule, Bus::actionChange, false, false}, {Operation::RejectDraft, Bus::actionChange, false, false},
|
||||
{Operation::FreezeCard, Bus::actionChange, false, false},
|
||||
{Operation::UnfreezeCard, Bus::actionUnfreezeCard, true, false}, {Operation::BlockCard, Bus::actionBlockCard, true, false},
|
||||
{Operation::AddConnection, Bus::actionConnectors, true, false}, {Operation::RemoveConnection, Bus::actionConnectors, true, false},
|
||||
{Operation::SetCheckoutAccount, Bus::actionConnectors, true, false},
|
||||
}};
|
||||
for(const auto& [operation, action, password, money] : operations) {
|
||||
Check(ActionOf(operation) == action && AsksPassword(operation) == password && MovesMoney(operation) == money, std::format("operation {} asks for {}", std::to_underlying(operation), action));
|
||||
}
|
||||
|
||||
Guidance told = Explained(DaemonMissing("not there"), Operation::Load);
|
||||
Check(told.problem == Problem::NoService && told.retry && !told.mayHaveHappened && told.detail.contains("README") && told.detail.contains("not there"), "no nostrod: how to get one");
|
||||
for(const std::string_view name : {"org.freedesktop.systemd1.NoSuchUnit", "org.freedesktop.DBus.Error.Spawn.ChildExited", "org.freedesktop.DBus.Error.NameHasNoOwner"}) {
|
||||
Check(Explained(DaemonError(std::string(name), "could not start"), Operation::Send).problem == Problem::NoService, "a nostrod the bus could not start is no nostrod");
|
||||
}
|
||||
told = Explained(NoSystemBus("No such file or directory"), Operation::Load);
|
||||
Check(told.problem == Problem::NoService && told.retry && !told.mayHaveHappened && told.title == "The system bus cannot be reached" && told.detail.contains("No such file or directory"), "no system bus to reach nostrod over");
|
||||
told = Explained(OutcomeUnknown("no answer"), Operation::Send);
|
||||
Check(told.problem == Problem::Unknown && told.mayHaveHappened && !told.retry && told.title == "It may have been paid" && told.detail.contains("activity"), "a payment without a clear answer may have been made");
|
||||
told = Explained(OutcomeUnknown("no answer"), Operation::RevokeRequest);
|
||||
Check(told.problem == Problem::Unknown && told.mayHaveHappened && told.title == "It may have been done", "and any other change may have been");
|
||||
told = Explained(std::invalid_argument("no account is called 'Nope'"), Operation::Send);
|
||||
Check(told.problem == Problem::Input && !told.mayHaveHappened && !told.retry && told.detail == "no account is called 'Nope'. Nothing was sent.", "what nostrod refused before it began");
|
||||
told = Explained(DaemonError(std::string(Bus::errorCancelled), "cancelled"), Operation::Send);
|
||||
Check(told.problem == Problem::NotConfirmed && told.detail.contains("Nothing was done") && told.detail.contains("agent"), "no password: nothing was done, and why no dialog may have come");
|
||||
told = Explained(DaemonError("org.freedesktop.DBus.Error.AccessDenied", "the system's policy does not allow it"), Operation::Send);
|
||||
Check(told.problem == Problem::NotAllowed && told.detail.starts_with("the system's policy does not allow it") && !told.retry, "refused by the system's policy");
|
||||
Check(Explained(DaemonError("org.freedesktop.DBus.Error.AccessDenied", "no"), Operation::Load).retry, "a reading may be tried again");
|
||||
told = Explained(DaemonError("org.freedesktop.DBus.Error.InteractiveAuthorizationRequired", "x"), Operation::Send);
|
||||
Check(told.problem == Problem::CannotAsk && told.detail.contains("README"), "nostrod could not ask");
|
||||
told = Explained(DaemonError(std::string(Bus::errorOAuthCannotPay), "x"), Operation::Send);
|
||||
Check(told.problem == Problem::OwnAccountsOnly && told.title == "This connection cannot pay others" && told.detail.contains("draft"), "a connection that pays the user's own accounts only");
|
||||
Check(!told.detail.contains("bunq") && !told.detail.contains("OAuth"), "said of no bank and of no way to connect to one");
|
||||
told = Explained(DaemonError(std::string(Bus::errorBank), "bunq POST /payment: Not enough money. (400)"), Operation::Send);
|
||||
Check(told.problem == Problem::Bank && told.title == "The bank refused" && told.detail.contains("Not enough money") && !told.retry && !told.mayHaveHappened, "the bank's own refusal");
|
||||
Check(Explained(DaemonError(std::string(Bus::errorBank), "x"), Operation::Load).retry, "of a reading, which may be tried again");
|
||||
for(const std::string_view name : {"org.freedesktop.DBus.Error.NoReply", "org.freedesktop.DBus.Error.Timeout"}) {
|
||||
told = Explained(DaemonError(std::string(name), "timed out"), Operation::Load);
|
||||
Check(told.problem == Problem::Late && told.retry, "a reading that got no answer in time is only late");
|
||||
}
|
||||
told = Explained(DaemonError(std::string(Bus::errorFailed), "the worker went"), Operation::Send);
|
||||
Check(told.problem == Problem::Unknown && told.mayHaveHappened, "a payment nostrod failed at may have been made");
|
||||
told = Explained(DaemonError(std::string(Bus::errorFailed), "already connected"), Operation::AddConnection);
|
||||
Check(told.problem == Problem::Failed && told.detail == "already connected" && !told.mayHaveHappened && !told.retry, "anything else it failed at is said as it says it");
|
||||
Check(Explained(DaemonError(std::string(Bus::errorFailed), "x"), Operation::Load).retry, "and a reading may be tried again");
|
||||
told = Explained(std::system_error(std::make_error_code(std::errc::bad_message), "cannot read"), Operation::Send);
|
||||
Check(told.problem == Problem::Unknown && told.mayHaveHappened, "an answer to a change that cannot be read leaves it open");
|
||||
told = Explained(std::system_error(std::make_error_code(std::errc::not_connected), "cannot call nostrod"), Operation::Load);
|
||||
Check(told.problem == Problem::Failed && told.retry && !told.mayHaveHappened, "one to a reading does not");
|
||||
told = Explained(std::runtime_error("bunq kept card 7 DEACTIVATED"), Operation::UnfreezeCard);
|
||||
Check(told.problem == Problem::Failed && told.detail == "bunq kept card 7 DEACTIVATED" && !told.retry, "any other error is said as it is");
|
||||
Check(Explained(std::runtime_error("x"), Operation::Load).retry, "and a reading may be tried again");
|
||||
}
|
||||
|
||||
// What the app knows of the banks: each with its ways to connect, found by what nostrod calls them, and a bank
|
||||
// or a way it does not know, which a newer nostrod may have, said by nostrod's own name for it.
|
||||
void Knowing() {
|
||||
Check(!Banks().empty(), "there is a bank to connect");
|
||||
for(const Bank& bank : Banks()) {
|
||||
Check(FindBank(bank.id) == &bank && !bank.name.empty() && !bank.ways.empty(), "a bank is found by what nostrod calls it, and has a name and a way in");
|
||||
Equal(BankName(bank.id), std::string(bank.name), "and is said by its own name");
|
||||
std::set<std::string_view> keys;
|
||||
std::set<ConnectForm> forms;
|
||||
for(const Way& way : bank.ways) {
|
||||
Check(FindWay(bank.id, way.auth) == &way, "a way is found by what nostrod calls it");
|
||||
Check(!way.key.empty() && !way.title.empty() && !way.about.empty() && !way.revoke.empty(), "and has its words");
|
||||
Equal(WayName(bank.id, way.auth), std::string(way.title), "it is said by its title");
|
||||
Equal(OwnAccountsOnly(bank.id, way.auth), way.ownAccountsOnly, "what a connection made that way can pay is the way's to say");
|
||||
Equal(Revoking(bank.id, way.auth), std::string(way.revoke), "and so is where it is revoked");
|
||||
keys.insert(way.key);
|
||||
forms.insert(way.form);
|
||||
}
|
||||
Check(keys.size() == bank.ways.size() && forms.size() == bank.ways.size(), "its ways are told apart, each with a form of its own");
|
||||
}
|
||||
|
||||
const Bank* const bunq = FindBank(BunqConnector::connectorId);
|
||||
Check(bunq != nullptr && bunq->name == "bunq" && bunq->ways.size() == 2, "bunq is one of them, by its connector's own id, with two ways in");
|
||||
Check(FindWay("bunq", "api key")->form == ConnectForm::BunqKey && FindWay("bunq", "api key")->key == "key" && !OwnAccountsOnly("bunq", "api key"), "an API key, which does all a user can");
|
||||
Check(FindWay("bunq", "oauth")->form == ConnectForm::BunqOAuth && FindWay("bunq", "oauth")->key == "oauth" && OwnAccountsOnly("bunq", "oauth"), "and OAuth, which bunq lets pay between the user's own accounts only");
|
||||
Equal(WayName("bunq", "api key"), std::string("API key"), "as nostrod's \"api key\" is said");
|
||||
Check(Revoking("bunq", "api key").contains("API key") && Revoking("bunq", "oauth").contains("permission"), "each stays valid at bunq until it is revoked there");
|
||||
|
||||
Check(FindBank("thrift") == nullptr && FindWay("thrift", "api key") == nullptr && FindWay("bunq", "handshake") == nullptr, "a bank or a way the app does not know is not found");
|
||||
Equal(BankName("thrift"), std::string("thrift"), "such a bank is said as nostrod calls it");
|
||||
Equal(WayName("thrift", "password"), std::string("password"), "and so is its way");
|
||||
Equal(WayName("bunq", "handshake"), std::string("handshake"), "or a new way of a bank it knows");
|
||||
Check(!OwnAccountsOnly("thrift", "oauth") && !OwnAccountsOnly("bunq", "handshake"), "of which the app knows no limit");
|
||||
Check(Revoking("thrift", "password").contains("at the bank") && Revoking("bunq", "handshake") == Revoking("thrift", "password"), "and no more of revoking it than that it is done at the bank");
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
setenv("TZ", "Europe/Amsterdam", 1);
|
||||
tzset();
|
||||
Words();
|
||||
Reading();
|
||||
Paying();
|
||||
Asking();
|
||||
Filtering();
|
||||
Connecting();
|
||||
Explaining();
|
||||
Knowing();
|
||||
return Test::Result();
|
||||
}
|
||||
152
tests/ShouldWrapText/main.cpp
Normal file
152
tests/ShouldWrapText/main.cpp
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// Nostro.Ui's geometry and text: boxes and colours, the size classes, UTF-8 by code point, widths, the tap that
|
||||
// finds a byte, the ellipsis and the word wrap. The measure is a fixed one, every code point ten pixels wide whatever
|
||||
// its size, so every offset and width below is exact.
|
||||
|
||||
import std;
|
||||
import Nostro.Ui;
|
||||
|
||||
#include "../Support/Check.inc"
|
||||
|
||||
using namespace Nostro::Ui;
|
||||
using Test::Check;
|
||||
using Test::Equal;
|
||||
|
||||
namespace {
|
||||
TextMeasure Fixed() {
|
||||
TextMeasure measure;
|
||||
measure.advance = [](FontFace, std::uint32_t, float) { return 10.0f; };
|
||||
measure.ascent = [](FontFace, float px) { return px * 0.8f; };
|
||||
measure.lineHeight = [](FontFace, float px) { return px * 1.25f; };
|
||||
return measure;
|
||||
}
|
||||
|
||||
// Lines as text, to compare and to print: each as its bytes and its width.
|
||||
std::string Show(const std::vector<WrappedLine>& lines) {
|
||||
std::string shown;
|
||||
for(const WrappedLine& line : lines) {
|
||||
shown += std::format("[{},{}){} ", line.begin, line.end, line.width);
|
||||
}
|
||||
return shown;
|
||||
}
|
||||
|
||||
void Lines(const std::vector<WrappedLine>& actual, const std::vector<WrappedLine>& expected, std::string_view what, std::source_location where = std::source_location::current()) {
|
||||
Equal(Show(actual), Show(expected), what, where);
|
||||
}
|
||||
|
||||
void Geometry() {
|
||||
const Box box{10, 20, 30, 40};
|
||||
Check(box.Right() == 40 && box.Bottom() == 60 && box.Center() == Point{25, 40}, "a box's edges and its middle");
|
||||
Check(box.Contains({10, 20}) && box.Contains({39, 59}) && !box.Contains({40, 20}) && !box.Contains({10, 60}) && !box.Contains({9, 30}) && !box.Contains({20, 19}), "the left and top edges are inside, the right and bottom ones are not");
|
||||
Check(!box.Empty() && Box{0, 0, 0, 5}.Empty() && Box{0, 0, 5, 0}.Empty(), "a box without a width or a height is empty");
|
||||
Equal(box.Inset(Insets::All(5)) == Box{15, 25, 20, 30}, true, "insets take from every side");
|
||||
Equal(box.Inset(Insets::Symmetric(5, 10)) == Box{15, 30, 20, 20}, true, "or from the sides and from top and bottom");
|
||||
Equal(box.Inset(Insets::All(50)) == Box{60, 70, 0, 0}, true, "insets that leave nothing leave an empty box, not one inside out");
|
||||
Equal(box.Intersect({30, 50, 100, 100}) == Box{30, 50, 10, 10}, true, "what two boxes share");
|
||||
Check(box.Intersect({40, 20, 10, 10}).Empty() && box.Intersect({10, 60, 10, 10}).Empty(), "boxes that share an edge share nothing");
|
||||
Check(box.Overlaps({39, 59, 5, 5}) && !box.Overlaps({100, 100, 5, 5}), "whether two boxes overlap");
|
||||
|
||||
const Color red{1, 0, 0};
|
||||
Check(red.WithAlpha(0.5f) == Color{1, 0, 0, 0.5f}, "a colour at another opacity");
|
||||
Check(red.Mixed({0, 0, 1}, 0.5f) == Color{0.5f, 0, 0.5f, 1}, "a colour mixed half with another");
|
||||
Check(Color{1, 1, 1}.Luminance() > 0.99f && Color{0, 0, 0}.Luminance() == 0 && Color{0, 1, 0}.Luminance() > Color{0, 0, 1}.Luminance(), "green is brighter to the eye than blue");
|
||||
|
||||
Check(Metrics{1}.Dp(16) == 16 && Metrics{1.75f}.Dp(16) == 28 && Metrics{2.75f}.Dp(1) == 3, "a size of the design in whole pixels at the window's scale");
|
||||
Check(SizeClassFor(360, 1) == SizeClass::Compact && SizeClassFor(599, 1) == SizeClass::Compact, "a phone held upright is compact");
|
||||
Check(SizeClassFor(600, 1) == SizeClass::Medium && SizeClassFor(899, 1) == SizeClass::Medium, "a narrow window is medium");
|
||||
Check(SizeClassFor(900, 1) == SizeClass::Expanded, "a desktop window is expanded");
|
||||
Check(SizeClassFor(1080, 3) == SizeClass::Compact && SizeClassFor(1920, 1.75f) == SizeClass::Expanded, "the class goes by the width at the window's scale");
|
||||
Check(SizeClassFor(700, 0) == SizeClass::Medium, "a scale of nothing is a scale of one");
|
||||
}
|
||||
|
||||
void Utf8() {
|
||||
// a, é, € and 😀: one, two, three and four bytes; boundaries 0 1 3 6 10.
|
||||
const std::string mixed = "aé€\U0001F600";
|
||||
Equal(mixed.size(), std::size_t{10}, "the sample is ten bytes");
|
||||
std::size_t i = 0;
|
||||
Check(DecodeUtf8(mixed, i) == 'a' && i == 1 && DecodeUtf8(mixed, i) == 0xE9 && i == 3 && DecodeUtf8(mixed, i) == 0x20AC && i == 6 && DecodeUtf8(mixed, i) == 0x1F600 && i == 10, "one to four bytes decode to one code point each");
|
||||
Check(DecodeUtf8(mixed, i) == 0 && i == 10, "nothing is left at the end");
|
||||
i = 0;
|
||||
Check(DecodeUtf8("\xff", i) == 0xFFFD && i == 1, "a stray byte is consumed as a replacement");
|
||||
i = 0;
|
||||
Check(DecodeUtf8("\xe2\x82", i) == 0xFFFD && i == 2, "a sequence the text's end cuts short");
|
||||
i = 0;
|
||||
Check(DecodeUtf8("\xe2x", i) == 0xFFFD && i == 1 && DecodeUtf8("\xe2x", i) == 'x', "a sequence another character cuts short leaves that character");
|
||||
Check(NextCodepoint(mixed, 0) == 1 && NextCodepoint(mixed, 1) == 3 && NextCodepoint(mixed, 3) == 6 && NextCodepoint(mixed, 6) == 10 && NextCodepoint(mixed, 10) == 10, "stepping forward over one to four bytes, and staying at the end");
|
||||
Check(PreviousCodepoint(mixed, 10) == 6 && PreviousCodepoint(mixed, 6) == 3 && PreviousCodepoint(mixed, 3) == 1 && PreviousCodepoint(mixed, 1) == 0 && PreviousCodepoint(mixed, 0) == 0, "stepping back, and staying at the start");
|
||||
Equal(PreviousCodepoint(mixed, 99), std::size_t{6}, "from past the end is from the end");
|
||||
Check(CountCodepoints(mixed) == 4 && CountCodepoints("") == 0, "code points counted");
|
||||
}
|
||||
|
||||
void Measuring() {
|
||||
const TextMeasure measure = Fixed();
|
||||
Check(TextWidth(measure, "héllo", FontFace::Regular, 16) == 50 && TextWidth(measure, "", FontFace::Regular, 16) == 0, "a width counts code points, not bytes");
|
||||
Equal(TextWidth(measure, "a\nb", FontFace::Regular, 16), 20.0f, "a newline has no width");
|
||||
Equal(NearestByte(measure, "héllo", FontFace::Regular, 16, -5), std::size_t{0}, "a tap before the line is its start");
|
||||
Equal(NearestByte(measure, "héllo", FontFace::Regular, 16, 4), std::size_t{0}, "nearer the start of a character than its end");
|
||||
Equal(NearestByte(measure, "héllo", FontFace::Regular, 16, 6), std::size_t{1}, "nearer its end");
|
||||
Equal(NearestByte(measure, "héllo", FontFace::Regular, 16, 19), std::size_t{3}, "past a two-byte character, by its bytes");
|
||||
Equal(NearestByte(measure, "héllo", FontFace::Regular, 16, 500), std::size_t{6}, "a tap past the line is its end");
|
||||
Equal(CenteredBaseline(measure, {0, 100, 50, 40}, FontFace::Regular, 16), 100 + (40 - 20) / 2.0f + 12.8f, "the baseline that centres a line in a box");
|
||||
|
||||
Equal(Ellipsize(measure, "hello world", FontFace::Regular, 16, 200), std::string("hello world"), "an ellipsis: it fits");
|
||||
Equal(Ellipsize(measure, "hello world", FontFace::Regular, 16, 110), std::string("hello world"), "it fits exactly");
|
||||
Equal(Ellipsize(measure, "hello world", FontFace::Regular, 16, 60), std::string("hello…"), "cut with room for the mark");
|
||||
Equal(Ellipsize(measure, "x", FontFace::Regular, 16, 5), std::string("…"), "nothing fits");
|
||||
Equal(Ellipsize(measure, "line one\nline two", FontFace::Regular, 16, 200), std::string("line one…"), "a line break cuts too");
|
||||
}
|
||||
|
||||
void Wrapping() {
|
||||
WordWrapper wrap(Fixed());
|
||||
const auto lines = [&wrap](std::string_view text, float width) { return wrap.Wrap(text, FontFace::Regular, 10, width); };
|
||||
Lines(lines("hello world", 200), {{0, 11, 110}}, "fits on one line");
|
||||
Lines(lines("hello world", 60), {{0, 5, 50}, {6, 11, 50}}, "breaks at the space, the space in neither line");
|
||||
Lines(lines("hello world", 60), {{0, 5, 50}, {7, 12, 50}}, "a run of spaces is skipped at the break");
|
||||
Lines(lines("ab cdef", 50), {{0, 2, 20}, {4, 8, 40}}, "a run of spaces before the overflow goes to neither line");
|
||||
Lines(lines("abcdef ghi", 60), {{0, 6, 60}, {7, 10, 30}}, "a split forced at a space starts the next line after it");
|
||||
Lines(lines("abcdefghij", 35), {{0, 3, 30}, {3, 6, 30}, {6, 9, 30}, {9, 10, 10}}, "a long word splits between code points");
|
||||
Lines(lines("a\nb", 100), {{0, 1, 10}, {2, 3, 10}}, "a newline is a hard break");
|
||||
Lines(lines("a\n\nb", 100), {{0, 1, 10}, {2, 2, 0}, {3, 4, 10}}, "an empty line between two newlines");
|
||||
Lines(lines("ab\n", 50), {{0, 2, 20}, {3, 3, 0}}, "a text ending in a newline has an empty last line");
|
||||
Lines(lines("", 100), {{0, 0, 0}}, "empty text is one empty line");
|
||||
Lines(lines("well-known word", 60), {{0, 5, 50}, {5, 10, 50}, {11, 15, 40}}, "a hyphen is a break that stays on its line");
|
||||
Lines(lines("héllo wörld", 60), {{0, 6, 50}, {7, 13, 50}}, "multi-byte code points count once");
|
||||
Lines(lines("x", 5), {{0, 1, 10}}, "a single code point wider than the line is kept");
|
||||
Lines(lines("ab cd ef", 50), {{0, 5, 50}, {6, 8, 20}}, "a space that overflows ends the line after the words that fit");
|
||||
Lines(lines("abcde ", 50), {{0, 5, 50}}, "a trailing space that overflows opens no empty line");
|
||||
Lines(lines("abcd ", 50), {{0, 4, 40}}, "nor does a run of them");
|
||||
Lines(lines(" \nabc", 30), {{0, 3, 30}, {6, 9, 30}}, "a run of spaces wider than the line, before a newline: the split forced at a space opens no blank line either");
|
||||
Lines(lines("x\n ", 30), {{0, 1, 10}, {2, 5, 30}}, "nor at the text's end");
|
||||
Lines(lines("abcde \nx", 50), {{0, 5, 50}, {7, 8, 10}}, "a space that overflows before a newline leaves no blank line between the two");
|
||||
Lines(lines("abcde \n", 50), {{0, 5, 50}, {7, 7, 0}}, "a text ending in a newline keeps its empty last line");
|
||||
Lines(lines(" abcdef", 30), {{0, 3, 30}, {3, 6, 30}, {6, 7, 10}}, "a leading space is no break: no empty first line, the space stays on its line");
|
||||
Lines(lines("x\n abcd", 30), {{0, 1, 10}, {2, 5, 30}, {5, 7, 20}}, "nor is a space right after a newline");
|
||||
Lines(lines(" abcdef", 30), {{0, 3, 30}, {3, 6, 30}, {6, 8, 20}}, "nor is a run of them: the line opens with its first word, the spaces before it on that line");
|
||||
Lines(lines("x\n abcd", 30), {{0, 1, 10}, {2, 5, 30}, {5, 8, 30}}, "the same after a newline");
|
||||
Lines(lines("abcd ef", 50), {{0, 4, 40}, {6, 8, 20}}, "a space that overflows right behind another: the line ends before the run, and the next begins after it");
|
||||
|
||||
const std::vector<WrappedLine>& first = wrap.Wrap("cached text", FontFace::Regular, 10, 60);
|
||||
const std::vector<WrappedLine>& again = wrap.Wrap("cached text", FontFace::Regular, 10, 60);
|
||||
Check(&first == &again, "the same text, font, size and width come from the cache");
|
||||
const std::size_t before = wrap.CacheSize();
|
||||
wrap.Wrap("cached text", FontFace::Regular, 10, 70);
|
||||
wrap.Wrap("cached text", FontFace::Medium, 10, 60);
|
||||
wrap.Wrap("cached text", FontFace::Regular, 12, 60);
|
||||
Equal(wrap.CacheSize(), before + 3, "another width, font or size is another entry");
|
||||
for(std::size_t i = 0; i < WordWrapper::cacheLimit + 1; i++) {
|
||||
wrap.Wrap(std::format("text {}", i), FontFace::Regular, 10, 60);
|
||||
}
|
||||
Check(wrap.CacheSize() <= WordWrapper::cacheLimit, "a full cache is emptied, not grown");
|
||||
Check(wrap.Measure().advance(FontFace::Regular, 'x', 10) == 10, "the wrapper gives out the measure it wraps with");
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
Geometry();
|
||||
Utf8();
|
||||
Measuring();
|
||||
Wrapping();
|
||||
return Test::Result();
|
||||
}
|
||||
|
|
@ -66,8 +66,9 @@ namespace Fake {
|
|||
std::uint64_t nextId = 1000;
|
||||
std::uint32_t clock = 0;
|
||||
std::size_t pageSize = 200; // a listing sends at most this many per page, whatever its count asks
|
||||
std::chrono::milliseconds latency{0}; // how long every answer takes: a real bank is a network away
|
||||
std::string scheduledName = "ScheduledPayment";
|
||||
bool cardsActivate = true; // false: PUT card ACTIVE leaves the card as it is, as the sandbox does
|
||||
bool cardsActivate = true; // false: PUT card ACTIVE leaves the card as it is, as bunq does for one that was never activated
|
||||
|
||||
struct Installation {
|
||||
std::uint64_t id;
|
||||
|
|
@ -179,7 +180,9 @@ namespace Fake {
|
|||
json card = {
|
||||
{"id", id},
|
||||
{"status", status},
|
||||
{"order_status", "VIRTUAL_DELIVERY"},
|
||||
// Plastic the user has and activated, unless `extra` says otherwise: a virtual card is VIRTUAL_DELIVERY, and
|
||||
// bunq has one as DEACTIVATED however it stands.
|
||||
{"order_status", "DELIVERED_TO_CUSTOMER"},
|
||||
{"product_type", "MASTERCARD_DEBIT"},
|
||||
{"name_on_card", "J. Tester"},
|
||||
{"second_line", "Nostro"},
|
||||
|
|
@ -454,9 +457,13 @@ namespace Fake {
|
|||
if(method == "PUT" && is({"user", "*", "card", "*"})) {
|
||||
for(json& item : cards[self]) {
|
||||
json& card = item.begin().value();
|
||||
if(card.at("id").get<std::uint64_t>() == number(3)) {
|
||||
// By its id, which what a test put among the cards to be skipped has none of.
|
||||
if(card.value("id", std::uint64_t{0}) == number(3)) {
|
||||
const std::string status = body.at("status").get<std::string>();
|
||||
if(status != "ACTIVE" || cardsActivate) {
|
||||
// As bunq does: a virtual card asked to freeze or to unfreeze is left as it is and answered
|
||||
// without an error. Reporting it lost or stolen takes, as for any card.
|
||||
const bool ignored = card.value("order_status", std::string()) == "VIRTUAL_DELIVERY" && (status == "ACTIVE" || status == "DEACTIVATED");
|
||||
if(!ignored && (status != "ACTIVE" || cardsActivate)) {
|
||||
card["status"] = status;
|
||||
}
|
||||
return {200, Response(json::array({item}))};
|
||||
|
|
@ -629,6 +636,15 @@ namespace Fake {
|
|||
}
|
||||
|
||||
Crafter::HTTPResponse Answer(const Crafter::HTTPRequest& request) {
|
||||
// The bank's own time, before the lock: whoever reads or changes the bank meanwhile is not kept waiting.
|
||||
std::chrono::milliseconds wait{0};
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
wait = latency;
|
||||
}
|
||||
if(wait.count() > 0) {
|
||||
std::this_thread::sleep_for(wait);
|
||||
}
|
||||
std::lock_guard lock(mutex);
|
||||
std::string path = request.path.substr(0, request.path.find('?'));
|
||||
const std::string query = request.path.contains('?') ? request.path.substr(request.path.find('?') + 1) : std::string();
|
||||
|
|
|
|||
|
|
@ -89,6 +89,12 @@ namespace Fake {
|
|||
dropping.emplace_back(name);
|
||||
}
|
||||
|
||||
// Ends every connection this test's own process has made, as when the bus goes away under a client.
|
||||
void DisconnectOwn() {
|
||||
std::lock_guard lock(mutex);
|
||||
droppingOwn = true;
|
||||
}
|
||||
|
||||
// The other processes connected now: nostrod, and its workers.
|
||||
std::vector<pid_t> Peers() {
|
||||
std::lock_guard lock(mutex);
|
||||
|
|
@ -130,6 +136,7 @@ namespace Fake {
|
|||
std::vector<Connection> connections;
|
||||
std::map<std::string, std::size_t, std::less<>> names;
|
||||
std::vector<std::string> dropping;
|
||||
bool droppingOwn = false;
|
||||
std::vector<Later> later;
|
||||
std::uint32_t nextUnique = 1;
|
||||
|
||||
|
|
@ -156,6 +163,13 @@ namespace Fake {
|
|||
Drop(owner->second);
|
||||
}
|
||||
}
|
||||
if(std::exchange(droppingOwn, false)) {
|
||||
for(std::size_t i = 0; i < connections.size(); i++) {
|
||||
if(connections[i].pid == getpid()) {
|
||||
Drop(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
AnswerLater();
|
||||
fds.push_back(pollfd{listener, POLLIN, 0});
|
||||
for(const Connection& connection : connections) {
|
||||
|
|
|
|||
54
tests/Support/Ui.inc
Normal file
54
tests/Support/Ui.inc
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// What the tests of Nostro.Ui and of the app build frames with, included after `import Nostro.Ui;` and Check.inc: a
|
||||
// font of known sizes, so every position is exact, and the reading of a frame: what it says, and where.
|
||||
|
||||
namespace Test {
|
||||
// Every code point half its size wide: at 16 pixels, eight a character. A line is 1.25 sizes tall, its baseline
|
||||
// 0.8 of a size down.
|
||||
inline Nostro::Ui::TextMeasure FixedMeasure() {
|
||||
Nostro::Ui::TextMeasure measure;
|
||||
measure.advance = [](Nostro::Ui::FontFace, std::uint32_t, float px) { return px * 0.5f; };
|
||||
measure.ascent = [](Nostro::Ui::FontFace, float px) { return px * 0.8f; };
|
||||
measure.lineHeight = [](Nostro::Ui::FontFace, float px) { return px * 1.25f; };
|
||||
return measure;
|
||||
}
|
||||
|
||||
// Every line of text the frame shown draws, one to a line: what a failed check prints.
|
||||
inline std::string Said(const Nostro::Ui::Context& ui) {
|
||||
std::string said;
|
||||
for(const std::string& text : ui.Shown().draw.Texts()) {
|
||||
said += text;
|
||||
said += '\n';
|
||||
}
|
||||
return said;
|
||||
}
|
||||
|
||||
// Whether a line the frame draws has `text` in it.
|
||||
inline bool Says(const Nostro::Ui::Context& ui, std::string_view text) {
|
||||
return std::ranges::any_of(ui.Shown().draw.Texts(), [text](const std::string& line) { return line.contains(text); });
|
||||
}
|
||||
|
||||
// The frame says `text`.
|
||||
inline void Shows(const Nostro::Ui::Context& ui, std::string_view text, std::string_view what, std::source_location where = std::source_location::current()) {
|
||||
if(!Says(ui, text)) {
|
||||
std::println("FAIL {}:{}: {}: the screen does not say '{}'. It says:\n{}", where.file_name(), where.line(), what, text, Said(ui));
|
||||
failures++;
|
||||
}
|
||||
}
|
||||
|
||||
// The frame does not say `text`.
|
||||
inline void Hides(const Nostro::Ui::Context& ui, std::string_view text, std::string_view what, std::source_location where = std::source_location::current()) {
|
||||
if(Says(ui, text)) {
|
||||
std::println("FAIL {}:{}: {}: the screen says '{}'", where.file_name(), where.line(), what, text);
|
||||
failures++;
|
||||
}
|
||||
}
|
||||
|
||||
// A press and its release at one point, a tenth of a second apart: a tap as a finger makes it.
|
||||
inline void TapAt(Nostro::Ui::Context& ui, Nostro::Ui::Point at, std::int64_t tMs = 0) {
|
||||
ui.Pointer(Nostro::Ui::PointerPhase::Down, at, tMs);
|
||||
ui.Pointer(Nostro::Ui::PointerPhase::Up, at, tMs + 100);
|
||||
}
|
||||
}
|
||||
|
|
@ -37,6 +37,18 @@ for test in tests/Should*/; do
|
|||
done
|
||||
|
||||
ignore='(lib/json\.hpp|/tests/|/Crafter\.|/app/|/usr/)'
|
||||
llvm-cov report "$@" -instr-profile="$out/nostro.profdata" -ignore-filename-regex="$ignore"
|
||||
llvm-cov report "$@" -instr-profile="$out/nostro.profdata" -ignore-filename-regex="$ignore" | tee "$out/report.txt"
|
||||
llvm-cov show "$@" -instr-profile="$out/nostro.profdata" -ignore-filename-regex="$ignore" -format=text > "$out/sources.txt"
|
||||
awk '/^\/.*:$/ { file = $0 } /^ *[0-9]+\| *0\|/ { split($0, part, "|"); gsub(/ /, "", part[1]); print "not run: " file part[1] }' "$out/sources.txt"
|
||||
|
||||
# The toolkit and the app are built only for what depends on them, so a source of theirs that no test links would be
|
||||
# missing from the report, not listed in it as never run: each of their implementation units has to be there. The
|
||||
# window's (Nostro.Ui.Shell) are not among them: no test opens a window.
|
||||
missing=0
|
||||
for source in implementations/Nostro.Ui-*.cpp implementations/Nostro.App-*.cpp; do
|
||||
if ! grep -q "^$source " "$out/report.txt"; then
|
||||
echo "not in the report: $source, which no test links"
|
||||
missing=1
|
||||
fi
|
||||
done
|
||||
[ "$missing" = 0 ]
|
||||
|
|
|
|||
Loading…
Reference in a new issue