Skip to content

Commit

Permalink
upgrade mockito
Browse files Browse the repository at this point in the history
  • Loading branch information
syphar committed Jun 30, 2023
1 parent 058ea55 commit 69c1d4a
Show file tree
Hide file tree
Showing 6 changed files with 140 additions and 48 deletions.
35 changes: 32 additions & 3 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ procfs = "0.15.1"
criterion = "0.5.1"
kuchiki = "0.8"
rand = "0.8"
mockito = "0.31.0"
mockito = "1.0.2"
test-case = "3.0.0"
aws-smithy-client = { version = "0.55.1", features = ["test-util"]}
aws-smithy-http = "0.55.1"
Expand Down
2 changes: 2 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub struct Config {
pub prefix: PathBuf,
pub registry_index_path: PathBuf,
pub registry_url: Option<String>,
pub registry_api_host: String,

// Database connection params
pub(crate) database_url: String,
Expand Down Expand Up @@ -135,6 +136,7 @@ impl Config {

registry_index_path: env("REGISTRY_INDEX_PATH", prefix.join("crates.io-index"))?,
registry_url: maybe_env("REGISTRY_URL")?,
registry_api_host: env("DOCSRS_REGISTRY_API_HOST", "https://crates.io".into())?,
prefix: prefix.clone(),

database_url: require_env("DOCSRS_DATABASE_URL")?,
Expand Down
50 changes: 32 additions & 18 deletions src/repositories/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ const GRAPHQL_SINGLE: &str = "query($owner: String!, $repo: String!) {
}";

pub struct GitHub {
endpoint: String,
client: HttpClient,
github_updater_min_rate_limit: u32,
}
Expand All @@ -51,6 +52,13 @@ impl GitHub {
/// Returns `Err` if the access token has invalid syntax (but *not* if it isn't authorized).
/// Returns `Ok(None)` if there is no access token.
pub fn new(config: &Config) -> Result<Option<Self>> {
Self::with_custom_endpoint(config, "https://github.com/gitapi/graphql")
}

pub fn with_custom_endpoint<E: AsRef<str>>(
config: &Config,
endpoint: E,
) -> Result<Option<Self>> {
let mut headers = HeaderMap::new();
headers.insert(USER_AGENT, HeaderValue::from_static(APP_USER_AGENT));
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
Expand All @@ -69,6 +77,7 @@ impl GitHub {

Ok(Some(GitHub {
client,
endpoint: endpoint.as_ref().to_owned(),
github_updater_min_rate_limit: config.github_updater_min_rate_limit,
}))
}
Expand Down Expand Up @@ -176,16 +185,9 @@ impl GitHub {
query: &str,
variables: impl serde::Serialize,
) -> Result<GraphResponse<T>> {
#[cfg(not(test))]
let host = "https://github.com/gitapi/graphql";
#[cfg(test)]
let host = format!("{}/graphql", mockito::server_url());
#[cfg(test)]
let host = &host;

Ok(self
.client
.post(host)
.post(&self.endpoint)
.json(&serde_json::json!({
"query": query,
"variables": variables,
Expand Down Expand Up @@ -256,19 +258,28 @@ struct GraphIssues {

#[cfg(test)]
mod tests {
use super::GitHub;
use super::{Config, GitHub};
use crate::repositories::updater::{repository_name, RepositoryForge};
use crate::repositories::RateLimitReached;
use mockito::mock;

fn mock_server_and_github(config: &Config) -> (mockito::ServerGuard, GitHub) {
let server = mockito::Server::new();
let updater = GitHub::with_custom_endpoint(config, format!("{}/graphql", server.url()))
.expect("GitHub::new failed")
.unwrap();

(server, updater)
}

#[test]
fn test_rate_limit_fail() {
crate::test::wrapper(|env| {
let mut config = env.base_config();
config.github_accesstoken = Some("qsjdnfqdq".to_owned());
let updater = GitHub::new(&config).expect("GitHub::new failed").unwrap();
let (mut server, updater) = mock_server_and_github(&config);

let _m1 = mock("POST", "/graphql")
let _m1 = server
.mock("POST", "/graphql")
.with_header("content-type", "application/json")
.with_body(
r#"{"errors":[{"type":"RATE_LIMITED","message":"API rate limit exceeded"}]}"#,
Expand All @@ -288,9 +299,10 @@ mod tests {
crate::test::wrapper(|env| {
let mut config = env.base_config();
config.github_accesstoken = Some("qsjdnfqdq".to_owned());
let updater = GitHub::new(&config).expect("GitHub::new failed").unwrap();
let (mut server, updater) = mock_server_and_github(&config);

let _m1 = mock("POST", "/graphql")
let _m1 = server
.mock("POST", "/graphql")
.with_header("content-type", "application/json")
.with_body(r#"{"data": {"nodes": [], "rateLimit": {"remaining": 0}}}"#)
.create();
Expand All @@ -308,9 +320,10 @@ mod tests {
crate::test::wrapper(|env| {
let mut config = env.base_config();
config.github_accesstoken = Some("qsjdnfqdq".to_owned());
let updater = GitHub::new(&config).expect("GitHub::new failed").unwrap();
let (mut server, updater) = mock_server_and_github(&config);

let _m1 = mock("POST", "/graphql")
let _m1 = server
.mock("POST", "/graphql")
.with_header("content-type", "application/json")
.with_body(
r#"{"data": {"nodes": [], "rateLimit": {"remaining": 100000}}, "errors":
Expand All @@ -334,9 +347,10 @@ mod tests {
crate::test::wrapper(|env| {
let mut config = env.base_config();
config.github_accesstoken = Some("qsjdnfqdq".to_owned());
let updater = GitHub::new(&config).expect("GitHub::new failed").unwrap();
let (mut server, updater) = mock_server_and_github(&config);

let _m1 = mock("POST", "/graphql")
let _m1 = server
.mock("POST", "/graphql")
.with_header("content-type", "application/json")
.with_body(
r#"{"data": {"repository": {"id": "hello", "nameWithOwner": "foo/bar",
Expand Down
50 changes: 36 additions & 14 deletions src/repositories/gitlab.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,19 @@ const GRAPHQL_SINGLE: &str = "query($fullPath: ID!) {
pub struct GitLab {
client: HttpClient,
host: &'static str,
endpoint: String,
}

impl GitLab {
pub fn new(host: &'static str, access_token: &Option<String>) -> Result<Self> {
Self::with_custom_endpoint(host, access_token, format!("https://{}/api/graphql", host))
}

pub fn with_custom_endpoint<E: AsRef<str>>(
host: &'static str,
access_token: &Option<String>,
endpoint: E,
) -> Result<Self> {
let mut headers = HeaderMap::new();
headers.insert(USER_AGENT, HeaderValue::from_static(APP_USER_AGENT));
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
Expand All @@ -64,7 +73,11 @@ impl GitLab {
}

let client = HttpClient::builder().default_headers(headers).build()?;
Ok(GitLab { client, host })
Ok(GitLab {
client,
host,
endpoint: endpoint.as_ref().to_string(),
})
}
}

Expand Down Expand Up @@ -165,14 +178,9 @@ impl GitLab {
query: &str,
variables: impl serde::Serialize,
) -> Result<(GraphResponse<T>, Option<usize>)> {
#[cfg(not(test))]
let host = format!("https://{}/api/graphql", self.host);
#[cfg(test)]
let host = format!("{}/api/graphql", mockito::server_url());

let res = self
.client
.post(host)
.post(&self.endpoint)
.json(&serde_json::json!({
"query": query,
"variables": variables,
Expand Down Expand Up @@ -252,13 +260,25 @@ mod tests {
use super::GitLab;
use crate::repositories::updater::{repository_name, RepositoryForge};
use crate::repositories::RateLimitReached;
use mockito::mock;

fn mock_server_and_gitlab() -> (mockito::ServerGuard, GitLab) {
let server = mockito::Server::new();
let updater = GitLab::with_custom_endpoint(
"gitlab.com",
&None,
format!("{}/api/graphql", server.url()),
)
.expect("GitLab::new failed");

(server, updater)
}

#[test]
fn test_rate_limit() {
let updater = GitLab::new("gitlab.com", &None).expect("GitLab::new failed");
let (mut server, updater) = mock_server_and_gitlab();

let _m1 = mock("POST", "/api/graphql")
let _m1 = server
.mock("POST", "/api/graphql")
.with_header("content-type", "application/json")
.with_header("RateLimit-Remaining", "0")
.with_body("{}")
Expand All @@ -278,9 +298,10 @@ mod tests {

#[test]
fn not_found() {
let updater = GitLab::new("gitlab.com", &None).expect("GitLab::new failed");
let (mut server, updater) = mock_server_and_gitlab();

let _m1 = mock("POST", "/api/graphql")
let _m1 = server
.mock("POST", "/api/graphql")
.with_header("content-type", "application/json")
.with_body(r#"{"data": {"projects": {"nodes": []}}}"#)
.create();
Expand All @@ -296,9 +317,10 @@ mod tests {

#[test]
fn get_repository_info() {
let updater = GitLab::new("gitlab.com", &None).expect("GitLab::new failed");
let (mut server, updater) = mock_server_and_gitlab();

let _m1 = mock("POST", "/api/graphql")
let _m1 = server
.mock("POST", "/api/graphql")
.with_header("content-type", "application/json")
.with_body(
r#"{"data": {"project": {"id": "hello", "fullPath": "foo/bar",
Expand Down
Loading

0 comments on commit 69c1d4a

Please sign in to comment.