aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSoispha Peetz <soispha@b-peetz.de>2026-11-28 21:23:44 +0100
committerSoispha Peetz <soispha@b-peetz.de>2026-11-28 21:23:44 +0100
commite63610720eccea66cc70359d88ee4c8f48993163 (patch)
tree8acb50f09e4c43504da546f409a86e4e15b37396
parenttest(crates/termsize): Comment out doctest (diff)
downloadyt-e63610720eccea66cc70359d88ee4c8f48993163.zip
test(crates/yt/storage/db/video/comments): Replace macro by function
Parsing the comment tests in an actual rust function makes it soo much easier to write, improves the compile times *and* was the reason I was able to update the tests to the new comment format.
Diffstat (limited to '')
-rw-r--r--crates/yt/src/storage/db/video/comments/display.rs6
-rw-r--r--crates/yt/src/storage/db/video/comments/mod.rs13
-rw-r--r--crates/yt/src/storage/db/video/comments/tests.rs486
3 files changed, 284 insertions, 221 deletions
diff --git a/crates/yt/src/storage/db/video/comments/display.rs b/crates/yt/src/storage/db/video/comments/display.rs
index ccf9991..78b00af 100644
--- a/crates/yt/src/storage/db/video/comments/display.rs
+++ b/crates/yt/src/storage/db/video/comments/display.rs
@@ -80,7 +80,7 @@ impl Comments {
write!(
f,
" [{}]",
- comment.raw.like_count.bold().red().render(color)
+ comment.raw.like_count.bold().red().render(color),
)?;
f.write_str(":\n")?;
@@ -103,7 +103,7 @@ impl Comments {
f.write_str("\n")?;
} else {
let mut children = comment.replies.clone();
- children.sort_by(|a, b| a.raw.timestamp.cmp(&b.raw.timestamp));
+ children.sort_by_key(|a| a.raw.timestamp);
for child in children {
format(&child, f, ident_count + 4, color)?;
@@ -117,7 +117,7 @@ impl Comments {
if !&self.inner.is_empty() {
let mut children = self.inner.clone();
- children.sort_by(|a, b| b.raw.like_count.cmp(&a.raw.like_count));
+ children.sort_by_key(|a| std::cmp::Reverse(a.raw.like_count));
for child in children {
format(&child, &mut f, 0, use_color)?;
diff --git a/crates/yt/src/storage/db/video/comments/mod.rs b/crates/yt/src/storage/db/video/comments/mod.rs
index aa46a5e..039580a 100644
--- a/crates/yt/src/storage/db/video/comments/mod.rs
+++ b/crates/yt/src/storage/db/video/comments/mod.rs
@@ -94,7 +94,11 @@ impl Comments {
&text[..end]
}
- debug!("**Searching for parent id: `{}`", ids.join("-"));
+ debug!(
+ "** Trying to inserting comment: `{}`",
+ first_line(&raw_comment.text)
+ );
+ debug!("** Searching for parent id: `{}`", ids.join("."));
let first = ids
.first()
@@ -103,13 +107,18 @@ impl Comments {
debug!(" -> {}: `{}`", first, first_line(&reply.raw.text));
for id in &ids[1..] {
- debug!(" **Searching for id: `{id}`");
+ debug!(" ** Searching for id: `{id}`");
reply = reply.get_id(id);
debug!(" -> {}: `{}`", id, first_line(&reply.raw.text));
}
+ debug!(
+ "** Inserting as reply to: `{}`",
+ first_line(&reply.raw.text)
+ );
+
raw_comment.text = raw_comment
.text
.trim()
diff --git a/crates/yt/src/storage/db/video/comments/tests.rs b/crates/yt/src/storage/db/video/comments/tests.rs
index a622761..9fb22d4 100644
--- a/crates/yt/src/storage/db/video/comments/tests.rs
+++ b/crates/yt/src/storage/db/video/comments/tests.rs
@@ -9,263 +9,317 @@
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.
-use pretty_assertions::assert_eq;
-use url::Url;
-
-use crate::storage::db::video::comments::{
- Comment, Comments, RawComment,
- raw::{Id, Parent},
+use std::{
+ iter::Peekable,
+ str::Chars,
+ string::ToString,
+ sync::atomic::{AtomicUsize, Ordering},
};
-/// Generate both an [`expected`] and an [`input`] value from an expected comment expression.
-macro_rules! mk_comments {
- () => {{
- let input: Vec<RawComment> = vec![];
- let expected: Comments = Comments {
- inner: vec![],
- };
+use pretty_assertions::assert_eq;
+use url::Url;
- (input, expected)
- }};
+use crate::storage::db::video::comments::{Comment, Comments, RawComment, raw};
+macro_rules! create_test {
(
+ # $name:ident;
$(
- parent: $parent:expr, $actual_parent:ident,
- (
- @ $name:ident : $comment:literal
- $(
- $reply_chain:tt
- )*
- )
- )+
- ) => {{
- use std::sync::atomic::{AtomicUsize, Ordering};
+ $block:tt
+ )*
+ ) => {
+ #[test]
+ fn $name() {
+ // stderrlog::new()
+ // .module("yt")
+ // .modules(&["yt_dlp".to_owned(), "libmpv2".to_owned()])
+ // .show_module_names(true)
+ // .color(stderrlog::ColorChoice::Auto)
+ // .verbosity(10)
+ // .timestamp(stderrlog::Timestamp::Off)
+ // .init()
+ // .expect("Let's just hope that this does not panic");
- static INDEX_INPUT: AtomicUsize = AtomicUsize::new(0);
- static INDEX_EXPECTED: AtomicUsize = AtomicUsize::new(0);
+ let (raw, expected) = mk_input_expected(stringify!($($block)*));
- let (nested_input, _) = mk_comments!(
- $(
- $(
- parent: $parent, $name,
- $reply_chain
- )*
- )+
- );
+ for raw in &raw {
+ eprintln!(
+ "{}{}: \"{}..\" [parent: {}; id: {}]",
+ match &raw.parent {
+ raw::Parent::Root => String::new(),
+ raw::Parent::Id(id) => " ".repeat(id.split('.').count())
+ },
+ raw.author,
+ raw.text.chars().take(35).collect::<String>(),
+ match &raw.parent {
+ raw::Parent::Root => "Root",
+ raw::Parent::Id(id) => id,
+ },
+ raw.id.id,
+ );
+ }
- let mut input: Vec<RawComment> = vec![
- $(
- mk_comments!(@to_raw input $name INDEX_INPUT.fetch_add(1, Ordering::Relaxed), $comment $parent, $actual_parent)
- ),+
- ];
- input.extend(nested_input);
+ assert_eq!(
+ Comments::from_raw(raw).render(true),
+ expected.render(true),
+ "Parsed vs. Expected"
+ );
+ }
+ };
+}
+
+#[derive(Debug)]
+struct Ast {
+ roots: Vec<AstValue>,
+}
+
+#[derive(Debug)]
+struct AstValue {
+ id: AstId,
+ name: String,
+ content: String,
- let expected: Comments = Comments {
- inner: vec![
- $(
- Comment {
- raw: mk_comments!(@to_raw expected $name INDEX_EXPECTED.fetch_add(1, Ordering::Relaxed), $comment $parent, $actual_parent),
- replies: {
- let (_, nested_expected) = mk_comments!(
- $(
- parent: $parent, $name,
- $reply_chain
- )*
- );
+ children: Vec<AstValue>,
+}
- nested_expected.inner
- },
- }
- ),+
- ]
+#[derive(Debug)]
+struct AstId(Vec<usize>);
+impl AstId {
+ fn new(parent: Option<&AstId>, id_gen: &AtomicUsize) -> Self {
+ let base = id_gen.fetch_add(1, Ordering::Relaxed);
+ let new = if let Some(parent) = parent {
+ let mut new = parent.0.clone();
+ new.push(base);
+ new
+ } else {
+ vec![base]
};
- (input, expected)
- }};
- (
- $(
- (
- @ $name:ident : $comment:literal
- $(
- $reply_chain:tt
- )*
- )
- )+
- ) => {{
- use std::sync::atomic::{AtomicUsize, Ordering};
+ Self(new)
+ }
- static INDEX_INPUT: AtomicUsize = AtomicUsize::new(0);
- static INDEX_EXPECTED: AtomicUsize = AtomicUsize::new(0);
+ fn to_id(&self) -> raw::Id {
+ raw::Id {
+ id: self
+ .0
+ .iter()
+ .map(ToString::to_string)
+ .collect::<Vec<_>>()
+ .join("."),
+ }
+ }
+}
- let (nested_input, _) = mk_comments!(
- $(
- $(
- parent: mk_comments!(@mk_id $name $comment), $name,
- $reply_chain
- )*
- )+
- );
+fn parse_comment(
+ iter: &mut Peekable<Chars<'_>>,
+ parent: Option<&AstId>,
+ siblings: &mut Vec<AstValue>,
+ id_gen: &AtomicUsize,
+) {
+ fn chomp(iter: &mut Peekable<Chars<'_>>, ch: char) -> char {
+ let next = iter
+ .next()
+ .unwrap_or_else(|| panic!("Expected `{ch}` but found nothing."));
+ assert_eq!(ch, next, "Expected `{ch}`, but found `{next}`");
+ // eprint!("{ch}");
+ ch
+ }
- let mut input: Vec<RawComment> = vec![
- $(
- mk_comments!(@to_raw input $name INDEX_INPUT.fetch_add(1, Ordering::Relaxed), $comment)
- ),+
- ];
- input.extend(nested_input);
+ fn skip_while(iter: &mut Peekable<Chars<'_>>, pred: impl Fn(char) -> bool) {
+ loop {
+ let next = iter.peek().copied();
- let expected: Comments = Comments {
- inner: vec![
- $(
- Comment {
- raw: mk_comments!(@to_raw expected $name INDEX_EXPECTED.fetch_add(1, Ordering::Relaxed), $comment),
- replies: {
- let (_, nested_expected) = mk_comments!(
- $(
- parent: mk_comments!(@mk_id $name $comment), $name,
- $reply_chain
- )*
- );
+ match next {
+ Some(next) if pred(next) => chomp(iter, next),
+ Some(_) | None => break,
+ };
+ }
+ }
+ fn take_until(iter: &mut Peekable<Chars<'_>>, pred: impl Fn(char) -> bool) -> String {
+ let mut acc = String::new();
+ loop {
+ let next = iter.peek().copied();
- nested_expected.inner
- },
- }
- ),+
- ]
- };
+ match next {
+ Some(next) if pred(next) => break acc,
+ Some(next) => acc.push(chomp(iter, next)),
+ None => break acc,
+ }
+ }
+ }
- (input, expected)
- }};
+ loop {
+ skip_while(iter, char::is_whitespace);
- (@mk_id $name:ident $comment:literal $($parent:expr)?) => {{
- use std::hash::{Hash, Hasher};
+ match iter.peek() {
+ None => {
+ // We are done.
+ break;
+ }
+ Some(')') => {
+ // We should return to the toplevel parsing.
+ break;
+ }
+ _ => (),
+ }
- let input = format!("{}{}", stringify!($name), $comment);
+ chomp(iter, '(');
- let mut digest = std::hash::DefaultHasher::new();
- input.hash(&mut digest);
+ skip_while(iter, char::is_whitespace);
- #[allow(unused_mut, unused_assignments)]
- {
- let mut parent_id = ".".to_owned();
+ chomp(iter, '@');
- $(
- parent_id = format!("{}.", $parent.id);
- )?
+ skip_while(iter, char::is_whitespace);
- Id { id: format!("{parent_id}{}", digest.finish().to_string()) }
- }
- }};
+ let name = take_until(iter, |ch| ch == ':');
- (@to_raw $state:ident $name:ident $index:expr, $comment:literal $($parent:expr, $actual_parent:ident)?) => {
- RawComment {
- original_order: $index,
- id: mk_comments!(@mk_id $name $comment $($parent)?),
- text: mk_comments!(@mk_text $state $comment $(, $actual_parent)?),
- like_count: 0,
- is_pinned: false,
- author_id: stringify!($name).to_owned(),
- author: format!("@{}", stringify!($name)),
- author_is_verified: false,
- author_thumbnail: Url::from_file_path("/dev/null").unwrap(),
- parent: mk_comments!(@mk_parent $($parent)?),
- edited: false,
- timestamp: 0,
- author_url: None,
- author_is_uploader: false,
- is_favorited: false,
- }
- };
+ skip_while(iter, char::is_whitespace);
- (@mk_parent) => {
- Parent::Root
- };
- (@mk_parent $parent:expr) => {
- Parent::Id($parent.id)
- };
+ chomp(iter, ':');
- (@mk_text input $text:expr) => {
- $text.to_owned()
- };
- (@mk_text input $text:expr, $actual_parent:ident) => {
- format!("@{} {}", stringify!($actual_parent), $text)
- };
- (@mk_text expected $text:expr $(, $_:tt)?) => {
- $text.to_owned()
- };
-}
+ skip_while(iter, char::is_whitespace);
-#[test]
-fn test_comments_toplevel() {
- let (input, expected) = mk_comments!(
- (@kant: "I think, that using the results of an action to determine morality is flawed.")
- (@hume: "I think, that we should use our feeling for morality more.")
- (@lock: "I think, that we should rely on the sum of happiness caused by an action to determine it's morality.")
- );
+ chomp(iter, '"');
+ let content = take_until(iter, |ch| ch == '"');
+ chomp(iter, '"');
- assert_eq!(Comments::from_raw(input), expected);
-}
+ skip_while(iter, char::is_whitespace);
-#[test]
-fn test_comments_replies_1_level() {
- let (input, expected) = mk_comments!(
- (@hume: "I think, that we should use our feeling for morality more."
- (@kant: "This is so wrong! I shall now dedicate my next 7? years to writing books that prove this.")
- (@lock: "It feels not very applicable, no? We should focus on something that can be used in the court of law!"))
- );
+ match iter.peek() {
+ Some(')') => {
+ siblings.push(AstValue {
+ id: AstId::new(parent, id_gen),
+ name,
+ content,
+ children: vec![],
+ });
+ chomp(iter, ')');
+ }
+ Some('(') => {
+ let mut children = vec![];
+ let new_parent = AstId::new(parent, id_gen);
- assert_eq!(
- Comments::from_raw(input).render(true),
- expected.render(true)
- );
+ parse_comment(iter, Some(&new_parent), &mut children, id_gen);
+ siblings.push(AstValue {
+ id: new_parent,
+ name,
+ content,
+ children,
+ });
+ chomp(iter, ')');
+ }
+ Some(next) => unreachable!("Unknown char: `{next}`"),
+ None => unreachable!("We cannot end without an ending paren"),
+ }
+ }
}
-#[test]
-fn test_comments_replies_2_levels() {
- let (input, expected) = mk_comments!(
- (@singer: "We perform medical studies on animals; Children have lower or similar mental ability as these animals.."
- (@singer: "Therefore, we should perform these studies on children instead, if we were to follow our own principals"
- (@james: "This is ridiculous! I will not entertain this thought.")
- (@singer: "Although one could also use this argument to argue for abortion _after_ birth.")))
- );
+fn to_raw(parent: raw::Parent, node: &AstValue) -> RawComment {
+ RawComment {
+ original_order: *node.id.0.last().unwrap(),
+ id: raw::Id {
+ id: node.id.0.last().unwrap().to_string(),
+ },
+ text: node.content.clone(),
+ like_count: 0,
+ is_pinned: false,
+ author_id: node.name.clone(),
+ author: format!("@{}", node.name),
+ author_is_verified: false,
+ author_thumbnail: Url::from_file_path("/dev/null").unwrap(),
+ parent,
+ edited: false,
+ timestamp: 0,
+ author_url: None,
+ author_is_uploader: false,
+ is_favorited: false,
+ }
+}
+fn to_raw_rec(all: &mut Vec<RawComment>, parent: raw::Parent, node: &AstValue) {
+ for child in &node.children {
+ to_raw_rec(all, raw::Parent::Id(node.id.to_id().id), child);
+ }
- assert_eq!(
- Comments::from_raw(input).render(true),
- expected.render(true)
- );
+ all.push(to_raw(parent, node));
}
-#[test]
-fn test_comments_replies_3_levels() {
- let (input, expected) = mk_comments!(
- (@singer: "We perform medical studies on animals; Children have lower or similar mental ability as these animals.."
- (@singer: "Therefore, we should perform these studies on children instead, if we were to follow our own principals"
- (@james: "This is ridiculous! I will not entertain this thought."
- (@singer: "You know that I am not actually suggesting that? This is but a way to critizise the society"))
- (@singer: "Although one could also use this argument to argue for abortion _after_ birth.")))
- );
+fn to_com_rec(inner: &mut Vec<Comment>, parent: raw::Parent, node: &AstValue) {
+ let mut replies = vec![];
+
+ for child in &node.children {
+ to_com_rec(&mut replies, raw::Parent::Id(node.id.to_id().id), child);
+ }
- assert_eq!(
- Comments::from_raw(input).render(true),
- expected.render(true)
- );
+ inner.push(Comment {
+ raw: to_raw(parent, node),
+ replies,
+ });
}
-#[test]
-fn test_comments_sub_answer_selection() {
- let (input, expected) = mk_comments!(
- (@coffeewolfproductions9113: "I mean, brothels and sex workers in of themselves are not a bad thing."
- (@aikikaname6508: "probably not so much in the 50s, pre contraception")
- (@as_ri1mb: "it’s an incredibly sad, degrading line of work, often resulting in self loathing and self-deletion."
- (@coffeewolfproductions9113: "Are you speaking from experience?"
- (@as_ri1mb: "what an immature response, as expected."
- (@coffeewolfproductions9113: "I literally just asked if you were talking from experience.")))))
+fn mk_input_expected(description: &'static str) -> (Vec<RawComment>, Comments) {
+ let mut iter = description.chars().peekable();
+
+ let mut roots = vec![];
+ let id_gen = AtomicUsize::new(0);
+ parse_comment(&mut iter, None, &mut roots, &id_gen);
- );
+ let ast = Ast { roots };
- eprintln!("{}", expected.render(true));
+ let raw = {
+ let mut all = vec![];
- assert_eq!(
- Comments::from_raw(input).render(true),
- expected.render(true)
- );
+ for root in &ast.roots {
+ to_raw_rec(&mut all, raw::Parent::Root, root);
+ }
+
+ all.sort_by_key(|raw| raw.original_order);
+ all
+ };
+ let expected = {
+ let mut inner = vec![];
+ for root in &ast.roots {
+ to_com_rec(&mut inner, raw::Parent::Root, root);
+ }
+
+ Comments { inner }
+ };
+
+ (raw, expected)
}
+
+create_test!(
+# test_comments_toplevel;
+
+(@kant: "I think, that using the results of an action to determine morality is flawed.")
+(@hume: "I think, that we should use our feeling for morality more.")
+(@lock: "I think, that we should rely on the sum of happiness caused by an action to determine it's morality.")
+);
+
+create_test!(
+# test_comments_replies_1_level;
+
+(@hume: "I think, that we should use our feeling for morality more."
+ (@kant: "This is so wrong! I shall now dedicate my next 7? years to writing books that prove this.")
+ (@lock: "It feels not very applicable, no? We should focus on something that can be used in the court of law!"))
+);
+
+create_test!(
+# test_comments_multiple_answers;
+
+(@singer: "We perform medical studies on animals; Children have lower or similar mental ability as these animals.."
+ (@singer: "Therefore, we should perform these studies on children instead, if we were to follow our own principals"
+ (@james: "This is ridiculous! I will not entertain this thought."
+ (@singer: "You know that I am not actually suggesting that? This is but a way to critizise the society"))
+ (@singer: "Although one could also use this argument to argue for abortion _after_ birth.")))
+);
+
+create_test!(
+# test_comments_sub_answer_selection;
+
+(@coffeewolfproductions9113: "I mean, brothels and sex workers in of themselves are not a bad thing."
+ (@aikikaname6508: "probably not so much in the 50s, pre contraception")
+ (@as_ri1mb: "it’s an incredibly sad, degrading line of work, often resulting in self loathing and self-deletion."
+ (@coffeewolfproductions9113: "Are you speaking from experience?"
+ (@as_ri1mb: "what an immature response, as expected."
+ (@coffeewolfproductions9113: "I literally just asked if you were talking from experience.")))))
+);