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
use futures::{stream, StreamExt};
use grep::regex::RegexMatcher;
use grep::searcher::sinks::UTF8;
use grep::searcher::Searcher;
use linkify::{LinkFinder, LinkKind};
use reqwest::redirect::Policy;
use spinners::{Spinner, Spinners};

use core::fmt;
use std::cmp::Ordering;
use std::io::Error;
use std::path::Path;
use std::time::Duration;

#[derive(Debug, Eq, Clone)]
pub struct UrlUpResult {
    url: String,
    status_code: Option<u16>,
    description: Option<String>,
}

impl Ord for UrlUpResult {
    fn cmp(&self, other: &Self) -> Ordering {
        self.url.cmp(&other.url)
    }
}

impl PartialOrd for UrlUpResult {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for UrlUpResult {
    fn eq(&self, other: &Self) -> bool {
        self.url == other.url
            && self.status_code == other.status_code
            && self.description == other.description
    }
}

impl UrlUpResult {
    pub fn is_ok(&self) -> bool {
        if let Some(num) = self.status_code {
            num == 200
        } else {
            false
        }
    }

    pub fn is_not_ok(&self) -> bool {
        !self.is_ok()
    }
}

impl fmt::Display for UrlUpResult {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(num) = &self.status_code {
            write!(f, "{} {}", num.to_string(), &self.url)
        } else if let Some(desc) = &self.description {
            write!(f, "{} {}", &self.url, desc)
        } else {
            unreachable!("UrlUpResult should always have status_code or description")
        }
    }
}

const MARKDOWN_URL_PATTERN: &str =
    r#"(http://|https://)[a-z0-9]+([-.]{1}[a-z0-9]+)*(.[a-z]{2,5})?(:[0-9]{1,5})?(/.*)?"#;

pub struct UrlsUp {}

pub struct UrlsUpOptions {
    // White listed URLs to allow being broken
    pub white_list: Option<Vec<String>>,
    // Timeout for getting a response
    pub timeout: Duration,
    // Status codes to allow being present
    pub allowed_status_codes: Option<Vec<u16>>,
    // Thread count
    pub thread_count: usize,
    // Allow URLs to time out
    pub allow_timeout: bool,
}

pub struct UrlsUpResult {
    // If any issues were found
    pub has_issues: bool,
}

impl UrlsUp {
    pub async fn check(&self, paths: Vec<&Path>, opts: UrlsUpOptions) -> UrlsUpResult {
        // Print options
        println!("> Using threads: {}", &opts.thread_count);
        println!("> Using timeout (seconds): {}", &opts.timeout.as_secs());
        println!("> Allow timeout: {}", &opts.allow_timeout);

        if let Some(white_list) = &opts.white_list {
            println!("> Ignoring white listed URLs");
            for (i, url) in white_list.iter().enumerate() {
                println!("{:4}. {}", i + 1, url.to_string());
            }
        }

        if let Some(allowed) = &opts.allowed_status_codes {
            println!("> Allowing status codes");
            for (i, status_code) in allowed.iter().enumerate() {
                println!("{:4}. {}", i + 1, status_code.to_string());
            }
        }

        let files_singular_plural = match &paths.len() {
            1 => "file",
            _ => "files",
        };

        println!(
            "> Will check URLs in {} {}",
            paths.len(),
            files_singular_plural
        );
        for (i, file) in paths.iter().enumerate() {
            println!("{:4}. {}", i + 1, file.display());
        }

        println!(); // Make output more readable

        let spinner_find_urls = self.spinner_start("Finding URLs in files...".to_string());

        // Find URLs from files
        let mut urls = self.find_urls(paths);

        // Apply white list
        if let Some(white_list) = &opts.white_list {
            urls = self.apply_white_list(urls, white_list);
        }

        // Save URL count to avoid having to clone URL list
        let url_count = urls.len();

        // Deduplicate URLs to avoid duplicate work
        let dedup_urls = self.dedup(urls);

        if let Some(sp) = spinner_find_urls {
            sp.stop();
        }

        let urls_singular_plural = match &dedup_urls.len() {
            1 => "URL",
            _ => "URLs",
        };

        println!(
            "\n\n> Found {} unique {}, {} in total",
            &dedup_urls.len(),
            urls_singular_plural,
            url_count
        );

        for (i, url) in dedup_urls.iter().enumerate() {
            println!("{:4}. {}", i + 1, url.to_string());
        }

        println!(); // Make output more readable

        let validation_spinner = self.spinner_start("Checking URLs...".into());

        // Check URLs
        let mut non_ok_urls: Vec<UrlUpResult> = self
            .check_urls(dedup_urls, &opts)
            .await
            .into_iter()
            .filter(|url_up_result| url_up_result.is_not_ok())
            .collect();

        if let Some(allowed) = &opts.allowed_status_codes {
            non_ok_urls = self.filter_allowed_status_codes(non_ok_urls, allowed.clone());
        }

        if opts.allow_timeout {
            non_ok_urls = self.filter_timeouts(non_ok_urls);
        }

        if let Some(sp) = validation_spinner {
            sp.stop();
        }

        if non_ok_urls.is_empty() {
            println!("\n\n> No issues!");
            return UrlsUpResult { has_issues: false };
        }

        println!("\n\n> Issues");
        for (i, url_up_result) in non_ok_urls.iter().enumerate() {
            println!("{:4}. {}", i + 1, url_up_result.to_string());
        }

        UrlsUpResult { has_issues: true }
    }

    fn find_urls(&self, paths: Vec<&Path>) -> Vec<String> {
        paths
            .into_iter()
            .flat_map(|path| {
                self.find_lines_with_url(path).unwrap_or_else(|_| {
                    panic!(
                        "Something went wrong parsing URL in file: {}",
                        path.display()
                    )
                })
            })
            .flat_map(|line| self.parse_urls(line))
            .collect()
    }

    fn find_lines_with_url(&self, path: &Path) -> Result<Vec<String>, Error> {
        let matcher = RegexMatcher::new(MARKDOWN_URL_PATTERN).unwrap();

        let mut matches = vec![];
        Searcher::new().search_path(
            &matcher,
            &path,
            UTF8(|_lnum, line| {
                matches.push(line.trim().to_string());
                Ok(true)
            }),
        )?;

        Ok(matches)
    }

    fn parse_urls(&self, line: String) -> Vec<String> {
        let mut finder = LinkFinder::new();
        finder.kinds(&[LinkKind::Url]);

        finder
            .links(line.as_str())
            .map(|url| url.as_str().to_string())
            .collect()
    }

    async fn check_urls(&self, urls: Vec<String>, opts: &UrlsUpOptions) -> Vec<UrlUpResult> {
        let redirect_policy = Policy::limited(10);
        let user_agent = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));

        let client = reqwest::Client::builder()
            .timeout(opts.timeout)
            .redirect(redirect_policy)
            .user_agent(user_agent)
            .build()
            .unwrap();

        let mut urls_and_responses = stream::iter(urls)
            .map(|url| {
                let client = &client;
                async move {
                    let response = client.get(&url).send().await;
                    (url.clone(), response)
                }
            })
            .buffer_unordered(opts.thread_count);

        let mut result = vec![];
        while let Some((url, response)) = urls_and_responses.next().await {
            let url_up_result = match response {
                Ok(res) => UrlUpResult {
                    url,
                    status_code: Some(res.status().as_u16()),
                    description: None,
                },
                Err(err) => UrlUpResult {
                    url,
                    status_code: None,
                    description: std::error::Error::source(&err).map(|e| e.to_string()),
                },
            };

            result.push(url_up_result);
        }

        result
    }

    fn apply_white_list(&self, urls: Vec<String>, white_list: &[String]) -> Vec<String> {
        urls.into_iter()
            .filter(|url| {
                // If white list URL matches URL
                if white_list.contains(url) {
                    return false;
                }

                // If URL begins with white list URL
                for white_listed_url in white_list.iter() {
                    if url.starts_with(white_listed_url) {
                        return false;
                    }
                }

                true
            })
            .collect()
    }

    fn filter_allowed_status_codes(
        &self,
        url_up_results: Vec<UrlUpResult>,
        allowed_status_codes: Vec<u16>,
    ) -> Vec<UrlUpResult> {
        url_up_results
            .into_iter()
            .filter(|uur| {
                if let Some(status_code) = uur.status_code {
                    if allowed_status_codes.contains(&status_code) {
                        return false;
                    }
                }

                true
            })
            .collect()
    }

    fn filter_timeouts(&self, url_up_results: Vec<UrlUpResult>) -> Vec<UrlUpResult> {
        url_up_results
            .into_iter()
            .filter(|uur| {
                if let Some(description) = &uur.description {
                    if description == "operation timed out" {
                        return false;
                    }
                }

                true
            })
            .collect()
    }

    fn dedup(&self, mut list: Vec<String>) -> Vec<String> {
        list.sort();
        list.dedup();
        list
    }

    fn spinner_start(&self, msg: String) -> Option<Spinner> {
        if term::stdout().is_some() {
            Some(Spinner::new(Spinners::Dots, msg))
        } else {
            println!("{}", msg);
            None
        }
    }
}

#[cfg(test)]
mod tests {
    #![allow(non_snake_case)]

    use super::*;
    use std::io::Write;

    type TestResult = Result<(), Box<dyn std::error::Error>>;

    #[test]
    fn test_parse_urls() {
        let urls_up = UrlsUp {};
        let md_link =
            "arbitrary [something](http://foo.bar) arbitrary http://foo2.bar arbitrary".to_string();
        let expected = vec!["http://foo.bar".to_string(), "http://foo2.bar".to_string()];
        let actual = urls_up.parse_urls(md_link);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_parse_img_url() {
        let urls_up = UrlsUp {};
        let md_link = "arbitrary ![image](http://foo.bar) arbitrary".to_string();
        let expected = vec!["http://foo.bar".to_string()];
        let actual = urls_up.parse_urls(md_link);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_parse_badge_url() {
        let urls_up = UrlsUp {};
        let md_link = "arbitrary [something]: http://foo.bar arbitrary".to_string();
        let expected = vec!["http://foo.bar".to_string()];
        let actual = urls_up.parse_urls(md_link);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_find_lines_with_url__from_file() -> TestResult {
        let urls_up = UrlsUp {};
        let mut file = tempfile::NamedTempFile::new()?;
        file.write_all(
            "arbitrary [something](http://specific-link.one) arbitrary\n\
             arbitrary [something](http://specific-link.two) arbitrary\n\
             arbitrary [badge-something]: http://specific-link.three arbitrary\n\
             arbitrary http://specific-link.four arbitrary"
                .as_bytes(),
        )?;

        let actual = urls_up.find_lines_with_url(file.path()).unwrap();

        let actual_line1 = &actual.get(0).unwrap().as_str().to_owned();
        let actual_line2 = &actual.get(1).unwrap().as_str().to_owned();
        let actual_line3 = &actual.get(2).unwrap().as_str().to_owned();
        let actual_line4 = &actual.get(3).unwrap().as_str().to_owned();

        assert_eq!(
            actual_line1,
            "arbitrary [something](http://specific-link.one) arbitrary"
        );
        assert_eq!(
            actual_line2,
            "arbitrary [something](http://specific-link.two) arbitrary"
        );
        assert_eq!(
            actual_line3,
            "arbitrary [badge-something]: http://specific-link.three arbitrary"
        );
        assert_eq!(
            actual_line4,
            "arbitrary http://specific-link.four arbitrary"
        );

        Ok(())
    }

    #[test]
    fn test_find_lines_with_urL__from_file__when_non_existing_file() -> TestResult {
        let urls_up = UrlsUp {};
        let non_existing_file = "non_existing_file.txt";
        let is_err = urls_up
            .find_lines_with_url(non_existing_file.as_ref())
            .is_err();

        assert!(is_err);

        Ok(())
    }

    #[test]
    fn test_dedup() {
        let urls_up = UrlsUp {};
        let duplicate: Vec<String> = vec!["duplicate", "duplicate", "unique-1", "unique-2"]
            .into_iter()
            .map(String::from)
            .collect();

        let actual = urls_up.dedup(duplicate);
        let expected: Vec<String> = vec!["duplicate", "unique-1", "unique-2"]
            .into_iter()
            .map(String::from)
            .collect();

        assert_eq!(actual, expected)
    }

    #[test]
    fn test_apply_white_list__filters_out_white_listed_urls() {
        let urls_up = UrlsUp {};
        let urls: Vec<String> = vec![
            "http://should-keep.com",
            "http://should-ignore.com",
            "http://should-also-ignore.com/something/something-else",
        ]
        .into_iter()
        .map(String::from)
        .collect();

        let white_list: Vec<String> =
            vec!["http://should-ignore.com", "http://should-also-ignore.com"]
                .into_iter()
                .map(String::from)
                .collect();

        let actual = urls_up.apply_white_list(urls, &white_list);
        let expected: Vec<String> = vec!["http://should-keep.com"]
            .into_iter()
            .map(String::from)
            .collect();

        assert_eq!(actual, expected)
    }

    #[test]
    fn test_filter_allowed_status_codes__removes_allowed_status_codes() {
        let urls_up = UrlsUp {};
        let ar1 = UrlUpResult {
            url: "keep-this".to_string(),
            status_code: Some(200),
            description: None,
        };
        let ar2 = UrlUpResult {
            url: "keep-this-2".to_string(),
            status_code: None,
            description: Some("arbitrary".to_string()),
        };
        let ar3 = UrlUpResult {
            url: "remove-this".to_string(),
            status_code: Some(404),
            description: None,
        };
        let actual = urls_up
            .filter_allowed_status_codes(vec![ar1.clone(), ar2.clone(), ar3.clone()], vec![404]);
        let expected = vec![ar1, ar2];

        assert_eq!(actual, expected)
    }

    #[test]
    fn test_filter_filter_timeouts__removes_timeouts() {
        let urls_up = UrlsUp {};
        let ar1 = UrlUpResult {
            url: "keep-this".to_string(),
            status_code: Some(200),
            description: None,
        };
        let ar2 = UrlUpResult {
            url: "keep-this-2".to_string(),
            status_code: None,
            description: Some("arbitrary".to_string()),
        };
        let ar3 = UrlUpResult {
            url: "remove-this".to_string(),
            status_code: None,
            description: Some("operation timed out".to_string()),
        };
        let actual = urls_up.filter_timeouts(vec![ar1.clone(), ar2.clone(), ar3.clone()]);
        let expected = vec![ar1, ar2];

        assert_eq!(actual, expected)
    }

    #[test]
    fn test_urls_up_result__is_ok() {
        let uup = UrlUpResult {
            url: "irrelevant".to_string(),
            status_code: Some(200),
            description: None,
        };

        assert!(uup.is_ok());
        assert!(!uup.is_not_ok());
    }

    #[test]
    fn test_urls_up_result__to_string() {
        let uup_200 = UrlUpResult {
            url: "http://some-domain.com".to_string(),
            status_code: Some(200),
            description: Some("should ignore this".to_string()),
        };

        assert_eq!(uup_200.to_string(), "200 http://some-domain.com");

        let uup_description = UrlUpResult {
            url: "http://some-domain.com".to_string(),
            status_code: None,
            description: Some("some-description".to_string()),
        };

        assert_eq!(
            uup_description.to_string(),
            "http://some-domain.com some-description"
        );
    }
}

#[cfg(test)]
mod integration_tests {
    #![allow(non_snake_case)]

    use super::*;
    use mockito::mock;
    use std::io::Write;

    type TestResult = Result<(), Box<dyn std::error::Error>>;

    #[tokio::test]
    async fn test_check_urls__handles_url_with_status_code() {
        let urls_up = UrlsUp {};
        let opts = UrlsUpOptions {
            white_list: None,
            timeout: Duration::from_secs(10),
            allowed_status_codes: None,
            thread_count: 1,
            allow_timeout: false,
        };
        let _m = mock("GET", "/200").with_status(200).create();
        let endpoint = mockito::server_url() + "/200";

        let results = urls_up.check_urls(vec![endpoint.clone()], &opts).await;
        let actual = results.first().expect("No UrlUpResults returned");

        assert_eq!(actual.url, endpoint);
        assert_eq!(actual.status_code, Some(200));
        assert_eq!(actual.description, None);
    }

    #[tokio::test]
    async fn test_check_urls__handles_not_available_url() {
        let urls_up = UrlsUp {};
        let opts = UrlsUpOptions {
            white_list: None,
            timeout: Duration::from_secs(10),
            allowed_status_codes: None,
            thread_count: 1,
            allow_timeout: false,
        };
        let endpoint = "https://localhost.urls_up".to_string();

        let results = urls_up.check_urls(vec![endpoint.clone()], &opts).await;
        let actual = results.first().expect("No UrlUpResults returned");

        assert_eq!(actual.url, endpoint);
        assert_eq!(actual.status_code, None);
        assert!(actual
            .description
            .as_ref()
            .unwrap()
            .contains("error trying to connect: dns error: failed to lookup address information:"));
    }

    #[tokio::test]
    async fn test_check_urls__timeout_reached() {
        let urls_up = UrlsUp {};
        let opts = UrlsUpOptions {
            white_list: None,
            timeout: Duration::from_nanos(1), // Use very small timeout
            allowed_status_codes: None,
            thread_count: 1,
            allow_timeout: false,
        };
        let _m = mock("GET", "/200").with_status(200).create();
        let endpoint = mockito::server_url() + "/200";

        let results = urls_up.check_urls(vec![endpoint.clone()], &opts).await;
        let actual = results.first().expect("No UrlUpResults returned");

        assert_eq!(actual.url, endpoint);
        assert_eq!(actual.description, Some("operation timed out".to_string()));
    }

    #[tokio::test]
    async fn test_check_urls__works() -> TestResult {
        let urls_up = UrlsUp {};
        let opts = UrlsUpOptions {
            white_list: None,
            timeout: Duration::from_secs(10),
            allowed_status_codes: None,
            thread_count: 1,
            allow_timeout: false,
        };
        let _m200 = mock("GET", "/200").with_status(200).create();
        let _m404 = mock("GET", "/404").with_status(404).create();
        let endpoint_200 = mockito::server_url() + "/200";
        let endpoint_404 = mockito::server_url() + "/404";
        let endpoint_non_existing = "https://localhost.urls_up".to_string();

        let mut file = tempfile::NamedTempFile::new()?;
        file.write_all(
            format!(
                "arbitrary {} arbitrary [arbitrary]({}) arbitrary {}",
                endpoint_200, endpoint_404, endpoint_non_existing
            )
            .as_bytes(),
        )?;

        let mut actual: Vec<UrlUpResult> = urls_up
            .check_urls(
                vec![
                    endpoint_200.clone(),
                    endpoint_404.clone(),
                    endpoint_non_existing.clone(),
                ],
                &opts,
            )
            .await;

        actual.sort(); // Sort to be able to assert deterministically

        assert_eq!(actual[0].url, endpoint_200);
        assert_eq!(actual[0].status_code, Some(200));
        assert_eq!(actual[0].description, None);

        assert_eq!(actual[1].url, endpoint_404);
        assert_eq!(actual[1].status_code, Some(404));
        assert_eq!(actual[1].description, None);

        assert_eq!(actual[2].url, endpoint_non_existing);
        assert_eq!(actual[2].status_code, None);
        assert!(actual[2]
            .description
            .as_ref()
            .unwrap()
            .contains("error trying to connect: dns error: failed to lookup address information:"));

        Ok(())
    }

    #[tokio::test]
    async fn test_check__has_no_issues() -> TestResult {
        let urls_up = UrlsUp {};
        let opts = UrlsUpOptions {
            white_list: None,
            timeout: Duration::from_secs(10),
            allowed_status_codes: None,
            thread_count: 1,
            allow_timeout: false,
        };
        let _m = mock("GET", "/200").with_status(200).create();
        let endpoint = mockito::server_url() + "/200";
        let mut file = tempfile::NamedTempFile::new()?;
        file.write_all(endpoint.as_bytes())?;

        let actual = urls_up.check(vec![file.path()], opts).await;

        assert!(!actual.has_issues);
        Ok(())
    }

    #[tokio::test]
    async fn test_check__has_issues() -> TestResult {
        let urls_up = UrlsUp {};
        let opts = UrlsUpOptions {
            white_list: None,
            timeout: Duration::from_secs(10),
            allowed_status_codes: None,
            thread_count: 1,
            allow_timeout: false,
        };
        let _m = mock("GET", "/404").with_status(404).create();
        let endpoint = mockito::server_url() + "/404";
        let mut file = tempfile::NamedTempFile::new()?;
        file.write_all(endpoint.as_bytes())?;

        let actual = urls_up.check(vec![file.path()], opts).await;

        assert!(actual.has_issues);
        Ok(())
    }

    #[tokio::test]
    async fn test_check__issues_when_timeout_reached() -> TestResult {
        let urls_up = UrlsUp {};
        let opts = UrlsUpOptions {
            white_list: None,
            timeout: Duration::from_nanos(1), // Use very small timeout
            allowed_status_codes: None,
            thread_count: 1,
            allow_timeout: false,
        };
        let _m = mock("GET", "/200").with_status(200).create();
        let endpoint = mockito::server_url() + "/200";
        let mut file = tempfile::NamedTempFile::new()?;
        file.write_all(endpoint.as_bytes())?;

        let actual = urls_up.check(vec![file.path()], opts).await;

        assert!(actual.has_issues);
        Ok(())
    }

    #[tokio::test]
    async fn test_check__no_issues_when_timeout_reached_and_allow_timeout() -> TestResult {
        let urls_up = UrlsUp {};
        let opts = UrlsUpOptions {
            white_list: None,
            timeout: Duration::from_nanos(1), // Use very small timeout
            allowed_status_codes: None,
            thread_count: 1,
            allow_timeout: true,
        };
        let _m = mock("GET", "/200").with_status(200).create();
        let endpoint = mockito::server_url() + "/200";
        let mut file = tempfile::NamedTempFile::new()?;
        file.write_all(endpoint.as_bytes())?;

        let actual = urls_up.check(vec![file.path()], opts).await;

        assert!(!actual.has_issues);
        Ok(())
    }
}