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 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
//! Goose Eggs are helpful in writing [`Goose`](https://docs.rs/goose) load tests. use goose::goose::GooseResponse; use goose::prelude::*; use log::info; use reqwest::header::HeaderMap; use regex::Regex; /// Define one or more items to be validated in a web page response. /// /// This structure is passed to [`validate_and_load_static_assets`]. /// /// # Example /// ```rust /// use goose_eggs::Validate; /// /// fn examples() { /// // Manually build a Validate strucuture that validates the page title and /// // some arbitrary texts in the response html. /// let _validate = Validate::new( /// None, Some("my page"), vec!["foo", r#"<a href="bar">"#], vec![] /// ); /// /// // Use `title_texts()` helper to perform the same validation. /// let _validate = Validate::title_texts("my page", vec!["foo", r#"<a href="bar">"#]); /// /// // Use `title_text()` helper to perform similar validation, validating only /// // one text on the page. /// let _validate = Validate::title_text("my page", r#"<a href="foo">"#); /// } #[derive(Clone, Debug)] pub struct Validate<'a> { /// Optionally validate the response status code. status: Option<u16>, /// Optionally validate the response title. title: Option<&'a str>, /// Optionally validate arbitrary texts in the response html. texts: Vec<&'a str>, /// Optionally validate the response headers. headers: Vec<&'a Header<'a>>, } impl<'a> Validate<'a> { /// Create a new Validate struct, specifying `status`, `title`, `texts` and `headers`. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::new( /// // Validate the response status code. /// Some(404), /// // Validate the response page title. /// Some("Page Not Found"), /// // Validate arbitrary text on the response page. /// vec!["Oops, something went wrong!"], /// // Validate that the response was sent via https. /// vec![&Header::name_value("scheme", "https")], /// ); /// ``` pub fn new( status: Option<u16>, title: Option<&'a str>, texts: Vec<&'a str>, headers: Vec<&'a Header<'a>>, ) -> Validate<'a> { Validate { status, title, texts, headers, } } /// Create a Validate object to validate the response status code. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::status(200); /// ``` pub fn status(status: u16) -> Validate<'a> { Validate::new(Some(status), None, vec![], vec![]) } /// Create a Validate object to validate the response title. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::title("Home page"); /// ``` pub fn title(title: &'a str) -> Validate<'a> { Validate::new(None, Some(title), vec![], vec![]) } /// Create a Validate object to validate the response status code and title. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::status_title(200, "Home page"); /// ``` pub fn status_title(status: u16, title: &'a str) -> Validate<'a> { Validate::new(Some(status), Some(title), vec![], vec![]) } /// Create a Validate object to validate specific text is on the response page. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::text("This text should be on the page."); /// ``` pub fn text(text: &'a str) -> Validate<'a> { Validate::new(None, None, vec![text], vec![]) } /// Create a Validate object to validate the response has the correct status code and /// contains specific text. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::status_text(200, "This text should be on the page."); /// ``` pub fn status_text(status: u16, text: &'a str) -> Validate<'a> { Validate::new(Some(status), None, vec![text], vec![]) } /// Create a Validate object to validate the response has the correct title and also /// contains specific text. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::title_text("Example", "This text should be on the page."); /// ``` pub fn title_text(title: &'a str, text: &'a str) -> Validate<'a> { Validate::new(None, Some(title), vec![text], vec![]) } /// Create a Validate object to validate the response code, that the page has the correct /// title and also contains specific text. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::status_title_text(200, "Example", "This text should be on the page."); /// ``` pub fn status_title_text(status: u16, title: &'a str, text: &'a str) -> Validate<'a> { Validate::new(Some(status), Some(title), vec![text], vec![]) } /// Create a Validate object to validate that the response page contains multiple specific /// texts. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::texts(vec!["This text should be on the page.", "And also this", r#"<span>and this</a>"#]); /// ``` pub fn texts(texts: Vec<&'a str>) -> Validate<'a> { Validate::new(None, None, texts, vec![]) } /// Create a Validate object to validate response status code and that the page contains /// multiple specific texts. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::status_texts(200, vec!["This text should be on the page.", "And also this", r#"<span>and this</a>"#]); /// ``` pub fn status_texts(status: u16, texts: Vec<&'a str>) -> Validate<'a> { Validate::new(Some(status), None, texts, vec![]) } /// Create a Validate object to validate the response title and that the page contains /// multiple specific texts. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::title_texts("Example", vec!["This text should be on the page.", "And also this", r#"<span>and this</a>"#]); /// ``` pub fn title_texts(title: &'a str, texts: Vec<&'a str>) -> Validate<'a> { Validate::new(None, Some(title), texts, vec![]) } /// Create a Validate object to validate the response status code, the page title and that the /// page contains multiple specific texts. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::status_title_texts(200, "Example", vec!["This text should be on the page.", "And also this", r#"<span>and this</a>"#]); /// ``` pub fn status_title_texts(status: u16, title: &'a str, texts: Vec<&'a str>) -> Validate<'a> { Validate::new(Some(status), Some(title), texts, vec![]) } /// Create a Validate object to validate the response included a specific header. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::header(&Header::name("x-cache")); /// ``` pub fn header(header: &'a Header<'a>) -> Validate<'a> { Validate::new(None, None, vec![], vec![header]) } /// Create a Validate object to validate the response status code and that it included a /// specific header. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::status_header(200, &Header::name("x-cache")); /// ``` pub fn status_header(status: u16, header: &'a Header<'a>) -> Validate<'a> { Validate::new(Some(status), None, vec![], vec![header]) } /// Create a Validate object to validate the response title and that it included a /// specific header. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::title_header("example", &Header::name("x-cache")); /// ``` pub fn title_header(title: &'a str, header: &'a Header<'a>) -> Validate<'a> { Validate::new(None, Some(title), vec![], vec![header]) } /// Create a Validate object to validate the response status code, title and that it /// included a specific header. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::status_title_header(200, "example", &Header::name("x-cache")); /// ``` pub fn status_title_header( status: u16, title: &'a str, header: &'a Header<'a>, ) -> Validate<'a> { Validate::new(Some(status), Some(title), vec![], vec![header]) } /// Create a Validate object to validate the response html contains specific text and that it /// included a specific header. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::text_header("The page has this text", &Header::name("x-cache")); /// ``` pub fn text_header(text: &'a str, header: &'a Header<'a>) -> Validate<'a> { Validate::new(None, None, vec![text], vec![header]) } /// Create a Validate object to validate the response status code, that the resposne html /// contains specific text and that it included a specific header. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::status_text_header(200, "The page has this text", &Header::name("x-cache")); /// ``` pub fn status_text_header(status: u16, text: &'a str, header: &'a Header<'a>) -> Validate<'a> { Validate::new(Some(status), None, vec![text], vec![header]) } /// Create a Validate object to validate the response html title, that it contains /// specific text and that it included a specific header. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::title_text_header("Example", "The page has this text", &Header::name("x-cache")); /// ``` pub fn title_text_header( title: &'a str, text: &'a str, header: &'a Header<'a>, ) -> Validate<'a> { Validate::new(None, Some(title), vec![text], vec![header]) } /// Create a Validate object to validate the response status code, the html title, that it /// contains specific text and that it included a specific header. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::status_title_text_header(200, "Example", "The page has this text", &Header::name("x-cache")); /// ``` pub fn status_title_text_header( status: u16, title: &'a str, text: &'a str, header: &'a Header<'a>, ) -> Validate<'a> { Validate::new(Some(status), Some(title), vec![text], vec![header]) } /// Create a Validate object to validate that the response included multiple specific headers. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::headers(vec![&Header::name("x-cache"), &Header::name("x-generator")]); /// ``` pub fn headers(headers: Vec<&'a Header<'a>>) -> Validate<'a> { Validate::new(None, None, vec![], headers) } /// Create a Validate object to validate the response status code and that it included multiple /// specific headers. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::status_headers(200, vec![&Header::name("x-cache"), &Header::name("x-generator")]); /// ``` pub fn status_headers(status: u16, headers: Vec<&'a Header<'a>>) -> Validate<'a> { Validate::new(Some(status), None, vec![], headers) } /// Create a Validate object to validate the response html title and that it included multiple /// specific headers. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::title_headers("Example", vec![&Header::name("x-cache"), &Header::name("x-generator")]); /// ``` pub fn title_headers(title: &'a str, headers: Vec<&'a Header<'a>>) -> Validate<'a> { Validate::new(None, Some(title), vec![], headers) } /// Create a Validate object to validate the response status code, the html title and that it /// included multiple specific headers. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::status_title_headers(200, "Example", vec![&Header::name("x-cache"), &Header::name("x-generator")]); /// ``` pub fn status_title_headers( status: u16, title: &'a str, headers: Vec<&'a Header<'a>>, ) -> Validate<'a> { Validate::new(Some(status), Some(title), vec![], headers) } /// Create a Validate object to validate the response html contained specific text and that /// the response also included multiple specific headers. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::text_headers("This text is on the page", vec![&Header::name("x-cache"), &Header::name("x-generator")]); /// ``` pub fn text_headers(text: &'a str, headers: Vec<&'a Header<'a>>) -> Validate<'a> { Validate::new(None, None, vec![text], headers) } /// Create a Validate object to validate the response status code, that the html contained /// specific text and that the response also included multiple specific headers. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::status_text_headers(200, "This text is on the page", vec![&Header::name("x-cache"), &Header::name("x-generator")]); /// ``` pub fn status_text_headers( status: u16, text: &'a str, headers: Vec<&'a Header<'a>>, ) -> Validate<'a> { Validate::new(Some(status), None, vec![text], headers) } /// Create a Validate object to validate the response html title, that the html contained /// specific text and that the response also included multiple specific headers. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::title_text_headers("Example", "This text is on the page", vec![&Header::name("x-cache"), &Header::name("x-generator")]); /// ``` pub fn title_text_headers( title: &'a str, text: &'a str, headers: Vec<&'a Header<'a>>, ) -> Validate<'a> { Validate::new(None, Some(title), vec![text], headers) } /// Create a Validate object to validate the response html includes multiple specific texts /// and that the response also included multiple specific headers. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::texts_headers(vec!["This text is on the page", r#"<a href="/foo">and so is this</a>"#], vec![&Header::name("x-cache"), &Header::name("x-generator")]); /// ``` pub fn texts_headers(texts: Vec<&'a str>, headers: Vec<&'a Header<'a>>) -> Validate<'a> { Validate::new(None, None, texts, headers) } /// Create a Validate object to validate the response status code, that html includes /// multiple specific texts and that the response also included multiple specific headers. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::status_texts_headers(200, vec!["This text is on the page", r#"<a href="/foo">and so is this</a>"#], vec![&Header::name("x-cache"), &Header::name("x-generator")]); /// ``` pub fn status_texts_headers( status: u16, texts: Vec<&'a str>, headers: Vec<&'a Header<'a>>, ) -> Validate<'a> { Validate::new(Some(status), None, texts, headers) } /// Create a Validate object to validate the response html title, that html includes /// multiple specific texts and that the response also included multiple specific headers. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::title_texts_headers("Example", vec!["This text is on the page", r#"<a href="/foo">and so is this</a>"#], vec![&Header::name("x-cache"), &Header::name("x-generator")]); /// ``` pub fn title_texts_headers( title: &'a str, texts: Vec<&'a str>, headers: Vec<&'a Header<'a>>, ) -> Validate<'a> { Validate::new(None, Some(title), texts, headers) } /// Create a Validate object to validate the response code, that html includes /// multiple specific texts and that the response also included multiple specific headers. /// /// # Example /// ```rust /// use goose_eggs::{Header, Validate}; /// /// let _validate = Validate::status_title_texts_headers(200, "Example", vec!["This text is on the page", r#"<a href="/foo">and so is this</a>"#], vec![&Header::name("x-cache"), &Header::name("x-generator")]); /// ``` pub fn status_title_texts_headers( status: u16, title: &'a str, texts: Vec<&'a str>, headers: Vec<&'a Header<'a>>, ) -> Validate<'a> { Validate::new(Some(status), Some(title), texts, headers) } } /// Used to validate that headers are included in the server response. /// /// # Example /// ```rust /// use goose_eggs::Header; /// /// fn example() { /// // Validate that the "x-varnish" header is set. /// let _header = Header::name("x-varnish"); /// } #[derive(Clone, Debug)] pub struct Header<'a> { /// The name of the header to validate, required. name: &'a str, /// The value of the header to validate, optional. value: Option<&'a str>, } impl<'a> Header<'a> { /// Create a new Header validation struct by specifying all fields. /// /// # Example /// ```rust /// use goose_eggs::Header; /// /// let _header = Header::new("foo", Some("bar")); /// ``` pub fn new(name: &'a str, value: Option<&'a str>) -> Header<'a> { Header { name, value } } /// Create a Header object to validate that a named header is set. /// /// # Example /// ```rust /// use goose_eggs::Header; /// /// // Create a Header object to validate that the "foo" header is set in the Response. /// let _header = Header::name("foo"); /// ``` pub fn name(name: &'a str) -> Header<'a> { Header::new(name, None) } /// Create a Header object to validate that a named header contains a specific value. /// /// # Example /// ```rust /// use goose_eggs::Header; /// /// // Create a Header object to validate that the "foo" header is set and contains "bar" /// // in the Response. /// let _header = Header::name_value("foo", "bar"); /// ``` pub fn name_value(name: &'a str, value: &'a str) -> Header<'a> { Header::new(name, Some(value)) } } /// Returns a [`bool`] indicating whether or not the title (case insensitive) is /// found within the html. /// /// A valid title starts with `<title>foo` where `foo` is the expected title text. /// Returns [`true`] if the expected title is found, otherwise returns [`false`]. /// /// This function is case insensitive, if a title of "foo" is specified it will /// match "foo" or "Foo" or "FOO". /// /// While you can invoke this function directly, it's generally preferred to invoke /// [`validate_and_load_static_assets`] which in turn invokes this function. /// /// # Example /// ```rust /// use goose::prelude::*; /// use goose_eggs::valid_title; /// /// task!(validate_title).set_on_start(); /// /// async fn validate_title(user: &GooseUser) -> GooseTaskResult { /// let mut goose = user.get("/").await?; /// /// match goose.response { /// Ok(response) => { /// // Copy the headers so we have them for logging if there are errors. /// let headers = &response.headers().clone(); /// match response.text().await { /// Ok(html) => { /// let title = "example"; /// if !valid_title(&html, title) { /// return user.set_failure( /// &format!("{}: title not found: {}", goose.request.raw.url, title), /// &mut goose.request, /// Some(&headers), /// Some(&html), /// ); /// } /// } /// Err(e) => { /// return user.set_failure( /// &format!("{}: failed to parse page: {}", goose.request.raw.url, e), /// &mut goose.request, /// Some(&headers), /// None, /// ); /// } /// } /// } /// Err(e) => { /// return user.set_failure( /// &format!("{}: no response from server: {}", goose.request.raw.url, e), /// &mut goose.request, /// None, /// None, /// ); /// } /// } /// /// Ok(()) /// } /// ``` pub fn valid_title(html: &str, title: &str) -> bool { html.to_ascii_lowercase() .contains(&("<title>".to_string() + title.to_ascii_lowercase().as_str())) } /// Returns a [`bool`] indicating whether or not an arbitrary str (case sensitive) is found /// within the html. /// /// Returns [`true`] if the expected str is found, otherwise returns [`false`]. /// /// This function is case sensitive, if the text "foo" is specified it will only match "foo", /// not "Foo" or "FOO". /// /// While you can invoke this function directly, it's generally preferred to invoke /// [`validate_and_load_static_assets`] which in turn invokes this function. /// /// # Example /// ```rust /// use goose::prelude::*; /// use goose_eggs::valid_text; /// /// task!(validate_text).set_on_start(); /// /// async fn validate_text(user: &GooseUser) -> GooseTaskResult { /// let mut goose = user.get("/").await?; /// /// match goose.response { /// Ok(response) => { /// // Copy the headers so we have them for logging if there are errors. /// let headers = &response.headers().clone(); /// match response.text().await { /// Ok(html) => { /// let text = r#"<code class="language-console">$ cargo new hello_world --bin"#; /// if !valid_text(&html, text) { /// return user.set_failure( /// &format!("{}: text not found: {}", goose.request.raw.url, text), /// &mut goose.request, /// Some(&headers), /// Some(&html), /// ); /// } /// } /// Err(e) => { /// return user.set_failure( /// &format!("{}: failed to parse page: {}", goose.request.raw.url, e), /// &mut goose.request, /// Some(&headers), /// None, /// ); /// } /// } /// } /// Err(e) => { /// return user.set_failure( /// &format!("{}: no response from server: {}", goose.request.raw.url, e), /// &mut goose.request, /// None, /// None, /// ); /// } /// } /// /// Ok(()) /// } /// ``` pub fn valid_text(html: &str, text: &str) -> bool { html.contains(text) } /// Returns a [`bool`] indicating whether or not a header was set in the server Response. /// /// Returns [`true`] if the expected header was set, otherwise returns [`false`]. /// /// While you can invoke this function directly, it's generally preferred to invoke /// [`validate_and_load_static_assets`] which in turn invokes this function. /// /// # Example /// ```rust /// use goose::prelude::*; /// use goose_eggs::{header_is_set, Header}; /// /// task!(validate_header).set_on_start(); /// /// async fn validate_header(user: &GooseUser) -> GooseTaskResult { /// let mut goose = user.get("/").await?; /// /// match goose.response { /// Ok(response) => { /// // Copy the headers so we have them for logging if there are errors. /// let headers = &response.headers().clone(); /// if !header_is_set(headers, &Header::name("server")) { /// return user.set_failure( /// &format!("{}: header not found: {}", goose.request.raw.url, "server"), /// &mut goose.request, /// Some(&headers), /// None, /// ); /// } /// } /// Err(e) => { /// return user.set_failure( /// &format!("{}: no response from server: {}", goose.request.raw.url, e), /// &mut goose.request, /// None, /// None, /// ); /// } /// } /// /// Ok(()) /// } /// ``` pub fn header_is_set(headers: &HeaderMap, header: &Header) -> bool { headers.contains_key(header.name) } /// Returns a [`bool`] indicating whether or not a header contains an expected value. /// /// Returns [`true`] if the expected value was found, otherwise returns [`false`]. /// /// While you can invoke this function directly, it's generally preferred to invoke /// [`validate_and_load_static_assets`] which in turn invokes this function. /// /// # Example /// ```rust /// use goose::prelude::*; /// use goose_eggs::{valid_header_value, Header}; /// /// task!(validate_header_value).set_on_start(); /// /// async fn validate_header_value(user: &GooseUser) -> GooseTaskResult { /// let mut goose = user.get("/").await?; /// /// match goose.response { /// Ok(response) => { /// // Copy the headers so we have them for logging if there are errors. /// let headers = &response.headers().clone(); /// if !valid_header_value(headers, &Header::name_value("server", "nginx")) { /// return user.set_failure( /// &format!("{}: server header value not correct: {}", goose.request.raw.url, "nginx"), /// &mut goose.request, /// Some(&headers), /// None, /// ); /// } /// } /// Err(e) => { /// return user.set_failure( /// &format!("{}: no response from server: {}", goose.request.raw.url, e), /// &mut goose.request, /// None, /// None, /// ); /// } /// } /// /// Ok(()) /// } /// ``` pub fn valid_header_value(headers: &HeaderMap, header: &Header) -> bool { if header_is_set(headers, header) { if let Some(value_to_validate) = header.value { let header_value = match headers.get(header.name) { // Extract the value of the header and try to convert to a &str. Some(v) => v.to_str().unwrap_or(""), None => "", }; // Check if the desired value is in the header. if header_value.contains(value_to_validate) { true } else { // Provide some extra debug. info!( r#"header does not contain expected value: "{}: {}""#, header.name, header_value ); false } } else { false } } else { info!("header ({}) not set", header.name); false } } /// Extract and load all local static elements from the the provided html. /// /// While you can invoke this function directly, it's generally preferred to invoke /// [`validate_and_load_static_assets`] which in turn invokes this function. /// /// # Example /// ```rust /// use goose::prelude::*; /// use goose_eggs::load_static_elements; /// /// task!(load_page_and_static_elements).set_on_start(); /// /// async fn load_page_and_static_elements(user: &GooseUser) -> GooseTaskResult { /// let mut goose = user.get("/").await?; /// /// match goose.response { /// Ok(response) => { /// // Copy the headers so we have them for logging if there are errors. /// let headers = &response.headers().clone(); /// match response.text().await { /// Ok(html) => { /// // Load all static elements on page. /// load_static_elements(user, &html).await; /// } /// Err(e) => { /// return user.set_failure( /// &format!("{}: failed to parse page: {}", goose.request.raw.url, e), /// &mut goose.request, /// Some(&headers), /// None, /// ); /// } /// } /// } /// Err(e) => { /// return user.set_failure( /// &format!("{}: no response from server: {}", goose.request.raw.url, e), /// &mut goose.request, /// None, /// None, /// ); /// } /// } /// /// Ok(()) /// } /// ``` pub async fn load_static_elements(user: &GooseUser, html: &str) { // Use a regular expression to find all src=<foo> in the HTML, where foo // is the URL to image and js assets. // @TODO: parse HTML5 srcset= also let image = Regex::new(r#"src="(.*?)""#).unwrap(); let mut urls = Vec::new(); for url in image.captures_iter(&html) { if url[1].starts_with("/sites") || url[1].starts_with("/core") { urls.push(url[1].to_string()); } } // Use a regular expression to find all href=<foo> in the HTML, where foo // is the URL to css assets. let css = Regex::new(r#"href="(/sites/default/files/css/.*?)""#).unwrap(); for url in css.captures_iter(&html) { urls.push(url[1].to_string()); } // Load all the static assets found on the page. for asset in &urls { let _ = user.get_named(asset, "static asset").await; } } /// Validate the HTML response then extract and load all static elements on the page. /// /// What is validated is defined with the [`Validate`] structure. /// /// # Example /// ```rust /// use goose::prelude::*; /// use goose_eggs::{validate_and_load_static_assets, Validate}; /// /// task!(load_page).set_on_start(); /// /// async fn load_page(user: &GooseUser) -> GooseTaskResult { /// let mut goose = user.get("/").await?; /// validate_and_load_static_assets( /// user, /// goose, /// // Validate title and other arbitrary text on the response html. /// &Validate::title_texts("my page", vec!["foo", r#"<a href="bar">"#]), /// ).await?; /// /// Ok(()) /// } /// ``` pub async fn validate_and_load_static_assets<'a>( user: &GooseUser, mut goose: GooseResponse, validate: &'a Validate<'a>, ) -> GooseTaskResult { match goose.response { Ok(response) => { // Copy the headers so we have them for logging if there are errors. let headers = &response.headers().clone(); let response_status = response.status(); match response.text().await { Ok(html) => { // Validate status code if defined. if let Some(status) = validate.status { if response_status != status { return user.set_failure( &format!( "{}: response status != {}]: {}", goose.request.raw.url, status, response_status ), &mut goose.request, Some(&headers), Some(&html), ); } } // Validate title if defined. if let Some(title) = validate.title { if !valid_title(&html, &title) { return user.set_failure( &format!("{}: title not found: {}", goose.request.raw.url, title), &mut goose.request, Some(&headers), Some(&html), ); } } // Validate texts in body if defined. for text in &validate.texts { if !valid_text(&html, text) { return user.set_failure( &format!( "{}: text not found on page: {}", goose.request.raw.url, text ), &mut goose.request, Some(&headers), Some(&html), ); } } // Validate headers if defined. for header in &validate.headers { if !header_is_set(headers, header) { return user.set_failure( &format!( "{}: header not included in response: {:?}", goose.request.raw.url, header ), &mut goose.request, Some(&headers), Some(&html), ); } if let Some(h) = header.value { if !valid_header_value(headers, header) { return user.set_failure( &format!( "{}: header does not contain expected value: {:?}", goose.request.raw.url, h ), &mut goose.request, Some(&headers), Some(&html), ); } } } load_static_elements(user, &html).await; } Err(e) => { return user.set_failure( &format!("{}: failed to parse page: {}", goose.request.raw.url, e), &mut goose.request, Some(&headers), None, ); } } } Err(e) => { return user.set_failure( &format!("{}: no response from server: {}", goose.request.raw.url, e), &mut goose.request, None, None, ); } } Ok(()) }