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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
// Copyright (c) 2018-2022 Brendan Molloy <brendan@bbqsrc.net>,
// Ilya Solovyiov <ilya.solovyiov@gmail.com>,
// Kai Ren <tyranron@gmail.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Top-level [Cucumber] executor.
//!
//! [Cucumber]: https://cucumber.io
use std::{
borrow::Cow,
fmt::{Debug, Formatter},
marker::PhantomData,
mem,
path::Path,
time::Duration,
};
use futures::{future::LocalBoxFuture, StreamExt as _};
use gherkin::tagexpr::TagOperation;
use regex::Regex;
use crate::{
cli, event, parser,
runner::{self, basic::RetryOptions},
step,
tag::Ext as _,
writer, Event, Parser, Runner, ScenarioType, Step, World, Writer,
WriterExt as _,
};
/// Top-level [Cucumber] executor.
///
/// Most of the time you don't need to work with it directly, just use
/// [`World::run()`] or [`World::cucumber()`] on your [`World`] deriver to get
/// [Cucumber] up and running.
///
/// Otherwise use [`Cucumber::new()`] to get the default [Cucumber] executor,
/// provide [`Step`]s with [`World::collection()`] or by hand with
/// [`Cucumber::given()`], [`Cucumber::when()`] and [`Cucumber::then()`].
///
/// In case you want a custom [`Parser`], [`Runner`] or [`Writer`], or some
/// other finer control, use [`Cucumber::custom()`] or
/// [`Cucumber::with_parser()`], [`Cucumber::with_runner()`] and
/// [`Cucumber::with_writer()`] to construct your dream [Cucumber] executor!
///
/// [Cucumber]: https://cucumber.io
pub struct Cucumber<W, P, I, R, Wr, Cli = cli::Empty>
where
W: World,
P: Parser<I>,
R: Runner<W>,
Wr: Writer<W>,
Cli: clap::Args,
{
/// [`Parser`] sourcing [`Feature`]s for execution.
///
/// [`Feature`]: gherkin::Feature
parser: P,
/// [`Runner`] executing [`Scenario`]s and producing [`event`]s.
///
/// [`Scenario`]: gherkin::Scenario
runner: R,
/// [`Writer`] outputting [`event`]s to some output.
writer: Wr,
/// CLI options this [`Cucumber`] has been run with.
///
/// If empty, then will be parsed from a command line.
#[allow(clippy::type_complexity)] // not really
cli: Option<cli::Opts<P::Cli, R::Cli, Wr::Cli, Cli>>,
/// Type of the [`World`] this [`Cucumber`] run on.
_world: PhantomData<W>,
/// Type of the input consumed by [`Cucumber::parser`].
_parser_input: PhantomData<I>,
}
impl<W, P, I, R, Wr, Cli> Cucumber<W, P, I, R, Wr, Cli>
where
W: World,
P: Parser<I>,
R: Runner<W>,
Wr: Writer<W>,
Cli: clap::Args,
{
/// Creates a custom [`Cucumber`] executor with the provided [`Parser`],
/// [`Runner`] and [`Writer`].
#[must_use]
pub const fn custom(parser: P, runner: R, writer: Wr) -> Self {
Self {
parser,
runner,
writer,
cli: None,
_world: PhantomData,
_parser_input: PhantomData,
}
}
/// Replaces [`Parser`].
#[allow(clippy::missing_const_for_fn)] // false positive: drop in const
#[must_use]
pub fn with_parser<NewP, NewI>(
self,
parser: NewP,
) -> Cucumber<W, NewP, NewI, R, Wr, Cli>
where
NewP: Parser<NewI>,
{
let Self { runner, writer, .. } = self;
Cucumber {
parser,
runner,
writer,
cli: None,
_world: PhantomData,
_parser_input: PhantomData,
}
}
/// Replaces [`Runner`].
#[allow(clippy::missing_const_for_fn)] // false positive: drop in const
#[must_use]
pub fn with_runner<NewR>(
self,
runner: NewR,
) -> Cucumber<W, P, I, NewR, Wr, Cli>
where
NewR: Runner<W>,
{
let Self { parser, writer, .. } = self;
Cucumber {
parser,
runner,
writer,
cli: None,
_world: PhantomData,
_parser_input: PhantomData,
}
}
/// Replaces [`Writer`].
#[allow(clippy::missing_const_for_fn)] // false positive: drop in const
#[must_use]
pub fn with_writer<NewWr>(
self,
writer: NewWr,
) -> Cucumber<W, P, I, R, NewWr, Cli>
where
NewWr: Writer<W>,
{
let Self { parser, runner, .. } = self;
Cucumber {
parser,
runner,
writer,
cli: None,
_world: PhantomData,
_parser_input: PhantomData,
}
}
/// Re-outputs [`Skipped`] steps for easier navigation.
///
/// # Example
///
/// Output with a regular [`Cucumber::run()`]:
/// <script
/// id="asciicast-0d92qlT8Mbc4WXyvRbHJmjsqN"
/// src="https://asciinema.org/a/0d92qlT8Mbc4WXyvRbHJmjsqN.js"
/// async data-autoplay="true" data-rows="17">
/// </script>
///
/// Adjust [`Cucumber`] to re-output all the [`Skipped`] steps at the end:
/// ```rust
/// # use cucumber::World;
/// #
/// # #[derive(Debug, Default, World)]
/// # struct MyWorld;
/// #
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// MyWorld::cucumber()
/// .repeat_skipped()
/// .run_and_exit("tests/features/readme")
/// .await;
/// # }
/// ```
/// <script
/// id="asciicast-ox14HynkBIw8atpfhyfvKrsO3"
/// src="https://asciinema.org/a/ox14HynkBIw8atpfhyfvKrsO3.js"
/// async data-autoplay="true" data-rows="19">
/// </script>
///
/// [`Scenario`]: gherkin::Scenario
/// [`Skipped`]: crate::event::Step::Skipped
#[must_use]
pub fn repeat_skipped(
self,
) -> Cucumber<W, P, I, R, writer::Repeat<W, Wr>, Cli>
where
Wr: writer::NonTransforming,
{
Cucumber {
parser: self.parser,
runner: self.runner,
writer: self.writer.repeat_skipped(),
cli: self.cli,
_world: PhantomData,
_parser_input: PhantomData,
}
}
/// Re-outputs [`Failed`] steps for easier navigation.
///
/// # Example
///
/// Output with a regular [`Cucumber::fail_on_skipped()`]:
/// ```rust,should_panic
/// # use cucumber::World;
/// #
/// # #[derive(Debug, Default, World)]
/// # struct MyWorld;
/// #
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// MyWorld::cucumber()
/// .fail_on_skipped()
/// .run_and_exit("tests/features/readme")
/// .await;
/// # }
/// ```
/// <script
/// id="asciicast-UcipuopO6IFEsIDty6vaJlCH9"
/// src="https://asciinema.org/a/UcipuopO6IFEsIDty6vaJlCH9.js"
/// async data-autoplay="true" data-rows="21">
/// </script>
///
/// Adjust [`Cucumber`] to re-output all the [`Failed`] steps at the end:
/// ```rust,should_panic
/// # use cucumber::World;
/// #
/// # #[derive(Debug, Default, World)]
/// # struct MyWorld;
/// #
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// MyWorld::cucumber()
/// .repeat_failed()
/// .fail_on_skipped()
/// .run_and_exit("tests/features/readme")
/// .await;
/// # }
/// ```
/// <script
/// id="asciicast-ofOljvyEMb41OTLhE081QKv68"
/// src="https://asciinema.org/a/ofOljvyEMb41OTLhE081QKv68.js"
/// async data-autoplay="true" data-rows="24">
/// </script>
///
/// [`Failed`]: crate::event::Step::Failed
#[must_use]
pub fn repeat_failed(
self,
) -> Cucumber<W, P, I, R, writer::Repeat<W, Wr>, Cli>
where
Wr: writer::NonTransforming,
{
Cucumber {
parser: self.parser,
runner: self.runner,
writer: self.writer.repeat_failed(),
cli: self.cli,
_world: PhantomData,
_parser_input: PhantomData,
}
}
/// Re-outputs steps by the given `filter` predicate.
///
/// # Example
///
/// Output with a regular [`Cucumber::fail_on_skipped()`]:
/// ```rust,should_panic
/// # use cucumber::World;
/// # use futures::FutureExt as _;
/// #
/// # #[derive(Debug, Default, World)]
/// # struct MyWorld;
/// #
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// MyWorld::cucumber()
/// .fail_on_skipped()
/// .run_and_exit("tests/features/readme")
/// .await;
/// # }
/// ```
/// <script
/// id="asciicast-UcipuopO6IFEsIDty6vaJlCH9"
/// src="https://asciinema.org/a/UcipuopO6IFEsIDty6vaJlCH9.js"
/// async data-autoplay="true" data-rows="21">
/// </script>
///
/// Adjust [`Cucumber`] to re-output all the [`Failed`] steps ta the end by
/// providing a custom `filter` predicate:
/// ```rust,should_panic
/// # use cucumber::World;
/// #
/// # #[derive(Debug, Default, World)]
/// # struct MyWorld;
/// #
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// MyWorld::cucumber()
/// .repeat_if(|ev| {
/// use cucumber::event::{
/// Cucumber, Feature, RetryableScenario, Rule, Scenario, Step,
/// };
///
/// matches!(
/// ev.as_deref(),
/// Ok(Cucumber::Feature(
/// _,
/// Feature::Rule(
/// _,
/// Rule::Scenario(
/// _,
/// RetryableScenario {
/// event: Scenario::Step(_, Step::Failed(..))
/// | Scenario::Background(
/// _,
/// Step::Failed(_, _, _, _),
/// ),
/// retries: _
/// }
/// )
/// ) | Feature::Scenario(
/// _,
/// RetryableScenario {
/// event: Scenario::Step(_, Step::Failed(..))
/// | Scenario::Background(_, Step::Failed(..)),
/// retries: _
/// }
/// )
/// )) | Err(_)
/// )
/// })
/// .fail_on_skipped()
/// .run_and_exit("tests/features/readme")
/// .await;
/// # }
/// ```
/// <script
/// id="asciicast-ofOljvyEMb41OTLhE081QKv68"
/// src="https://asciinema.org/a/ofOljvyEMb41OTLhE081QKv68.js"
/// async data-autoplay="true" data-rows="24">
/// </script>
///
/// [`Failed`]: crate::event::Step::Failed
#[must_use]
pub fn repeat_if<F>(
self,
filter: F,
) -> Cucumber<W, P, I, R, writer::Repeat<W, Wr, F>, Cli>
where
F: Fn(&parser::Result<Event<event::Cucumber<W>>>) -> bool,
Wr: writer::NonTransforming,
{
Cucumber {
parser: self.parser,
runner: self.runner,
writer: self.writer.repeat_if(filter),
cli: self.cli,
_world: PhantomData,
_parser_input: PhantomData,
}
}
/// Consider [`Skipped`] [`Background`] or regular [`Step`]s as [`Failed`]
/// if their [`Scenario`] isn't marked with `@allow.skipped` tag.
///
/// It's useful option for ensuring that all the steps were covered.
///
/// # Example
///
/// Output with a regular [`Cucumber::run()`]:
/// <script
/// id="asciicast-0d92qlT8Mbc4WXyvRbHJmjsqN"
/// src="https://asciinema.org/a/0d92qlT8Mbc4WXyvRbHJmjsqN.js"
/// async data-autoplay="true" data-rows="17">
/// </script>
///
/// To fail all the [`Skipped`] steps setup [`Cucumber`] like this:
/// ```rust,should_panic
/// # use cucumber::World;
/// #
/// # #[derive(Debug, Default, World)]
/// # struct MyWorld;
/// #
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// MyWorld::cucumber()
/// .fail_on_skipped()
/// .run_and_exit("tests/features/readme")
/// .await;
/// # }
/// ```
/// <script
/// id="asciicast-IHLxMEgku9BtBVkR4k2DtOjMd"
/// src="https://asciinema.org/a/IHLxMEgku9BtBVkR4k2DtOjMd.js"
/// async data-autoplay="true" data-rows="21">
/// </script>
///
/// To intentionally suppress some [`Skipped`] steps failing, use the
/// `@allow.skipped` tag:
/// ```gherkin
/// Feature: Animal feature
///
/// Scenario: If we feed a hungry cat it will no longer be hungry
/// Given a hungry cat
/// When I feed the cat
/// Then the cat is not hungry
///
/// @allow.skipped
/// Scenario: If we feed a satiated dog it will not become hungry
/// Given a satiated dog
/// When I feed the dog
/// Then the dog is not hungry
/// ```
///
/// [`Background`]: gherkin::Background
/// [`Failed`]: crate::event::Step::Failed
/// [`Scenario`]: gherkin::Scenario
/// [`Skipped`]: crate::event::Step::Skipped
/// [`Step`]: gherkin::Step
#[must_use]
pub fn fail_on_skipped(
self,
) -> Cucumber<W, P, I, R, writer::FailOnSkipped<Wr>, Cli> {
Cucumber {
parser: self.parser,
runner: self.runner,
writer: self.writer.fail_on_skipped(),
cli: self.cli,
_world: PhantomData,
_parser_input: PhantomData,
}
}
/// Consider [`Skipped`] [`Background`] or regular [`Step`]s as [`Failed`]
/// if the given `filter` predicate returns `true`.
///
/// # Example
///
/// Output with a regular [`Cucumber::run()`]:
/// <script
/// id="asciicast-0d92qlT8Mbc4WXyvRbHJmjsqN"
/// src="https://asciinema.org/a/0d92qlT8Mbc4WXyvRbHJmjsqN.js"
/// async data-autoplay="true" data-rows="17">
/// </script>
///
/// Adjust [`Cucumber`] to fail on all [`Skipped`] steps, but the ones
/// marked with a `@dog` tag:
/// ```rust,should_panic
/// # use cucumber::World;
/// #
/// # #[derive(Debug, Default, World)]
/// # struct MyWorld;
/// #
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// MyWorld::cucumber()
/// .fail_on_skipped_with(|_, _, s| !s.tags.iter().any(|t| t == "dog"))
/// .run_and_exit("tests/features/readme")
/// .await;
/// # }
/// ```
/// ```gherkin
/// Feature: Animal feature
///
/// Scenario: If we feed a hungry cat it will no longer be hungry
/// Given a hungry cat
/// When I feed the cat
/// Then the cat is not hungry
///
/// Scenario: If we feed a satiated dog it will not become hungry
/// Given a satiated dog
/// When I feed the dog
/// Then the dog is not hungry
/// ```
/// <script
/// id="asciicast-IHLxMEgku9BtBVkR4k2DtOjMd"
/// src="https://asciinema.org/a/IHLxMEgku9BtBVkR4k2DtOjMd.js"
/// async data-autoplay="true" data-rows="21">
/// </script>
///
/// And to avoid failing, use the `@dog` tag:
/// ```gherkin
/// Feature: Animal feature
///
/// Scenario: If we feed a hungry cat it will no longer be hungry
/// Given a hungry cat
/// When I feed the cat
/// Then the cat is not hungry
///
/// @dog
/// Scenario: If we feed a satiated dog it will not become hungry
/// Given a satiated dog
/// When I feed the dog
/// Then the dog is not hungry
/// ```
///
/// [`Background`]: gherkin::Background
/// [`Failed`]: crate::event::Step::Failed
/// [`Scenario`]: gherkin::Scenario
/// [`Skipped`]: crate::event::Step::Skipped
/// [`Step`]: gherkin::Step
#[must_use]
pub fn fail_on_skipped_with<Filter>(
self,
filter: Filter,
) -> Cucumber<W, P, I, R, writer::FailOnSkipped<Wr, Filter>, Cli>
where
Filter: Fn(
&gherkin::Feature,
Option<&gherkin::Rule>,
&gherkin::Scenario,
) -> bool,
{
Cucumber {
parser: self.parser,
runner: self.runner,
writer: self.writer.fail_on_skipped_with(filter),
cli: self.cli,
_world: PhantomData,
_parser_input: PhantomData,
}
}
}
impl<W, P, I, R, Wr, Cli> Cucumber<W, P, I, R, Wr, Cli>
where
W: World,
P: Parser<I>,
R: Runner<W>,
Wr: Writer<W> + writer::Normalized,
Cli: clap::Args,
{
/// Runs [`Cucumber`].
///
/// [`Feature`]s sourced from a [`Parser`] are fed to a [`Runner`], which
/// produces events handled by a [`Writer`].
///
/// [`Feature`]: gherkin::Feature
pub async fn run(self, input: I) -> Wr {
self.filter_run(input, |_, _, _| true).await
}
/// Consumes already parsed [`cli::Opts`].
///
/// This method allows to pre-parse [`cli::Opts`] for custom needs before
/// using them inside [`Cucumber`].
///
/// Also, any additional custom CLI options may be specified as a
/// [`clap::Args`] deriving type, used as the last type parameter of
/// [`cli::Opts`].
///
/// > ⚠️ __WARNING__: Any CLI options of [`Parser`], [`Runner`], [`Writer`]
/// or custom ones should not overlap, otherwise
/// [`cli::Opts`] will fail to parse on startup.
///
/// # Example
///
/// ```rust
/// # use std::time::Duration;
/// #
/// # use cucumber::{cli, World};
/// # use futures::FutureExt as _;
/// # use tokio::time;
/// #
/// # #[derive(Debug, Default, World)]
/// # struct MyWorld;
/// #
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// #[derive(clap::Args)]
/// struct CustomCli {
/// /// Additional time to wait in a before hook.
/// #[clap(
/// long,
/// parse(try_from_str = humantime::parse_duration)
/// )]
/// before_time: Option<Duration>,
/// }
///
/// let cli = cli::Opts::<_, _, _, CustomCli>::parsed();
/// let time = cli.custom.before_time.unwrap_or_default();
///
/// MyWorld::cucumber()
/// .before(move |_, _, _, _| time::sleep(time).boxed_local())
/// .with_cli(cli)
/// .run_and_exit("tests/features/readme")
/// .await;
/// # }
/// ```
/// ```gherkin
/// Feature: Animal feature
///
/// Scenario: If we feed a hungry cat it will no longer be hungry
/// Given a hungry cat
/// When I feed the cat
/// Then the cat is not hungry
/// ```
/// <script
/// id="asciicast-0KvTxnfaMRjsvsIKsalS611Ta"
/// src="https://asciinema.org/a/0KvTxnfaMRjsvsIKsalS611Ta.js"
/// async data-autoplay="true" data-rows="14">
/// </script>
///
/// Also, specifying `--help` flag will describe `--before-time` now.
///
/// [`Feature`]: gherkin::Feature
#[allow(clippy::missing_const_for_fn)] // false positive: drop in const
pub fn with_cli<CustomCli>(
self,
cli: cli::Opts<P::Cli, R::Cli, Wr::Cli, CustomCli>,
) -> Cucumber<W, P, I, R, Wr, CustomCli>
where
CustomCli: clap::Args,
{
let Self {
parser,
runner,
writer,
..
} = self;
Cucumber {
parser,
runner,
writer,
cli: Some(cli),
_world: PhantomData,
_parser_input: PhantomData,
}
}
/// Runs [`Cucumber`] with [`Scenario`]s filter.
///
/// [`Feature`]s sourced from a [`Parser`] are fed to a [`Runner`], which
/// produces events handled by a [`Writer`].
///
/// # Example
///
/// Adjust [`Cucumber`] to run only [`Scenario`]s marked with `@cat` tag:
/// ```rust
/// # use cucumber::World;
/// #
/// # #[derive(Debug, Default, World)]
/// # struct MyWorld;
/// #
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// MyWorld::cucumber()
/// .filter_run("tests/features/readme", |_, _, sc| {
/// sc.tags.iter().any(|t| t == "cat")
/// })
/// .await;
/// # }
/// ```
/// ```gherkin
/// Feature: Animal feature
///
/// @cat
/// Scenario: If we feed a hungry cat it will no longer be hungry
/// Given a hungry cat
/// When I feed the cat
/// Then the cat is not hungry
///
/// @dog
/// Scenario: If we feed a satiated dog it will not become hungry
/// Given a satiated dog
/// When I feed the dog
/// Then the dog is not hungry
/// ```
/// <script
/// id="asciicast-0KvTxnfaMRjsvsIKsalS611Ta"
/// src="https://asciinema.org/a/0KvTxnfaMRjsvsIKsalS611Ta.js"
/// async data-autoplay="true" data-rows="14">
/// </script>
///
/// [`Feature`]: gherkin::Feature
/// [`Scenario`]: gherkin::Scenario
pub async fn filter_run<F>(self, input: I, filter: F) -> Wr
where
F: Fn(
&gherkin::Feature,
Option<&gherkin::Rule>,
&gherkin::Scenario,
) -> bool
+ 'static,
{
let cli::Opts {
re_filter,
tags_filter,
parser: parser_cli,
runner: runner_cli,
writer: writer_cli,
..
} = self.cli.unwrap_or_else(cli::Opts::<_, _, _, _>::parsed);
let filter = move |feat: &gherkin::Feature,
rule: Option<&gherkin::Rule>,
scenario: &gherkin::Scenario| {
re_filter.as_ref().map_or_else(
|| {
tags_filter.as_ref().map_or_else(
|| filter(feat, rule, scenario),
|tags| {
// The order `Feature` -> `Rule` -> `Scenario`
// matters here.
tags.eval(
feat.tags
.iter()
.chain(
rule.into_iter()
.flat_map(|r| r.tags.iter()),
)
.chain(scenario.tags.iter()),
)
},
)
},
|re| re.is_match(&scenario.name),
)
};
let Self {
parser,
runner,
mut writer,
..
} = self;
let features = parser.parse(input, parser_cli);
let filtered = features.map(move |feature| {
let mut feature = feature?;
let feat_scenarios = mem::take(&mut feature.scenarios);
feature.scenarios = feat_scenarios
.into_iter()
.filter(|s| filter(&feature, None, s))
.collect();
let mut rules = mem::take(&mut feature.rules);
for r in &mut rules {
let rule_scenarios = mem::take(&mut r.scenarios);
r.scenarios = rule_scenarios
.into_iter()
.filter(|s| filter(&feature, Some(r), s))
.collect();
}
feature.rules = rules;
Ok(feature)
});
let events_stream = runner.run(filtered, runner_cli);
futures::pin_mut!(events_stream);
while let Some(ev) = events_stream.next().await {
writer.handle_event(ev, &writer_cli).await;
}
writer
}
}
impl<W, P, I, R, Wr, Cli> Debug for Cucumber<W, P, I, R, Wr, Cli>
where
W: World,
P: Debug + Parser<I>,
R: Debug + Runner<W>,
Wr: Debug + Writer<W>,
Cli: clap::Args,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Cucumber")
.field("parser", &self.parser)
.field("runner", &self.runner)
.field("writer", &self.writer)
.finish()
}
}
/// Shortcut for the [`Cucumber`] type returned by its [`Default`] impl.
pub(crate) type DefaultCucumber<W, I> = Cucumber<
W,
parser::Basic,
I,
runner::Basic<W>,
writer::Summarize<writer::Normalize<W, writer::Basic>>,
>;
impl<W, I> Default for DefaultCucumber<W, I>
where
W: World + Debug,
I: AsRef<Path>,
{
fn default() -> Self {
Self::custom(
parser::Basic::new(),
runner::Basic::default(),
writer::Basic::stdout().summarized(),
)
}
}
impl<W, I> DefaultCucumber<W, I>
where
W: World + Debug,
I: AsRef<Path>,
{
/// Creates a default [`Cucumber`] executor.
///
/// * [`Parser`] — [`parser::Basic`]
///
/// * [`Runner`] — [`runner::Basic`]
/// * [`ScenarioType`] — [`Concurrent`] by default, [`Serial`] if
/// `@serial` [tag] is present on a [`Scenario`];
/// * Allowed to run up to 64 [`Concurrent`] [`Scenario`]s.
///
/// * [`Writer`] — [`Normalize`] and [`Summarize`] [`writer::Basic`].
///
/// [`Concurrent`]: runner::basic::ScenarioType::Concurrent
/// [`Normalize`]: writer::Normalize
/// [`Parser`]: parser::Parser
/// [`Scenario`]: gherkin::Scenario
/// [`Serial`]: runner::basic::ScenarioType::Serial
/// [`ScenarioType`]: runner::basic::ScenarioType
/// [`Summarize`]: writer::Summarize
///
/// [tag]: https://cucumber.io/docs/cucumber/api/#tags
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
impl<W, I, R, Wr, Cli> Cucumber<W, parser::Basic, I, R, Wr, Cli>
where
W: World,
R: Runner<W>,
Wr: Writer<W>,
Cli: clap::Args,
I: AsRef<Path>,
{
/// Sets the provided language of [`gherkin`] files.
///
/// # Errors
///
/// If the provided language isn't supported.
pub fn language(
mut self,
name: impl Into<Cow<'static, str>>,
) -> Result<Self, parser::basic::UnsupportedLanguageError> {
self.parser = self.parser.language(name)?;
Ok(self)
}
}
impl<W, I, P, Wr, F, B, A, Cli>
Cucumber<W, P, I, runner::Basic<W, F, B, A>, Wr, Cli>
where
W: World,
P: Parser<I>,
Wr: Writer<W>,
Cli: clap::Args,
F: Fn(
&gherkin::Feature,
Option<&gherkin::Rule>,
&gherkin::Scenario,
) -> ScenarioType
+ 'static,
B: for<'a> Fn(
&'a gherkin::Feature,
Option<&'a gherkin::Rule>,
&'a gherkin::Scenario,
&'a mut W,
) -> LocalBoxFuture<'a, ()>
+ 'static,
A: for<'a> Fn(
&'a gherkin::Feature,
Option<&'a gherkin::Rule>,
&'a gherkin::Scenario,
Option<&'a mut W>,
) -> LocalBoxFuture<'a, ()>
+ 'static,
{
/// If `max` is [`Some`] number of concurrently executed [`Scenario`]s will
/// be limited.
///
/// [`Scenario`]: gherkin::Scenario
#[must_use]
pub fn max_concurrent_scenarios(
mut self,
max: impl Into<Option<usize>>,
) -> Self {
self.runner = self.runner.max_concurrent_scenarios(max);
self
}
/// Makes failed [`Scenario`]s being retried the specified number of times.
///
/// [`Scenario`]: gherkin::Scenario
#[must_use]
pub fn retries(mut self, retries: impl Into<Option<usize>>) -> Self {
self.runner = self.runner.retries(retries);
self
}
/// Makes failed [`Scenario`]s being retried after the specified
/// [`Duration`] passes.
///
/// [`Scenario`]: gherkin::Scenario
#[must_use]
pub fn retry_after(mut self, after: impl Into<Option<Duration>>) -> Self {
self.runner = self.runner.retry_after(after);
self
}
/// Makes failed [`Scenario`]s being retried only if they're matching the
/// specified `tag_expression`.
///
/// [`Scenario`]: gherkin::Scenario
#[must_use]
pub fn retry_filter(
mut self,
tag_expression: impl Into<Option<TagOperation>>,
) -> Self {
self.runner = self.runner.retry_filter(tag_expression);
self
}
/// Function determining whether a [`Scenario`] is [`Concurrent`] or
/// a [`Serial`] one.
///
/// [`Concurrent`]: ScenarioType::Concurrent
/// [`Serial`]: ScenarioType::Serial
/// [`Scenario`]: gherkin::Scenario
#[must_use]
pub fn which_scenario<Which>(
self,
func: Which,
) -> Cucumber<W, P, I, runner::Basic<W, Which, B, A>, Wr, Cli>
where
Which: Fn(
&gherkin::Feature,
Option<&gherkin::Rule>,
&gherkin::Scenario,
) -> ScenarioType
+ 'static,
{
let Self {
parser,
runner,
writer,
cli,
..
} = self;
Cucumber {
parser,
runner: runner.which_scenario(func),
writer,
cli,
_world: PhantomData,
_parser_input: PhantomData,
}
}
/// Function determining [`Scenario`]'s [`RetryOptions`].
///
/// [`Scenario`]: gherkin::Scenario
#[must_use]
pub fn retry_options<Retry>(mut self, func: Retry) -> Self
where
Retry: Fn(
&gherkin::Feature,
Option<&gherkin::Rule>,
&gherkin::Scenario,
&runner::basic::Cli,
) -> Option<RetryOptions>
+ 'static,
{
self.runner = self.runner.retry_options(func);
self
}
/// Sets a hook, executed on each [`Scenario`] before running all its
/// [`Step`]s, including [`Background`] ones.
///
/// [`Background`]: gherkin::Background
/// [`Scenario`]: gherkin::Scenario
/// [`Step`]: gherkin::Step
#[must_use]
pub fn before<Before>(
self,
func: Before,
) -> Cucumber<W, P, I, runner::Basic<W, F, Before, A>, Wr, Cli>
where
Before: for<'a> Fn(
&'a gherkin::Feature,
Option<&'a gherkin::Rule>,
&'a gherkin::Scenario,
&'a mut W,
) -> LocalBoxFuture<'a, ()>
+ 'static,
{
let Self {
parser,
runner,
writer,
cli,
..
} = self;
Cucumber {
parser,
runner: runner.before(func),
writer,
cli,
_world: PhantomData,
_parser_input: PhantomData,
}
}
/// Sets a hook, executed on each [`Scenario`] after running all its
/// [`Step`]s, even after [`Skipped`] of [`Failed`] [`Step`]s.
///
/// Last `World` argument is supplied to the function, in case it was
/// initialized before by running [`before`] hook or any [`Step`].
///
/// [`before`]: Self::before()
/// [`Failed`]: event::Step::Failed
/// [`Scenario`]: gherkin::Scenario
/// [`Skipped`]: event::Step::Skipped
/// [`Step`]: gherkin::Step
#[must_use]
pub fn after<After>(
self,
func: After,
) -> Cucumber<W, P, I, runner::Basic<W, F, B, After>, Wr, Cli>
where
After: for<'a> Fn(
&'a gherkin::Feature,
Option<&'a gherkin::Rule>,
&'a gherkin::Scenario,
Option<&'a mut W>,
) -> LocalBoxFuture<'a, ()>
+ 'static,
{
let Self {
parser,
runner,
writer,
cli,
..
} = self;
Cucumber {
parser,
runner: runner.after(func),
writer,
cli,
_world: PhantomData,
_parser_input: PhantomData,
}
}
/// Replaces [`Collection`] of [`Step`]s.
///
/// [`Collection`]: step::Collection
/// [`Step`]: step::Step
#[must_use]
pub fn steps(mut self, steps: step::Collection<W>) -> Self {
self.runner = self.runner.steps(steps);
self
}
/// Inserts [Given] [`Step`].
///
/// [Given]: https://cucumber.io/docs/gherkin/reference/#given
#[must_use]
pub fn given(mut self, regex: Regex, step: Step<W>) -> Self {
self.runner = self.runner.given(regex, step);
self
}
/// Inserts [When] [`Step`].
///
/// [When]: https://cucumber.io/docs/gherkin/reference/#When
#[must_use]
pub fn when(mut self, regex: Regex, step: Step<W>) -> Self {
self.runner = self.runner.when(regex, step);
self
}
/// Inserts [Then] [`Step`].
///
/// [Then]: https://cucumber.io/docs/gherkin/reference/#then
#[must_use]
pub fn then(mut self, regex: Regex, step: Step<W>) -> Self {
self.runner = self.runner.then(regex, step);
self
}
}
impl<W, I, P, R, Wr, Cli> Cucumber<W, P, I, R, Wr, Cli>
where
W: World,
P: Parser<I>,
R: Runner<W>,
Wr: writer::Stats<W> + writer::Normalized,
Cli: clap::Args,
{
/// Runs [`Cucumber`].
///
/// [`Feature`]s sourced from a [`Parser`] are fed to a [`Runner`], which
/// produces events handled by a [`Writer`].
///
/// # Panics
///
/// If encountered errors while parsing [`Feature`]s or at least one
/// [`Step`] [`Failed`].
///
/// [`Failed`]: crate::event::Step::Failed
/// [`Feature`]: gherkin::Feature
/// [`Step`]: gherkin::Step
pub async fn run_and_exit(self, input: I) {
self.filter_run_and_exit(input, |_, _, _| true).await;
}
/// Runs [`Cucumber`] with [`Scenario`]s filter.
///
/// [`Feature`]s sourced from a [`Parser`] are fed to a [`Runner`], which
/// produces events handled by a [`Writer`].
///
/// # Panics
///
/// If encountered errors while parsing [`Feature`]s or at least one
/// [`Step`] [`Failed`].
///
/// # Example
///
/// Adjust [`Cucumber`] to run only [`Scenario`]s marked with `@cat` tag:
/// ```rust
/// # use cucumber::World;
/// #
/// # #[derive(Debug, Default, World)]
/// # struct MyWorld;
/// #
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// MyWorld::cucumber()
/// .filter_run_and_exit("tests/features/readme", |_, _, sc| {
/// sc.tags.iter().any(|t| t == "cat")
/// })
/// .await;
/// # }
/// ```
/// ```gherkin
/// Feature: Animal feature
///
/// @cat
/// Scenario: If we feed a hungry cat it will no longer be hungry
/// Given a hungry cat
/// When I feed the cat
/// Then the cat is not hungry
///
/// @dog
/// Scenario: If we feed a satiated dog it will not become hungry
/// Given a satiated dog
/// When I feed the dog
/// Then the dog is not hungry
/// ```
/// <script
/// id="asciicast-0KvTxnfaMRjsvsIKsalS611Ta"
/// src="https://asciinema.org/a/0KvTxnfaMRjsvsIKsalS611Ta.js"
/// async data-autoplay="true" data-rows="14">
/// </script>
///
/// [`Failed`]: crate::event::Step::Failed
/// [`Feature`]: gherkin::Feature
/// [`Scenario`]: gherkin::Scenario
/// [`Step`]: crate::Step
pub async fn filter_run_and_exit<Filter>(self, input: I, filter: Filter)
where
Filter: Fn(
&gherkin::Feature,
Option<&gherkin::Rule>,
&gherkin::Scenario,
) -> bool
+ 'static,
{
let writer = self.filter_run(input, filter).await;
if writer.execution_has_failed() {
let mut msg = Vec::with_capacity(3);
let failed_steps = writer.failed_steps();
if failed_steps > 0 {
msg.push(format!(
"{failed_steps} step{} failed",
(failed_steps > 1).then_some("s").unwrap_or_default(),
));
}
let parsing_errors = writer.parsing_errors();
if parsing_errors > 0 {
msg.push(format!(
"{parsing_errors} parsing error{}",
(parsing_errors > 1).then_some("s").unwrap_or_default(),
));
}
let hook_errors = writer.hook_errors();
if hook_errors > 0 {
msg.push(format!(
"{hook_errors} hook error{}",
(hook_errors > 1).then_some("s").unwrap_or_default(),
));
}
panic!("{}", msg.join(", "));
}
}
}