Skip to main content

codecov_rust_mcp/
client.rs

1//! HTTP client for the Codecov API v2.
2
3use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};
4use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
5use std::time::Duration;
6
7use crate::report::{
8    miss_files_result, pull_coverage_report, CoverageReport, MissFilesResult, PullComparison,
9    PullCoverageReport, ReportFile,
10};
11
12/// Encode path/query components; keep unreserved `-_.` but encode `/`.
13const COMPONENT: &AsciiSet = &NON_ALPHANUMERIC.remove(b'-').remove(b'_').remove(b'.');
14
15/// Default Codecov API v2 base (no trailing slash).
16pub const DEFAULT_API_URL: &str = "https://api.codecov.io/api/v2";
17
18const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
19const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
20const MAX_RESPONSE_SIZE: usize = 10 * 1024 * 1024;
21
22/// Errors from Codecov client construction or HTTP calls.
23#[derive(Debug)]
24pub enum ClientError {
25    /// `CODECOV_TOKEN` missing or empty.
26    MissingToken,
27    /// Token does not match Bearer credential syntax or an HTTP header value.
28    InvalidAuthHeader,
29    /// Underlying HTTP transport failure.
30    Http(reqwest::Error),
31    /// Codecov response body exceeds the configured size limit.
32    ResponseTooLarge { max_bytes: usize },
33    /// Non-success HTTP status from Codecov.
34    Api { status: u16, body: String },
35    /// Response JSON could not be decoded.
36    Json(serde_json::Error),
37    /// Codecov returned an unexpected comparison report.
38    Report(String),
39}
40
41impl std::fmt::Display for ClientError {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        match self {
44            Self::MissingToken => {
45                write!(f, "CODECOV_TOKEN is missing or empty")
46            }
47            Self::InvalidAuthHeader => {
48                write!(
49                    f,
50                    "CODECOV_TOKEN is not a valid Bearer credential or HTTP header value"
51                )
52            }
53            Self::Http(err) => write!(f, "HTTP error: {err}"),
54            Self::ResponseTooLarge { max_bytes } => {
55                write!(
56                    f,
57                    "Codecov response exceeds the {max_bytes}-byte size limit"
58                )
59            }
60            Self::Api { status, body } => {
61                let snippet = truncate(body, 400);
62                write!(f, "Codecov API {status}: {snippet}")
63            }
64            Self::Json(err) => write!(f, "JSON error: {err}"),
65            Self::Report(err) => write!(f, "Codecov comparison report error: {err}"),
66        }
67    }
68}
69
70impl std::error::Error for ClientError {
71    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
72        match self {
73            Self::Http(err) => Some(err),
74            Self::Json(err) => Some(err),
75            Self::MissingToken
76            | Self::InvalidAuthHeader
77            | Self::ResponseTooLarge { .. }
78            | Self::Api { .. }
79            | Self::Report(_) => None,
80        }
81    }
82}
83
84impl From<reqwest::Error> for ClientError {
85    fn from(value: reqwest::Error) -> Self {
86        Self::Http(value)
87    }
88}
89
90impl From<serde_json::Error> for ClientError {
91    fn from(value: serde_json::Error) -> Self {
92        Self::Json(value)
93    }
94}
95
96/// Reject empty / whitespace-only tokens.
97///
98/// # Errors
99///
100/// Returns [`ClientError::MissingToken`] when `s` is empty after trim.
101pub fn require_token(s: &str) -> Result<(), ClientError> {
102    if s.trim().is_empty() {
103        Err(ClientError::MissingToken)
104    } else {
105        Ok(())
106    }
107}
108
109/// Codecov API client (Bearer token + base URL).
110fn is_valid_bearer_token(token: &str) -> bool {
111    let mut has_token_character = false;
112    let mut has_padding = false;
113    for byte in token.bytes() {
114        if byte == b'=' {
115            if !has_token_character {
116                return false;
117            }
118            has_padding = true;
119        } else if !has_padding && is_bearer_token_character(byte) {
120            has_token_character = true;
121        } else {
122            return false;
123        }
124    }
125    has_token_character
126}
127
128const fn is_bearer_token_character(byte: u8) -> bool {
129    byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~' | b'+' | b'/')
130}
131
132#[derive(Clone)]
133pub struct CodecovClient {
134    token: String,
135    api_base: String,
136    http: reqwest::Client,
137}
138
139impl std::fmt::Debug for CodecovClient {
140    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141        f.debug_struct("CodecovClient")
142            .field("has_token", &!self.token.is_empty())
143            .field("api_base", &self.api_base)
144            .finish_non_exhaustive()
145    }
146}
147
148impl CodecovClient {
149    /// Builds a client with an explicit token and API base URL.
150    ///
151    /// # Errors
152    ///
153    /// Returns [`ClientError::MissingToken`] for an empty token,
154    /// [`ClientError::InvalidAuthHeader`] for an invalid Bearer token or Authorization header,
155    /// or [`ClientError::Http`] if the HTTP client cannot be constructed.
156    pub fn new(token: impl Into<String>, api_base: impl Into<String>) -> Result<Self, ClientError> {
157        let mut headers = HeaderMap::new();
158        let token = token.into();
159        require_token(&token)?;
160        if !is_valid_bearer_token(&token) {
161            return Err(ClientError::InvalidAuthHeader);
162        }
163        let value = format!("bearer {token}");
164        let value = HeaderValue::from_str(&value).map_err(|_| ClientError::InvalidAuthHeader)?;
165        headers.insert(AUTHORIZATION, value);
166        let http = reqwest::Client::builder()
167            .default_headers(headers)
168            .connect_timeout(CONNECT_TIMEOUT)
169            .timeout(REQUEST_TIMEOUT)
170            .build()?;
171        Ok(Self {
172            token,
173            api_base: trim_trailing_slash(api_base.into()),
174            http,
175        })
176    }
177
178    /// Builds a client from `CODECOV_TOKEN` and optional `CODECOV_API_URL`.
179    ///
180    /// Loads an optional `.env` file first (does not override existing process env).
181    ///
182    /// # Errors
183    ///
184    /// Returns a client construction error when the token is missing or invalid.
185    pub fn from_env() -> Result<Self, ClientError> {
186        crate::env_file::load_dotenv();
187        let token = std::env::var("CODECOV_TOKEN").unwrap_or_default();
188        require_token(&token)?;
189        let api_base =
190            std::env::var("CODECOV_API_URL").unwrap_or_else(|_| DEFAULT_API_URL.to_string());
191        Self::new(token, api_base)
192    }
193
194    /// API base URL without trailing slash.
195    #[must_use]
196    pub fn api_base(&self) -> &str {
197        &self.api_base
198    }
199
200    /// Builds the totals URL for a GitHub repo.
201    #[must_use]
202    pub fn totals_url(
203        api_base: &str,
204        owner: &str,
205        repo: &str,
206        branch: Option<&str>,
207        sha: Option<&str>,
208    ) -> String {
209        let base = trim_trailing_slash(api_base.to_string());
210        let mut url = format!("{base}/github/{}/repos/{}/totals/", enc(owner), enc(repo));
211        append_branch_sha(&mut url, branch, sha);
212        url
213    }
214
215    /// Builds the file report URL for a path inside a GitHub repo.
216    #[must_use]
217    pub fn file_report_url(
218        api_base: &str,
219        owner: &str,
220        repo: &str,
221        path: &str,
222        branch: Option<&str>,
223        sha: Option<&str>,
224    ) -> String {
225        let base = trim_trailing_slash(api_base.to_string());
226        // No trailing slash after the file path: Codecov treats `parser.rs/` as a
227        // different key and returns 404 for line coverage.
228        let mut url = format!(
229            "{base}/github/{}/repos/{}/file_report/{}",
230            enc(owner),
231            enc(repo),
232            enc(path)
233        );
234        append_branch_sha(&mut url, branch, sha);
235        url
236    }
237
238    /// Builds the Codecov pull comparison URL for a pull request.
239    #[must_use]
240    pub fn pull_comparison_url(api_base: &str, owner: &str, repo: &str, pull_id: u64) -> String {
241        let base = trim_trailing_slash(api_base.to_string());
242        format!(
243            "{base}/github/{}/repos/{}/compare/?pullid={pull_id}",
244            enc(owner),
245            enc(repo)
246        )
247    }
248
249    /// Fetches commit coverage totals (including per-file breakdown).
250    ///
251    /// # Errors
252    ///
253    /// Returns [`ClientError::Http`], [`ClientError::Api`], or [`ClientError::Json`].
254    pub async fn totals(
255        &self,
256        owner: &str,
257        repo: &str,
258        branch: Option<&str>,
259        sha: Option<&str>,
260    ) -> Result<CoverageReport, ClientError> {
261        let url = Self::totals_url(&self.api_base, owner, repo, branch, sha);
262        self.get_json(&url).await
263    }
264
265    /// Files with misses, sorted descending, capped by `limit` (`0` = uncapped).
266    ///
267    /// The complete totals report is fetched from Codecov before filtering;
268    /// `limit` controls only the number of files returned by this method.
269    ///
270    /// # Errors
271    ///
272    /// Same as [`Self::totals`].
273    pub async fn miss_files(
274        &self,
275        owner: &str,
276        repo: &str,
277        branch: Option<&str>,
278        sha: Option<&str>,
279        limit: usize,
280    ) -> Result<MissFilesResult, ClientError> {
281        let report = self.totals(owner, repo, branch, sha).await?;
282        Ok(miss_files_result(&report, limit))
283    }
284
285    /// Fetches line coverage for a single file path.
286    ///
287    /// # Errors
288    ///
289    /// Same as [`Self::totals`].
290    pub async fn file_report(
291        &self,
292        owner: &str,
293        repo: &str,
294        path: &str,
295        branch: Option<&str>,
296        sha: Option<&str>,
297    ) -> Result<ReportFile, ClientError> {
298        let url = Self::file_report_url(&self.api_base, owner, repo, path, branch, sha);
299        self.get_json(&url).await
300    }
301
302    /// Fetches a pull request's Codecov patch comparison and missed changed lines.
303    ///
304    /// # Errors
305    ///
306    /// Returns [`ClientError::Http`], [`ClientError::Api`], or [`ClientError::Json`].
307    pub async fn pull_report(
308        &self,
309        owner: &str,
310        repo: &str,
311        pull_id: u64,
312    ) -> Result<PullCoverageReport, ClientError> {
313        let url = Self::pull_comparison_url(&self.api_base, owner, repo, pull_id);
314        let comparison: PullComparison = self.get_json(&url).await?;
315        pull_coverage_report(pull_id, comparison).map_err(ClientError::Report)
316    }
317
318    pub(crate) async fn get_json<T: serde::de::DeserializeOwned>(
319        &self,
320        url: &str,
321    ) -> Result<T, ClientError> {
322        let response = self.http.get(url).send().await?;
323        let status = response.status();
324        let body = read_response_body(response, MAX_RESPONSE_SIZE).await?;
325        if !status.is_success() {
326            return Err(ClientError::Api {
327                status: status.as_u16(),
328                body: String::from_utf8_lossy(&body).into_owned(),
329            });
330        }
331        Ok(serde_json::from_slice(&body)?)
332    }
333}
334
335async fn read_response_body(
336    mut response: reqwest::Response,
337    max_bytes: usize,
338) -> Result<Vec<u8>, ClientError> {
339    if response
340        .content_length()
341        .is_some_and(|length| length > max_bytes as u64)
342    {
343        return Err(ClientError::ResponseTooLarge { max_bytes });
344    }
345
346    let mut body = Vec::new();
347    while let Some(chunk) = response.chunk().await? {
348        let length = body
349            .len()
350            .checked_add(chunk.len())
351            .ok_or(ClientError::ResponseTooLarge { max_bytes })?;
352        if length > max_bytes {
353            return Err(ClientError::ResponseTooLarge { max_bytes });
354        }
355        body.extend_from_slice(&chunk);
356    }
357    Ok(body)
358}
359
360fn enc(s: &str) -> String {
361    utf8_percent_encode(s, COMPONENT).to_string()
362}
363
364fn trim_trailing_slash(mut s: String) -> String {
365    while s.ends_with('/') {
366        s.pop();
367    }
368    s
369}
370
371fn append_branch_sha(url: &mut String, branch: Option<&str>, sha: Option<&str>) {
372    let mut sep = '?';
373    if let Some(branch) = branch.filter(|b| !b.is_empty()) {
374        url.push(sep);
375        url.push_str("branch=");
376        url.push_str(&enc(branch));
377        sep = '&';
378    }
379    if let Some(sha) = sha.filter(|s| !s.is_empty()) {
380        url.push(sep);
381        url.push_str("sha=");
382        url.push_str(&enc(sha));
383    }
384}
385
386fn truncate(s: &str, max: usize) -> String {
387    let count = s.chars().count();
388    if count <= max {
389        s.to_string()
390    } else {
391        s.chars().take(max).collect()
392    }
393}
394
395#[cfg(test)]
396#[allow(clippy::await_holding_lock)] // env mutex must span HTTP mocks
397mod tests {
398    use super::*;
399    use crate::test_env::{env_lock, restore_env};
400    use serde_json::json;
401    use std::error::Error;
402    use wiremock::matchers::{method, path_regex};
403    use wiremock::{Mock, MockServer, ResponseTemplate};
404
405    fn sample_totals_json() -> serde_json::Value {
406        json!({
407            "totals": {
408                "files": 1,
409                "lines": 10,
410                "hits": 8,
411                "misses": 2,
412                "partials": 0,
413                "coverage": 80.0,
414                "branches": 0,
415                "methods": 0
416            },
417            "files": [{
418                "name": "a.rs",
419                "totals": {
420                    "files": 0,
421                    "lines": 10,
422                    "hits": 8,
423                    "misses": 2,
424                    "partials": 0,
425                    "coverage": 80.0,
426                    "branches": 0,
427                    "methods": 0
428                },
429                "line_coverage": []
430            }]
431        })
432    }
433
434    fn sample_file_report_json() -> serde_json::Value {
435        json!({
436            "name": "a.rs",
437            "totals": {
438                "files": 0,
439                "lines": 10,
440                "hits": 8,
441                "misses": 2,
442                "partials": 0,
443                "coverage": 80.0,
444                "branches": 0,
445                "methods": 0
446            },
447            "line_coverage": [[1, 1], [2, 0]]
448        })
449    }
450
451    #[test]
452    fn require_token_rejects_empty() {
453        assert!(matches!(require_token(""), Err(ClientError::MissingToken)));
454        assert!(matches!(
455            require_token("   "),
456            Err(ClientError::MissingToken)
457        ));
458        assert!(require_token("tok").is_ok());
459    }
460
461    #[test]
462    fn client_error_display_and_source() {
463        let missing = ClientError::MissingToken;
464        assert!(missing.to_string().contains("CODECOV_TOKEN"));
465        assert!(missing.source().is_none());
466
467        let oversized = ClientError::ResponseTooLarge { max_bytes: 10 };
468        assert_eq!(
469            oversized.to_string(),
470            "Codecov response exceeds the 10-byte size limit"
471        );
472        assert!(oversized.source().is_none());
473
474        let api = ClientError::Api {
475            status: 500,
476            body: "short".into(),
477        };
478        assert_eq!(api.to_string(), "Codecov API 500: short");
479        assert!(api.source().is_none());
480
481        let long_body: String = "x".repeat(450);
482        let truncated = ClientError::Api {
483            status: 502,
484            body: long_body,
485        };
486        let display = truncated.to_string();
487        assert!(display.starts_with("Codecov API 502: "));
488        assert_eq!(
489            display.chars().count(),
490            "Codecov API 502: ".chars().count() + 400
491        );
492
493        let json_err = ClientError::from(serde_json::from_str::<()>("x").unwrap_err());
494        assert!(json_err.to_string().contains("JSON error"));
495        assert!(json_err.source().is_some());
496
497        let report = ClientError::Report("missing line number".into());
498        assert_eq!(
499            report.to_string(),
500            "Codecov comparison report error: missing line number"
501        );
502        assert!(report.source().is_none());
503    }
504
505    #[tokio::test]
506    async fn client_error_http_display_and_from() {
507        let err = reqwest::Client::new()
508            .get("http://127.0.0.1:9/")
509            .send()
510            .await
511            .expect_err("connection should fail");
512        let http = ClientError::from(err);
513        assert!(http.to_string().contains("HTTP error"));
514        assert!(http.source().is_some());
515    }
516
517    #[test]
518    fn debug_hides_token() {
519        let client = CodecovClient::new("secret-token", DEFAULT_API_URL).expect("client");
520        let debug = format!("{client:?}");
521        assert!(debug.contains("has_token: true"));
522        assert!(!debug.contains("secret-token"));
523        assert!(debug.contains(DEFAULT_API_URL));
524    }
525
526    #[test]
527    fn totals_url_encodes_and_queries() {
528        let url = CodecovClient::totals_url(
529            DEFAULT_API_URL,
530            "Interchouette-ITC",
531            "rustashop",
532            Some("dev"),
533            None,
534        );
535        assert_eq!(
536            url,
537            "https://api.codecov.io/api/v2/github/Interchouette-ITC/repos/rustashop/totals/?branch=dev"
538        );
539    }
540
541    #[test]
542    fn totals_url_with_sha() {
543        let url = CodecovClient::totals_url(
544            "https://api.codecov.io/api/v2/",
545            "o",
546            "r",
547            Some("main"),
548            Some("abc123"),
549        );
550        assert_eq!(
551            url,
552            "https://api.codecov.io/api/v2/github/o/repos/r/totals/?branch=main&sha=abc123"
553        );
554    }
555
556    #[test]
557    fn file_report_url_encodes_path_without_trailing_slash() {
558        let url = CodecovClient::file_report_url(
559            DEFAULT_API_URL,
560            "o",
561            "r",
562            "crates/foo/src/lib.rs",
563            Some("dev"),
564            None,
565        );
566        assert_eq!(
567            url,
568            "https://api.codecov.io/api/v2/github/o/repos/r/file_report/crates%2Ffoo%2Fsrc%2Flib.rs?branch=dev"
569        );
570        assert!(
571            !url.contains("lib.rs/"),
572            "trailing slash after path breaks Codecov file_report lookups: {url}"
573        );
574    }
575
576    #[test]
577    fn pull_comparison_url_uses_codecove_pull_id_endpoint() {
578        let url = CodecovClient::pull_comparison_url(
579            "https://api.codecov.io/api/v2/",
580            "Interchouette-ITC",
581            "rangular",
582            97,
583        );
584        assert_eq!(
585            url,
586            "https://api.codecov.io/api/v2/github/Interchouette-ITC/repos/rangular/compare/?pullid=97"
587        );
588    }
589
590    #[test]
591    fn new_stores_trimmed_base() {
592        let client = CodecovClient::new("tok", "https://api.codecov.io/api/v2/").expect("client");
593        assert_eq!(client.api_base(), DEFAULT_API_URL);
594        assert_ne!(client.token, "");
595    }
596
597    #[tokio::test]
598    async fn totals_miss_files_and_file_report_ok() {
599        let server = MockServer::start().await;
600        Mock::given(method("GET"))
601            .and(path_regex(r".*/totals/.*"))
602            .respond_with(ResponseTemplate::new(200).set_body_json(sample_totals_json()))
603            .mount(&server)
604            .await;
605        Mock::given(method("GET"))
606            .and(path_regex(r".*/file_report/.*"))
607            .respond_with(ResponseTemplate::new(200).set_body_json(sample_file_report_json()))
608            .mount(&server)
609            .await;
610
611        let client = CodecovClient::new("tok", server.uri()).expect("client");
612        let report = client
613            .totals("o", "r", Some("dev"), None)
614            .await
615            .expect("totals");
616        assert_eq!(report.totals.misses, 2);
617        assert_eq!(report.files.len(), 1);
618
619        let misses = client
620            .miss_files("o", "r", None, Some("abc"), 10)
621            .await
622            .expect("miss_files");
623        assert_eq!(misses.returned, 1);
624        assert_eq!(misses.files[0].name, "a.rs");
625
626        let file = client
627            .file_report("o", "r", "a.rs", Some("dev"), None)
628            .await
629            .expect("file_report");
630        assert_eq!(file.name, "a.rs");
631        assert_eq!(file.line_coverage.len(), 2);
632    }
633
634    #[tokio::test]
635    async fn get_json_api_error() {
636        let server = MockServer::start().await;
637        Mock::given(method("GET"))
638            .respond_with(ResponseTemplate::new(500).set_body_string("boom"))
639            .mount(&server)
640            .await;
641
642        let client = CodecovClient::new("tok", server.uri()).expect("client");
643        let url = format!("{}/github/o/repos/r/totals/", client.api_base());
644        match client.get_json::<serde_json::Value>(&url).await {
645            Err(ClientError::Api { status, body }) => {
646                assert_eq!(status, 500);
647                assert_eq!(body, "boom");
648            }
649            other => panic!("expected Api error, got {other:?}"),
650        }
651    }
652
653    #[tokio::test]
654    async fn get_json_invalid_json() {
655        let server = MockServer::start().await;
656        Mock::given(method("GET"))
657            .respond_with(ResponseTemplate::new(200).set_body_string("not-json"))
658            .mount(&server)
659            .await;
660
661        let client = CodecovClient::new("tok", server.uri()).expect("client");
662        let url = format!("{}/github/o/repos/r/totals/", client.api_base());
663        let json_err = client.get_json::<serde_json::Value>(&url).await;
664        assert!(matches!(json_err, Err(ClientError::Json(_))));
665    }
666
667    #[tokio::test]
668    async fn read_response_body_rejects_oversized_body() {
669        let server = MockServer::start().await;
670        Mock::given(method("GET"))
671            .respond_with(
672                ResponseTemplate::new(200)
673                    .insert_header("content-length", "5")
674                    .set_body_string("12345"),
675            )
676            .mount(&server)
677            .await;
678
679        let client = CodecovClient::new("tok", server.uri()).expect("client");
680        let response = client
681            .http
682            .get(server.uri())
683            .send()
684            .await
685            .expect("response");
686        assert_eq!(response.content_length(), Some(5));
687        assert!(matches!(
688            read_response_body(response, 4).await,
689            Err(ClientError::ResponseTooLarge { max_bytes: 4 })
690        ));
691    }
692
693    #[tokio::test]
694    async fn read_response_body_rejects_oversized_chunked_body() {
695        use tokio::io::{AsyncReadExt, AsyncWriteExt};
696
697        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
698            .await
699            .expect("bind test listener");
700        let address = listener.local_addr().expect("listener address");
701        let server = tokio::spawn(async move {
702            for _ in 0..2 {
703                let (mut stream, _) = listener.accept().await.expect("accept request");
704                let mut request = Vec::new();
705                let mut buffer = [0; 1024];
706                loop {
707                    let count = stream.read(&mut buffer).await.expect("read request");
708                    if count == 0 {
709                        break;
710                    }
711                    request.extend_from_slice(&buffer[..count]);
712                    if request.windows(4).any(|window| window == b"\r\n\r\n") {
713                        break;
714                    }
715                }
716                stream
717                    .write_all(
718                        b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n5\r\n12345\r\n0\r\n\r\n",
719                    )
720                    .await
721                    .expect("write response");
722            }
723        });
724
725        let mut incomplete = tokio::net::TcpStream::connect(address)
726            .await
727            .expect("connect incomplete request");
728        incomplete
729            .write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n")
730            .await
731            .expect("write incomplete request");
732        incomplete
733            .shutdown()
734            .await
735            .expect("close incomplete request");
736        let mut raw_response = Vec::new();
737        incomplete
738            .read_to_end(&mut raw_response)
739            .await
740            .expect("read raw response");
741
742        let url = format!("http://{address}/");
743        let client = CodecovClient::new("tok", &url).expect("client");
744        let response = client.http.get(&url).send().await.expect("response");
745        assert_eq!(response.content_length(), None);
746        assert!(matches!(
747            read_response_body(response, 4).await,
748            Err(ClientError::ResponseTooLarge { max_bytes: 4 })
749        ));
750        server.await.expect("test HTTP server");
751    }
752
753    #[tokio::test]
754    async fn get_json_http_transport_error() {
755        let client = CodecovClient::new("tok", "http://127.0.0.1:9").expect("client");
756        let err = client
757            .get_json::<serde_json::Value>("http://127.0.0.1:9/github/o/repos/r/totals/")
758            .await;
759        assert!(matches!(err, Err(ClientError::Http(_))));
760    }
761
762    #[tokio::test]
763    async fn from_env_uses_token_and_api_url() {
764        let _guard = env_lock();
765        let server = MockServer::start().await;
766        Mock::given(method("GET"))
767            .and(path_regex(r".*/totals/.*"))
768            .respond_with(ResponseTemplate::new(200).set_body_json(sample_totals_json()))
769            .mount(&server)
770            .await;
771
772        let prev_token = std::env::var("CODECOV_TOKEN").ok();
773        let prev_url = std::env::var("CODECOV_API_URL").ok();
774        std::env::set_var("CODECOV_TOKEN", "env-tok");
775        std::env::set_var("CODECOV_API_URL", server.uri());
776
777        let client = CodecovClient::from_env().expect("from_env");
778        assert_eq!(client.api_base(), server.uri().trim_end_matches('/'));
779        let report = client.totals("o", "r", None, None).await.expect("totals");
780        assert_eq!(report.totals.hits, 8);
781
782        restore_env("CODECOV_TOKEN", prev_token);
783        restore_env("CODECOV_API_URL", prev_url);
784    }
785
786    #[test]
787    fn new_rejects_malformed_bearer_tokens() {
788        for token in ["bad\ntoken", "abc def", " abc", "abc ", "abc=def", "=abc"] {
789            assert!(
790                matches!(
791                    CodecovClient::new(token, DEFAULT_API_URL),
792                    Err(ClientError::InvalidAuthHeader)
793                ),
794                "accepted invalid token {token:?}"
795            );
796        }
797    }
798
799    #[test]
800    fn new_accepts_bearer_token_alphabet_and_padding() {
801        assert!(CodecovClient::new("Az09-._~+/==", DEFAULT_API_URL).is_ok());
802    }
803
804    #[test]
805    fn new_rejects_empty_token() {
806        assert!(matches!(
807            CodecovClient::new(" ", DEFAULT_API_URL),
808            Err(ClientError::MissingToken)
809        ));
810    }
811
812    #[test]
813    fn from_env_defaults_api_url() {
814        let _guard = env_lock();
815        let prev_token = std::env::var("CODECOV_TOKEN").ok();
816        let prev_url = std::env::var("CODECOV_API_URL").ok();
817        std::env::set_var("CODECOV_TOKEN", "default-url-tok");
818        std::env::remove_var("CODECOV_API_URL");
819        let client = CodecovClient::from_env().expect("from_env");
820        assert_eq!(client.api_base(), DEFAULT_API_URL);
821        restore_env("CODECOV_TOKEN", prev_token);
822        restore_env("CODECOV_API_URL", prev_url);
823    }
824
825    #[tokio::test]
826    async fn miss_files_propagates_totals_error() {
827        let server = MockServer::start().await;
828        Mock::given(method("GET"))
829            .respond_with(ResponseTemplate::new(500).set_body_string("nope"))
830            .mount(&server)
831            .await;
832        let client = CodecovClient::new("tok", server.uri()).expect("client");
833        let err = client.miss_files("o", "r", None, None, 10).await;
834        assert!(matches!(err, Err(ClientError::Api { .. })));
835    }
836
837    #[test]
838    fn from_env_missing_token() {
839        let _guard = env_lock();
840        let prev_token = std::env::var("CODECOV_TOKEN").ok();
841        let prev_url = std::env::var("CODECOV_API_URL").ok();
842        // Empty (not removed): load_dotenv must not refill from a checkout `.env`.
843        std::env::set_var("CODECOV_TOKEN", "");
844        std::env::remove_var("CODECOV_API_URL");
845        assert!(matches!(
846            CodecovClient::from_env(),
847            Err(ClientError::MissingToken)
848        ));
849        restore_env("CODECOV_TOKEN", prev_token);
850        restore_env("CODECOV_API_URL", prev_url);
851    }
852}