Nostro/tests/ShouldAnswerAsynchronously/main.cpp

398 lines
21 KiB
C++
Raw Normal View History

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>
2026-11-19 12:27:14 +01:00
// 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");
feat: open payto links on the pay form, and take the checkout over D-Bus out An app could have nostrod pay an order: it called Pay of net.catcrafts.Nostro1.Checkout on the system bus, and nostrod paid from an account the user had chosen, after a dialog of its own. On 2026-11-22 the owner decided that a link takes its place. The app registers for payto links (RFC 8905), so that an app or a website can hand one to the desktop, and shows a link as its pay form filled in. The link: - The app's desktop entry takes the scheme (Exec=nostro-app %u, MimeType=x-scheme-handler/payto), and nostro-app takes an argument that is no option as a link: it overwrites it in argv and hands it to App::Open once the app has started. - ReadPaymentLink (Nostro.App:Forms) reads payto://iban/<IBAN> with the options amount, receiver-name and message, and refuses a link rather than guess at it, in a sentence of the app's own with nothing of the link in it. Among what it refuses: an IBAN whose check digits do not hold, one of the three options given twice, instruction, a comma in the amount, and a name or a message with a code point that is Unshown, or Blank and no plain space. - A link that is read waits until the accounts are read and DefaultCheckoutAccount has answered or failed, with a line on the accounts' page. Then App::TakeLink fills in the pay form, which says in a banner that a link filled it in, and with more than one account opens it under the choice of accounts that the form's From row has. A link pays nothing: the form's button sends, and polkit's dialog confirms as for any payment (design rule 12, and 14, which is new). - Unshown and Blank are the two tables the worker's Shown() works from. They move into Nostro:Utils, where the app's reader asks them too. The move is within the library. The reader holds a link's name to those two and to no more of Shown(): a name with an & is read, and the dialog shows it with a + as it does any name. The checkout: - nostrod serves one interface under one bus name. Gone are net.catcrafts.Nostro1.Checkout with its XML and its activation file, the polkit action Checkout, the module Nostro.Checkout with --product=checkout, and the worker's record of orders. That changes the published contract after a release, 0.0.0, and design rule 10 records it as the owner's decision. - DefaultCheckoutAccount and SetDefaultCheckoutAccount keep their names and signatures. The account they keep is where a link's pay form starts: nostrod's dialog for choosing it says "have pay links start from", the app's setting reads "Pay links start from", and `nostro checkout account` prints "pay links start from". - The D-Bus policy still lets nostrod own the old name: the nostrod of 0.0.0 asks for it when it starts, and the system files can be newer than the Flatpak it runs from. install.sh removes the old name's activation file. A user's checkouts.cdb is read by nothing any more, and is left where it is. - The Arch package stops installing the checkout's two files, and its pkgrel goes up to 2. Where makepkg -si finds a package of the version already built it installs that one again, which would bring the activation file back. The guide now says that pkgrel goes up with a change to what the package installs. - Bus::Interface goes too: the worker called it in two places, to tell a call to the checkout from one to the main interface. The review's own files follow. gate0 loses the build of --product=checkout, and the three lens sections that named the checkout no longer do, and ask about a link. The README has "Pay links" in place of "Checkout for apps", and AGENTS.consumer.md says what the app reads of a link. Its line on lib/json.hpp no longer gives a release: the file is of none, and the guide names its commit. The pay form and the accounts' page change only by a banner each, shown while a link is in play, which docs/screenshots/take.sh never has: the README's pictures stand. Tests: ShouldValidateForms reads and refuses links and fills the form from one. ShouldDriveTheApp opens links against a real nostrod on the fake bus: before the accounts are known, with no account, with one and with several, with the accounts known and the system bus gone, for a second user whose first connection pays their own accounts only, one that cannot be read, one whose name has an &, and through polkit's dialog to the payment. It now counts nostrod's answers to hold that the account pay links start from is read again once a connection is removed: the check it had there passed without that. ShouldHandleMoneyAndText holds the two tables at the ends of their ranges. ShouldServeEveryUser holds that nostrod serves no checkout, that the bus's policy lets an older nostrod own the old name, and the account pay links start from. ShouldRunCommands holds the CLI's wording. The review's gate0 passes at this commit: the version check, 17 tests, the builds of the CLI, the library, nostrod, the fake system, the app and its --debug-api build, and five lint runs that report nothing. tests/coverage.sh reports lines, functions and regions at 100.00%. Looked at on 2026-11-22 on the made-up system (run fake), on a desktop (KWin at a scale of 1.85). At 420x760, at --scale 3 --size 360x760 and at 1100x720 in the light look: a link's pay form under the choice of accounts, the form after a tap beside that choice, and the accounts' page while a link waits, its line above the rows that stand in for the accounts (--bank-delay 10000). At 420x760: that line above what the page says when the accounts cannot be read (--polkit deny) and above the accounts themselves (--polkit slow, the link opened in the running app), the settings' row and page for the account pay links start from, the sheet for a link that cannot be read, and with --empty the sheet for no account.
2026-11-22 13:35:51 +01:00
Check(!Result<std::optional<Account>>(loop, [&client](auto then) { return client.DefaultCheckoutAccount(std::move(then)); }).has_value(), "no account is the one pay links start from yet");
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>
2026-11-19 12:27:14 +01:00
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 = [&notes](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();
}