1
use sqlx::{PgPool, types::Uuid};
2
use supp_macro::local_db_sqlx_test;
3

            
4
use super::config::{GetConfig, GetTimezone, SetConfig};
5
use super::{CmdError, CmdResult, connection};
6
use crate::config::{ConfigOption, set_config_on};
7
use crate::db::install_test_pool;
8
use crate::timezone::Tz;
9
use crate::user::User;
10

            
11
4
async fn setup() {
12
4
    crate::telemetry::init_test_logging();
13
4
}
14

            
15
2
async fn set_timezone(user_id: Uuid, value: &str) -> Result<(), CmdError> {
16
2
    SetConfig::new()
17
2
        .user_id(user_id)
18
2
        .name("timezone".to_string())
19
2
        .value(value.to_string())
20
2
        .run()
21
2
        .await
22
2
        .map(drop)
23
2
}
24

            
25
3
async fn zone(user_id: Uuid) -> anyhow::Result<Tz> {
26
3
    match GetTimezone::new().user_id(user_id).run().await? {
27
3
        Some(CmdResult::Timezone(zone)) => Ok(zone),
28
        other => anyhow::bail!("not a timezone: {other:?}"),
29
    }
30
3
}
31

            
32
#[local_db_sqlx_test]
33
async fn an_unset_timezone_is_utc(pool: PgPool) -> anyhow::Result<()> {
34
    assert_eq!(zone(Uuid::new_v4()).await?, Tz::UTC);
35
}
36

            
37
#[local_db_sqlx_test]
38
async fn a_set_timezone_is_stored_trimmed_and_read_back(pool: PgPool) -> anyhow::Result<()> {
39
    let user_id = Uuid::new_v4();
40
    set_timezone(user_id, " Asia/Tokyo ").await?;
41
    assert_eq!(zone(user_id).await?, Tz::Asia__Tokyo);
42
    let stored = GetConfig::new()
43
        .user_id(user_id)
44
        .name("timezone".to_string())
45
        .run()
46
        .await?
47
1
        .map(|value| value.to_string());
48
    assert_eq!(stored.as_deref(), Some("Asia/Tokyo"));
49
}
50

            
51
#[local_db_sqlx_test]
52
async fn an_unknown_timezone_is_refused_and_not_stored(pool: PgPool) -> anyhow::Result<()> {
53
    let user_id = Uuid::new_v4();
54
    let refused = set_timezone(user_id, "Mars/Olympus").await;
55
    assert!(
56
        matches!(&refused, Err(CmdError::Refused(msg)) if msg.contains("Mars/Olympus")),
57
        "{refused:?}"
58
    );
59
    assert_eq!(zone(user_id).await?, Tz::UTC);
60
}
61

            
62
#[local_db_sqlx_test]
63
async fn a_bad_stored_timezone_is_refused_naming_the_value_and_the_fix(
64
    pool: PgPool,
65
) -> anyhow::Result<()> {
66
    let user_id = Uuid::new_v4();
67
    let mut conn = connection(&User { id: user_id }).await?;
68
    set_config_on(
69
        &mut conn,
70
        "timezone",
71
        ConfigOption::String("Mars/Olympus".into()),
72
    )
73
    .await?;
74
    drop(conn);
75

            
76
    let refused = GetTimezone::new().user_id(user_id).run().await;
77
    assert!(
78
        matches!(&refused, Err(CmdError::Refused(msg))
79
            if msg.contains("Mars/Olympus") && msg.contains("set-config")),
80
        "{refused:?}"
81
    );
82
}