Skip to content

Commit

Permalink
fix: unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
discord9 committed Dec 3, 2024
1 parent 772462c commit 9a76968
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 11 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src/common/base/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,5 @@ zeroize = { version = "1.6", default-features = false, features = ["alloc"] }

[dev-dependencies]
common-test-util.workspace = true
serde_json.workspace = true
toml.workspace = true
77 changes: 75 additions & 2 deletions src/common/base/src/ttl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,65 @@
use std::fmt::Display;
use std::time::Duration;

use serde::de::Visitor;
use serde::{Deserialize, Serialize};

/// Time To Live
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Serialize, Deserialize)]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default)]
pub enum TimeToLive {
/// immediately throw away on insert
Immediate,
/// Duration to keep the data, this duration should be non-zero
#[serde(with = "humantime_serde")]
Duration(Duration),
/// Keep the data forever
#[default]
Forever,
// TODO(discord9): add a new variant
// that can't be overridden by database level ttl? call it ForceForever?
}

impl Serialize for TimeToLive {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
Self::Immediate => serializer.serialize_str("immediate"),
Self::Duration(d) => humantime_serde::serialize(d, serializer),
Self::Forever => serializer.serialize_str("forever"),
}
}
}

impl<'de> Deserialize<'de> for TimeToLive {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct StrVisitor;
impl Visitor<'_> for StrVisitor {
type Value = TimeToLive;

fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a string of time, 'immediate', 'forever' or null")
}

fn visit_unit<E>(self) -> Result<Self::Value, E> {
Ok(TimeToLive::Forever)
}

fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
TimeToLive::from_humantime_or_str(value).map_err(serde::de::Error::custom)
}
}
// deser a string or null
let any = deserializer.deserialize_any(StrVisitor)?;
Ok(any)
}
}

impl Display for TimeToLive {
Expand Down Expand Up @@ -106,3 +151,31 @@ impl From<humantime::Duration> for TimeToLive {
Self::from(*duration)
}
}

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

#[test]
fn test_serde() {
let cases = vec![
("\"immediate\"", TimeToLive::Immediate),
("\"forever\"", TimeToLive::Forever),
("\"10d\"", Duration::from_secs(86400 * 10).into()),
(
"\"10000 years\"",
humantime::parse_duration("10000 years").unwrap().into(),
),
("null", TimeToLive::Forever),
];

for (s, expected) in cases {
let serialized = serde_json::to_string(&expected).unwrap();
let deserialized: TimeToLive = serde_json::from_str(&serialized).unwrap();
assert_eq!(deserialized, expected);

let deserialized: TimeToLive = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, expected);
}
}
}
4 changes: 2 additions & 2 deletions src/common/meta/src/ddl/alter_database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ fn build_new_schema_value(
AlterDatabaseKind::UnsetDatabaseOptions(keys) => {
for key in keys.0.iter() {
match key {
UnsetDatabaseOption::Ttl => value.ttl = TimeToLive::Forever,
UnsetDatabaseOption::Ttl => value.ttl = TimeToLive::default(),
}
}
}
Expand Down Expand Up @@ -242,6 +242,6 @@ mod tests {
]));
let new_schema_value =
build_new_schema_value(current_schema_value, &unset_ttl_alter_kind).unwrap();
assert_eq!(new_schema_value.ttl, TimeToLive::Forever);
assert_eq!(new_schema_value.ttl, TimeToLive::default());
}
}
12 changes: 5 additions & 7 deletions src/common/meta/src/key/schema_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ mod tests {
#[test]
fn test_display_schema_value() {
let schema_value = SchemaNameValue {
ttl: TimeToLive::Forever,
ttl: TimeToLive::default(),
};
assert_eq!("", schema_value.to_string());

Expand Down Expand Up @@ -355,9 +355,7 @@ mod tests {
assert_eq!(value, from_value);

let parsed = SchemaNameValue::try_from_raw_value(
serde_json::json!({"ttl": {"Duration": "10s"}})
.to_string()
.as_bytes(),
serde_json::json!({"ttl": "10s"}).to_string().as_bytes(),
)
.unwrap();
assert_eq!(Some(value), parsed);
Expand All @@ -366,18 +364,18 @@ mod tests {
ttl: TimeToLive::Immediate,
};
let parsed = SchemaNameValue::try_from_raw_value(
serde_json::json!({"ttl": "Immediate"})
serde_json::json!({"ttl": "immediate"})
.to_string()
.as_bytes(),
)
.unwrap();
assert_eq!(Some(imme), parsed);

let forever = SchemaNameValue {
ttl: TimeToLive::Forever,
ttl: TimeToLive::default(),
};
let parsed = SchemaNameValue::try_from_raw_value(
serde_json::json!({"ttl": "Forever"}).to_string().as_bytes(),
serde_json::json!({"ttl": "forever"}).to_string().as_bytes(),
)
.unwrap();
assert_eq!(Some(forever), parsed);
Expand Down

0 comments on commit 9a76968

Please sign in to comment.