-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
test(webserver): add test for selecting primary email of github user
- Loading branch information
Showing
1 changed file
with
46 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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)] | ||
|
@@ -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) | ||
} | ||
|
||
async fn fetch_user_full_name(&self, access_token: &str) -> Result<String> { | ||
|
@@ -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()); | ||
} | ||
} |