Skip to content

Commit

Permalink
test(webserver): add test for selecting primary email of github user
Browse files Browse the repository at this point in the history
  • Loading branch information
boxbeam committed May 23, 2024
1 parent 47f10cd commit 23dda96
Showing 1 changed file with 46 additions and 9 deletions.
55 changes: 46 additions & 9 deletions ee/tabby-webserver/src/oauth/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use tabby_schema::auth::{AuthenticationService, OAuthCredential, OAuthProvider};

use super::OAuthClient;
use crate::bail;
use anyhow::anyhow;

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
Expand Down Expand Up @@ -121,14 +122,7 @@ impl OAuthClient for GithubClient {
.await?;

let emails = resp.json::<Vec<GithubUserEmail>>().await?;

for item in &emails {
if item.primary {
return Ok(item.email.clone());
}
}

bail!("No primary email address found");
select_primary_email(emails)

Check warning on line 125 in ee/tabby-webserver/src/oauth/github.rs

View check run for this annotation

Codecov / codecov/patch

ee/tabby-webserver/src/oauth/github.rs#L125

Added line #L125 was not covered by tests
}

async fn fetch_user_full_name(&self, access_token: &str) -> Result<String> {
Expand Down Expand Up @@ -169,13 +163,56 @@ fn create_authorization_url(client_id: &str) -> Result<String> {
Ok(url.to_string())
}

fn select_primary_email(emails: Vec<GithubUserEmail>) -> Result<String> {
emails
.into_iter()
.find(|item| item.primary)
.map(|item| item.email)
.ok_or(anyhow!("No primary email address found"))
}

#[cfg(test)]
mod tests {
use super::create_authorization_url;
use super::*;

#[test]
fn test_create_authorization_url() {
let url = create_authorization_url("client_id").unwrap();
assert_eq!(url, "https://github.com/login/oauth/authorize?client_id=client_id&response_type=code&scope=read%3Auser+user%3Aemail");
}

#[test]
fn test_select_primary_email() {
let emails = vec![
GithubUserEmail {
email: "[email protected]".into(),
primary: false,
verified: true,
visibility: None,
},
GithubUserEmail {
email: "[email protected]".into(),
primary: true,
verified: true,
visibility: None,
},
GithubUserEmail {
email: "[email protected]".into(),
primary: false,
verified: true,
visibility: None,
},
];

assert_eq!(select_primary_email(emails).unwrap(), "[email protected]");

let emails = vec![GithubUserEmail {
email: "[email protected]".into(),
primary: false,
verified: true,
visibility: None,
}];

assert!(select_primary_email(emails).is_err());
}
}

0 comments on commit 23dda96

Please sign in to comment.