Skip to content

Commit

Permalink
New testing infrastructure
Browse files Browse the repository at this point in the history
  • Loading branch information
tascord committed Apr 8, 2024
1 parent ab373a2 commit 64a23b2
Show file tree
Hide file tree
Showing 5 changed files with 113 additions and 23 deletions.
13 changes: 12 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "ptv"
version = "0.1.2"
version = "0.2.0"
edition = "2021"
license = "MIT"
description = "A Rust library for the Public Transport Victoria (PTV) API"
Expand All @@ -11,6 +11,7 @@ repository = "https://github.com/tascord/ptvrs"
[dependencies]
anyhow = "1.0.81"
chrono = "0.4.35"
colored = "2.1.0"
dotenv = "0.15.0"
hex = "0.4.3"
hmac = "0.12.1"
Expand Down
9 changes: 3 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,6 @@ impl Client {
let hash = hex::encode(hasher.finalize().into_bytes());
let url = format!("{API_URL}{}&signature={}", path, hash);

println!("{}", path);
println!("{}, {}", self.devid, self.key);
println!("{url}");
let res = reqwest::get(&url).await?;
if !res.status().is_success() {
return Err(anyhow::anyhow!("Request failed: {}", res.status()));
Expand All @@ -59,7 +56,7 @@ impl Client {
&self,
route_type: RouteType,
stop_id: i32,
options: DeparturesStopOps,
options: DeparturesStopOpts,
) -> Result<DeparturesResponse> {
self.rq(format!(
"v3/departures/route_type/{}/stop/{}?{}",
Expand All @@ -76,10 +73,10 @@ impl Client {
route_type: RouteType,
route_id: i32,
stop_id: i32,
options: DeparturesStopOps,
options: DeparturesStopRouteOpts,
) -> Result<DeparturesResponse> {
self.rq(format!(
"v3/departures/route_type/{}/route/{}/stop/{}?{}",
"v3/departures/route_type/{}/stop/{}/route/{}?{}",
route_type,
route_id,
stop_id,
Expand Down
2 changes: 1 addition & 1 deletion src/ty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ pub struct Status {
//

#[derive(Serialize, Default)]
pub struct DeparturesStopOps {
pub struct DeparturesStopOpts {
/// Filter by platform number at stop
#[serde(skip_serializing_if = "Option::is_none")]
pub platform_numbers: Option<Vec<i32>>,
Expand Down
109 changes: 95 additions & 14 deletions tests/main.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,114 @@
#[cfg(test)]
pub mod test {
use std::{
collections::HashMap, future::Future, pin::Pin, sync::Arc,
};

use colored::Colorize;
use dotenv::dotenv;
use once_cell::sync::Lazy;
use ptv::*;

static CLIENT: Lazy<Client> = Lazy::new(|| {
dotenv().ok();

// Load .env file if DEVID and KEY are not set
if !std::env::vars().any(|(k, _)| k == "DEVID" || k == "KEY") {
dotenv().ok();
}

Client::new(
std::env::var("DEVID").unwrap(),
std::env::var("KEY").unwrap(),
)
});

// TODO: Find sensible constants
static ROUTE_TYPE: RouteType = RouteType::Train;
static ROUTE_ID: i32 = 1;
static STOP_ID: i32 = 1;

type Task =
Arc<dyn Fn() -> Pin<Box<dyn Future<Output = anyhow::Result<String>>>> + Send + Sync>;
pub static TASKS: Lazy<HashMap<&str, Task>> = Lazy::new(|| {
let mut map = HashMap::<&str, Task>::new();

// > Departures
map.insert(
"departures_stop",
Arc::new(|| {
Box::pin(async {
let res = CLIENT
.departures_stop(ROUTE_TYPE, STOP_ID, DeparturesStopOpts::default())
.await?;

Ok(format!("{:?}", res))
})
}),
);

map.insert(
"departures_stop_route",
Arc::new(|| {
Box::pin(async {
let res = CLIENT
.departures_stop_route(
ROUTE_TYPE,
ROUTE_ID,
STOP_ID,
DeparturesStopRouteOpts::default(),
)
.await?;

Ok(format!("{:?}", res))
})
}),
);

map
});

//

#[tokio::test]
pub async fn test() {
println!(
"{:?}",
CLIENT
.departures_stop(
RouteType::Train,
1071,
DeparturesStopOps {
expand: Some(vec![ExpandOptions::All]),
..Default::default()
}
)
.await
);
let mut failed = 0;
for (i, (name, task)) in TASKS.iter().enumerate() {
println!("[{}] Running test: {}", "~".cyan(), name.yellow());
let start = std::time::Instant::now();
let res = task().await;
let elapsed = start.elapsed();
match res {
Ok(res) => println!(
"[{}] {} {} in {:?}:\n{}",
"+".green(),
name.yellow(),
"passed".green(),
elapsed,
res.cyan()
),
Err(e) => {
failed += 1;
println!(
"[{}] {} {} in {:?}:\n{}",
"-".red(),
name.yellow(),
"failed".red(),
elapsed,
e.to_string().cyan()
)
}
}

if i < TASKS.len() - 1 {
println!("\n[{}] Waiting 5 seconds to avoid limiting.\n", "~".cyan());
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
}
}

if failed > 0 {
panic!("{} tests failed", failed);
}

println!("\n{}", "All tests passed! :3".green());
}
}

0 comments on commit 64a23b2

Please sign in to comment.