mirror of
https://github.com/TheFunny/TelegramTwitterMediaBot.git
synced 2026-09-23 23:32:05 +00:00
test: drop redundant tests, make the vacuous ones real
Audit of all 205 tests (five read-only passes plus a line-by-line
re-check). Ten test functions were removed or merged and eight
subsumed assertion blocks trimmed; the suite is down to 180 tests with
no loss of mutation coverage, and four tests that were passing for
nothing now fail when the code they name is broken.
Redundant (deleted or merged):
- twitter: `syndication_text_only_has_no_media` (re-asserts its own
empty fixture), `..._keeps_multibyte_text` (both transforms are
no-ops for that text), `..._strips_trailing_short_link_without_entities`
(same branch as `..._media_short_link`, which now also covers the
real multibyte tweet), `..._regardless_of_index_units` (its
`display_text_range` rationale outlived the function it described).
- pixiv: `test_fetch` (a bare `is_ok()` on the illustration
`download_media_pixiv_original_with_referer` already asserts and
downloads, and the only network touch in a plain `cargo test`),
`startup_validation_only_disables_on_a_definitive_failure` (four rows
that are a subset of the retry-policy table; the `validate()` branch
it was named for is not asserted at all).
- bilibili: `from_item_legacy_draw_shape_still_parses` (its fixture is
the same legacy `draw` shape `from_item_maps_draw_images_and_topic`
builds, with a subset of its assertions).
- site/mod.rs: two `Ok(None)` cases merged into one test.
- urls.rs: `cache_hit_success_keeps_the_cache_entry` (the `/test` test
asserts the same two things under stricter settings), plus a
`assert_ne!` loop that re-states the mapping assertions above it.
- send/mod.rs: `media_group_success_and_forward_ok` (the forward half is
covered by `post_send_forwards_immediately_when_configured`; the
`is_ok()` half cannot see the returned file ids), and two boundary
rows implied by the constant they sit next to.
- commands.rs: the parse tail that `every_documented_invocation_parses`
already covers per README form, and three `debug_report` rows the
escaping test pins with stronger input.
Passing for nothing (now real):
- `truncate_caption_does_not_split_an_html_entity` — the cut lands
inside the entity, so `!contains("&")` never fired; it now asserts
the exact output in both directions and fails when the guard in
`truncate_caption` is deleted (verified).
- `pipeline_resizes_oversized_jpeg` — magic bytes and a non-empty buffer
pass for a copy-through; it now decodes the output's headers and
fails when the JPEG branch skips the resize (verified).
- `live_validate_with_bogus_token_fails` — expected `PixivError::Api`,
which the status check before the body read made unreachable; a bogus
token is a 4xx. Confirmed against the live endpoint: the old
assertion fails with `got Err(Status(400))`, the new one passes.
- bsky `live_fetch_with_photos` — its URL is a text-only post and it had
a byte-identical twin, so no live test pinned media; it now points at a
labelled post with photos and asserts media + the label (live-verified).
Also fixed, found by turning the runtime-sweep test into a real one:
the 30 s lease-expiry sweep recovered crashed rows but never woke a
worker, so a recovered task waited for the next unrelated enqueue (every
worker is parked on `notify` when no row is pending). `recover_update`
now reports its count, `recover_expired` wakes a worker when it changed
something, and `runtime_sweep_recovers_expired_lease` drives the spawned
loop with a paused clock instead of calling the recovery by hand — it
fails on both the missing wake-up and a sweep that recovers nothing.
Verified: `cargo fmt --check`, `cargo clippy --workspace --all-targets
--locked -- -D warnings`, `cargo test --workspace --locked` (180 passed,
14 ignored) and `cargo test -p x-media -- --ignored live` (13 passed).
This commit is contained in:
@@ -563,7 +563,8 @@ mod tests {
|
||||
/// bot keeps ignoring them instead of answering with a failure.
|
||||
#[test]
|
||||
fn pattern_ignores_short_links() {
|
||||
assert!(!PATTERN.is_match("https://b23.tv/abc123"));
|
||||
// Short links usually point at videos, so they stay unmatched: no cache
|
||||
// key, and the fetch dispatcher answers `Ok(None)` (silence).
|
||||
assert_eq!(cache_key("https://b23.tv/abc123"), None);
|
||||
}
|
||||
|
||||
@@ -583,6 +584,8 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The legacy `major.draw` shape stays supported alongside the
|
||||
/// `itemOpusStyle` serialization that moves pictures to `major.opus.pics`.
|
||||
#[test]
|
||||
fn from_item_maps_draw_images_and_topic() {
|
||||
let fetched = parse(item_json(
|
||||
@@ -746,24 +749,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The legacy shape stays supported: bilibili's `itemOpusStyle` flag is
|
||||
/// what moves the pictures to `major.opus.pics`, but `major.draw` items
|
||||
/// and a text-only `desc` must keep working if it is retired.
|
||||
#[test]
|
||||
fn from_item_legacy_draw_shape_still_parses() {
|
||||
let fetched = parse(item_json(
|
||||
draw_item("http://i0.hdslb.com/bfs/new_dyn/l.jpg"),
|
||||
"legacy 正文",
|
||||
));
|
||||
assert_eq!(fetched.title, "");
|
||||
assert_eq!(fetched.content, "legacy 正文");
|
||||
assert_eq!(fetched.media.len(), 1);
|
||||
assert_eq!(
|
||||
fetched.media[0].url(),
|
||||
"https://i0.hdslb.com/bfs/new_dyn/l.jpg"
|
||||
);
|
||||
}
|
||||
|
||||
/// The video stream is out of scope; an AV dynamic still yields its cover.
|
||||
#[test]
|
||||
fn from_item_maps_archive_cover() {
|
||||
|
||||
@@ -490,31 +490,18 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
/// The one live bsky check: a labelled post with photos — source URL,
|
||||
/// caption, media and the sensitive label all survive the parse. This
|
||||
/// replaced a second byte-identical live test whose URL is a *text-only*
|
||||
/// post, so neither copy pinned any media.
|
||||
#[tokio::test]
|
||||
#[ignore = "live network: requires outbound HTTPS to public.api.bsky.app"]
|
||||
async fn live_fetch_with_photos() {
|
||||
let fetched =
|
||||
fetch_from_url("https://bsky.app/profile/asagi0398.bsky.social/post/3mqkhrq5w6k2m")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fetched.source_url,
|
||||
"https://bsky.app/profile/asagi0398.bsky.social/post/3mqkhrq5w6k2m"
|
||||
);
|
||||
assert!(!fetched.caption.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "live network: requires outbound HTTPS to public.api.bsky.app"]
|
||||
async fn live_fetch_smoke() {
|
||||
let fetched =
|
||||
fetch_from_url("https://bsky.app/profile/fu-futa.bsky.social/post/3laoveufjv224")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fetched.source_url,
|
||||
"https://bsky.app/profile/fu-futa.bsky.social/post/3laoveufjv224"
|
||||
);
|
||||
let url = "https://bsky.app/profile/fu-futa.bsky.social/post/3laoveufjv224";
|
||||
let fetched = fetch_from_url(url).await.unwrap();
|
||||
assert_eq!(fetched.source_url, url);
|
||||
assert!(!fetched.caption.is_empty());
|
||||
assert!(!fetched.media.is_empty(), "expected photos in {url}");
|
||||
assert!(fetched.sensitive, "expected a label on {url}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -778,13 +778,25 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn truncate_caption_does_not_split_an_html_entity() {
|
||||
// An entity crossing the cut must not be left half-open (& without ;).
|
||||
let mut long = "a".repeat(MAX_CAPTION_CHARS - 4);
|
||||
long.push_str("&bbbb");
|
||||
let out = truncate_caption(&long);
|
||||
assert!(out.chars().count() <= MAX_CAPTION_CHARS);
|
||||
assert!(!out.contains("&"), "half entity left: {out:?}");
|
||||
assert!(!out.ends_with('&'));
|
||||
// The exact output is what pins the guard: a cut that keeps `&am` (no
|
||||
// `;`) leaves a half-open entity that `!contains("&")` cannot see,
|
||||
// so the old assertions stayed green with the guard deleted. Both
|
||||
// directions matter — an entity the cut falls inside is dropped whole,
|
||||
// one the cut falls after is kept whole.
|
||||
for (long, expected) in [
|
||||
(
|
||||
"a".repeat(MAX_CAPTION_CHARS - 4) + "&bbbb",
|
||||
"a".repeat(MAX_CAPTION_CHARS - 4) + "…",
|
||||
),
|
||||
(
|
||||
"a".repeat(MAX_CAPTION_CHARS - 6) + "&bbbb",
|
||||
"a".repeat(MAX_CAPTION_CHARS - 6) + "&…",
|
||||
),
|
||||
] {
|
||||
let out = truncate_caption(&long);
|
||||
assert_eq!(out, expected);
|
||||
assert!(out.chars().count() <= MAX_CAPTION_CHARS, "{out:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -796,15 +808,15 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unsupported_url_returns_none() {
|
||||
let result = fetch("https://example.com/some/article").await;
|
||||
assert!(matches!(result, Ok(None)), "got {result:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unknown_scheme_returns_none() {
|
||||
let result = fetch("not a url at all").await;
|
||||
assert!(matches!(result, Ok(None)), "got {result:?}");
|
||||
async fn unsupported_urls_return_none() {
|
||||
// Neither a URL no site pattern matches nor a string that is no URL at
|
||||
// all is an error: both answer `Ok(None)`, which is what keeps the bot
|
||||
// silent on links it cannot handle (only a registered-but-disabled site
|
||||
// gets a reply).
|
||||
for url in ["https://example.com/some/article", "not a url at all"] {
|
||||
let result = fetch(url).await;
|
||||
assert!(matches!(result, Ok(None)), "{url}: got {result:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -398,35 +398,20 @@ mod tests {
|
||||
use super::*;
|
||||
use dotenv::dotenv;
|
||||
|
||||
/// Skips when `PIXIV_REFRESH_TOKEN` is absent or empty (CI without the
|
||||
/// secret must stay green; GitHub Actions exposes an unset secret as an
|
||||
/// empty string, so `is_err()` alone is not enough).
|
||||
fn require_pixiv_token() -> bool {
|
||||
std::env::var("PIXIV_REFRESH_TOKEN")
|
||||
.ok()
|
||||
.filter(|s| !s.is_empty())
|
||||
.is_some()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_fetch() {
|
||||
dotenv().ok();
|
||||
if !require_pixiv_token() {
|
||||
eprintln!("skipping: no PIXIV_REFRESH_TOKEN");
|
||||
return;
|
||||
}
|
||||
let result = fetch(126839080).await;
|
||||
assert!(result.is_ok());
|
||||
println!("{:#?}", result);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "live network: requires outbound HTTPS to oauth.secure.pixiv.net"]
|
||||
async fn live_validate_with_bogus_token_fails() {
|
||||
dotenv().ok();
|
||||
// A bogus token must surface as Api error (invalid_grant), not panic.
|
||||
// A rejected credential must surface as a permanent status, not a panic
|
||||
// and not a retryable class: the exchange answers 4xx and the status is
|
||||
// checked before the body is read (api.rs, `get_access_token`). This
|
||||
// used to assert `Api`, which that check made unreachable — `Api` is
|
||||
// only reached from a 2xx body without an `access_token`.
|
||||
let client = PixivAPI::new("bogus_token_for_testing".to_string());
|
||||
let result = client.get_access_token().await;
|
||||
assert!(matches!(result, Err(PixivError::Api(_))), "got {result:?}");
|
||||
assert!(
|
||||
matches!(result, Err(PixivError::Status(code)) if (400..500).contains(&code)),
|
||||
"got {result:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -422,16 +422,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_validation_only_disables_on_a_definitive_failure() {
|
||||
// A bad moment: the site must stay enabled for later links.
|
||||
assert!(pixiv_error_is_retryable(&PixivError::Status(503)));
|
||||
assert!(pixiv_error_is_retryable(&PixivError::Status(429)));
|
||||
// A rejected credential is what `disable()` is for.
|
||||
assert!(!pixiv_error_is_retryable(&PixivError::Status(403)));
|
||||
assert!(!pixiv_error_is_retryable(&PixivError::NoAuth));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_retryable_classifies_transient_and_permanent() {
|
||||
// Transient: network errors, explicit transient, pixiv 429/5xx.
|
||||
|
||||
@@ -524,14 +524,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syndication_text_only_has_no_media() {
|
||||
let raw = fixture(serde_json::json!([]));
|
||||
let tweet = Tweet::from_syndication_json(&raw.to_string()).unwrap();
|
||||
let fetched: Fetched = tweet.into();
|
||||
assert!(fetched.media.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syndication_gif_maps_to_animated() {
|
||||
let raw = fixture(serde_json::json!([
|
||||
@@ -550,54 +542,30 @@ mod tests {
|
||||
#[test]
|
||||
fn syndication_text_strips_trailing_media_short_link() {
|
||||
// Real syndication shape: the appended media short link sits after the
|
||||
// visible text; the unmapped t.co link is stripped by content.
|
||||
let raw = serde_json::json!({
|
||||
"__typename": "Tweet",
|
||||
"id_str": "1",
|
||||
"text": "hello world https://t.co/abc123",
|
||||
"user": { "name": "N", "screen_name": "h" },
|
||||
"mediaDetails": []
|
||||
});
|
||||
let tweet = Tweet::from_syndication_json(&raw.to_string()).unwrap();
|
||||
assert_eq!(tweet.text, "hello world");
|
||||
assert!(!tweet.caption().contains("t.co"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syndication_text_strips_trailing_link_regardless_of_index_units() {
|
||||
// Real tweet 2084567054481571919: the visible text is 30 code points
|
||||
// but 41 UTF-16 units, and the two endpoints historically reported
|
||||
// display_text_range in different units (UTF-16 on syndication, code
|
||||
// points on GraphQL). The FxEmbed-style content-based strip ignores
|
||||
// the range entirely, so the appended media link is removed for any
|
||||
// response shape.
|
||||
let text = "妄想𝑨𝒅𝒅𝒊𝒄𝒕𝒊𝒐𝒏…🩷💚❤️\n#ゼンゼロ #zzzero https://t.co/XnIi83EkEB";
|
||||
let visible = "妄想𝑨𝒅𝒅𝒊𝒄𝒕𝒊𝒐𝒏…🩷💚❤️\n#ゼンゼロ #zzzero";
|
||||
let raw = serde_json::json!({
|
||||
"__typename": "Tweet",
|
||||
"id_str": "2084567054481571919",
|
||||
"text": text,
|
||||
"user": { "name": "N", "screen_name": "h" },
|
||||
"mediaDetails": []
|
||||
});
|
||||
let tweet = Tweet::from_syndication_json(&raw.to_string()).unwrap();
|
||||
assert_eq!(tweet.text, visible, "left a partial link");
|
||||
assert!(!tweet.caption().contains("t.co"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syndication_text_strips_trailing_short_link_without_entities() {
|
||||
// No URL entities at all: the leftover t.co link is stripped by the
|
||||
// content regex.
|
||||
let raw = serde_json::json!({
|
||||
"__typename": "Tweet",
|
||||
"id_str": "1",
|
||||
"text": "hello https://t.co/abc123",
|
||||
"user": { "name": "N", "screen_name": "h" },
|
||||
"mediaDetails": []
|
||||
});
|
||||
let tweet = Tweet::from_syndication_json(&raw.to_string()).unwrap();
|
||||
assert_eq!(tweet.text, "hello");
|
||||
// visible text and there are no URL entities, so the unmapped t.co link
|
||||
// is stripped by content alone. The second row is real tweet
|
||||
// 2084567054481571919 (30 code points but 41 UTF-16 units, and the two
|
||||
// endpoints historically reported `display_text_range` in different
|
||||
// units): a content-based strip cannot leave a partial link behind for
|
||||
// either unit system.
|
||||
for (text, visible) in [
|
||||
("hello world https://t.co/abc123", "hello world"),
|
||||
(
|
||||
"妄想𝑨𝒅𝒅𝒊𝒄𝒕𝒊𝒐𝒏…🩷💚❤️\n#ゼンゼロ #zzzero https://t.co/XnIi83EkEB",
|
||||
"妄想𝑨𝒅𝒅𝒊𝒄𝒕𝒊𝒐𝒏…🩷💚❤️\n#ゼンゼロ #zzzero",
|
||||
),
|
||||
] {
|
||||
let raw = serde_json::json!({
|
||||
"__typename": "Tweet",
|
||||
"id_str": "1",
|
||||
"text": text,
|
||||
"user": { "name": "N", "screen_name": "h" },
|
||||
"mediaDetails": []
|
||||
});
|
||||
let tweet = Tweet::from_syndication_json(&raw.to_string()).unwrap();
|
||||
assert_eq!(tweet.text, visible, "left a partial link in {text:?}");
|
||||
assert!(!tweet.caption().contains("t.co"), "{text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -666,23 +634,6 @@ mod tests {
|
||||
assert!(!tweet.caption().contains("t.co"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syndication_text_keeps_multibyte_text() {
|
||||
// Text-only tweet: no short links, the multibyte text is untouched.
|
||||
let text = "コミティア落ちたので、明日は行きません。🙏ごめんなさい";
|
||||
let units: Vec<u16> = text.encode_utf16().collect();
|
||||
assert_eq!(units.len(), 28);
|
||||
let raw = serde_json::json!({
|
||||
"__typename": "Tweet",
|
||||
"id_str": "1",
|
||||
"text": text,
|
||||
"user": { "name": "N", "screen_name": "h" },
|
||||
"mediaDetails": []
|
||||
});
|
||||
let tweet = Tweet::from_syndication_json(&raw.to_string()).unwrap();
|
||||
assert_eq!(tweet.text, text, "full text kept intact");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn original_twimg_url_rewrites_photo_urls() {
|
||||
assert_eq!(
|
||||
@@ -706,9 +657,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn syndication_token_matches_js_formula() {
|
||||
// JS: ((861627479294746624 / 1e15) * PI).toString(36) == "236.vrsocvda"
|
||||
let token = syndication_token(861627479294746624);
|
||||
assert!(token.starts_with("236.v"), "got {token}");
|
||||
// JS: ((861627479294746624 / 1e15) * PI).toString(36) == "236.vrsocvda".
|
||||
// This loop truncates ten base-36 fraction digits instead of rendering
|
||||
// the shortest round-tripping one, so it agrees with JS on the stem and
|
||||
// diverges in the tail (`…d9ui` vs `…da`). Pinned exactly, because the
|
||||
// token is a fixed function of the id: a stub or a wrong constant must
|
||||
// not pass. The endpoint currently serves public tweets regardless of
|
||||
// the token, which is why the tail is left as is.
|
||||
assert_eq!(syndication_token(861627479294746624), "236.vrsocvd9ui");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user