hacked-in async tests

pull/5/head
Mingwei Samuel 2019-10-20 00:54:01 -07:00
parent 346e12656b
commit c7b3cab8b0
9 changed files with 186 additions and 21 deletions

View File

@ -12,7 +12,6 @@ exclude = [
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
async-std = "0.99"
log = "0.4" log = "0.4"
num-traits = "0.2" num-traits = "0.2"
num-derive = "0.3" 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" ] } reqwest = { version = "0.10.0-alpha.1", features = [ "gzip", "json" ] }
scan_fmt = "0.2" scan_fmt = "0.2"
serde = { version = "1.0", features = [ "derive" ] } serde = { version = "1.0", features = [ "derive" ] }
tokio-timer = "0.3.0-alpha.5"
url = "2.1" url = "2.1"
[dev-dependencies] [dev-dependencies]
colored = "1.8"
env_logger = "0.7" env_logger = "0.7"
lazy_static = "1.4"
tokio = "0.2.0-alpha.6" tokio = "0.2.0-alpha.6"
[build-dependencies]
os_pipe = "0.9"

View File

@ -32,6 +32,7 @@ mod tests {
#[test] #[test]
#[ignore]
fn it_works() { fn it_works() {
env_logger::init(); env_logger::init();
@ -45,12 +46,10 @@ mod tests {
let riot_api = RiotApi::with_key(api_key); let riot_api = RiotApi::with_key(api_key);
for i in 0..2 { for i in 0..2 {
// https://na1.api.riotgames.com/lol/champion-mastery/v4/scores/by-summoner/SBM8Ubipo4ge2yj7bhEzL7yvV0C9Oc1XA2l6v5okGMA_nCw let my_future = riot_api.champion_mastery_v4_get_all_champion_masteries(
let my_future = riot_api.get::<u32>("asdf", consts::Region::NA, consts::Region::NA, "SBM8Ubipo4ge2yj7bhEzL7yvV0C9Oc1XA2l6v5okGMA_nCw");
"/lol/champion-mastery/v4/scores/by-summoner/SBM8Ubipo4ge2yj7bhEzL7yvV0C9Oc1XA2l6v5okGMA_nCw",
&[]);
let val = rt.block_on(my_future).unwrap(); let val = rt.block_on(my_future).unwrap();
println!("VAL {}: {}", i, val.unwrap()); println!("VAL {}: {:#?}", i, val.unwrap());
} }
} }
} }

View File

@ -1,7 +1,7 @@
use std::sync::Arc; use std::sync::Arc;
use async_std::task;
use reqwest::{ Client, StatusCode, Url }; use reqwest::{ Client, StatusCode, Url };
use tokio_timer::delay_for;
use crate::riot_api_config::RiotApiConfig; use crate::riot_api_config::RiotApiConfig;
use crate::consts::Region; use crate::consts::Region;
@ -53,7 +53,7 @@ impl<'a> RegionalRequester<'a> {
// Rate limiting. // Rate limiting.
while let Some(delay) = RateLimit::get_both_or_delay(&self.app_rate_limit, &*method_rate_limit) { 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. // Send request.

View File

@ -9,7 +9,7 @@ use super::RegionalRequester;
pub struct RequesterManager<'a> { pub struct RequesterManager<'a> {
/// Configuration settings. /// Configuration settings.
riot_api_config: RiotApiConfig<'a>, pub riot_api_config: RiotApiConfig<'a>,
/// Client for making requests. /// Client for making requests.
client: Client, client: Client,

View File

@ -1,5 +1,4 @@
use crate::*; use crate::RiotApiConfig;
use crate::consts::Region;
use crate::req::RequesterManager; use crate::req::RequesterManager;
pub struct RiotApi<'a> { pub struct RiotApi<'a> {
@ -19,11 +18,4 @@ impl<'a> RiotApi<'a> {
pub fn with_key(api_key: &'a str) -> Self { pub fn with_key(api_key: &'a str) -> Self {
Self::with_config(RiotApiConfig::with_key(api_key)) Self::with_config(RiotApiConfig::with_key(api_key))
} }
pub async fn get<T: serde::de::DeserializeOwned>(
&'a self, method_id: &'a str, region: Region, path: &str,
query: Option<&str>) -> Result<Option<T>, reqwest::Error>
{
self.requester_manager.get(method_id, region, path, query).await
}
} }

View File

@ -1,3 +1,4 @@
#[derive(Debug)]
pub struct RiotApiConfig<'a> { pub struct RiotApiConfig<'a> {
pub api_key: &'a str, pub api_key: &'a str,
pub retries: u8, pub retries: u8,

67
tests/async_tests.rs Normal file
View File

@ -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) };
}

75
tests/tests.rs.bak Normal file
View File

@ -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(())
}

32
tests/tests2.rs Normal file
View File

@ -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(())
},
}
}