Update unit test

This commit is contained in:
2022-09-25 03:13:19 +00:00
committed by GitHub
parent 597310a663
commit bb8078ce6a
4 changed files with 105 additions and 4 deletions

View File

@@ -25,6 +25,8 @@ pub enum PixivDownloaderError {
ToStrError(http::header::ToStrError),
#[cfg(all(feature = "server", feature = "db_sqlite", test))]
JSONError(json::Error),
#[cfg(feature = "openssl")]
OpenSSLError(openssl::error::ErrorStack),
}
impl From<&str> for PixivDownloaderError {

View File

@@ -1,4 +1,6 @@
use crate::ext::json::ToJson2;
#[cfg(test)]
use crate::ext::json::{FromJson, ToJson};
use crate::gettext;
use json::JsonValue;
@@ -118,3 +120,29 @@ impl ToJson2 for JSONResult {
}
}
}
#[cfg(test)]
impl FromJson for JSONResult {
type Err = crate::error::PixivDownloaderError;
fn from_json<T: ToJson>(value: T) -> Result<Self, <Self as FromJson>::Err> {
let value = value.to_json().ok_or("Failed to convert to json")?;
let ok = value["ok"].as_bool().ok_or("ok not found.")?;
if ok {
Ok(Self::Ok(value["result"].clone()))
} else {
let code = value["code"].as_i32().ok_or("code not found.")?;
let msg = value["msg"].as_str().ok_or("msg not found.")?.to_owned();
let debug_msg = value["debug_msg"].clone();
Ok(Self::Err(JSONError {
code,
msg,
debug_msg: if debug_msg.is_null() {
None
} else {
Some(debug_msg)
},
}))
}
}
}

View File

@@ -1,7 +1,13 @@
use super::UnitTestContext;
use crate::error::PixivDownloaderError;
use crate::ext::json::FromJson;
use crate::server::result::JSONResult;
use bytes::BytesMut;
use hyper::{Body, Request};
use openssl::{
pkey::Public,
rsa::{Padding, Rsa},
};
/// Test authentification methods
/// Returns token
@@ -11,9 +17,28 @@ pub async fn test(ctx: &UnitTestContext) -> Result<BytesMut, PixivDownloaderErro
assert_eq!(res["has_root_user"].as_bool(), Some(false));
let re = Request::builder().uri("/auth/pubkey").body(Body::empty())?;
let res = ctx.request_json(re).await?.unwrap();
let ok = res["ok"].as_bool().unwrap();
if !ok {
panic!("Failed to get public key.");
}
let result = JSONResult::from_json(res)?.expect("Failed to get public key:");
let pubkey = result["key"].as_str().expect("No pubkey found.");
let key = Rsa::public_key_from_pem(pubkey.as_bytes())?;
let mut password = BytesMut::with_capacity(64);
password.resize(64, 0);
openssl::rand::rand_bytes(&mut password)?;
let tosize = key.size() as usize;
let mut encypted = BytesMut::with_capacity(tosize);
encypted.resize(tosize, 0);
key.public_encrypt(&password, &mut encypted, Padding::PKCS1)?;
let b64_password = base64::encode(&encypted);
let re = ctx
.request_json2(
"/auth/user/add",
&json::object! {
"username" => "test",
"name" => "test",
"password" => b64_password,
},
)
.await?
.unwrap();
let result = JSONResult::from_json(re)?.expect("Failed to add user:");
Ok(BytesMut::new())
}

View File

@@ -61,6 +61,52 @@ impl UnitTestContext {
None => None,
})
}
pub async fn request_json2(
&self,
uri: &str,
params: &JsonValue,
) -> Result<Option<JsonValue>, PixivDownloaderError> {
let mut par = Vec::new();
for (key, obj) in params.entries() {
if let Some(s) = obj.as_str() {
par.push(format!(
"{}={}",
urlparse::quote_plus(key, b"")?,
urlparse::quote_plus(s, b"")?
));
} else if obj.is_array() {
for s in obj.members() {
if let Some(s) = s.as_str() {
par.push(format!(
"{}={}",
urlparse::quote_plus(key, b"")?,
urlparse::quote_plus(s, b"")?
));
} else {
par.push(format!(
"{}={}",
urlparse::quote_plus(key, b"")?,
urlparse::quote_plus(&(s.dump()), b"")?
));
}
}
} else {
par.push(format!(
"{}={}",
urlparse::quote_plus(key, b"")?,
urlparse::quote_plus(&(obj.dump()), b"")?
));
}
}
let par = par.join("&");
let req = Request::builder()
.method("POST")
.uri(uri)
.header("Content-Type", "application/x-www-form-urlencoded")
.body(Body::from(par))?;
self.request_json(req).await
}
}
#[proc_macros::async_timeout_test(120s)]