use crate::step::StepError;
use crate::world::BrowserWorld;
use ferridriver_bdd_macros::{given, step, then};
use ferridriver_test::expect::{AssertionFailure, expect};
fn to_step_err(e: AssertionFailure) -> StepError {
StepError {
message: e.message,
diff: e.diff.map(|d| (d, String::new())),
pending: false,
}
}
#[given("I navigate to {string}")]
async fn navigate(world: &mut BrowserWorld, url: String) {
let resolved = resolve_url(&url);
world
.page()
.goto(&resolved, None)
.await
.map_err(|e| StepError::wrap(format!("navigate to \"{resolved}\""), e))?;
}
fn resolve_url(url: &str) -> String {
if url.starts_with("http://") || url.starts_with("https://") || url.starts_with("data:") {
return url.to_string();
}
if let Ok(base) = std::env::var("FERRIDRIVER_BASE_URL") {
let base = base.trim_end_matches('/');
let path = url.strip_prefix('/').unwrap_or(url);
return format!("{base}/{path}");
}
url.to_string()
}
#[given("I go back")]
async fn go_back(world: &mut BrowserWorld) {
world
.page()
.go_back(None)
.await
.map_err(|e| StepError::wrap("go back", e))?;
}
#[given("I go forward")]
async fn go_forward(world: &mut BrowserWorld) {
world
.page()
.go_forward(None)
.await
.map_err(|e| StepError::wrap("go forward", e))?;
}
#[step("I reload the page")]
async fn reload(world: &mut BrowserWorld) {
world
.page()
.reload(None)
.await
.map_err(|e| StepError::wrap("reload", e))?;
}
#[then("the URL should contain {string}")]
async fn url_contains(world: &mut BrowserWorld, expected: String) {
expect(world.page())
.to_contain_url(&expected)
.await
.map_err(to_step_err)?;
}
#[then("the URL should be {string}")]
async fn url_equals(world: &mut BrowserWorld, expected: String) {
expect(world.page())
.to_have_url(expected.as_str())
.await
.map_err(to_step_err)?;
}