diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index d2020cfb..8644339b 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -1,3 +1,29 @@ # cargo-mutants settings, used by scripts/mutants.sh. # Build and test with the lock file, as CI does. additional_cargo_args = ["--locked"] + +# Mutants no test can tell apart from the real code, or that only hang. +exclude_re = [ + # crates/bot-core/src/ai_calculator.rs: `index *= 1` never moves the tokenizer forward, so a + # test hangs until the timeout, which costs 2 minutes per mutant and finds nothing. The + # mutant name does not say which `+=` it changes, so this also covers the two `index += 2` + # sites (`**` and `//`), which do not hang. The unspaced `2**3` and `100//3` tests check them. + "replace \\+= with \\*= in tokenize$", + # crates/bot-core/src/bcra.rs: at exactly 100 bps, one decimal prints "100.0", which `trimmed` turns back into "100", + # the same as no decimals. No other value changes. + "replace < with <= in risk_decimals$", + # Moving the parser back makes it read the same operand again, forever. + "replace \\+= with -= in Parser<'a>::parse_(additive|multiplicative|primary)$", + # Without the exponent cap, the tests' large powers run until the timeout: the slow work the + # cap exists to refuse. The tests check the cap's error text where the result is too big. + "replace \\|\\| with && in power$", + # crates/bot-core/src/base_conversion.rs: `value *= target` grows the number forever. + "replace /= with \\*= in convert_base$", + # crates/bot-core/src/command_normalization.rs: `start *= length` stays at 0 forever, and + # `start *= 1` after an ASCII character stays where it is. Both hang the tests. + "replace \\+= with \\*= in romanize_japanese$", + # crates/bot-core/src/polymarket.rs: at exactly 10%, 1 and 2 decimals both print "10". + "replace < with <= in render_elections$", + # crates/bot-core/src/price_queries.rs: the last dot and the last comma are never at the same index. + "replace > with >= in parse_conversion_amount$", +] diff --git a/Cargo.lock b/Cargo.lock index 8ddf25e8..1ab36fa6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -233,6 +233,7 @@ dependencies = [ "emojis", "ib-romaji", "num-bigint 0.5.1", + "num-integer", "proptest", "regex", "serde", diff --git a/Cargo.toml b/Cargo.toml index eed5cae7..de8876de 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,6 +29,7 @@ qrcode = { version = "0.15.0", default-features = false, features = ["image"] } ib-romaji = "0.2.1" emojis = "0.9.1" num-bigint = "0.5.1" +num-integer = "0.1.47" native-tls = "0.2.18" postgres = { version = "0.19.14", features = ["with-serde_json-1"] } postgres-native-tls = "0.5.3" diff --git a/crates/bot-adapters/src/bcra.rs b/crates/bot-adapters/src/bcra.rs index 0f21fab8..640e875a 100644 --- a/crates/bot-adapters/src/bcra.rs +++ b/crates/bot-adapters/src/bcra.rs @@ -5,6 +5,7 @@ use std::{collections::BTreeMap, io::Cursor, thread, time::Duration}; use bot_core::{ bcra::{BcraBands, BcraSnapshot, BcraVariable, CountryRisk, ItcrmDetails, render_bcra}, cache_policy::request_cache_history_key, + calendar::{checked_days_from_civil, civil_from_days, days_from_civil}, locale::Locale, }; use calamine::{Data, Reader, Xlsx}; @@ -180,33 +181,11 @@ fn floor(value: i64, divisor: i64) -> i64 { if r < 0 { q - 1 } else { q } } -fn civil(days: i64) -> (i64, i64, i64) { - let z = days + 719_468; - let era = floor(z, 146_097); - let doe = z - era * 146_097; - let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; - let mut year = yoe + era * 400; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let day = doy - (153 * mp + 2) / 5 + 1; - let month = mp + if mp < 10 { 3 } else { -9 }; - year += i64::from(month <= 2); - (year, month, day) -} - -fn days(year: i64, month: i64, day: i64) -> i64 { - let y = year - i64::from(month <= 2); - let era = if y >= 0 { y } else { y - 399 } / 400; - let yoe = y - era * 400; - let mp = month + if month > 2 { -3 } else { 9 }; - era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + (153 * mp + 2) / 5 + day - 1 - 719_468 -} - pub(crate) fn parse_date(value: &str) -> Option { let value = value.trim().split(['T', ' ']).next()?; if let Some((y, rest)) = value.split_once('-') { let (m, d) = rest.split_once('-')?; - return Some(days(y.parse().ok()?, m.parse().ok()?, d.parse().ok()?)); + return checked_days_from_civil(y.parse().ok()?, m.parse().ok()?, d.parse().ok()?); } let mut p = value.split('/'); let (d, m, mut y) = ( @@ -217,22 +196,22 @@ pub(crate) fn parse_date(value: &str) -> Option { if y < 100 { y += 2_000; } - Some(days(y, m, d)) + checked_days_from_civil(y, m, d) } pub(crate) fn iso(day: i64) -> String { - let (y, m, d) = civil(day); + let (y, m, d) = civil_from_days(day); format!("{y:04}-{m:02}-{d:02}") } fn display(day: i64) -> String { - let (y, m, d) = civil(day); + let (y, m, d) = civil_from_days(day); format!("{d:02}/{m:02}/{:02}", y.rem_euclid(100)) } pub(crate) fn ba_day(now: i64) -> i64 { floor(now.saturating_sub(10_800), 86_400) } fn now_iso(now: i64) -> String { - let (y, m, d) = civil(floor(now, 86_400)); + let (y, m, d) = civil_from_days(floor(now, 86_400)); let s = now.rem_euclid(86_400); format!( "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}+00:00", @@ -611,7 +590,7 @@ fn risk_label(value: &str) -> Option { let (h, m) = time.split_once(':')?; let minutes = h.parse::().ok()? * 60 + m.parse::().ok()? - 180; let adjusted = day + floor(minutes, 1440); - let (_, month, date) = civil(adjusted); + let (_, month, date) = civil_from_days(adjusted); Some(format!( "{date:02}/{month:02} {:02}:{:02}", minutes.rem_euclid(1440) / 60, @@ -639,7 +618,7 @@ fn cell_date(value: &Data) -> Option { match value { Data::DateTime(v) => { let (y, m, d, _, _, _, _) = v.to_ymd_hms_milli(); - Some(days(i64::from(y), i64::from(m), i64::from(d))) + Some(days_from_civil(i64::from(y), i64::from(m), i64::from(d))) } Data::String(v) | Data::DateTimeIso(v) => parse_date(v), _ => None, @@ -1346,7 +1325,7 @@ mod tests { #[test] fn daily_tcrm_uses_only_observations_available_on_the_target_date() { - let now = days(2024, 9, 1) * 86_400 + 15 * 3_600; + let now = days_from_civil(2024, 9, 1) * 86_400 + 15 * 3_600; let variable = json!({"idVariable":5,"descripcion":"Tipo de cambio mayorista"}); let variables = variable.as_object().into_iter().collect::>(); let request = BcraRequest::Series { id: 5, limit: 32 }; @@ -1550,7 +1529,7 @@ mod tests { #[test] fn current_itcrm_excludes_future_and_malformed_cached_details() { - let now = days(2024, 9, 1) * 86_400 + 15 * 3600; + let now = days_from_civil(2024, 9, 1) * 86_400 + 15 * 3600; for latest in [ None, Some(json!({"date":"2024-09-02","value":250.0})), @@ -1588,7 +1567,7 @@ mod tests { #[test] fn uncached_itcrm_response_supplies_daily_history_without_a_second_fetch() -> TestResult { - let now = days(2026, 9, 2) * 86_400 + 15 * 3600; + let now = days_from_civil(2026, 9, 2) * 86_400 + 15 * 3600; let bytes = base64::engine::general_purpose::STANDARD.decode(ITCRM_WORKBOOK)?; let transport = Transport { responses: RefCell::new(VecDeque::from([ @@ -2020,6 +1999,18 @@ mod tests { fn dates_rows_and_band_descriptions_tolerate_partial_provider_data() { assert_eq!(parse_date("19/09/2025"), parse_date("19/09/25")); assert_eq!(parse_date("2025-09-19"), parse_date("19/09/25")); + // Only years below 100 are short years. + assert_eq!(parse_date("01/01/99"), parse_date("2099-01-01")); + assert_eq!(parse_date("01/01/100"), parse_date("100-01-01")); + assert_ne!(parse_date("01/01/100"), parse_date("2100-01-01")); + for date in [ + "31/02/2025", + "19/13/2025", + "2025-02-30", + "19/9223372036854775807/2025", + ] { + assert_eq!(parse_date(date), None, "{date}"); + } let rows = json!({"results":[{"detalle":[ {"fecha":"2025-09-18","valor":930}, {"fecha":"2025-09-19"}, diff --git a/crates/bot-adapters/src/weather.rs b/crates/bot-adapters/src/weather.rs index 24d9c14c..7f3072b2 100644 --- a/crates/bot-adapters/src/weather.rs +++ b/crates/bot-adapters/src/weather.rs @@ -3,6 +3,7 @@ use std::thread; use std::time::Duration; +use bot_core::calendar::civil_from_days; use bot_core::weather::{ DEFAULT_WEATHER_LOCATION, WeatherObservation, search_key, select_forecast_hour, select_location_candidate, @@ -300,20 +301,6 @@ fn location_label(location: &Location) -> String { parts.join(", ") } -fn civil_from_days(days: i64) -> (i64, i64, i64) { - let days = days + 719_468; - let era = days.div_euclid(146_097); - let day_of_era = days - era * 146_097; - let year_of_era = - (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; - let year = year_of_era + era * 400; - let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); - let month_prime = (5 * day_of_year + 2) / 153; - let day = day_of_year - (153 * month_prime + 2) / 5 + 1; - let month = month_prime + if month_prime < 10 { 3 } else { -9 }; - (year + i64::from(month <= 2), month, day) -} - fn buenos_aires_hour(now_unix: i64) -> String { let local_seconds = now_unix.saturating_sub(3 * 3_600); let days = local_seconds.div_euclid(86_400); diff --git a/crates/bot-core/Cargo.toml b/crates/bot-core/Cargo.toml index c725b901..e696a49a 100644 --- a/crates/bot-core/Cargo.toml +++ b/crates/bot-core/Cargo.toml @@ -13,6 +13,7 @@ deunicode.workspace = true emojis.workspace = true ib-romaji.workspace = true num-bigint.workspace = true +num-integer.workspace = true regex.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/crates/bot-core/src/admin_commands.rs b/crates/bot-core/src/admin_commands.rs index 1a571009..ecbd3162 100644 --- a/crates/bot-core/src/admin_commands.rs +++ b/crates/bot-core/src/admin_commands.rs @@ -293,10 +293,8 @@ fn metadata_credit(metadata: &Map, keys: &[&str]) -> i64 { fn optional_id(metadata: &Map, key: &str, fallback: Option) -> String { metadata.get(key).map_or_else( || fallback.map_or_else(|| "None".to_owned(), |value| value.to_string()), - |value| match value { - Value::Null => "None".to_owned(), - _ => python_string(Some(value), "None"), - }, + // `python_string` also turns a JSON null into "None". + |value| python_string(Some(value), "None"), ) } diff --git a/crates/bot-core/src/admin_reports.rs b/crates/bot-core/src/admin_reports.rs index 8e25d98b..967cb257 100644 --- a/crates/bot-core/src/admin_reports.rs +++ b/crates/bot-core/src/admin_reports.rs @@ -23,12 +23,10 @@ pub fn parse_creditlog_limit(message_text: &str) -> CreditLogLimit { return CreditLogLimit::UnsupportedNumericInput; } let bytes = normalized.as_bytes(); + // An underscore must follow a digit and must not end the number. Any other character after + // it makes the parse below fail, so only those two checks are needed here. let underscores_are_valid = bytes.iter().enumerate().all(|(index, byte)| { - *byte != b'_' - || (index > 0 - && index + 1 < bytes.len() - && bytes[index - 1].is_ascii_digit() - && bytes[index + 1].is_ascii_digit()) + *byte != b'_' || (index > 0 && index + 1 < bytes.len() && bytes[index - 1].is_ascii_digit()) }); if !underscores_are_valid { return CreditLogLimit::Invalid; @@ -37,18 +35,11 @@ pub fn parse_creditlog_limit(message_text: &str) -> CreditLogLimit { let Some(value) = BigInt::parse_bytes(compact.as_bytes(), 10) else { return CreditLogLimit::Invalid; }; - let minimum = BigInt::from(1_u8); - let maximum = BigInt::from(25_u8); - if value < minimum { - CreditLogLimit::Valid(1) - } else if value > maximum { - CreditLogLimit::Valid(25) - } else { - value - .to_string() - .parse::() - .map_or(CreditLogLimit::Invalid, CreditLogLimit::Valid) - } + value + .clamp(BigInt::from(1_u8), BigInt::from(25_u8)) + .to_string() + .parse::() + .map_or(CreditLogLimit::Invalid, CreditLogLimit::Valid) } /// Truncate a report by Unicode scalar count and append the localized marker. @@ -85,6 +76,10 @@ mod tests { ("1", CreditLogLimit::Valid(1)), ("1_0", CreditLogLimit::Valid(10)), ("1__0", CreditLogLimit::Invalid), + ("1", CreditLogLimit::Valid(1)), + ("25", CreditLogLimit::Valid(25)), + ("26", CreditLogLimit::Valid(25)), + ("1_a", CreditLogLimit::Invalid), ] { assert_eq!(parse_creditlog_limit(input), expected, "{input}"); } diff --git a/crates/bot-core/src/ai_calculator.rs b/crates/bot-core/src/ai_calculator.rs index 7dd1404b..f0515834 100644 --- a/crates/bot-core/src/ai_calculator.rs +++ b/crates/bot-core/src/ai_calculator.rs @@ -1,6 +1,7 @@ //! Safe arithmetic evaluator shared by the AI `calculate` tool. use num_bigint::BigInt; +use num_integer::Integer; use crate::locale::Locale; @@ -134,8 +135,8 @@ fn tokenize(expression: &str) -> Result, CalculationError> { match chars[index] { value if value.is_whitespace() => index += 1, value if value.is_ascii_digit() || value == '.' => { + // The loop takes the first character too: it is a digit or '.'. let start = index; - index += 1; while index < chars.len() && (chars[index].is_ascii_digit() || matches!(chars[index], '.' | 'e' | 'E') @@ -353,17 +354,9 @@ fn floor_divide(left: Number, right: Number) -> Result return Err(CalculationError::ZeroDivision); } match (left, right) { + // Python's `//` rounds toward negative infinity, like `div_floor`. (Number::Integer(left), Number::Integer(right)) => { - let quotient = &left / &right; - let remainder = &left % &right; - let opposite_signs = (left < BigInt::from(0)) != (right < BigInt::from(0)); - Ok(Number::Integer( - if remainder != BigInt::from(0) && opposite_signs { - quotient - 1 - } else { - quotient - }, - )) + Ok(Number::Integer(left.div_floor(&right))) } (left, right) => Ok(Number::Float( (left.as_float()? / right.as_float()?).floor(), @@ -376,16 +369,9 @@ fn modulo(left: Number, right: Number) -> Result { return Err(CalculationError::ZeroDivision); } match (left, right) { + // Python's `%` takes the sign of the divisor, like `mod_floor`. (Number::Integer(left), Number::Integer(right)) => { - let remainder = &left % &right; - let opposite_signs = (remainder < BigInt::from(0)) != (right < BigInt::from(0)); - Ok(Number::Integer( - if remainder != BigInt::from(0) && opposite_signs { - remainder + right - } else { - remainder - }, - )) + Ok(Number::Integer(left.mod_floor(&right))) } (left, right) => { let left = left.as_float()?; @@ -425,6 +411,9 @@ mod tests { assert_eq!(calculate_expression("2 + 3 * 4", Locale::En), "14"); assert_eq!(calculate_expression("(2 + 3) * 4", Locale::En), "20"); assert_eq!(calculate_expression("2 ** 10", Locale::En), "1024"); + // Without spaces, the two-character operators start after index 1. + assert_eq!(calculate_expression("2**3", Locale::En), "8"); + assert_eq!(calculate_expression("100//3", Locale::En), "33"); assert_eq!(calculate_expression("2 ** -2", Locale::En), "0.25"); assert_eq!( calculate_expression("100000000000000000000 + 1", Locale::En), @@ -503,6 +492,13 @@ mod tests { calculate_expression(&"1+".repeat(201), Locale::En), "expression is too long" ); + // Exactly MAX_SYNTAX_NODES tokens: "-(", 98 times "1+", then "1)". + let longest = format!("-({}1)", "1+".repeat(98)); + assert_eq!(calculate_expression(&longest, Locale::En), "-99"); + assert_eq!( + calculate_expression(&format!("-{longest}"), Locale::En), + "expression is too long" + ); for expression in ["2 ** 100001", "2 ** 4294967296"] { assert_eq!( calculate_expression(expression, Locale::En), diff --git a/crates/bot-core/src/ai_reserve.rs b/crates/bot-core/src/ai_reserve.rs index 38ec2981..f4a0ff3b 100644 --- a/crates/bot-core/src/ai_reserve.rs +++ b/crates/bot-core/src/ai_reserve.rs @@ -170,9 +170,8 @@ pub fn estimate_transcription_reserve_credit_units( return Ok(1); } let usd_micros = (seconds * usd_micros_per_hour as f64 / 3_600.0).ceil(); - if usd_micros > i128::MAX as f64 { - return Err(ReserveEstimateError::Overflow); - } + // `as` saturates at i128::MAX, and a value that large overflows the i64 credit units, so + // `credit_units_from_usd_micros` already returns `Overflow` for it. Ok(credit_units_from_usd_micros(usd_micros as i128)?.max(1)) } diff --git a/crates/bot-core/src/ai_response_cleanup.rs b/crates/bot-core/src/ai_response_cleanup.rs index a308904d..dc30ce63 100644 --- a/crates/bot-core/src/ai_response_cleanup.rs +++ b/crates/bot-core/src/ai_response_cleanup.rs @@ -143,9 +143,6 @@ fn collapse_double_periods(text: &str) -> String { #[must_use] pub fn strip_leading_context(response: &str, contexts: &[Option]) -> String { - if response.is_empty() || contexts.is_empty() { - return response.to_owned(); - } let normalized = contexts .iter() .filter_map(|context| context.as_deref().map(str::trim)) diff --git a/crates/bot-core/src/bcra.rs b/crates/bot-core/src/bcra.rs index 9c41c460..9f98b7ae 100644 --- a/crates/bot-core/src/bcra.rs +++ b/crates/bot-core/src/bcra.rs @@ -2,6 +2,7 @@ use unicode_normalization::UnicodeNormalization; +use crate::calendar::{checked_days_from_civil, days_from_civil}; use crate::locale::Locale; use crate::regex_cache::cached_regex; @@ -72,6 +73,11 @@ fn trimmed(value: f64, decimals: usize) -> String { .to_owned() } +/// Country risk shows one decimal below 100 bps and none from 100 up. +fn risk_decimals(bps: f64) -> usize { + usize::from(bps.abs() < 100.0) +} + fn format_bcra_value(value: &str, percentage: bool) -> String { let normalized = if percentage { value.replace(',', ".") @@ -228,7 +234,7 @@ fn parse_date(value: &str) -> Option<(i64, i64, i64)> { let first = value.split_whitespace().next()?; if let Some((year, rest)) = first.split_once('-') { let (month, day) = rest.split_once('-')?; - return Some((year.parse().ok()?, month.parse().ok()?, day.parse().ok()?)); + return existing((year.parse().ok()?, month.parse().ok()?, day.parse().ok()?)); } let mut parts = first.split('/'); let day = parts.next()?.parse().ok()?; @@ -239,17 +245,12 @@ fn parse_date(value: &str) -> Option<(i64, i64, i64)> { } else { raw_year }; - Some((year, month, day)) + existing((year, month, day)) } -fn days_from_civil(year: i64, month: i64, day: i64) -> i64 { - let year = year - i64::from(month <= 2); - let era = if year >= 0 { year } else { year - 399 } / 400; - let year_of_era = year - era * 400; - let month_prime = month + if month > 2 { -3 } else { 9 }; - let day_of_year = (153 * month_prime + 2) / 5 + day - 1; - let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; - era * 146_097 + day_of_era - 719_468 +/// Keeps only a date that exists, so a bad date from the API is skipped instead of counted. +fn existing(date: (i64, i64, i64)) -> Option<(i64, i64, i64)> { + checked_days_from_civil(date.0, date.1, date.2).map(|_| date) } #[must_use] @@ -335,12 +336,13 @@ pub fn render_bcra(snapshot: &BcraSnapshot, locale: Locale, today_days: i64) -> } } if let Some(risk) = &snapshot.country_risk { - let decimals = usize::from(risk.value_bps.abs() < 100.0); + let decimals = risk_decimals(risk.value_bps); let value = trimmed(risk.value_bps, decimals); let mut details = risk.valuation_label.iter().cloned().collect::>(); if let Some(delta) = risk.delta_one_day.filter(|delta| delta.abs() >= 0.05) { - let decimals = usize::from(delta.abs() < 100.0); - let sign = if delta > 0.0 { "+" } else { "-" }; + let decimals = risk_decimals(delta); + // The filter above keeps only nonzero changes. + let sign = if delta.is_sign_negative() { "-" } else { "+" }; let change = format!("{sign}{}", trimmed(delta.abs(), decimals)); details.push(match locale { Locale::Es => format!("{change} bps vs ayer"), @@ -410,10 +412,65 @@ pub fn render_bcra(snapshot: &BcraSnapshot, locale: Locale, today_days: i64) -> mod tests { use super::{ BcraBands, BcraSnapshot, BcraVariable, CountryRisk, ItcrmDetails, classify_bcra_command, - days_from_civil, render_bcra, + render_bcra, }; + use crate::calendar::days_from_civil; use crate::locale::Locale; + #[test] + fn two_digit_years_are_in_this_century() { + assert_eq!(super::parse_date("15/01/99"), Some((2_099, 1, 15))); + assert_eq!(super::parse_date("15/01/100"), Some((100, 1, 15))); + assert_eq!(super::parse_date("2025-01-15"), Some((2_025, 1, 15))); + } + + #[test] + fn the_title_date_needs_more_than_half_of_the_variables() { + let snapshot = |dates: &[&str]| BcraSnapshot { + variables: [ + "Base monetaria", + "Tasa TAMAR", + "Tasa BADLAR", + "Reservas internacionales", + "Tipo de cambio mayorista", + ] + .iter() + .zip(dates) + .map(|(description, date)| BcraVariable { + description: (*description).to_owned(), + value: "1,0".to_owned(), + date: (*date).to_owned(), + }) + .collect(), + bands: None, + itcrm: None, + country_risk: None, + stale: false, + }; + let today = days_from_civil(2025, 1, 20); + let half = snapshot(&["15/01/2025", "15/01/2025", "16/01/2025", "16/01/2025"]); + assert!(render_bcra(&half, Locale::En, today).starts_with("BCRA indicators\n\n")); + // One dated variable is not a shared date. + let single = snapshot(&["15/01/2025"]); + assert!(render_bcra(&single, Locale::En, today).starts_with("BCRA indicators\n\n")); + let most = snapshot(&["15/01/2025", "15/01/2025", "15/01/2025", "16/01/2025"]); + assert!( + render_bcra(&most, Locale::En, today).starts_with("BCRA indicators as of 15/01/25\n\n") + ); + // 3 of 5 is more than half. + let three_of_five = snapshot(&[ + "15/01/2025", + "15/01/2025", + "15/01/2025", + "16/01/2025", + "17/01/2025", + ]); + assert!( + render_bcra(&three_of_five, Locale::En, today) + .starts_with("BCRA indicators as of 15/01/25\n\n") + ); + } + #[test] fn recognizes_public_aliases() { assert!(classify_bcra_command("/bcra")); @@ -721,6 +778,15 @@ mod tests { assert_eq!(super::parse_date("2025-01"), None); assert_eq!(super::parse_date("2025-01-15 10:00"), Some((2025, 1, 15))); assert_eq!(super::parse_date("15/01/25"), Some((2025, 1, 15))); + // Dates that do not exist are skipped. + for date in [ + "31/02/2025", + "15/13/2025", + "2025-00-15", + "15/9223372036854775807/2025", + ] { + assert_eq!(super::parse_date(date), None, "{date}"); + } } #[test] @@ -763,12 +829,4 @@ mod tests { fn old_four_digit_years_stay_verbatim() { assert_eq!(super::short_year("15/01/1999"), "15/01/1999"); } - - #[test] - fn civil_days_count_back_before_year_zero() { - assert_eq!(super::days_from_civil(1970, 1, 1), 0); - assert_eq!(super::days_from_civil(0, 3, 1), -719_468); - // January of year 0 is counted as part of year -1. - assert_eq!(super::days_from_civil(0, 1, 1), -719_528); - } } diff --git a/crates/bot-core/src/calendar.rs b/crates/bot-core/src/calendar.rs new file mode 100644 index 00000000..676328cd --- /dev/null +++ b/crates/bot-core/src/calendar.rs @@ -0,0 +1,123 @@ +//! Calendar dates as day counts from 1970-01-01, in the proleptic Gregorian calendar. +//! +//! Howard Hinnant's `days_from_civil` and `civil_from_days`: plain integer math that gives an +//! answer for every input, so dates from clocks and parsers need no error path. + +/// Days from 1970-01-01 to `year`-`month`-`day`, for a date that exists. It does not check +/// the date: a day past the end of the month counts on into the next month, and a month or +/// year far out of range overflows. Use [`checked_days_from_civil`] for untrusted dates. +#[must_use] +pub fn days_from_civil(year: i64, month: i64, day: i64) -> i64 { + // The year starts in March, so February's leap day is the last day of the year. + let year = year - i64::from(month <= 2); + let era = year.div_euclid(400); + let year_of_era = year - era * 400; + let month_from_march = month + if month > 2 { -3 } else { 9 }; + let day_of_year = (153 * month_from_march + 2) / 5 + day - 1; + let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; + era * 146_097 + day_of_era - 719_468 +} + +/// Days from 1970-01-01 to `year`-`month`-`day`, or `None` when the date does not exist or +/// its year is outside -1,000,000..=1,000,000. The limits keep the math from overflowing. +#[must_use] +pub fn checked_days_from_civil(year: i64, month: i64, day: i64) -> Option { + if !(-1_000_000..=1_000_000).contains(&year) + || !(1..=12).contains(&month) + || !(1..=31).contains(&day) + { + return None; + } + let days = days_from_civil(year, month, day); + // A day past the end of its month gives a date in the next month. + (civil_from_days(days) == (year, month, day)).then_some(days) +} + +/// The `(year, month, day)` of a day count from [`days_from_civil`]. +#[must_use] +pub fn civil_from_days(days: i64) -> (i64, i64, i64) { + let days = days + 719_468; + let era = days.div_euclid(146_097); + let day_of_era = days - era * 146_097; + let year_of_era = + (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; + let year = year_of_era + era * 400; + let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); + let month_from_march = (5 * day_of_year + 2) / 153; + let day = day_of_year - (153 * month_from_march + 2) / 5 + 1; + let month = month_from_march + if month_from_march < 10 { 3 } else { -9 }; + (year + i64::from(month <= 2), month, day) +} + +#[cfg(test)] +mod tests { + use chrono::{Datelike, NaiveDate}; + + use super::{checked_days_from_civil, civil_from_days, days_from_civil}; + + /// chrono counts 0001-01-01 as day 1, so 1970-01-01 is its day 719 163. + const UNIX_EPOCH_FROM_CE: i64 = 719_163; + + #[test] + fn every_day_from_year_minus_500_to_4980_matches_chrono() -> Result<(), &'static str> { + for days in -900_000..1_100_000 { + let date = i32::try_from(days + UNIX_EPOCH_FROM_CE) + .ok() + .and_then(NaiveDate::from_num_days_from_ce_opt) + .ok_or("a day is outside chrono's range")?; + let civil = ( + i64::from(date.year()), + i64::from(date.month()), + i64::from(date.day()), + ); + assert_eq!(civil_from_days(days), civil, "{date}"); + assert_eq!(days_from_civil(civil.0, civil.1, civil.2), days, "{date}"); + } + Ok(()) + } + + #[test] + fn checked_dates_must_exist_and_stay_in_range() { + assert_eq!( + checked_days_from_civil(2024, 2, 29), + Some(days_from_civil(2024, 2, 29)) + ); + assert_eq!( + checked_days_from_civil(1_000_000, 12, 31), + Some(days_from_civil(1_000_000, 12, 31)) + ); + assert_eq!( + checked_days_from_civil(-1_000_000, 1, 1), + Some(days_from_civil(-1_000_000, 1, 1)) + ); + for (year, month, day) in [ + (2025, 2, 29), + (2025, 4, 31), + (2025, 0, 1), + (2025, 13, 1), + (2025, 1, 0), + (2025, 1, 32), + (1_000_001, 1, 1), + (-1_000_001, 1, 1), + // Values that would overflow the math if they got that far. + (i64::MAX, 1, 1), + (i64::MIN, 1, 1), + (2025, i64::MAX, 1), + (2025, 1, i64::MAX), + ] { + assert_eq!( + checked_days_from_civil(year, month, day), + None, + "{year}-{month}-{day}" + ); + } + } + + #[test] + fn counts_back_before_year_zero() { + assert_eq!(days_from_civil(1970, 1, 1), 0); + assert_eq!(days_from_civil(0, 3, 1), -719_468); + // January of year 0 is counted as part of year -1. + assert_eq!(days_from_civil(0, 1, 1), -719_528); + } +} diff --git a/crates/bot-core/src/charge_history.rs b/crates/bot-core/src/charge_history.rs index 873d5c94..1d7c14f3 100644 --- a/crates/bot-core/src/charge_history.rs +++ b/crates/bot-core/src/charge_history.rs @@ -5,6 +5,7 @@ use std::collections::BTreeMap; use num_bigint::BigInt; use serde_json::{Map, Value}; +use crate::calendar::{civil_from_days, days_from_civil}; use crate::command_parsing::parse_command; use crate::credit_units::{CreditUnits, display_credit_units}; use crate::locale::Locale; @@ -386,15 +387,13 @@ fn raw_components(metadata: &Map, locale: Locale) -> Vec<(String, ); } } - if web_micros > 0 { - let component_label = if web_count > 1 { - format!("{} ({web_count}x)", label(locale, "web")) - } else { - label(locale, "web").to_owned() - }; - add(component_label, web_micros); - } - totals.retain(|(_, amount)| *amount > 0); + let web_label = if web_count > 1 { + format!("{} ({web_count}x)", label(locale, "web")) + } else { + label(locale, "web").to_owned() + }; + add(web_label, web_micros); + // `allocate_components` drops the parts that cost nothing. totals } @@ -556,30 +555,6 @@ fn payer_suffix(entries: &[ChargeHistoryEntry], locale: Locale) -> String { } } -fn days_from_civil(year: i64, month: i64, day: i64) -> i64 { - let year = year - i64::from(month <= 2); - let era = year.div_euclid(400); - let year_of_era = year - era * 400; - let adjusted_month = month + if month > 2 { -3 } else { 9 }; - let day_of_year = (153 * adjusted_month + 2) / 5 + day - 1; - let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; - era * 146_097 + day_of_era - 719_468 -} - -fn civil_from_days(days: i64) -> (i64, i64, i64) { - let days = days + 719_468; - let era = days.div_euclid(146_097); - let day_of_era = days - era * 146_097; - let year_of_era = - (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; - let year = year_of_era + era * 400; - let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); - let month_prime = (5 * day_of_year + 2) / 153; - let day = day_of_year - (153 * month_prime + 2) / 5 + 1; - let month = month_prime + if month_prime < 10 { 3 } else { -9 }; - (year + i64::from(month <= 2), month, day) -} - fn parse_number(raw: &str, start: usize, end: usize) -> Option { raw.get(start..end)?.parse().ok() } @@ -762,6 +737,27 @@ pub fn render_charge_history_page( mod tests { use serde_json::json; + #[test] + fn credits_go_only_to_parts_that_cost_something() { + let parts = |raw: &[(&str, i64)]| { + raw.iter() + .map(|(name, amount)| ((*name).to_owned(), *amount)) + .collect::>() + }; + assert_eq!( + super::allocate_components(5, parts(&[("free", 0), ("paid", 3)])), + parts(&[("paid", 5)]) + ); + assert_eq!( + super::allocate_components(0, parts(&[("paid", 3)])), + Vec::new() + ); + assert_eq!( + super::allocate_components(5, parts(&[("free", 0)])), + Vec::new() + ); + } + use super::{ ChargeHistoryCallbackPlan, ChargeHistoryDirection, ChargeHistoryEntry, ChargeHistoryGroup, ChargeHistoryPage, ChargesCommandContext, ChargesCommandPlan, charge_callback_answer, diff --git a/crates/bot-core/src/chat_members.rs b/crates/bot-core/src/chat_members.rs index 56aaf5de..d28255cb 100644 --- a/crates/bot-core/src/chat_members.rs +++ b/crates/bot-core/src/chat_members.rs @@ -135,6 +135,22 @@ mod tests { ); } + #[test] + fn a_minute_and_an_hour_start_a_new_band() { + let member = |age: i64| KnownChatMember { + user_id: "1".to_owned(), + first_name: "A".to_owned(), + username: String::new(), + last_seen: 10_000 - age, + is_bot: false, + }; + let seen = |age| render_chat_members(&[member(age)], 10_000, Locale::En); + assert!(seen(59).contains("a few seconds ago"), "{}", seen(59)); + assert!(seen(60).contains("1 min ago"), "{}", seen(60)); + assert!(seen(3_599).contains("59 min ago"), "{}", seen(3_599)); + assert!(!seen(3_600).contains("min ago"), "{}", seen(3_600)); + } + #[test] fn renders_all_relative_time_bands_and_empty_state() { let members = [ diff --git a/crates/bot-core/src/command_normalization.rs b/crates/bot-core/src/command_normalization.rs index d5536f63..f4974252 100644 --- a/crates/bot-core/src/command_normalization.rs +++ b/crates/bot-core/src/command_normalization.rs @@ -106,7 +106,9 @@ fn transliterate_remaining_scripts(input: &str) -> String { .to_string() .nfd() .any(|part| part.is_ascii_alphanumeric()); - if character.is_ascii() || matches!(character, 'ñ' | 'Ñ') || latin_with_diacritic { + // ASCII stays as it is: deunicode drops control characters such as a new line. A Latin + // letter or digit keeps its accents (ñ is n plus a tilde). deunicode transliterates the rest. + if character.is_ascii() || latin_with_diacritic { result.push(character); } else if let Some(transliterated) = deunicode::deunicode_char(character) { result.push_str(transliterated); @@ -372,6 +374,8 @@ mod tests { assert_eq!(super::replace_enye("Ñ_"), "NI_"); assert_eq!(super::replace_enye("Ñ"), "ENIE"); assert_eq!(super::transliterate_remaining_scripts("a\u{E000}b"), "ab"); + let ascii = (0..=127_u8).map(char::from).collect::(); + assert_eq!(super::transliterate_remaining_scripts(&ascii), ascii); assert!(!super::is_word_character('-')); } } diff --git a/crates/bot-core/src/compaction_policy.rs b/crates/bot-core/src/compaction_policy.rs index 1a62dfb1..00a612d8 100644 --- a/crates/bot-core/src/compaction_policy.rs +++ b/crates/bot-core/src/compaction_policy.rs @@ -82,6 +82,34 @@ mod tests { CompactionDisposition, MAX_ATTEMPTS, evaluate_compaction, is_due, retry_after_failure, }; + #[test] + fn a_recovered_result_needs_both_the_summary_and_the_marker() { + // Only the summary matches the result. + assert_eq!( + evaluate_compaction( + Some("new"), + Some("m1"), + Some("new"), + Some("m1"), + Some("new"), + "m2" + ), + CompactionDisposition::SaveAndSettle + ); + // Only the marker matches the target. + assert_eq!( + evaluate_compaction( + Some("old"), + Some("m2"), + Some("old"), + Some("m2"), + Some("new"), + "m2" + ), + CompactionDisposition::SaveAndSettle + ); + } + #[test] fn evaluates_recovery_obsolescence_generation_and_save_paths() { assert_eq!( diff --git a/crates/bot-core/src/config_callbacks.rs b/crates/bot-core/src/config_callbacks.rs index a2ba4a12..15a8c7b2 100644 --- a/crates/bot-core/src/config_callbacks.rs +++ b/crates/bot-core/src/config_callbacks.rs @@ -71,7 +71,8 @@ fn evaluate_creditless(input: &ConfigCallbackInput) -> ConfigCallbackEvaluation let current = input.current_creditless_limit; let limit = match input.value.as_str() { "none" => Some(0), - "decrease" => current.map(|value| if value < 0 { value } else { (value - 1).max(0) }), + // A negative limit means unlimited and stays as it is; 0 cannot go lower. + "decrease" => current.map(|value| if value > 0 { value - 1 } else { value }), "increase" => current.map(|value| { if value < 0 { value @@ -537,6 +538,13 @@ mod tests { ..current.clone() }, ), + ( + "cfg:creditless:increase", + ChatConfig { + creditless_user_hourly_limit: current.creditless_user_hourly_limit + 1, + ..current.clone() + }, + ), ( "cfg:creditless:unlimited", ChatConfig { @@ -623,6 +631,27 @@ mod tests { )); } + #[test] + fn a_creditless_limit_of_zero_increases_to_1_and_does_not_go_below_0() { + for (value, expected) in [("increase", 1), ("decrease", 0)] { + let mut zero = input("creditless", value); + zero.current_creditless_limit = Some(0); + assert_eq!( + evaluate_config_callback(&zero), + ConfigCallbackEvaluation::SetCreditlessLimit(expected), + "{value}" + ); + } + for number in [0, -1] { + let mut explicit = input("creditless", "n"); + explicit.numeric_value = Some(number); + assert_eq!( + evaluate_config_callback(&explicit), + ConfigCallbackEvaluation::SetCreditlessLimit(number) + ); + } + } + #[test] fn decreasing_an_unlimited_creditless_limit_keeps_it_unlimited() { let mut unlimited = input("creditless", "decrease"); diff --git a/crates/bot-core/src/config_command.rs b/crates/bot-core/src/config_command.rs index dd4047bd..cd455e0f 100644 --- a/crates/bot-core/src/config_command.rs +++ b/crates/bot-core/src/config_command.rs @@ -414,6 +414,48 @@ mod tests { } } + #[test] + fn link_modes_and_a_zero_creditless_limit_have_their_own_texts() { + let texts = |markup: &InlineKeyboardMarkup| { + markup + .inline_keyboard + .iter() + .flatten() + .map(|button| button.text.clone()) + .collect::>() + }; + for (mode, selected, summary) in [ + ("reply", "✓ Reply with link", "Reply with link"), + ("delete", "✓ Replace original", "Replace original"), + ("off", "✓ Off", "Off"), + ] { + let config = ChatConfig { + link_mode: mode.to_owned(), + creditless_user_hourly_limit: 0, + ..ChatConfig::default() + }; + let (_, page) = render_config_page(&config, Locale::En, true, "link"); + assert!( + texts(&page).iter().any(|text| text == selected), + "{mode}: {:?}", + texts(&page) + ); + let (_, home) = render_config(&config, Locale::En, true); + assert!( + home.inline_keyboard[1][0] + .text + .ends_with(&format!(": {summary}")), + "{}", + home.inline_keyboard[1][0].text + ); + assert!( + home.inline_keyboard[7][0].text.ends_with(": 0"), + "{}", + home.inline_keyboard[7][0].text + ); + } + } + #[test] fn details_preserve_selected_options_and_timezone_bounds() { let config = ChatConfig { diff --git a/crates/bot-core/src/dollar.rs b/crates/bot-core/src/dollar.rs index 047394ce..8e851aff 100644 --- a/crates/bot-core/src/dollar.rs +++ b/crates/bot-core/src/dollar.rs @@ -426,6 +426,26 @@ mod tests { } } + #[test] + fn english_names_the_wholesale_and_card_rates() { + let rates = [ + DollarRate { + name: "Mayorista", + price: 1000.0, + change: Some(1.0), + }, + DollarRate { + name: "Tarjeta", + price: 1500.0, + change: Some(2.0), + }, + ]; + assert_eq!( + render_dollar_rates(&rates, None, 6, Locale::En).as_deref(), + Some("Dollar in pesos, 6h change\n\nWholesale: 1,000 (+1%)\nCard: 1,500 (+2%)") + ); + } + #[test] fn short_timeframes_with_history_skip_the_missing_history_note() { let rates = [DollarRate { diff --git a/crates/bot-core/src/lib.rs b/crates/bot-core/src/lib.rs index 74353d4f..10f532b2 100644 --- a/crates/bot-core/src/lib.rs +++ b/crates/bot-core/src/lib.rs @@ -15,6 +15,7 @@ pub mod bcra; pub mod billing_commands; pub mod bitcoin_commands; pub mod cache_policy; +pub mod calendar; pub mod charge_history; pub mod chart_layout; pub mod chat_bans; diff --git a/crates/bot-core/src/links.rs b/crates/bot-core/src/links.rs index 5318a70c..ac299512 100644 --- a/crates/bot-core/src/links.rs +++ b/crates/bot-core/src/links.rs @@ -346,9 +346,7 @@ pub fn plan_link_actions( /// surrogate pairs in the same way as the legacy adapter's decoding policy. #[must_use] pub fn utf16_slice(text: &str, offset: i64, length: i64) -> String { - if text.is_empty() || length <= 0 { - return String::new(); - } + // Empty text or a length of 0 or less gives an empty range below. let units = text.encode_utf16().collect::>(); let start = usize::try_from(offset.max(0)) .unwrap_or(usize::MAX) @@ -436,6 +434,7 @@ mod tests { assert_eq!(utf16_slice(text, 1, 1), ""); assert_eq!(utf16_slice(text, -5, 1), "a"); assert_eq!(utf16_slice(text, 0, 0), ""); + assert_eq!(utf16_slice(text, 0, -1), ""); assert_eq!(utf16_slice("", 0, 2), ""); } diff --git a/crates/bot-core/src/market_prices.rs b/crates/bot-core/src/market_prices.rs index e855ea38..118b491a 100644 --- a/crates/bot-core/src/market_prices.rs +++ b/crates/bot-core/src/market_prices.rs @@ -4294,6 +4294,18 @@ mod tests { vec![unnamed("BTC", "btc"), unnamed("XYZ", "abc")], ); assert_eq!(rows.len(), 4); + // Without ids, the same symbol on another slug is another asset. + let mut rows = vec![unnamed("ABC", "abc")]; + merge_assets( + &mut rows, + vec![unnamed("ABC", "abc-two"), unnamed("ABC", "abc")], + ); + assert_eq!( + rows.iter() + .map(|asset| asset.slug.as_str()) + .collect::>(), + ["abc", "abc-two"] + ); } #[test] @@ -4326,6 +4338,80 @@ mod tests { ); } + #[test] + fn slug_requests_split_on_commas_and_spaces_and_skip_listed_symbols() { + let named = |symbol: &str, name: &str| { + let mut asset = coin(symbol, 1.0); + asset.name = name.to_owned(); + asset + }; + assert_eq!( + explicit_slug_requests( + "examplecoin, othercoin othercoin", + &[named("EXC", "Examplecoin"), named("OTC", "Othercoin")] + ), + vec!["EXAMPLECOIN".to_owned(), "OTHERCOIN".to_owned()] + ); + // A listed symbol is a symbol request, not a slug. + assert!(explicit_slug_requests("longcoin", &[named("LONGCOIN", "Longcoin")]).is_empty()); + } + + #[test] + fn a_request_with_a_usable_quote_is_not_missing() { + assert!( + missing_usable_tokens(&[coin("FOOCOIN", 1.0)], &["FOOCOIN".to_owned()], "USD") + .is_empty() + ); + } + + #[test] + fn merging_keeps_a_usable_price_and_other_ids_apart() { + let mut rows = vec![coin("BTC", 1.0)]; + merge_assets(&mut rows, vec![coin("BTC", 2.0), coin("ETH", 3.0)]); + assert_eq!( + rows.iter() + .map(|asset| (asset.symbol.as_str(), asset.quotes["USD"].price)) + .collect::>(), + vec![("BTC", 1.0), ("ETH", 3.0)] + ); + } + + #[test] + fn slug_quotes_keep_only_the_requested_slugs() { + let slugged = |slug: &str| { + let mut asset = coin("EXC", 1.0); + asset.slug = slug.to_owned(); + asset + }; + let mut rows = vec![slugged("examplecoin"), slugged("other")]; + retain_requested_slugs(&mut rows, &["EXAMPLECOIN".to_owned()]); + assert_eq!( + rows.iter() + .map(|asset| asset.slug.as_str()) + .collect::>(), + vec!["examplecoin"] + ); + } + + #[test] + fn a_query_of_several_unknown_words_goes_to_stocks_as_typed() { + let nothing = Selection { + rows: Vec::new(), + count: 0, + requested: Vec::new(), + explicit_requested: Vec::new(), + }; + let words = ["APPLE".to_owned(), "INC".to_owned()]; + assert_eq!( + stock_fallback_query("apple inc", ¬hing, &words), + "apple inc" + ); + assert_eq!( + stock_fallback_query("apple inc", ¬hing, &words[..1]), + "APPLE" + ); + } + #[test] fn top_list_counts_include_unrequested_coins_within_the_count() { assert_eq!(select_assets("foo,5", &[coin("BTC", 1.0)]).rows.len(), 1); diff --git a/crates/bot-core/src/output_format.rs b/crates/bot-core/src/output_format.rs index 2c1e18ae..373f4703 100644 --- a/crates/bot-core/src/output_format.rs +++ b/crates/bot-core/src/output_format.rs @@ -98,7 +98,9 @@ mod tests { assert_eq!(readable_number("-1234567"), "-1,234,567"); assert_eq!(readable_number("+62.68"), "+62.68"); assert_eq!(readable_number("150"), "150"); - for raw in ["N/A", "nan", "", "1.", ".5", "1e-20", "+"] { + for raw in [ + "N/A", "nan", "", "1.", "1234.", "1234.5a", ".5", "1e-20", "+", + ] { assert_eq!(readable_number(raw), raw); } } diff --git a/crates/bot-core/src/polymarket.rs b/crates/bot-core/src/polymarket.rs index ff5c83a7..b20b25a8 100644 --- a/crates/bot-core/src/polymarket.rs +++ b/crates/bot-core/src/polymarket.rs @@ -875,6 +875,21 @@ mod tests { assert_eq!(country_flag_from_name("atlantis"), ""); } + #[test] + fn outcomes_under_ten_percent_get_two_decimals() { + let events = parse_election_events(&json!([ + {"title": "Vote", "slug": "vote", "liquidity": 500, "markets": [ + {"groupItemTitle": "Favorite", "outcomes": ["Yes"], "outcomePrices": [0.1234]}, + {"groupItemTitle": "Long shot", "outcomes": ["Yes"], "outcomePrices": [0.05123]} + ]} + ])); + let text = render_elections(&events, &HashMap::new(), Locale::En); + assert!( + text.contains("\nFavorite 12.3% | Long shot 5.12%\n"), + "{text}" + ); + } + #[test] fn events_without_a_slug_are_skipped() { let events = parse_election_events(&json!([ diff --git a/crates/bot-core/src/price_queries.rs b/crates/bot-core/src/price_queries.rs index 8b1bc336..6ff90180 100644 --- a/crates/bot-core/src/price_queries.rs +++ b/crates/bot-core/src/price_queries.rs @@ -462,6 +462,8 @@ mod tests { ("1.", None), ("a.5", None), ("1,a", None), + ("1,5e3", None), + ("+1,5", None), ] { assert_eq!(super::parse_conversion_amount(raw), expected); } diff --git a/crates/bot-core/src/provider_runtime_policy.rs b/crates/bot-core/src/provider_runtime_policy.rs index 540bde52..f17ed2c5 100644 --- a/crates/bot-core/src/provider_runtime_policy.rs +++ b/crates/bot-core/src/provider_runtime_policy.rs @@ -296,5 +296,8 @@ mod tests { assert!(!super::positive_float(Some(&json!("inf")))); assert!(!super::positive_float(Some(&json!("NaN")))); assert!(super::positive_integer(&json!(u64::MAX))); + assert!(!super::positive_float(Some(&json!(0.0)))); + assert!(!super::positive_integer(&json!(0.5))); + assert!(!super::positive_integer(&json!("0"))); } } diff --git a/crates/bot-core/src/rulo.rs b/crates/bot-core/src/rulo.rs index 5e463063..a3bfd4ef 100644 --- a/crates/bot-core/src/rulo.rs +++ b/crates/bot-core/src/rulo.rs @@ -385,6 +385,32 @@ mod tests { ); } + #[test] + fn usdt_route_keeps_the_first_of_equal_quotes_and_buys_with_the_ask() { + let quote = |exchange: &str, price| ExchangeQuote { + exchange: exchange.to_owned(), + price, + }; + let mut input = complete_input(); + input.mep = None; + input.blue = None; + input.usd_to_usdt = vec![quote("first", Some(1.25)), quote("second", Some(1.25))]; + input.usdt_to_ars = vec![quote("alpha", Some(1500.0)), quote("beta", Some(1500.0))]; + let text = render_rulo(&evaluate_rulo(&input), Locale::En); + assert!( + text.contains("Route: USD→USDT FIRST, USDT→ARS ALPHA"), + "{text}" + ); + assert!( + text.contains("1,000 USD → 800 USDT → 1,200,000 ARS"), + "{text}" + ); + + input.usdt_to_ars = vec![quote("free", Some(0.0))]; + let text = render_rulo(&evaluate_rulo(&input), Locale::En); + assert!(!text.contains("USDT"), "{text}"); + } + #[test] fn usdt_route_picks_the_cheapest_ask_and_the_best_bid() { let quote = |exchange: &str, price| ExchangeQuote { diff --git a/crates/bot-core/src/task_commands.rs b/crates/bot-core/src/task_commands.rs index 1fb18508..b66ea281 100644 --- a/crates/bot-core/src/task_commands.rs +++ b/crates/bot-core/src/task_commands.rs @@ -551,6 +551,22 @@ mod tests { Ok(()) } + #[test] + fn a_28_character_task_keeps_its_whole_text_on_one_page() -> Result<(), TaskStateError> { + let mut only = task("task0001", TaskSchedule::Once, NEXT)?; + only.text = "x".repeat(28); + let view = super::render_task_page(&[only], Locale::En, 0); + let rows = view.keyboard.map_or(Vec::new(), |k| k.inline_keyboard); + assert!( + rows[0][0].text.ends_with(&"x".repeat(28)), + "{}", + rows[0][0].text + ); + // One task row and the close row: no page buttons. + assert_eq!(rows.len(), 2); + Ok(()) + } + #[test] fn task_pages_keep_ids_in_callbacks_and_require_explicit_cancel() -> Result<(), TaskStateError> { diff --git a/crates/bot-core/src/telegram_actions.rs b/crates/bot-core/src/telegram_actions.rs index 4c6ab442..9994d0ab 100644 --- a/crates/bot-core/src/telegram_actions.rs +++ b/crates/bot-core/src/telegram_actions.rs @@ -233,6 +233,16 @@ mod tests { let text = format!("{prefix}\n{}", "b".repeat(1000)); assert_eq!(truncate_text(&text), format!("{prefix}...")); + let middle = format!( + "{}\n{}", + "a".repeat(100), + "b".repeat(MAX_TELEGRAM_TEXT_LENGTH) + ); + assert_eq!( + truncate_text(&middle).chars().count(), + MAX_TELEGRAM_TEXT_LENGTH + ); + let early = format!("line\n{}", "b".repeat(MAX_TELEGRAM_TEXT_LENGTH + 10)); assert_eq!( truncate_text(&early).chars().count(), diff --git a/crates/bot-core/src/telegram_payments.rs b/crates/bot-core/src/telegram_payments.rs index 758eaf7f..5d12ebdf 100644 --- a/crates/bot-core/src/telegram_payments.rs +++ b/crates/bot-core/src/telegram_payments.rs @@ -364,7 +364,8 @@ fn payer_order(config: &ChatConfig, locale: Locale) -> String { } .to_owned(); } - let cap = (limit > 0).then(|| match locale { + // `limit` is not 0 here, and a negative limit has no cap. + let cap = u64::try_from(limit).ok().map(|limit| match locale { Locale::Es if limit == 1 => ", hasta 1 mensaje por hora a cada uno".to_owned(), Locale::Es => format!(", hasta {limit} mensajes por hora a cada uno"), Locale::En if limit == 1 => ", up to 1 message per hour per person".to_owned(), @@ -761,12 +762,12 @@ pub fn evaluate_pre_checkout( }; let payload = string_or_empty(query.get("invoice_payload")); let (pack_id, payload_user_id) = parse_topup_payload(&payload); - let total_amount = strict_python_int(query.get("total_amount")).unwrap_or(-1); + let total_amount = strict_python_int(query.get("total_amount")); let currency = string_or_empty(query.get("currency")); let valid = expected_pack.is_some_and(|pack| { pack_id.as_deref() == Some(pack.id.as_str()) && currency == "XTR" - && total_amount == pack.xtr_amount + && total_amount == Some(pack.xtr_amount) && (payload_user_id == Some(user_id) || payload == format!("topup:{}", pack.id)) }); Ok(if valid { diff --git a/crates/bot-core/src/token_signals.rs b/crates/bot-core/src/token_signals.rs index cae02501..8e5fcf6c 100644 --- a/crates/bot-core/src/token_signals.rs +++ b/crates/bot-core/src/token_signals.rs @@ -521,8 +521,8 @@ fn candle_change_for_span(candles: &[Vec], seconds: i64) -> Option<(f64, i6 } let (oldest_timestamp, oldest_close) = closes.first().copied()?; let actual = latest_timestamp.saturating_sub(oldest_timestamp); - (actual > 0 && oldest_close > 0.0) - .then_some(((latest_close / oldest_close - 1.0) * 100.0, actual)) + // Every kept close is positive. + (actual > 0).then_some(((latest_close / oldest_close - 1.0) * 100.0, actual)) } fn format_available_period(seconds: i64) -> Option { @@ -1091,7 +1091,8 @@ pub fn format_signal_caption_for_period_with_candles( .filter(|timestamp| *timestamp > 0); (pump_ath, timestamp) } else if let Some((ath_price, timestamp)) = - ath(&signal.candles, (price > 0.0).then_some(price)) + // `is_usable_chart_candle` ignores a reference price that is not positive. + ath(&signal.candles, Some(price)) { let value = if price > 0.0 && market_cap > 0.0 { market_cap * ath_price / price @@ -1102,7 +1103,7 @@ pub fn format_signal_caption_for_period_with_candles( } else { (0.0, None) }; - let ath_line = if ath_value > 0.0 { + let ath_line = (ath_value > 0.0).then(|| { let drawdown_base = if market_cap > 0.0 { market_cap } else { price }; let drawdown = if drawdown_base == 0.0 { 0.0 @@ -1120,9 +1121,7 @@ pub fn format_signal_caption_for_period_with_candles( format_money(ath_value, false), format_percentage(drawdown) ) - } else { - "?".to_owned() - }; + }); let age = age_from_milliseconds(&pair.pair_created_at, now_unix) .or_else(|| { signal @@ -1163,7 +1162,7 @@ pub fn format_signal_caption_for_period_with_candles( if period == "1h" && (!pair.txns.h1.buys.is_null() || !pair.txns.h1.sells.is_null()) { stats.push(format!("1h: 🟩 {buys} 🟥 {sells}")); } - if ath_value > 0.0 { + if let Some(ath_line) = ath_line { stats.push(format!("ATH {ath_line}")); } let mut rows = vec![ @@ -1263,7 +1262,6 @@ pub fn build_signal_keyboard_localized( pub fn callback_text(key: &str, locale: Locale) -> &'static str { match (key, locale) { ("expired", Locale::Es) => "Esta tarjeta ya venció", - ("expired", Locale::En) => "This card expired", ("owner_only", Locale::Es) => "Solo quien pidió la tarjeta o un admin puede hacer eso", ("owner_only", Locale::En) => "Only the requester or an admin can do that", ("deleted", Locale::Es) => "Tarjeta borrada", @@ -1717,6 +1715,59 @@ mod tests { assert!(caption.contains("ATH $51.6K")); } + #[test] + fn published_ath_age_counts_days_from_its_millisecond_timestamp() { + let mut signal = signal(); + signal.pump = Some(PumpMetadata { + ath_market_cap: json!(51_600), + ath_market_cap_timestamp: json!(1_710_100_000_000_i64), + ..PumpMetadata::default() + }); + // 9,900,000 seconds after the ATH. + let caption = format_signal_caption(&signal, 1_720_000_000); + assert!(caption.contains(" / 114d)"), "{caption}"); + } + + #[test] + fn captions_ignore_history_far_from_the_live_price() { + let mut signal = signal(); + signal.pair.price_usd = json!(1.0); + signal.pair.market_cap = json!(1_000_000.0); + signal.candles = vec![ + vec![1.0, 0.9, 1.1, 0.8, 1.0], + // Consistent in itself, but 2.2 million times the live price. + vec![2.0, 2_000_000.0, 2_200_000.0, 2_000_000.0, 2_000_000.0], + ]; + let caption = format_signal_caption(&signal, 1_700_000_000); + assert!(caption.contains("ATH $1.10M"), "{caption}"); + } + + #[test] + fn a_zero_supply_is_not_shown() { + let mut signal = signal(); + signal.supply = Some(0.0); + let caption = format_signal_caption(&signal, 1_720_000_000); + assert!(!caption.contains("Supply"), "{caption}"); + } + + #[test] + fn a_zero_close_is_not_a_price() { + let candles = [ + vec![0.0, 1.0, 1.0, 1.0, 100.0], + vec![3_600.0, 1.0, 1.0, 1.0, 110.0], + vec![7_200.0, 1.0, 1.0, 1.0, 0.0], + ]; + let (change, span) = super::candle_change_for_span(&candles, 3_600).unwrap_or_default(); + assert!((change - 10.0).abs() < 1e-9, "{change}"); + assert_eq!(span, 3_600); + } + + #[test] + fn tiny_changes_read_as_zero_and_half_a_tenth_rounds_up() { + assert_eq!(super::format_percentage(-0.03), "+0%"); + assert_eq!(super::format_percentage(0.05), "+0.1%"); + } + #[test] fn usable_chart_requires_five_nonflat_candles() { let mut signal = signal(); @@ -1726,6 +1777,8 @@ mod tests { assert!(!has_usable_chart(&signal)); signal.candles = [candles(), candles()].concat(); assert!(has_usable_chart(&signal)); + signal.candles.truncate(5); + assert!(has_usable_chart(&signal)); } #[test]