-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
github.rs
78 lines (60 loc) 路 2.01 KB
/
github.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
use crate::registry::Registry;
use crate::{Error, HTTPClient, Package};
use serde::Deserialize;
use std::time::Duration;
#[cfg(test)]
use mockito;
#[cfg(not(test))]
const REGISTRY_URL: &str = "https://api.github.com";
#[derive(Deserialize)]
struct Response {
tag_name: String,
}
/// The most popular and largest project hosting.
pub struct GitHub;
#[cfg(not(test))]
fn get_base_url() -> String {
format!("{}/repos", REGISTRY_URL)
}
#[cfg(test)]
fn get_base_url() -> String {
format!("{}/repos", &mockito::server_url())
}
impl Registry for GitHub {
fn get_latest_version(pkg: &Package, timeout: Duration) -> Result<Option<String>, Error> {
let url = format!("{}/{}/releases/latest", get_base_url(), pkg);
let resp: Response = HTTPClient::new(&url, timeout)
.add_header("Accept", "application/vnd.github.v3+json")
.call()?;
if resp.tag_name.starts_with('v') {
return Ok(Some(resp.tag_name[1..].to_string()));
}
Ok(Some(resp.tag_name))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_helper::mock_github;
const PKG_NAME: &str = "owner/repo";
const FIXTURES_PATH: &str = "tests/fixtures/registry/github";
#[test]
fn failure_test() {
let pkg = Package::new(PKG_NAME);
let data_path = format!("{}/not_found.json", FIXTURES_PATH);
let _mock = mock_github(&pkg, 404, &data_path);
let result = GitHub::get_latest_version(&pkg);
assert!(result.is_err());
}
#[test]
fn success_test() {
let pkg = Package::new(PKG_NAME);
let data_path = format!("{}/release.json", FIXTURES_PATH);
let (_mock, data) = mock_github(&pkg, 200, &data_path);
let json: Response = serde_json::from_str(&data).expect("deserialize json");
let latest_version = json.tag_name[1..].to_string();
let result = GitHub::get_latest_version(&pkg);
assert!(result.is_ok());
assert_eq!(result.expect("get result"), Some(latest_version));
}
}