Skip to content

Commit

Permalink
Add tests for github and gitlab modules
Browse files Browse the repository at this point in the history
  • Loading branch information
autarch committed Dec 24, 2024
1 parent 8aa76d0 commit 25e078f
Show file tree
Hide file tree
Showing 6 changed files with 146 additions and 9 deletions.
5 changes: 3 additions & 2 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ platforms = "3.5.0"
regex = "1.11.1"
reqwest = { version = "0.12.9", default-features = false, features = ["gzip", "json"] }
serde = { version = "1.0.215", features = ["derive"] }
serde_json = "1.0.134"
strum = { version = "0.26.3", features = ["derive"] }
tempfile = "3.14.0"
test-case = "3.3.1"
Expand Down
1 change: 1 addition & 0 deletions ubi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ platforms.workspace = true
regex.workspace = true
reqwest.workspace = true
serde.workspace = true
serde_json.workspace = true
strum.workspace = true
tempfile.workspace = true
thiserror.workspace = true
Expand Down
70 changes: 68 additions & 2 deletions ubi/src/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use reqwest::{
header::{HeaderValue, AUTHORIZATION},
Client, RequestBuilder,
};
use serde::Deserialize;
use serde::{Deserialize, Serialize};
use std::env;
use url::Url;

Expand All @@ -21,7 +21,7 @@ pub(crate) struct GitHub {
token: Option<String>,
}

#[derive(Debug, Deserialize)]
#[derive(Debug, Deserialize, Serialize)]
pub(crate) struct Release {
pub(crate) assets: Vec<Asset>,
}
Expand Down Expand Up @@ -95,3 +95,69 @@ impl GitHub {
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use mockito::Server;
use reqwest::Client;
use test_log::test;

#[test(tokio::test)]
async fn test_fetch_assets_without_token() -> Result<()> {
test_fetch_assets(None, None).await
}

#[test(tokio::test)]
async fn test_fetch_assets_with_token() -> Result<()> {
test_fetch_assets(None, Some("ghp_fakeToken")).await
}

#[test(tokio::test)]
async fn test_fetch_assets_with_tag() -> Result<()> {
test_fetch_assets(Some("v1.0.0"), None).await
}

async fn test_fetch_assets(tag: Option<&str>, token: Option<&str>) -> Result<()> {
let assets = vec![Asset {
name: "asset1".to_string(),
url: Url::parse("https://api.github.com/repos/houseabsolute/ubi/releases/assets/1")?,
}];

let expect_path = if let Some(tag) = tag {
format!("/repos/houseabsolute/ubi/releases/tags/{tag}")
} else {
"/repos/houseabsolute/ubi/releases/latest".to_string()
};
let authorization_header_matcher = if token.is_some() {
mockito::Matcher::Exact(format!("Bearer {}", token.unwrap()))
} else {
mockito::Matcher::Missing
};
let mut server = Server::new_async().await;
let m = server
.mock("GET", expect_path.as_str())
.match_header("Authorization", authorization_header_matcher)
.with_status(200)
.with_body(serde_json::to_string(&Release {
assets: assets.clone(),
})?)
.create_async()
.await;

let github = GitHub::new(
"houseabsolute/ubi".to_string(),
tag.map(String::from),
Some(Url::parse(&server.url())?),
token,
);

let client = Client::new();
let got_assets = github.fetch_assets(&client).await?;
assert_eq!(got_assets, assets);

m.assert_async().await;

Ok(())
}
}
74 changes: 71 additions & 3 deletions ubi/src/gitlab.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use anyhow::Result;
use async_trait::async_trait;
use log::debug;
use reqwest::{header::HeaderValue, header::AUTHORIZATION, Client, RequestBuilder};
use serde::Deserialize;
use serde::{Deserialize, Serialize};
use std::env;
use url::Url;

Expand All @@ -18,12 +18,12 @@ pub(crate) struct GitLab {
token: Option<String>,
}

#[derive(Debug, Deserialize)]
#[derive(Debug, Deserialize, Serialize)]
struct Release {
assets: GitLabAssets,
}

#[derive(Debug, Deserialize)]
#[derive(Debug, Deserialize, Serialize)]
struct GitLabAssets {
links: Vec<Asset>,
}
Expand Down Expand Up @@ -97,3 +97,71 @@ impl GitLab {
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use mockito::Server;
use reqwest::Client;
use test_log::test;

#[test(tokio::test)]
async fn test_fetch_assets_without_token() -> Result<()> {
test_fetch_assets(None, None).await
}

#[test(tokio::test)]
async fn test_fetch_assets_with_token() -> Result<()> {
test_fetch_assets(None, Some("glpat-fakeToken")).await
}

#[test(tokio::test)]
async fn test_fetch_assets_with_tag() -> Result<()> {
test_fetch_assets(Some("v1.0.0"), None).await
}

async fn test_fetch_assets(tag: Option<&str>, token: Option<&str>) -> Result<()> {
let assets = vec![Asset {
name: "asset1".to_string(),
url: Url::parse("https://gitlab.com/api/v4/projects/owner%2Frepo/releases/assets/1")?,
}];

let expect_path = if let Some(tag) = tag {
format!("/projects/houseabsolute%2Fubi/releases/{tag}")
} else {
"/projects/houseabsolute%2Fubi/releases/permalink/latest".to_string()
};
let authorization_header_matcher = if token.is_some() {
mockito::Matcher::Exact(format!("Bearer {}", token.unwrap()))
} else {
mockito::Matcher::Missing
};
let mut server = Server::new_async().await;
let m = server
.mock("GET", expect_path.as_str())
.match_header("Authorization", authorization_header_matcher)
.with_status(200)
.with_body(serde_json::to_string(&Release {
assets: GitLabAssets {
links: assets.clone(),
},
})?)
.create_async()
.await;

let github = GitLab::new(
"houseabsolute/ubi".to_string(),
tag.map(String::from),
Some(Url::parse(&server.url())?),
token,
);

let client = Client::new();
let got_assets = github.fetch_assets(&client).await?;
assert_eq!(got_assets, assets);

m.assert_async().await;

Ok(())
}
}
4 changes: 2 additions & 2 deletions ubi/src/ubi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use reqwest::{
header::{HeaderValue, ACCEPT},
Client, StatusCode,
};
use serde::Deserialize;
use serde::{Deserialize, Serialize};
use std::{fs::File, io::Write, path::PathBuf};
use tempfile::{tempdir, TempDir};
use url::Url;
Expand All @@ -21,7 +21,7 @@ pub struct Ubi<'a> {
reqwest_client: Client,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
pub(crate) struct Asset {
pub(crate) name: String,
pub(crate) url: Url,
Expand Down

0 comments on commit 25e078f

Please sign in to comment.