From c7b3cab8b026060f4f8d3f881fac8c4cd63e7322 Mon Sep 17 00:00:00 2001 From: Mingwei Samuel Date: Sun, 20 Oct 2019 00:54:01 -0700 Subject: [PATCH] hacked-in async tests --- Cargo.toml | 7 ++-- src/lib.rs | 9 ++--- src/req/regional_requester.rs | 4 +- src/req/requester_manager.rs | 2 +- src/riot_api.rs | 10 +---- src/riot_api_config.rs | 1 + tests/async_tests.rs | 67 +++++++++++++++++++++++++++++++ tests/tests.rs.bak | 75 +++++++++++++++++++++++++++++++++++ tests/tests2.rs | 32 +++++++++++++++ 9 files changed, 186 insertions(+), 21 deletions(-) create mode 100644 tests/async_tests.rs create mode 100644 tests/tests.rs.bak create mode 100644 tests/tests2.rs diff --git a/Cargo.toml b/Cargo.toml index d5b81d7..05533a7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,6 @@ exclude = [ # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -async-std = "0.99" log = "0.4" num-traits = "0.2" num-derive = "0.3" @@ -20,11 +19,11 @@ parking_lot = { version = "0.9", features = [ "nightly" ] } reqwest = { version = "0.10.0-alpha.1", features = [ "gzip", "json" ] } scan_fmt = "0.2" serde = { version = "1.0", features = [ "derive" ] } +tokio-timer = "0.3.0-alpha.5" url = "2.1" [dev-dependencies] +colored = "1.8" env_logger = "0.7" +lazy_static = "1.4" tokio = "0.2.0-alpha.6" - -[build-dependencies] -os_pipe = "0.9" diff --git a/src/lib.rs b/src/lib.rs index 5fbf9d8..0860187 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,6 +32,7 @@ mod tests { #[test] + #[ignore] fn it_works() { env_logger::init(); @@ -45,12 +46,10 @@ mod tests { let riot_api = RiotApi::with_key(api_key); for i in 0..2 { - // https://na1.api.riotgames.com/lol/champion-mastery/v4/scores/by-summoner/SBM8Ubipo4ge2yj7bhEzL7yvV0C9Oc1XA2l6v5okGMA_nCw - let my_future = riot_api.get::("asdf", consts::Region::NA, - "/lol/champion-mastery/v4/scores/by-summoner/SBM8Ubipo4ge2yj7bhEzL7yvV0C9Oc1XA2l6v5okGMA_nCw", - &[]); + let my_future = riot_api.champion_mastery_v4_get_all_champion_masteries( + consts::Region::NA, "SBM8Ubipo4ge2yj7bhEzL7yvV0C9Oc1XA2l6v5okGMA_nCw"); let val = rt.block_on(my_future).unwrap(); - println!("VAL {}: {}", i, val.unwrap()); + println!("VAL {}: {:#?}", i, val.unwrap()); } } } diff --git a/src/req/regional_requester.rs b/src/req/regional_requester.rs index c770c78..becc70f 100644 --- a/src/req/regional_requester.rs +++ b/src/req/regional_requester.rs @@ -1,7 +1,7 @@ use std::sync::Arc; -use async_std::task; use reqwest::{ Client, StatusCode, Url }; +use tokio_timer::delay_for; use crate::riot_api_config::RiotApiConfig; use crate::consts::Region; @@ -53,7 +53,7 @@ impl<'a> RegionalRequester<'a> { // Rate limiting. while let Some(delay) = RateLimit::get_both_or_delay(&self.app_rate_limit, &*method_rate_limit) { - task::sleep(delay).await; + delay_for(delay).await; } // Send request. diff --git a/src/req/requester_manager.rs b/src/req/requester_manager.rs index a232f7d..5fceece 100644 --- a/src/req/requester_manager.rs +++ b/src/req/requester_manager.rs @@ -9,7 +9,7 @@ use super::RegionalRequester; pub struct RequesterManager<'a> { /// Configuration settings. - riot_api_config: RiotApiConfig<'a>, + pub riot_api_config: RiotApiConfig<'a>, /// Client for making requests. client: Client, diff --git a/src/riot_api.rs b/src/riot_api.rs index 643cb61..5240457 100644 --- a/src/riot_api.rs +++ b/src/riot_api.rs @@ -1,5 +1,4 @@ -use crate::*; -use crate::consts::Region; +use crate::RiotApiConfig; use crate::req::RequesterManager; pub struct RiotApi<'a> { @@ -19,11 +18,4 @@ impl<'a> RiotApi<'a> { pub fn with_key(api_key: &'a str) -> Self { Self::with_config(RiotApiConfig::with_key(api_key)) } - - pub async fn get( - &'a self, method_id: &'a str, region: Region, path: &str, - query: Option<&str>) -> Result, reqwest::Error> - { - self.requester_manager.get(method_id, region, path, query).await - } } diff --git a/src/riot_api_config.rs b/src/riot_api_config.rs index 40d652b..d5f8a60 100644 --- a/src/riot_api_config.rs +++ b/src/riot_api_config.rs @@ -1,3 +1,4 @@ +#[derive(Debug)] pub struct RiotApiConfig<'a> { pub api_key: &'a str, pub retries: u8, diff --git a/tests/async_tests.rs b/tests/async_tests.rs new file mode 100644 index 0000000..cfc5fea --- /dev/null +++ b/tests/async_tests.rs @@ -0,0 +1,67 @@ +/// This is just a huge hack to make a test runner (with no test cases) +/// look as if it's running a bunch of (async) test cases. +#[macro_export] +macro_rules! async_tests { + ( $runner:ident { $( $name:ident : async $eval:block, )* } ) => { + fn $runner(_: &[()]) { + const TUPLE_OK: (u32, u32) = (1, 0); + const TUPLE_ERR: (u32, u32) = (0, 1); + + std::process::exit({ + let mut rt = Runtime::new().expect("Failed to create runtime."); + + let (_, errs) = rt.block_on(async { + println!(); + println!("running tests"); + println!(); + let mut oks: u32 = 0; + let mut errs: u32 = 0; + $( + let $name = async { + let result: Result<(), String> = async { + $eval + }.await; + print!("test {} ... ", stringify!($name)); + match &result { + Ok(_) => { + println!("{}", "ok".green()); + TUPLE_OK + } + Err(msg) => { + println!("{}", "error".bright_red()); + println!("{}", msg); + TUPLE_ERR + } + } + }; + )* + $( + let $name = $name.await; + oks += $name.0; errs += $name.1; + )* + println!(); + print!("test result: {}. ", if errs > 0 { "error".bright_red() } else { "ok".green() }); + println!("{} passed; {} failed; 0 ignored; 0 measured; 0 filtered out", oks, errs); + println!(); + (oks, errs) + }); + // Just returns #errs as exit code. + errs as i32 + }); + } + }; +} + +#[macro_export] +macro_rules! rassert { + ( $x:expr ) => { + { + if $x { Ok(()) } else { Err(stringify!($x)) }? + } + }; +} + +#[macro_export] +macro_rules! rassert_eq { + ( $a:expr, $b:expr ) => { rassert!($a == $b) }; +} diff --git a/tests/tests.rs.bak b/tests/tests.rs.bak new file mode 100644 index 0000000..42da5a9 --- /dev/null +++ b/tests/tests.rs.bak @@ -0,0 +1,75 @@ +#![feature(custom_test_frameworks)] +#![test_runner(my_runner)] +// use std::future::Future; + +use colored::*; +use lazy_static::lazy_static; +use riven::RiotApi; +use tokio::runtime::current_thread::Runtime; + + +lazy_static! { + static ref API_KEY: String = { + let api_key = std::fs::read_to_string("apikey.txt").unwrap(); // TODO don't use unwrap. + api_key.trim().to_owned() + }; + static ref RIOT_API: RiotApi<'static> = { + RiotApi::with_key(&API_KEY) + }; +} + +fn my_runner(tests: &[()]) { + std::process::exit({ + let mut rt = Runtime::new().expect("Failed to create runtime."); + + let result = rt.block_on(async { + let a = async { + let result = plus_one(&RIOT_API).await; + print!("plus_one ... "); + match &result { + Ok(_) => println!("{}", "ok".green()), + Err(msg) => println!("{}: {}", "error".red(), msg), + }; + result + }; + let b = async { + let result = plus_two(&RIOT_API).await; + print!("plus_two ... "); + match &result { + Ok(_) => println!("{}", "ok".green()), + Err(msg) => println!("{}: {}", "error".bright_red(), msg), + }; + result + }; + let err = None; + let err = err.or(a.await.err()); + let err = err.or(b.await.err()); + err.map_or(Ok(()), |e| Err(e)) + }); + match &result { + Ok(_) => 0, + Err(_) => 2, + } + }); +} + +macro_rules! rassert { + ( $x:expr ) => { + { + if $x { Ok(()) } else { Err(stringify!($x)) }? + } + }; +} +macro_rules! rassert_eq { + ( $a:expr, $b:expr ) => { rassert!($a == $b) }; +} + +async fn plus_one(riot_api: &'static RiotApi<'static>) -> Result<(), String> { + rassert_eq!("world", "world"); + Ok(()) +} + +async fn plus_two(riot_api: &'static RiotApi<'static>) -> Result<(), String> { + rassert_eq!("hello", "world"); + Ok(()) +} diff --git a/tests/tests2.rs b/tests/tests2.rs new file mode 100644 index 0000000..e5a0503 --- /dev/null +++ b/tests/tests2.rs @@ -0,0 +1,32 @@ +#![feature(custom_test_frameworks)] +#![test_runner(my_runner)] + +mod async_tests; + +use colored::*; +use lazy_static::lazy_static; +use riven::RiotApi; +use tokio::runtime::current_thread::Runtime; + +lazy_static! { + static ref API_KEY: String = { + let api_key = std::fs::read_to_string("apikey.txt").unwrap(); // TODO don't use unwrap. + api_key.trim().to_owned() + }; + static ref RIOT_API: RiotApi<'static> = { + RiotApi::with_key(&API_KEY) + }; +} + +async_tests!{ + my_runner { + test_1: async { + rassert_eq!("world", "world"); + Ok(()) + }, + test_2: async { + rassert_eq!("hello", "hello"); + Ok(()) + }, + } +}