usaidwat 4.0.0

Answers the age-old question, "Where does a Redditor comment the most?"
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
// SPDX-License-Identifier: Apache-2.0
// Copyright (C) 2025 Michael Dippery <michael@monkey-robot.com>

//! A "thing" in the Reddit sense.
//!
//! Historically, in the Reddit API and its old source code, a "Thing" was
//! any element of the Reddit system: users, posts, comments, etc. This
//! module encapsulates that idea and provides an easy way to more or less
//! work with JSON data from the Reddit API.

use crate::filter::Searchable;
use crate::{markdown, text};
use horologe::{DateTime, Utc, age::HasAge};
use serde::{Deserialize, Deserializer};
use thiserror::Error;

/// An error processing or creating a thing.
#[derive(Debug, Error)]
pub enum Error {
    /// A parsing error.
    #[error("Parsing error occurred: {0}")]
    Parse(#[from] serde_json::Error),
}

/// A standard parsing result.
pub type Result<T> = std::result::Result<T, Error>;

/// A thing that is attached to a subreddit.
pub trait HasSubreddit {
    /// The subreddit the thing appears in.
    fn subreddit(&self) -> &str;
}

/// A Reddit user account.
#[derive(Debug)]
pub struct User {
    about: About,
    comments: Vec<Comment>,
    submissions: Vec<Submission>,
}

/// Reddit user account data.
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct About {
    name: String,
    id: String,
    #[serde(deserialize_with = "from_timestamp_f64")]
    created_utc: DateTime<Utc>,
    link_karma: i64,
    comment_karma: i64,
}

/// A Reddit comment.
#[derive(Clone, Debug, Deserialize)]
#[allow(dead_code)]
pub struct Comment {
    id: String,
    name: String,
    subreddit_id: String,
    subreddit: String,
    link_title: String,
    link_id: String,
    #[serde(deserialize_with = "from_timestamp_f64")]
    created_utc: DateTime<Utc>,
    body: String,
    ups: i64,
    downs: i64,
    score: i64,
}

/// A Reddit Post.
#[derive(Clone, Debug, Deserialize)]
#[allow(dead_code)]
pub struct Submission {
    id: String,
    name: String,
    permalink: String,
    author: String,
    domain: String,
    subreddit_id: String,
    subreddit: String,
    url: String,
    title: String,
    selftext: String,
    #[serde(deserialize_with = "from_timestamp_f64")]
    created_utc: DateTime<Utc>,
    num_comments: u64,
    ups: i64,
    downs: i64,
    score: i64,
}

impl User {
    /// Parses text responses from the Reddit API into the associated
    /// data structures.
    ///
    /// `user_data` is the result of a call to `/users/<user>/about.json`
    /// and contains account medata, `comment_data` is the result of a call
    /// to `/users/<user>/comments.json`, and `post_data` is the result of
    /// a call to `/users/<user>/submitted.json`.
    ///
    /// Obviously parsing can fail so this method returns an `Option`.
    pub fn parse<S>(user_data: S, comment_data: S, post_data: S) -> Result<Self>
    where
        S: AsRef<str>,
    {
        let about = About::parse(user_data.as_ref())?;
        let comments = Comment::parse(comment_data.as_ref())?;
        let submissions = Submission::parse(post_data.as_ref())?;
        Ok(User {
            about,
            comments,
            submissions,
        })
    }

    /// Returns account data for the user.
    pub fn about(&self) -> &About {
        &self.about
    }

    /// User's comments.
    pub fn comments(&self) -> impl Iterator<Item = Comment> {
        self.comments.clone().into_iter()
    }

    /// User's submissions.
    pub fn submissions(&self) -> impl Iterator<Item = Submission> {
        self.submissions.clone().into_iter()
    }
}

impl About {
    /// Parses a text response from the Reddit API into user data.
    ///
    /// Specifically, `user_data` is the result of a call to
    /// `/users/<user>/about.json`.
    ///
    /// This method is generally invoked by `User`, not directly.
    fn parse(user_data: &str) -> Result<Self> {
        Ok(serde_json::from_str(user_data).map(|wrapper: AboutResponse| wrapper.data)?)
    }

    /// The date on which the account was created.
    pub fn created_utc(&self) -> DateTime<Utc> {
        self.created_utc
    }

    /// User's current karma for submissions.
    pub fn link_karma(&self) -> i64 {
        self.link_karma
    }

    /// User's current karma for comments.
    pub fn comment_karma(&self) -> i64 {
        self.comment_karma
    }
}

impl Comment {
    /// Parses a text response from the Reddit API into a list of comments.
    ///
    /// Specifically, `comment_data` is the result of a call to
    /// `/users/<user>/comments.json`.
    ///
    /// This method is generally invoked by `User`, not directly.
    fn parse(comment_data: &str) -> Result<Vec<Self>> {
        let json_object = serde_json::from_str(comment_data).map(
            |comment_listing: ListingResponse<CommentResponse>| {
                comment_listing
                    .data
                    .children
                    .into_iter()
                    .map(|comment_wrapper| comment_wrapper.data)
                    .collect()
            },
        )?;
        Ok(json_object)
    }

    /// The full URL at which the comment can be retrieved.
    pub fn permalink(&self) -> String {
        self.link_id.split("_").last().map(|link_id| {
            // Reddit itself uses the submission title here, but in practice,
            // it can be anything. Since a Comment doesn't have a link back
            // to its submission, we'll just use a placeholder instead of
            // the submission title.
            let placeholder = String::from("z");

            let subreddit = self.subreddit();
            let comment_id = &self.id;
            format!("https://www.reddit.com/r/{subreddit}/comments/{link_id}/{placeholder}/{comment_id}")
        }).unwrap_or(String::from("?"))
    }

    /// The title of the link for which the comment was posted.
    ///
    /// HTML entities in the title will be converted.
    pub fn link_title(&self) -> String {
        text::convert_html_entities(&self.link_title).replace('\n', "")
    }

    /// The comment's total score.
    pub fn score(&self) -> i64 {
        self.score
    }

    /// The comment body, as formatted Markdown text.
    ///
    /// The formatted text converts Markdown markup into terminal escape
    /// codes for elegant display in a terminal.
    pub fn body(&self) -> String {
        markdown::parse(&self.body, textwrap::termwidth())
    }

    /// A summarized form of the comment body, suitable for passing to
    /// an LLM.
    ///
    /// This is essentially the comment's body stripped of all markup so
    /// it is only the basic text. Text contained in extra markup, like link
    /// text and quotes, are completely removed.
    ///
    /// Paragraphs are unwrapped (they appear on one line), and spaces between
    /// paragraphs are removed.
    pub fn summarized_body(&self) -> String {
        markdown::summarize(&self.body)
    }

    /// The comment body, as raw Markdown text, with HTML entities converted
    /// to their respective characters.
    ///
    /// Reddit converts some raw Markdown characters to HTML entities;
    /// for example, `>` in raw Markdown markup will be returned from
    /// Reddit as `&gt;` to be compatible with HTML and XML. This method
    /// will convert HTML entities like `&gt;` into their corresponding
    /// characters, but it will not do any additional parsing of Markdown
    /// text. In other words, the text returned by this method is suitable
    /// for passing into a Markdown parser.
    ///
    /// The returned text is wrapped to the current terminal width, so it
    /// is also suitable for output to a terminal. For raw, unwrapped text,
    /// without converted entities, use [`Comment::markdown_body`].
    pub fn raw_body(&self) -> String {
        textwrap::fill(
            &text::convert_html_entities(&self.body),
            textwrap::termwidth(),
        )
    }

    /// The raw Markdown markup for the comment, as returned from the Reddit
    /// API.
    ///
    /// Like [`Comment::raw_body`], this text is suitable for passing to a
    /// Markdown parser. Unlike [`Comment::raw_body`], the text is not wrapped,
    /// and HTML entities have not yet been converted.
    pub fn markdown_body(&self) -> &str {
        &self.body
    }
}

impl HasAge for Comment {
    /// The time the comment was created, in UTC.
    fn created_utc(&self) -> DateTime<Utc> {
        self.created_utc
    }
}

impl HasSubreddit for Comment {
    /// The subreddit the comment was posted in.
    fn subreddit(&self) -> &str {
        self.subreddit.trim()
    }
}

impl Searchable for Comment {
    fn search_text(&self) -> String {
        self.body()
    }
}

impl Submission {
    /// Parses a text response from the Reddit API into a list of
    /// submissions (posts).
    ///
    /// Specifically, `post_data` is the result of a call to
    /// `/users/<user>/submitted.json`.
    ///
    /// This method is generally invoked by `User`, not directly.
    fn parse(post_data: &str) -> Result<Vec<Self>> {
        let json_object = serde_json::from_str(post_data).map(
            |comment_listing: ListingResponse<SubmissionResponse>| {
                comment_listing
                    .data
                    .children
                    .into_iter()
                    .map(|comment_wrapper| comment_wrapper.data)
                    .collect()
            },
        )?;
        Ok(json_object)
    }

    /// True if the submission is a self post.
    pub fn is_self(&self) -> bool {
        self.domain.starts_with("self.")
    }

    /// The submission's permalink.
    pub fn permalink(&self) -> String {
        let path = &self.permalink;
        format!("https://www.reddit.com{path}")
    }

    /// The submission's title.
    pub fn title(&self) -> String {
        text::convert_html_entities(&self.title)
    }

    /// The URL to which the submission points.
    pub fn url(&self) -> &str {
        &self.url
    }
}

impl HasAge for Submission {
    fn created_utc(&self) -> DateTime<Utc> {
        self.created_utc
    }
}

impl HasSubreddit for Submission {
    /// The subreddit in which the submission was posted.
    fn subreddit(&self) -> &str {
        &self.subreddit
    }
}

impl Searchable for Submission {
    fn search_text(&self) -> String {
        // We really don't use this and only implement it so we can pass
        // Submissions to SubredditFilter, but using the title as the
        // searchable text seems like the most reasonable thing to do,
        // and might be useful in the future.
        String::from(&self.title)
    }
}

// Deserializers
// --------------------------------------------------------------------------

fn from_timestamp_f64<'de, D>(deserializer: D) -> std::result::Result<DateTime<Utc>, D::Error>
where
    D: Deserializer<'de>,
{
    let ts_f64 = f64::deserialize(deserializer)?;
    let ts = f64_to_i64(ts_f64)
        .ok_or_else(|| serde::de::Error::custom(format!("Invalid Unix timestamp: {ts_f64}")))?;
    DateTime::from_timestamp(ts, 0)
        .ok_or_else(|| serde::de::Error::custom(format!("Invalid Unix timestamp: {ts}")))
}

fn f64_to_i64(n: f64) -> Option<i64> {
    if n.is_finite() && n <= i64::MAX as f64 {
        Some(n.trunc() as i64)
    } else {
        None
    }
}

// Response wrappers
// --------------------------------------------------------------------------
// These are necessary because the Reddit API returns data wrapped in "data"
// and "children" keys, so serde_json has to first parse these parent keys
// that we don't really care about to get to the "real" data.

#[derive(Debug, Deserialize)]
struct AboutResponse {
    data: About,
}

#[derive(Debug, Deserialize)]
struct ListingResponse<T> {
    data: ChildrenResponse<T>,
}

#[derive(Debug, Deserialize)]
struct ChildrenResponse<T> {
    children: Vec<T>,
}

#[derive(Debug, Deserialize)]
struct CommentResponse {
    data: Comment,
}

#[derive(Debug, Deserialize)]
struct SubmissionResponse {
    data: Submission,
}

// Unit tests
// --------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    mod about {
        use super::super::*;
        use crate::test_utils::load_data;

        #[test]
        fn it_cannot_parse_invalid_data() {
            let about = About::parse(&load_data("about_404"));
            assert!(about.is_err(), "should be Err, was {about:?}");
        }

        #[test]
        fn it_can_parse_valid_data() {
            let about = About::parse(&load_data("about_mipadi"));
            assert!(about.is_ok());
        }

        #[test]
        fn it_parses_fields() {
            let about = About::parse(&load_data("about_mipadi")).unwrap();
            let expected_created_at = DateTime::from_timestamp(1207004126, 0).unwrap();
            assert_eq!(about.created_utc(), expected_created_at);
            assert_eq!(
                about.created_utc().to_rfc2822(),
                "Mon, 31 Mar 2008 22:55:26 +0000"
            );
            assert_eq!(
                about.created_utc().to_rfc3339(),
                "2008-03-31T22:55:26+00:00"
            );
            assert_eq!(about.link_karma(), 11729);
            assert_eq!(about.comment_karma(), 121995);
        }
    }

    mod comments {
        use super::super::*;
        use crate::test_utils::{load_data, load_output};
        use chrono::Local;
        use pretty_assertions::assert_eq;

        #[test]
        fn it_cannot_parse_invalid_data() {
            let comments = Comment::parse(&load_data("comments_404"));
            assert!(comments.is_err(), "should be Err, was {comments:?}");
        }

        #[test]
        fn it_can_parse_valid_data() {
            let comments = Comment::parse(&load_data("comments_mipadi"));
            assert!(comments.is_ok());
        }

        #[test]
        fn it_can_parse_empty_data() {
            let comments = Comment::parse(&load_data("comments_empty"));
            assert!(comments.is_ok());
        }

        #[test]
        fn it_parses_fields() {
            let comments = Comment::parse(&load_data("comments_mipadi")).unwrap();
            assert_eq!(comments.len(), 100);

            let expected_link_title = "I dont want to play and we didn't even start";
            let expected_body = "Honestly, min/maxing and system mastery is a big part of the \
                Pathfinder community. It's a fairly crunchy system that draws in the sort of \
                players who really like finding ways to exploit the rules. Supposedly some groups \
                are more focused on roleplaying, but I have yet to meet a PF2 player in real life \
                who gives a shit about pesky, whimsical things like _story_. If that's not your \
                thing, you probably won't see eye to eye with the Pathfinder players you meet.\
                \n\nI'm in a slightly similar boat right now: I don't care that much about \
                min/maxing, but I put up with my Pathfinder friends because I really like our \
                group and I like them as people well enough.";
            let expected_created_utc = DateTime::from_timestamp(1743054429, 0).unwrap();

            // Parse comment 9 because it has negative ups and I want to test for that
            let comment = &comments[9];
            assert_eq!(comment.id, "mjyuqdz");
            assert_eq!(comment.name, "t1_mjyuqdz");
            assert_eq!(comment.subreddit_id, "t5_2qh2s");
            assert_eq!(comment.subreddit, "rpg");
            assert_eq!(comment.link_title, expected_link_title);
            assert_eq!(comment.link_id, "t3_1jktw0c");
            assert_eq!(comment.created_utc, expected_created_utc);
            assert_eq!(
                comment.created_utc.to_rfc2822(),
                "Thu, 27 Mar 2025 05:47:09 +0000"
            );
            assert_eq!(
                comment.created_utc.to_rfc3339(),
                "2025-03-27T05:47:09+00:00"
            );
            assert_eq!(comment.body, expected_body);
            assert_eq!(comment.ups, -3);
            assert_eq!(comment.downs, 0);
            assert_eq!(comment.score, -3);
        }

        #[test]
        fn it_returns_its_score() {
            let comments = Comment::parse(&load_data("comments_mipadi")).unwrap();
            let comment = &comments[9];
            assert_eq!(comment.score(), -3);
        }

        #[test]
        fn it_returns_its_subreddit() {
            let comments = Comment::parse(&load_data("comments_mipadi")).unwrap();
            let comment = &comments[0];
            assert_eq!(comment.subreddit(), "cyphersystem");
        }

        #[test]
        fn it_trims_whitespace_from_its_subreddit() {
            let comments = Comment::parse(&load_data("comments_subreddit_whitespace")).unwrap();
            let comment = &comments[0];
            assert_eq!(comment.subreddit(), "LowSodiumHellDivers");
        }

        #[test]
        fn it_returns_its_permalink() {
            let comments = Comment::parse(&load_data("comments_mipadi")).unwrap();
            let comment = &comments[0];
            let expected = "https://www.reddit.com/r/cyphersystem/comments/1k1iixf/z/mnpd3zh";
            let actual = comment.permalink();
            assert_eq!(actual, expected);
        }

        #[test]
        fn it_returns_its_link_title() {
            let comments = Comment::parse(&load_data("comments_mipadi")).unwrap();
            // Get the 0th comment because it has an ampersand and I want to test the conversion
            let comment = &comments[0];
            assert_eq!(comment.link_title(), "Cypher System & ChatGPT");
        }

        #[test]
        #[ignore]
        fn it_trims_whitespace_from_link_titles() {
            let expected = "this link title has a lot of whitespace";
            let comments = Comment::parse(&load_data("comments_whitespace")).unwrap();
            let comment = &comments[0];
            let actual = comment.link_title();
            assert_eq!(actual, expected);
        }

        #[test]
        fn it_returns_its_body() {
            let expected = load_output("comments_body");
            let comments = Comment::parse(&load_data("comments_mipadi")).unwrap();
            let comment = &comments[9];
            let actual = comment.body();
            assert_eq!(actual, expected, "\nleft:\n{actual}\n\nright:\n{expected}");
        }

        #[test]
        fn it_converts_html_entities_in_its_body() {
            let expected = load_output("comments_html_entities");
            let comments = Comment::parse(&load_data("comments_mipadi")).unwrap();
            let comment = &comments[3];
            let actual = comment.body();
            assert_eq!(actual, expected, "\nleft:\n{actual}\n\nright:\n{expected}");
        }

        #[test]
        fn it_trims_whitespace_from_its_body() {
            let expected = "No more whitespace!";
            let comments = Comment::parse(&load_data("comments_whitespace")).unwrap();
            let comment = &comments[0];
            let actual = comment.body();
            assert_eq!(actual, expected);
        }

        #[test]
        fn it_returns_a_summarized_body() {
            let expected = load_output("comments_body_summary");
            let comments = Comment::parse(&load_data("comments_mipadi")).unwrap();
            let comment = &comments[9];
            let actual = comment.summarized_body();
            assert_eq!(actual, expected, "\nleft:\n{actual}\n\nright:\n{expected}");
        }

        #[test]
        fn it_returns_a_raw_body() {
            let expected = load_output("comments_body_raw");
            let comments = Comment::parse(&load_data("comments_mipadi")).unwrap();
            let comment = &comments[2];
            let actual = comment.raw_body();
            assert_eq!(actual, expected, "\nleft:\n{actual}\n\nright:\n{expected}");
        }

        #[test]
        fn it_returns_a_really_raw_body() {
            let expected = load_output("comments_body_raw_markdown");
            let comments = Comment::parse(&load_data("comments_mipadi")).unwrap();
            let comment = &comments[2];
            let actual = comment.markdown_body();
            assert_eq!(actual, expected, "\nleft:\n{actual}\n\nright:\n{expected}");
        }

        #[test]
        fn it_matches_a_fixed_string() {
            let comments = Comment::parse(&load_data("comments_mipadi")).unwrap();
            let comment = &comments[9];
            let result = comment.matches("min/maxing");
            assert!(result, "{result} != true");
        }

        #[test]
        fn it_matches_a_fixed_string_case_insensitively() {
            let comments = Comment::parse(&load_data("comments_mipadi")).unwrap();
            let comment = &comments[9];

            let result = comment.matches("Pathfinder");
            assert!(result, "'Pathfinder' not found in text");

            let result = comment.matches("pathfinder");
            assert!(result, "'pathfinder' not found in text");
        }

        #[test]
        fn it_matches_a_fixed_string_with_a_space() {
            let comments = Comment::parse(&load_data("comments_mipadi")).unwrap();
            let comment = &comments[9];
            let result = comment.matches("see eye to eye");
            assert!(result, "{result} != true");
        }

        #[test]
        fn it_does_not_match_a_fixed_string() {
            let comments = Comment::parse(&load_data("comments_mipadi")).unwrap();
            let comment = &comments[9];
            let result = comment.matches("D&D");
            assert!(!result, "{} should not match 'D&D'", comment.search_text());
        }

        #[test]
        fn it_returns_its_creation_time() {
            let comments = Comment::parse(&load_data("comments_mipadi")).unwrap();
            let comment = &comments[9];
            let datetime = DateTime::parse_from_rfc3339("2025-03-27T05:47:09+00:00")
                .unwrap()
                .with_timezone(&Utc);
            assert_eq!(comment.created_utc(), datetime);
        }

        #[test]
        fn it_returns_its_creation_time_in_local_time() {
            let comments = Comment::parse(&load_data("comments_mipadi")).unwrap();
            let comment = &comments[9];
            let datetime = DateTime::parse_from_rfc3339("2025-03-27T05:47:09+00:00")
                .unwrap()
                .with_timezone(&Local);
            assert_eq!(comment.created_local(), datetime);
        }

        #[test]
        fn it_returns_an_empty_collection() {
            let comments = Comment::parse(&load_data("comments_empty")).unwrap();
            assert!(comments.is_empty());
        }

        #[test]
        fn it_removes_new_lines_in_comment_title() {
            let comments = Comment::parse(&load_data("comments_title_newline")).unwrap();
            let comment = &comments[0];
            let expected = "[OC] I've always wondered if people know this shortcut exists, or if it's just largely unknown. I've been using it almost since the game's release and haven't seen anyone else use it yet.";
            assert_eq!(comment.link_title(), expected);
        }
    }

    mod submissions {
        use super::super::*;
        use crate::test_utils::load_data;

        #[test]
        fn it_cannot_parse_invalid_data() {
            let submissions = Submission::parse(&load_data("submitted_404"));
            assert!(submissions.is_err(), "should be Err, was {submissions:?}");
        }

        #[test]
        fn it_can_parse_valid_data() {
            let submissions = Submission::parse(&load_data("submitted_mipadi"));
            assert!(submissions.is_ok());
        }

        #[test]
        fn it_can_parse_empty_data() {
            let submissions = Submission::parse(&load_data("submitted_empty"));
            assert!(submissions.is_ok());
        }

        #[test]
        fn it_parses_fields() {
            let submissions = Submission::parse(&load_data("submitted_mipadi")).unwrap();
            assert_eq!(submissions.len(), 100);

            let submission = &submissions[0];
            let expected_created_utc = DateTime::from_timestamp(1736196841, 0).unwrap();
            assert_eq!(submission.id, "1hv9k9l");
            assert_eq!(submission.name, "t3_1hv9k9l");
            assert_eq!(
                submission.permalink,
                "/r/rpg/comments/1hv9k9l/collections_coinage_and_the_tyranny_of_fantasy/"
            );
            assert_eq!(submission.author, "mipadi");
            assert_eq!(submission.domain, "acoup.blog");
            assert_eq!(submission.subreddit_id, "t5_2qh2s");
            assert_eq!(submission.subreddit, "rpg");
            assert_eq!(
                submission.url,
                "https://acoup.blog/2025/01/03/collections-coinage-and-the-tyranny-of-fantasy-gold/"
            );
            assert_eq!(
                submission.title,
                "Collections: Coinage and the Tyranny of Fantasy \"Gold\""
            );
            assert_eq!(submission.selftext, "");
            assert_eq!(submission.created_utc, expected_created_utc);
            assert_eq!(
                submission.created_utc.to_rfc2822(),
                "Mon, 6 Jan 2025 20:54:01 +0000"
            );
            assert_eq!(
                submission.created_utc.to_rfc3339(),
                "2025-01-06T20:54:01+00:00"
            );
            assert_eq!(submission.num_comments, 22);
            assert_eq!(submission.ups, 60);
            assert_eq!(submission.downs, 0);
            assert_eq!(submission.score, 60);
        }

        #[test]
        fn it_parses_fields_of_self_posts() {
            let submissions = Submission::parse(&load_data("submitted_mipadi")).unwrap();
            assert_eq!(submissions.len(), 100);

            let expected_selftext = "I have two types of technology upgrades available for my \
                exosuit: items listed as _protection units_, and items listed as _protection \
                upgrades_. The ones listed as upgrades have text that generally says something \
                like \"an almost total rework of the &lt;damage type&gt; Protection, this upgrade \
                brings unparalleled improvements to &lt;damage type&gt; Shielding and &lt;damage \
                type&gt; Protection\", whereas the upgrade units give a percentage of resistance.\
                \n\nShould I install both, or do I just need to install one or the other? For \
                example:\n\n- I have a \"High-Energy Bio-Integrity Unit\" which is a _protection \
                upgrade_, and I can build a \"Radiation Reflector\" which is a _protection unit_. \
                Should I install both?\n- I have a \"Specialist De-Toxifier\" and I can build a \
                \"Toxin Suppressor\". Should I install both?\n- I have a \"Carbon Sublimation \
                Pump\" and I can build a \"Coolant Network\". Should I install both?\n- I have a \
                \"Nitroged-Based Thermal Stabilizer\" and I can build a \"Thermic Layer\". Should \
                I install both?\n\nAnd then for something similar but a little different:\n\n- I \
                have a \"Deep Water Depth Protection\" which says it is an \"almost total rework \
                of the Aeration Membrance\", and I can also build an Aeration Membrane. Will \
                crafting and installing an Aeration Membrane bring any extra benefits?";
            let expected_created_utc = DateTime::from_timestamp(1721503204, 0).unwrap();

            let submission = &submissions[3];
            assert_eq!(submission.id, "1e83c2w");
            assert_eq!(submission.name, "t3_1e83c2w");
            assert_eq!(
                submission.permalink,
                "/r/NoMansSkyTheGame/comments/1e83c2w/should_i_install_both_protection_upgrades_and/"
            );
            assert_eq!(submission.author, "mipadi");
            assert_eq!(submission.domain, "self.NoMansSkyTheGame");
            assert_eq!(submission.subreddit_id, "t5_325lr");
            assert_eq!(submission.subreddit, "NoMansSkyTheGame");
            assert_eq!(
                submission.url,
                "https://www.reddit.com/r/NoMansSkyTheGame/comments/1e83c2w/should_i_install_both_protection_upgrades_and/"
            );
            assert_eq!(
                submission.title,
                "Should I install both protection upgrades and protection units in an exosuit?"
            );
            assert_eq!(submission.selftext, expected_selftext);
            assert_eq!(submission.created_utc, expected_created_utc);
            assert_eq!(
                submission.created_utc.to_rfc2822(),
                "Sat, 20 Jul 2024 19:20:04 +0000"
            );
            assert_eq!(
                submission.created_utc.to_rfc3339(),
                "2024-07-20T19:20:04+00:00"
            );
            assert_eq!(submission.num_comments, 7);
            assert_eq!(submission.ups, 1);
            assert_eq!(submission.downs, 0);
            assert_eq!(submission.score, 1);
        }

        #[test]
        fn it_returns_its_subreddit() {
            let submissions = Submission::parse(&load_data("submitted_mipadi")).unwrap();
            let submission = &submissions[0];
            assert_eq!(submission.subreddit(), "rpg");
        }

        #[test]
        fn it_returns_its_permalink() {
            let submissions = Submission::parse(&load_data("submitted_mipadi")).unwrap();
            let submission = &submissions[0];
            let expected = "https://www.reddit.com/r/rpg/comments/1hv9k9l/collections_coinage_and_the_tyranny_of_fantasy/";
            assert_eq!(submission.permalink(), expected);
        }

        #[test]
        fn it_returns_its_title() {
            let submissions = Submission::parse(&load_data("submitted_mipadi")).unwrap();
            let submission = &submissions[0];
            let expected = "Collections: Coinage and the Tyranny of Fantasy \"Gold\"";
            assert_eq!(submission.title(), expected);
        }

        #[test]
        fn it_converts_html_entities_in_its_title() {
            let submissions = Submission::parse(&load_data("submitted_mipadi")).unwrap();
            let submission = &submissions[10];
            let expected = "System Scorn: The Excesses of 3rd Edition Dungeons & Dragons";
            assert_eq!(submission.title(), expected);
        }

        #[test]
        fn it_returns_its_url() {
            let submissions = Submission::parse(&load_data("submitted_mipadi")).unwrap();
            let submission = &submissions[0];
            let expected = "https://acoup.blog/2025/01/03/collections-coinage-and-the-tyranny-of-fantasy-gold/";
            assert_eq!(submission.url(), expected);
        }

        #[test]
        fn it_returns_true_if_it_is_a_self_post() {
            let submissions = Submission::parse(&load_data("submitted_mipadi")).unwrap();
            let submission = &submissions[3];
            assert!(submission.is_self());
        }

        #[test]
        fn it_returns_false_if_it_is_a_self_post() {
            let submissions = Submission::parse(&load_data("submitted_mipadi")).unwrap();
            let submission = &submissions[0];
            assert!(!submission.is_self());
        }

        #[test]
        fn it_returns_its_creation_time() {
            let submissions = Submission::parse(&load_data("submitted_mipadi")).unwrap();
            let submission = &submissions[0];
            let expected = DateTime::parse_from_rfc3339("2025-01-06T20:54:01+00:00")
                .expect("could not parse datetime string");
            assert_eq!(submission.created_utc(), expected);
        }

        #[test]
        fn it_returns_an_empty_collection() {
            let submissions = Submission::parse(&load_data("submitted_empty")).unwrap();
            assert!(submissions.is_empty());
        }
    }
}