Lines
95.6 %
Functions
96.25 %
Branches
100 %
//! A real `web` server and a headless Chrome over chromedriver, against a
//! freshly registered tenant of the test database.
use std::collections::HashMap;
use std::future::Future;
use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
use anyhow::{Context, Result, anyhow, bail};
use axum::Json;
use server::command::{
CmdResult, FinanceEntity, account::CreateAccount, commodity::CreateCommodity,
};
use sqlx::Connection;
use tempfile::TempDir;
use tests_integration::tenant_guard::TestTenant;
use uuid::Uuid;
use web::model::RegisterUserSchema;
use super::driver::Driver;
use super::listener::owned_by;
const STARTUP: Duration = Duration::from_secs(90);
/// How long a page or an element may take to be ready. The server bounds each
/// database acquire and connect at 10 s. A cold page request waits on up to
/// three (the directory route, the tenant connect, the tenant acquire), the
/// options fetch behind `data-suggest-ready` on one more, and two more cover
/// the browser's own navigation and a WebDriver round trip stalled by the
/// same contention.
pub(super) const READY_DEADLINE: Duration = Duration::from_secs(6 * 10);
const PASSWORD: &str = "e2e-password-1";
/// A child in the test's own process group, so whatever kills the test also
/// reaches it. Dropping it kills its descendants (Chrome) and then itself.
pub(super) struct Process(Child);
impl Process {
pub(super) fn spawn(command: &mut Command) -> std::io::Result<Self> {
command.spawn().map(Self)
}
pub(super) fn id(&self) -> u32 {
self.0.id()
/// Every descendant of `pid`, children before their parents.
pub(super) fn descendants(pid: u32) -> Vec<u32> {
let children = Command::new("pgrep")
.args(["-P", &pid.to_string()])
.stderr(Stdio::null())
.output()
.map(|out| String::from_utf8_lossy(&out.stdout).into_owned())
.unwrap_or_default();
let children: Vec<u32> = children
.lines()
.filter_map(|l| l.trim().parse().ok())
.collect();
children
.iter()
.flat_map(|child| descendants(*child))
.chain(children.iter().copied())
.collect()
impl Drop for Process {
fn drop(&mut self) {
for pid in descendants(self.0.id()) {
drop(
Command::new("kill")
.args(["-KILL", &pid.to_string()])
.status(),
);
drop(self.0.kill());
drop(self.0.wait());
fn free_port() -> Result<u16> {
Ok(TcpListener::bind("127.0.0.1:0")?.local_addr()?.port())
/// Attempts to start a listener on a fresh port before giving up.
const START_ATTEMPTS: usize = 3;
/// Spawns `start(port)` on a fresh port until it listens. A port picked by
/// `free_port` can be taken by a parallel test before the child binds it, so a
/// child that exits before listening is retried on a new port.
async fn start_listening<F>(what: &str, mut start: F) -> Result<(Process, u16)>
where
F: FnMut(u16) -> Result<Process>,
{
let mut last = anyhow!("{what} was never started");
for _ in 0..START_ATTEMPTS {
let port = free_port()?;
let mut process = start(port)?;
match wait_for_port(port, &mut process, what, STARTUP).await {
Ok(()) => return Ok((process, port)),
Err(err) => last = err,
Err(last)
/// Waits until `process` itself listens on `port`. A connect alone is not
/// enough: a foreign listener that won the port answers it too.
pub(super) async fn wait_for_port(
port: u16,
process: &mut Process,
what: &str,
startup: Duration,
) -> Result<()> {
let deadline = Instant::now() + startup;
while Instant::now() < deadline {
if let Some(status) = process.0.try_wait()? {
bail!("{what} exited with {status} before listening on {port}");
if owned_by(process.0.id(), port) && TcpStream::connect(("127.0.0.1", port)).is_ok() {
return Ok(());
tokio::time::sleep(Duration::from_millis(100)).await;
bail!("{what} did not listen on {port} within {startup:?}")
/// A chromedriver whose temp files (its `scoped_dir`, Chrome's singleton
/// directories) all land under `tmp`.
pub(super) async fn chromedriver(tmp: &Path) -> Result<(Process, String)> {
let (process, port) = start_listening("chromedriver", |port| {
Process::spawn(
Command::new("chromedriver")
.arg(format!("--port={port}"))
.env("TMPDIR", tmp)
.stdout(Stdio::null())
.stderr(Stdio::null()),
)
.context("chromedriver must be on PATH")
})
.await?;
Ok((process, format!("http://127.0.0.1:{port}")))
/// `DATABASE_URL` naming `database` instead.
fn database_url(database: &str) -> Result<String> {
let base = std::env::var("DATABASE_URL")?;
let (head, query) = base.split_once('?').unwrap_or((&base, ""));
let (server, _) = head
.rsplit_once('/')
.ok_or_else(|| anyhow!("DATABASE_URL names no database"))?;
let query = if query.is_empty() {
String::new()
} else {
format!("?{query}")
Ok(format!("{server}/{database}{query}"))
/// The server's own directory database, so its boot migrates nothing the
/// other tests share.
struct Directory {
url: String,
_guard: TestTenant,
impl Directory {
async fn create() -> Result<Self> {
let name = format!("nomisync_e2e_{}", Uuid::new_v4().simple());
let guard = TestTenant::database(name.clone());
let mut conn = server::db::get_connection().await?;
sqlx::query(sqlx::AssertSqlSafe(format!("CREATE DATABASE {name}")))
.execute(&mut *conn)
let url = database_url(&name)?;
Ok(Self { url, _guard: guard })
/// Copies the directory row of `user` from the shared directory.
async fn admit(&self, user: Uuid) -> Result<()> {
let mut shared = server::db::get_connection().await?;
let row: (String, String, String, String, String) = sqlx::query_as(
"SELECT user_name, email, user_password, database_name, jwt_public_key \
FROM users WHERE id = $1",
.bind(user)
.fetch_one(&mut *shared)
let mut own = sqlx::PgConnection::connect(&self.url).await?;
sqlx::query(
"INSERT INTO users (id, user_name, email, user_password, database_name, \
jwt_public_key, verified) VALUES ($1, $2, $3, $4, $5, $6, TRUE)",
.bind(row.0)
.bind(row.1)
.bind(row.2)
.bind(row.3)
.bind(row.4)
.execute(&mut own)
Ok(own.close().await?)
async fn web_server(directory: &Directory) -> Result<(Process, String)> {
let manifest = Path::new(env!("CARGO_MANIFEST_DIR"));
let redis = crate::common::redis_url();
let (process, port) = start_listening("web", |port| {
let child = Command::new(env!("CARGO_BIN_EXE_web"))
.env("WEB_LISTEN", format!("127.0.0.1:{port}"))
.env("METRICS_LISTEN", format!("127.0.0.1:{}", free_port()?))
.env("STATIC_PATH", manifest.join("static"))
.env("TRUSTED_PROXIES", "none")
.env("INSECURE_COOKIES", "1")
.env("REDIS_URL", &redis)
.env("DATABASE_URL", &directory.url)
.env("RUST_LOG", "warn")
.spawn()
.context("the web binary")?;
Ok(Process(child))
/// Where the screenshots go: `E2E_SHOTS`, else a temporary directory.
fn shots_dir() -> PathBuf {
std::env::var_os("E2E_SHOTS").map_or_else(
|| std::env::temp_dir().join("nomisync-e2e-shots"),
PathBuf::from,
/// A registered user who can log in, and the ids of what was seeded.
pub struct Tenant {
pub id: Uuid,
pub email: String,
pub password: &'static str,
pub accounts: HashMap<&'static str, Uuid>,
pub commodities: HashMap<&'static str, Uuid>,
async fn register() -> Result<(Uuid, String, TestTenant)> {
let email = format!("e2e-{}@example.test", Uuid::new_v4().simple());
let guard = TestTenant::registered(email.clone());
let schema = RegisterUserSchema {
name: "E2E".to_string(),
email: email.clone(),
password: PASSWORD.to_string(),
let registered = web::register::register_user_handler(Json(schema)).await;
registered
.map(drop)
.map_err(|e| anyhow!("register: {e:?}"))?;
let verified = server::command::user::verify_user_password(&email, PASSWORD)
.await
.map_err(|e| anyhow!("verify: {e:?}"))?
.ok_or_else(|| anyhow!("the registered user cannot log in"))?;
Ok((verified.user_id, email, guard))
async fn account(user: Uuid, name: &str, parent: Option<Uuid>) -> Result<Uuid> {
let mut command = CreateAccount::new().name(name.to_string()).user_id(user);
if let Some(parent) = parent {
command = command.parent(parent);
match command.run().await.map_err(|e| anyhow!("{e:?}"))? {
Some(CmdResult::Entity(FinanceEntity::Account(account))) => Ok(account.id),
other => bail!("expected an account, got {other:?}"),
async fn commodity(user: Uuid, symbol: &str) -> Result<Uuid> {
let created = CreateCommodity::new()
.symbol(symbol.to_string())
.name(symbol.to_string())
.user_id(user)
.run()
.map_err(|e| anyhow!("{e:?}"))?;
match created {
Some(CmdResult::String(id)) => Ok(Uuid::parse_str(&id)?),
other => bail!("expected a commodity id, got {other:?}"),
/// Two top-level accounts named `Cafe` (`Cafe` and `Cafe2` here), a child
/// of each top-level name, and plain accounts.
async fn seed(id: Uuid, email: String) -> Result<Tenant> {
let mut accounts = HashMap::new();
for name in ["Suica", "Wallet", "Bank", "Transportation", "Cafe"] {
accounts.insert(name, account(id, name, None).await?);
accounts.insert("Cafe2", account(id, "Cafe", None).await?);
accounts.insert(
"JR",
account(id, "JR", Some(accounts["Transportation"])).await?,
"McDonalds",
account(id, "McDonalds", Some(accounts["Cafe"])).await?,
let mut commodities = HashMap::new();
for symbol in ["JPY", "EUR"] {
commodities.insert(symbol, commodity(id, symbol).await?);
Ok(Tenant {
id,
email,
password: PASSWORD,
accounts,
commodities,
pub struct Harness {
pub driver: Driver,
pub base: String,
pub tenant: Tenant,
pub shots: PathBuf,
_web: Process,
_chromedriver: Process,
// Removed after the processes that use them are killed.
_directory: Directory,
_tenant: TestTenant,
// Declared last: removed only after chromedriver and Chrome are killed.
_tmp: TempDir,
impl Harness {
async fn start() -> Result<Self> {
let (id, email, guard) = register().await?;
let tenant = seed(id, email).await?;
let directory = Directory::create().await?;
let tmp = TempDir::new()?;
let (web, base) = web_server(&directory).await?;
directory.admit(tenant.id).await?;
let (chromedriver, endpoint) = chromedriver(tmp.path()).await?;
let driver = Driver::connect(&endpoint).await?;
let shots = shots_dir();
std::fs::create_dir_all(&shots)?;
Ok(Self {
driver,
base,
tenant,
shots,
_web: web,
_chromedriver: chromedriver,
_directory: directory,
_tenant: guard,
_tmp: tmp,
pub fn url(&self, path: &str) -> String {
format!("{}{path}", self.base)
pub fn account(&self, name: &str) -> Uuid {
self.tenant.accounts.get(name).copied().unwrap_or_default()
pub fn commodity(&self, symbol: &str) -> Uuid {
self.tenant
.commodities
.get(symbol)
.copied()
.unwrap_or_default()
pub type Scenario<'a> = Pin<Box<dyn Future<Output = Result<()>> + 'a>>;
/// Runs `body` against a fresh harness; its tenant and database are removed
/// when the harness drops, however `body` ends.
pub async fn with_harness(body: impl for<'a> FnOnce(&'a Harness) -> Scenario<'a>) -> Result<()> {
let harness = Harness::start().await?;
let outcome = body(&harness).await;
drop(harness.driver.quit().await);
outcome