Skip to content
This repository was archived by the owner on Jan 2, 2026. It is now read-only.

Commit 0c67c6e

Browse files
committed
feat: more coverage
1 parent d1fe08f commit 0c67c6e

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

src/database/api_keys.rs

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,15 @@ use crate::StdError;
1212
use crate::database::Database;
1313
use crate::errors::SonataDbError;
1414

15+
/// Constant used to determine how long auto-generated tokens are supposed to be.
16+
pub const STANDARD_TOKEN_LENGTH: usize = 128;
17+
1518
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
1619
pub struct ApiKey {
1720
token: String,
1821
}
1922

23+
#[cfg_attr(coverage_nightly, coverage(off))]
2024
impl Deref for ApiKey {
2125
type Target = str;
2226

@@ -41,13 +45,15 @@ impl ApiKey {
4145
Ok(Self { token: token.to_owned() })
4246
}
4347

48+
#[cfg_attr(coverage_nightly, coverage(off))]
49+
/// Getter for the internal token.
4450
pub fn token(&self) -> &str {
4551
&self.token
4652
}
4753

48-
/// Generates a new, random [ApiKey] which is 128 characters in length.
54+
/// Generates a new, random [ApiKey] which is [STANDARD_TOKEN_LENGTH] characters in length.
4955
pub fn new_random(rng: &mut ThreadRng) -> Self {
50-
Self { token: Alphanumeric.sample_string(rng, 128) }
56+
Self { token: Alphanumeric.sample_string(rng, STANDARD_TOKEN_LENGTH) }
5157
}
5258
}
5359

@@ -69,3 +75,30 @@ pub(crate) async fn add_api_key_to_database(
6975
.map_err(SonataDbError::Sqlx)?;
7076
Ok(key)
7177
}
78+
79+
#[cfg(test)]
80+
mod test {
81+
use rand::rng;
82+
use sqlx::{Pool, Postgres};
83+
84+
use super::*;
85+
86+
#[test]
87+
fn token_length() {
88+
assert!(ApiKey::new("").is_err());
89+
assert!(ApiKey::new("token").is_err());
90+
assert!(ApiKey::new(['c'; 256].iter().collect::<String>().as_str()).is_err());
91+
assert!(ApiKey::new("transrightsarehumanrights_thefirstpridewasariot").is_ok());
92+
}
93+
94+
#[test]
95+
fn auto_gen_token() {
96+
assert_eq!(ApiKey::new_random(&mut rng()).len(), STANDARD_TOKEN_LENGTH);
97+
}
98+
99+
#[sqlx::test]
100+
async fn insert_key_into_db(db: Pool<Postgres>) {
101+
let key = ApiKey::new_random(&mut rng());
102+
assert!(add_api_key_to_database(key.token(), &Database { pool: db }).await.is_ok());
103+
}
104+
}

0 commit comments

Comments
 (0)