Skip to content
Repos

DevPlaceApp

C++ 20.1 KB477 lines Opens in site

Directory Raw Download

// Real path tests: DevPlaceRequest / ProdDevPlaceApi / LiveMessagesSocket through dp::NetworkService against a local
// aiohttpcpp server on 127.0.0.1 (random port). The SDL loop is replaced by TestPump.
#include <atomic>
#include <cstdio>

#include "ModelSamples.hpp"
#include "TestHarness.hpp"
#include "TestPump.hpp"
#include "TestTempDir.hpp"
#include "api/DevPlaceRequest.hpp"
#include "api/ProdDevPlaceApi.hpp"
#include "api/TestServer.hpp"
#include "core/AlertMessage.hpp"
#include "net/NetworkService.hpp"
#include "spec/NetLimits.hpp"
#include "store/AppState.hpp"
#include "store/SessionStore.hpp"

using namespace dp;
using dp::test::Reply;
using dp::test::SeenRequest;
using dp::test::Samples;
using dp::test::TestServer;

namespace {

bool startsWith(const std::string& text, const std::string& prefix) { return text.rfind(prefix, 0) == 0; }

// Fresh app state, network started once, base URL pointed at `server`, session store in a temp dir.
struct Env {
  explicit Env(TestServer* server) {
    static bool started = false;
    if (!started) {
      NetworkService::instance().start();
      started = true;
    }
    NetworkService::instance().setBaseUrl(server ? server->baseUrl() : "http://127.0.0.1:1/");
    SessionStore::instance().rebind(sessionDir.path());
    AppState::instance().clear();
  }
  ~Env() {
    AppState::instance().clear();
    NetworkService::instance().setBaseUrl(spec::NetLimits::kBaseUrl);
  }
  test::TempDir sessionDir;
};

AuthToken tokenIn(int seconds, const std::string& name) {
  AuthToken t;
  t.tokenType = "bearer";
  t.accessToken = name;
  t.expireTime = DateCodec::now() + std::chrono::seconds(seconds);
  return t;
}

template <class T>
struct Slot {
  bool done = false;
  std::optional<Result<T>> result;
  Done<T> callback() {
    return [this](Result<T> r) {
      result = std::move(r);
      done = true;
    };
  }
  bool wait() { return test::pumpUntil([this] { return done; }); }
};

Reply json(const std::string& body, int status = 200) { return Reply{status, body, "application/json", 0.0}; }

TestServer::Handler routes() {
  return [](const SeenRequest& r) -> Reply {
    if (r.path == "/auth/token") {
      Json body = Json::parse(r.body, nullptr, false);
      if (body.is_object() && body.value("password", "") == "good") return json(Samples::authToken(7200));
      return json(R"({"error":"Invalid email or password"})", 401);
    }
    if (r.path == "/profile") return json(Samples::profile());
    if (r.path == "/notifications/counts") return json(R"({"notifications":4,"messages":2})");
    if (r.path == "/feed") return json(Samples::feed());
    if (r.path == "/posts/create") return json(R"({"ok":true})");
    if (r.path == "/votes/post/p1") return json(R"({"ok":true})");
    if (r.path == "/uploads/upload") {
      return json(R"({"uid":"up1","original_filename":"pic.png","url":"https://x/pic.png","size":6,"is_image":true,"is_video":false,"is_audio":false,"mime_type":"image/png"})");
    }
    if (r.path == "/messages/ws-ticket") return json(R"({"ticket":"tick&et","expires_in":60})");
    if (r.path == "/fail422") return json(R"({"error":{"status":422,"errors":["Title too long","x"]}})", 422);
    if (r.path == "/fail500") return json("<html>oops</html>", 500);
    if (r.path == "/garbage") return json("not json at all");
    if (r.path == "/slow") return Reply{200, "{}", "application/json", 1.5};
    if (r.path == "/reports/reasons") return json(R"({"reasons":[{"key":"spam","label":"Spam"}]})");
    return json(R"({"error":"unknown route"})", 404);
  };
}

}  // namespace

DP_TEST(prod_login_stores_token_and_profile_user) {
  TestServer server(routes());
  Env env(&server);
  Slot<Unit> slot;
  ProdDevPlaceApi api;
  api.logIn("a@b.c", "good", slot.callback());
  CHECK(slot.wait());
  CHECK(slot.result->ok());
  auto seen = server.seen();
  CHECK_EQ(seen.size(), static_cast<std::size_t>(2));
  CHECK_EQ(seen[0].method, std::string("POST"));
  CHECK_EQ(seen[0].path, std::string("/auth/token"));
  CHECK_EQ(seen[0].contentType, std::string("application/json"));
  CHECK_EQ(seen[0].accept, std::string("application/json"));
  CHECK_EQ(seen[0].authorization, std::string(""));
  CHECK_EQ(Json::parse(seen[0].body)["email"].get<std::string>(), std::string("a@b.c"));
  CHECK_EQ(seen[1].path, std::string("/profile"));
  CHECK_EQ(seen[1].authorization, std::string("Bearer tok-abc"));
  CHECK_EQ(seen[1].contentType, std::string("application/x-www-form-urlencoded"));
  CHECK(AppState::instance().isLoggedIn());
  CHECK_EQ(AppState::instance().token()->accessToken, std::string("tok-abc"));
  CHECK_EQ(AppState::instance().currentUser()->username, std::string("alice"));
}

DP_TEST(prod_login_401_maps_error_and_alert) {
  TestServer server(routes());
  Env env(&server);
  Slot<Unit> slot;
  ProdDevPlaceApi api;
  api.logIn("a@b.c", "bad", slot.callback());
  CHECK(slot.wait());
  CHECK(!slot.result->ok());
  const Error& e = slot.result->error();
  CHECK(e.kind == Error::Kind::Unauthorized);
  CHECK_EQ(e.status, 401);
  CHECK(e.isSpecific);
  CHECK_EQ(e.message, std::string("Invalid email or password"));
  CHECK_EQ(AlertMessage::presentedError(e).message, std::string("Invalid email or password"));
  CHECK(!AppState::instance().isLoggedIn());
  CHECK_EQ(server.seen().size(), static_cast<std::size_t>(1));  // no profile call after a failed login
}

DP_TEST(prod_without_token_fails_not_logged_in_without_network) {
  TestServer server(routes());
  Env env(&server);
  ProdDevPlaceApi api;
  Slot<NotificationCounts> a;
  api.notificationCounts(a.callback());
  Slot<Unit> b;
  api.vote(TargetType::Post, "p1", Vote(Vote::Up), b.callback());
  CHECK(a.wait() && b.wait());
  CHECK(!a.result->ok() && a.result->error().message == "Not logged in");
  CHECK(!b.result->ok() && b.result->error().kind == Error::Kind::Local);
  CHECK(server.seen().empty());
  // feed works anonymously (token optional), no Authorization header
  Slot<Feed> f;
  api.feed(f.callback());
  CHECK(f.wait());
  CHECK(f.result->ok());
  CHECK_EQ(f.result->value().posts.size(), static_cast<std::size_t>(2));
  CHECK_EQ(server.last().authorization, std::string(""));
  // own profile needs a token
  Slot<Profile> p;
  api.profile(std::nullopt, p.callback());
  CHECK(p.wait());
  CHECK(!p.result->ok() && p.result->error().message == "Not logged in");
}

DP_TEST(prod_bearer_header_and_decode) {
  TestServer server(routes());
  Env env(&server);
  AppState::instance().setToken(tokenIn(7200, "live-token"));
  ProdDevPlaceApi api;
  Slot<NotificationCounts> slot;
  api.notificationCounts(slot.callback());
  CHECK(slot.wait());
  CHECK(slot.result->ok());
  CHECK_EQ(slot.result->value().notifications, 4);
  CHECK_EQ(server.last().authorization, std::string("Bearer live-token"));
  CHECK_EQ(server.last().path, std::string("/notifications/counts"));
  AppState& state = AppState::instance();
  bool loaded = false;
  state.loadUnreadCounts(api, [&] { loaded = true; });
  CHECK(test::pumpUntil([&] { return loaded; }));
  CHECK_EQ(state.unreadNotificationCount(), 4);
  CHECK_EQ(state.unreadMessageCount(), 2);
}

DP_TEST(request_error_and_decode_mapping) {
  TestServer server(routes());
  Env env(&server);
  DevPlaceRequest request;
  Slot<Feed> a;
  request.getFeed(std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, a.callback());
  CHECK(a.wait() && a.result->ok());
  // 422 object error: errors.first, specific
  Slot<Unit> b;
  AuthToken t = tokenIn(7200, "t");
  request.deleteComment("fail422", t, [&](Result<Unit>) {});
  request.forgotPassword("x", b.callback());  // 404 unknown route -> specific "unknown route"
  CHECK(b.wait());
  CHECK(!b.result->ok() && b.result->error().message == "unknown route" && b.result->error().status == 404);
  // dedicated paths through getProfile (path controlled by username)
  Slot<Profile> c;
  request.getProfile(std::string("fail422"), std::nullopt, std::nullopt, c.callback());
  CHECK(c.wait());
  CHECK(!c.result->ok());
  // server path is /profile/fail422 -> 404 by the router, still an API error
  CHECK_EQ(c.result->error().status, 404);
}

DP_TEST(request_generic_and_unreadable_errors) {
  TestServer server([](const SeenRequest& r) -> Reply {
    if (r.path == "/news") return Reply{500, "<html>oops</html>", "text/html", 0};
    if (r.path == "/leaderboard") return Reply{200, "not json", "application/json", 0};
    if (r.path == "/gists") return Reply{200, R"({"gists":[]})", "application/json", 0};  // required keys missing
    return Reply{422, R"({"error":{"status":422,"errors":["Title too long","x"]}})", "application/json", 0};
  });
  Env env(&server);
  DevPlaceRequest request;
  Slot<News> news;
  request.getNews(std::nullopt, std::nullopt, news.callback());
  CHECK(news.wait());
  CHECK(news.result->error().kind == Error::Kind::Http && news.result->error().status == 500);
  CHECK_EQ(AlertMessage::presentedError(news.result->error()).message, std::string("(500) Something went wrong. Please try again."));
  Slot<Leaderboard> lb;
  request.getLeaderboard(std::nullopt, lb.callback());
  CHECK(lb.wait());
  CHECK(lb.result->error().kind == Error::Kind::Decode);
  Slot<Gists> gists;
  request.getGists(std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, gists.callback());
  CHECK(gists.wait());
  CHECK(gists.result->error().kind == Error::Kind::Decode);
  Slot<Unit> post;
  request.createPost(std::nullopt, std::nullopt, "content", {}, std::nullopt, {}, std::nullopt, tokenIn(10, "t"), post.callback());
  CHECK(post.wait());
  CHECK(post.result->error().kind == Error::Kind::Api && post.result->error().message == "Title too long" && post.result->error().isSpecific);
}

DP_TEST(request_bodies_queries_and_paths) {
  TestServer server(routes());
  Env env(&server);
  DevPlaceRequest request;
  const AuthToken token = tokenIn(7200, "tk");
  Slot<Unit> a;
  request.createPost(std::optional<std::string>("T"), std::optional<PostTopic>(PostTopic::Devlog), "body text here", {}, std::nullopt,
                     {"x", "y"}, std::nullopt, token, a.callback());
  CHECK(a.wait() && a.result->ok());
  Json body = Json::parse(server.last().body);
  CHECK_EQ(body["topic"].get<std::string>(), std::string("devlog"));
  CHECK(!body.contains("poll_question"));
  CHECK(!body.contains("project_uid"));
  CHECK_EQ(body["attachment_uids"].size(), static_cast<std::size_t>(0));
  CHECK_EQ(body["poll_options"].size(), static_cast<std::size_t>(2));
  CHECK_EQ(server.last().authorization, std::string("Bearer tk"));

  Slot<Unit> v;
  request.vote(TargetType::Post, "p1", Vote(Vote::Up), token, v.callback());
  CHECK(v.wait() && v.result->ok());
  CHECK_EQ(server.last().path, std::string("/votes/post/p1"));
  CHECK_EQ(Json::parse(server.last().body)["value"].get<int>(), 1);

  Slot<Feed> f;
  Date before = *DateCodec::parseIso8601("2026-11-28T10:20:30Z");
  request.getFeed(std::nullopt, std::optional<std::string>("fun"), std::nullopt, before, std::nullopt, f.callback());
  CHECK(f.wait() && f.result->ok());
  CHECK(server.last().query.find("before=2026-11-28T10:20:30Z") != std::string::npos ||
        server.last().query.find("before=2026-11-28T10%3A20%3A30Z") != std::string::npos);
  CHECK(server.last().query.find("topic=fun") != std::string::npos);

  Slot<Unit> d;
  request.deleteAttachment("att 1", token, d.callback());
  CHECK(d.wait());
  CHECK_EQ(server.last().method, std::string("DELETE"));
  CHECK_EQ(server.last().path, std::string("/uploads/delete/att 1"));  // the server decodes the path

  CHECK_EQ(request.messagesWebSocketUrl("tick&et q%"), std::string("ws://127.0.0.1:" + std::to_string(server.port()) + "/messages/ws?ticket=tick&et%20q%25"));
  NetworkService::instance().setBaseUrl("https://devplace.net");
  CHECK_EQ(request.messagesWebSocketUrl("t"), std::string("wss://devplace.net/messages/ws?ticket=t"));
}

DP_TEST(request_multipart_upload) {
  TestServer server(routes());
  Env env(&server);
  DevPlaceRequest request;
  Slot<UploadResponse> up;
  const std::string bytes("\x89PNG\r\n\x1a\n-data", 14);
  request.uploadFile(bytes, "pic.png", "image/png", tokenIn(7200, "tk"), up.callback());
  CHECK(up.wait());
  if (!up.result->ok()) std::fprintf(stderr, "upload error: %s (%d)\n", up.result->error().message.c_str(), up.result->error().status);
  CHECK(up.result->ok());
  CHECK_EQ(up.result->value().id, std::string("up1"));
  CHECK(up.result->value().isImage);
  const SeenRequest s = server.last();
  CHECK(startsWith(s.contentType, "multipart/form-data; boundary=Boundary-"));
  const std::string boundary = s.contentType.substr(std::string("multipart/form-data; boundary=").size());
  CHECK(startsWith(s.body, "--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"pic.png\"\r\nContent-Type: image/png\r\n\r\n"));
  CHECK(s.body.find(bytes) != std::string::npos);
  CHECK(s.body.size() >= boundary.size() + 8 && s.body.substr(s.body.size() - boundary.size() - 8) == "\r\n--" + boundary + "--\r\n");
}

DP_TEST(offline_maps_to_offline_error) {
  Env env(nullptr);  // nothing listens on 127.0.0.1:1
  DevPlaceRequest request;
  Slot<Leaderboard> slot;
  request.getLeaderboard(std::nullopt, slot.callback());
  CHECK(slot.wait());
  CHECK(!slot.result->ok());
  CHECK(slot.result->error().kind == Error::Kind::Offline);
  CHECK_EQ(AlertMessage::presentedError(slot.result->error()).message, slot.result->error().message);
}

DP_TEST(timeout_maps_to_timeout_error) {
  TestServer server(routes());
  Env env(&server);
  HttpRequest request;
  request.path = "slow";
  request.timeoutSeconds = 0.3;
  request.maxRetries = 0;
  Slot<HttpResponse> slot;
  NetworkService::instance().send(request, slot.callback());
  CHECK(slot.wait());
  CHECK(!slot.result->ok());
  CHECK(slot.result->error().kind == Error::Kind::Timeout);
  CHECK_EQ(slot.result->error().message, std::string("The request timed out."));
}

DP_TEST(cancelled_request_never_calls_back) {
  TestServer server(routes());
  Env env(&server);
  DevPlaceRequest request;
  bool called = false;
  auto token = request.getLeaderboard(std::nullopt, [&](Result<Leaderboard>) { called = true; });
  token->cancel();
  test::pumpFor(0.4);
  CHECK(!called);
}

DP_TEST(token_refresh_before_request_uses_stored_credentials) {
  std::atomic<int> logins{0};
  TestServer server([&](const SeenRequest& r) -> Reply {
    if (r.path == "/auth/token") {
      const int n = ++logins;
      return json(R"({"token_type":"bearer","access_token":"tok)" + std::to_string(n) + R"(","expires_in":7200})");
    }
    if (r.path == "/profile") return json(Samples::profile());
    if (r.path == "/notifications/counts") return json(R"({"notifications":1,"messages":0})");
    if (r.path == "/feed") return json(Samples::feed());
    return json(R"({"error":"unknown"})", 404);
  });
  Env env(&server);
  ProdDevPlaceApi api;
  SessionStore::instance().setEmail(std::string("a@b.c"));
  SessionStore::instance().setPassword(std::string("good"));

  // Fresh token: no re-login.
  AppState::instance().setToken(tokenIn(7200, "fresh"));
  Slot<NotificationCounts> a;
  api.notificationCounts(a.callback());
  CHECK(a.wait());
  CHECK_EQ(logins.load(), 0);
  CHECK_EQ(server.last().authorization, std::string("Bearer fresh"));

  // Token expiring in 60 s: logs in again BEFORE the request, but the captured (stale) token is used (Swift parity).
  AppState::instance().setToken(tokenIn(60, "stale"));
  server.clearSeen();
  Slot<NotificationCounts> b;
  api.notificationCounts(b.callback());
  CHECK(b.wait() && b.result->ok());
  CHECK_EQ(logins.load(), 1);
  auto seen = server.seen();
  CHECK_EQ(seen.size(), static_cast<std::size_t>(3));
  CHECK_EQ(seen[0].path, std::string("/auth/token"));
  CHECK_EQ(seen[1].path, std::string("/profile"));
  CHECK_EQ(seen[2].path, std::string("/notifications/counts"));
  CHECK_EQ(seen[2].authorization, std::string("Bearer stale"));
  CHECK_EQ(AppState::instance().token()->accessToken, std::string("tok1"));

  // feed() reads the token AFTER the refresh.
  AppState::instance().setToken(tokenIn(60, "stale2"));
  server.clearSeen();
  Slot<Feed> c;
  api.feed(c.callback());
  CHECK(c.wait() && c.result->ok());
  CHECK_EQ(logins.load(), 2);
  CHECK_EQ(server.last().path, std::string("/feed"));
  CHECK_EQ(server.last().authorization, std::string("Bearer tok2"));
}

DP_TEST(token_refresh_failure_is_reported) {
  TestServer server([](const SeenRequest&) { return json(R"({"error":"Invalid email or password"})", 401); });
  Env env(&server);
  ProdDevPlaceApi api;
  SessionStore::instance().setEmail(std::string("a@b.c"));
  SessionStore::instance().setPassword(std::string("changed"));
  AppState::instance().setToken(tokenIn(10, "stale"));
  Slot<NotificationCounts> slot;
  api.notificationCounts(slot.callback());
  CHECK(slot.wait());
  CHECK(!slot.result->ok());
  CHECK(slot.result->error().kind == Error::Kind::Unauthorized);
  CHECK_EQ(server.seen().size(), static_cast<std::size_t>(1));  // the counts request never went out
}

DP_TEST(token_without_stored_credentials_still_sends_request) {
  TestServer server(routes());
  Env env(&server);
  AppState::instance().setToken(tokenIn(10, "keep"));
  ProdDevPlaceApi api;
  Slot<NotificationCounts> slot;
  api.notificationCounts(slot.callback());
  CHECK(slot.wait() && slot.result->ok());
  CHECK_EQ(server.last().authorization, std::string("Bearer keep"));
  CHECK_EQ(server.seen().size(), static_cast<std::size_t>(1));
}

DP_TEST(report_reasons_need_no_token) {
  TestServer server(routes());
  Env env(&server);
  ProdDevPlaceApi api;
  Slot<std::vector<ReportReason>> slot;
  api.reportReasons(slot.callback());
  CHECK(slot.wait() && slot.result->ok());
  CHECK_EQ(slot.result->value()[0].key, std::string("spam"));
  CHECK_EQ(server.last().authorization, std::string(""));
}

DP_TEST(messages_socket_ticket_flow_events_and_reconnect) {
  TestServer server(routes());
  server.setWsGreeting({R"({"type":"ready","user_uid":"u1"})",
                        R"({"type":"message","uid":"m1","sender_uid":"u2","receiver_uid":"u1","content":"hi","created_at":"2026-11-29T08:00:00Z"})"},
                       false);
  Env env(&server);
  AppState::instance().setToken(tokenIn(7200, "ws-token"));
  ProdDevPlaceApi api;
  auto socket = api.makeMessagesSocket("u2");
  std::vector<ChatSocketEvent> events;
  socket->setEventHandler([&](const ChatSocketEvent& e) { events.push_back(e); });
  socket->sendTyping();  // not connected yet: silently dropped
  socket->connect();
  CHECK(test::pumpUntil([&] { return events.size() >= 2; }));
  CHECK(events[0].type == ChatSocketEvent::Type::Ready && events[0].userUid == "u1");
  CHECK(events[1].type == ChatSocketEvent::Type::Message && events[1].message->content == "hi");
  CHECK_EQ(server.last().path, std::string("/messages/ws-ticket"));
  CHECK_EQ(server.last().authorization, std::string("Bearer ws-token"));
  CHECK_EQ(server.wsLastQuery(), std::string("ticket=tick&et"));
  socket->sendTyping();
  socket->send("hello/world", {"a1"}, "cid-1");
  socket->sendRead("u2");
  CHECK(test::pumpUntil([&] { return server.wsReceived().size() >= 3; }));
  auto got = server.wsReceived();
  CHECK_EQ(got[0], std::string(R"({"type":"typing","receiver_uid":"u2"})"));
  CHECK_EQ(got[1], std::string(R"({"type":"send","receiver_uid":"u2","content":"hello\/world","attachment_uids":["a1"],"client_id":"cid-1"})"));
  CHECK_EQ(got[2], std::string(R"({"type":"read","with_uid":"u2"})"));
  socket->disconnect();
  const int connections = server.wsConnections();
  test::pumpFor(0.5);
  CHECK_EQ(server.wsConnections(), connections);  // no reconnect after disconnect()
}

DP_TEST(messages_socket_reconnects_with_fresh_ticket_after_server_close) {
  TestServer server(routes());
  server.setWsGreeting({R"({"type":"ready","user_uid":"u1"})"}, true);  // server closes right after the greeting
  Env env(&server);
  AppState::instance().setToken(tokenIn(7200, "ws-token"));
  ProdDevPlaceApi api;
  auto socket = api.makeMessagesSocket("u2");
  int ready = 0, disconnected = 0;
  socket->setEventHandler([&](const ChatSocketEvent& e) {
    if (e.type == ChatSocketEvent::Type::Ready) ++ready;
    if (e.type == ChatSocketEvent::Type::Disconnected) ++disconnected;
  });
  socket->connect();
  CHECK(test::pumpUntil([&] { return ready >= 2 && disconnected >= 1; }, 10.0));
  int tickets = 0;
  for (const auto& r : server.seen()) tickets += r.path == "/messages/ws-ticket" ? 1 : 0;
  CHECK(tickets >= 2);  // a new ticket per connect
  CHECK(server.wsConnections() >= 2);
  socket->disconnect();
}
49.1ms