-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathbasic.rs
3732 lines (3475 loc) · 116 KB
/
basic.rs
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
// Copyright (c) 2018-2025 Brendan Molloy <[email protected]>,
// Ilya Solovyiov <[email protected]>,
// Kai Ren <[email protected]>
//
// 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.
//! Default [`Runner`] implementation.
use std::{
any::Any,
cmp,
collections::HashMap,
fmt, iter, mem,
ops::ControlFlow,
panic::{self, AssertUnwindSafe},
sync::{
atomic::{AtomicBool, AtomicU64, Ordering},
Arc,
},
thread,
time::{Duration, Instant},
};
#[cfg(feature = "tracing")]
use crossbeam_utils::atomic::AtomicCell;
use derive_more::{Display, FromStr};
use drain_filter_polyfill::VecExt;
use futures::{
channel::{mpsc, oneshot},
future::{self, Either, LocalBoxFuture},
lock::Mutex,
pin_mut,
stream::{self, LocalBoxStream},
FutureExt as _, Stream, StreamExt as _, TryFutureExt as _,
TryStreamExt as _,
};
use gherkin::tagexpr::TagOperation;
use itertools::Itertools as _;
use regex::{CaptureLocations, Regex};
#[cfg(feature = "tracing")]
use crate::tracing::{Collector as TracingCollector, SpanCloseWaiter};
use crate::{
event::{self, HookType, Info, Retries, Source},
feature::Ext as _,
future::{select_with_biased_first, FutureExt as _},
parser, step,
tag::Ext as _,
Event, Runner, Step, World,
};
/// CLI options of a [`Basic`] [`Runner`].
#[derive(clap::Args, Clone, Debug, Default)]
#[group(skip)]
pub struct Cli {
/// Number of scenarios to run concurrently. If not specified, uses the
/// value configured in tests runner, or 64 by default.
#[arg(long, short, value_name = "int", global = true)]
pub concurrency: Option<usize>,
/// Run tests until the first failure.
#[arg(long, global = true, visible_alias = "ff")]
pub fail_fast: bool,
/// Number of times a scenario will be retried in case of a failure.
#[arg(long, value_name = "int", global = true)]
pub retry: Option<usize>,
/// Delay between each scenario retry attempt.
///
/// Duration is represented in a human-readable format like `12min5s`.
/// Supported suffixes:
/// - `nsec`, `ns` — nanoseconds.
/// - `usec`, `us` — microseconds.
/// - `msec`, `ms` — milliseconds.
/// - `seconds`, `second`, `sec`, `s` - seconds.
/// - `minutes`, `minute`, `min`, `m` - minutes.
#[arg(
long,
value_name = "duration",
value_parser = humantime::parse_duration,
verbatim_doc_comment,
global = true,
)]
pub retry_after: Option<Duration>,
/// Tag expression to filter retried scenarios.
#[arg(long, value_name = "tagexpr", global = true)]
pub retry_tag_filter: Option<TagOperation>,
}
/// Type determining whether [`Scenario`]s should run concurrently or
/// sequentially.
///
/// [`Scenario`]: gherkin::Scenario
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ScenarioType {
/// Run [`Scenario`]s sequentially (one-by-one).
///
/// [`Scenario`]: gherkin::Scenario
Serial,
/// Run [`Scenario`]s concurrently.
///
/// [`Scenario`]: gherkin::Scenario
Concurrent,
}
/// Options for retrying [`Scenario`]s.
///
/// [`Scenario`]: gherkin::Scenario
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RetryOptions {
/// Number of [`Retries`].
pub retries: Retries,
/// Delay before next retry attempt will be executed.
pub after: Option<Duration>,
}
impl RetryOptions {
/// Returns [`Some`], in case next retry attempt is available, or [`None`]
/// otherwise.
#[must_use]
pub fn next_try(self) -> Option<Self> {
self.retries.next_try().map(|num| Self {
retries: num,
after: self.after,
})
}
/// Parses [`RetryOptions`] from [`Feature`]'s, [`Rule`]'s, [`Scenario`]'s
/// tags and [`Cli`] options.
///
/// [`Feature`]: gherkin::Feature
/// [`Rule`]: gherkin::Rule
/// [`Scenario`]: gherkin::Scenario
#[must_use]
pub fn parse_from_tags(
feature: &gherkin::Feature,
rule: Option<&gherkin::Rule>,
scenario: &gherkin::Scenario,
cli: &Cli,
) -> Option<Self> {
#[expect(clippy::shadow_unrelated, reason = "actually related")]
let parse_tags = |tags: &[String]| {
tags.iter().find_map(|tag| {
tag.strip_prefix("retry").map(|retries| {
let (num, rest) = retries
.strip_prefix('(')
.and_then(|s| {
s.split_once(')').and_then(|(num, rest)| {
num.parse::<usize>()
.ok()
.map(|num| (Some(num), rest))
})
})
.unwrap_or((None, retries));
let after = rest.strip_prefix(".after").and_then(|after| {
after.strip_prefix('(').and_then(|after| {
let (dur, _) = after.split_once(')')?;
humantime::parse_duration(dur).ok()
})
});
(num, after)
})
})
};
let apply_cli = |options: Option<_>| {
let matched = cli.retry_tag_filter.as_ref().map_or_else(
|| cli.retry.is_some() || cli.retry_after.is_some(),
|op| {
op.eval(scenario.tags.iter().chain(
rule.iter().flat_map(|r| &r.tags).chain(&feature.tags),
))
},
);
(options.is_some() || matched).then(|| Self {
retries: Retries::initial(
options.and_then(|(r, _)| r).or(cli.retry).unwrap_or(1),
),
after: options.and_then(|(_, a)| a).or(cli.retry_after),
})
};
apply_cli(
parse_tags(&scenario.tags)
.or_else(|| rule.and_then(|r| parse_tags(&r.tags)))
.or_else(|| parse_tags(&feature.tags)),
)
}
/// Constructs [`RetryOptionsWithDeadline`], that will reschedule
/// [`Scenario`] [`after`] delay.
///
/// [`after`]: RetryOptions::after
/// [`Scenario`]: gherkin::Scenario
fn with_deadline(self, now: Instant) -> RetryOptionsWithDeadline {
RetryOptionsWithDeadline {
retries: self.retries,
after: self.after.map(|at| (at, Some(now))),
}
}
/// Constructs [`RetryOptionsWithDeadline`], that will reschedule
/// [`Scenario`] immediately, ignoring [`RetryOptions::after`]. Used for
/// initial [`Scenario`] run, where we don't need to wait for the delay.
///
/// [`Scenario`]: gherkin::Scenario
fn without_deadline(self) -> RetryOptionsWithDeadline {
RetryOptionsWithDeadline {
retries: self.retries,
after: self.after.map(|at| (at, None)),
}
}
}
/// [`RetryOptions`] with an [`Option`]al [`Instant`] to determine, whether
/// [`Scenario`] should be already rescheduled or not.
///
/// [`Scenario`]: gherkin::Scenario
#[derive(Clone, Copy, Debug)]
pub struct RetryOptionsWithDeadline {
/// Number of [`Retries`].
pub retries: Retries,
/// Delay before next retry attempt will be executed.
pub after: Option<(Duration, Option<Instant>)>,
}
impl From<RetryOptionsWithDeadline> for RetryOptions {
fn from(v: RetryOptionsWithDeadline) -> Self {
Self {
retries: v.retries,
after: v.after.map(|(at, _)| at),
}
}
}
impl RetryOptionsWithDeadline {
/// Returns [`Duration`] after which a [`Scenario`] could be retried. If
/// [`None`], then [`Scenario`] is ready for the retry.
///
/// [`Scenario`]: gherkin::Scenario
fn left_until_retry(&self) -> Option<Duration> {
let (dur, instant) = self.after?;
dur.checked_sub(instant?.elapsed())
}
}
/// Alias for [`fn`] used to determine whether a [`Scenario`] is [`Concurrent`]
/// or a [`Serial`] one.
///
/// [`Concurrent`]: ScenarioType::Concurrent
/// [`Serial`]: ScenarioType::Serial
/// [`Scenario`]: gherkin::Scenario
pub type WhichScenarioFn = fn(
&gherkin::Feature,
Option<&gherkin::Rule>,
&gherkin::Scenario,
) -> ScenarioType;
/// Alias for [`Arc`]ed [`Fn`] used to determine [`Scenario`]'s
/// [`RetryOptions`].
///
/// [`Scenario`]: gherkin::Scenario
pub type RetryOptionsFn = Arc<
dyn Fn(
&gherkin::Feature,
Option<&gherkin::Rule>,
&gherkin::Scenario,
&Cli,
) -> Option<RetryOptions>,
>;
/// Alias for [`fn`] executed on each [`Scenario`] before running all [`Step`]s.
///
/// [`Scenario`]: gherkin::Scenario
/// [`Step`]: gherkin::Step
pub type BeforeHookFn<World> = for<'a> fn(
&'a gherkin::Feature,
Option<&'a gherkin::Rule>,
&'a gherkin::Scenario,
&'a mut World,
) -> LocalBoxFuture<'a, ()>;
/// Alias for [`fn`] executed on each [`Scenario`] after running all [`Step`]s.
///
/// [`Scenario`]: gherkin::Scenario
/// [`Step`]: gherkin::Step
pub type AfterHookFn<World> = for<'a> fn(
&'a gherkin::Feature,
Option<&'a gherkin::Rule>,
&'a gherkin::Scenario,
&'a event::ScenarioFinished,
Option<&'a mut World>,
) -> LocalBoxFuture<'a, ()>;
/// Alias for a failed [`Scenario`].
///
/// [`Scenario`]: gherkin::Scenario
type IsFailed = bool;
/// Alias for a retried [`Scenario`].
///
/// [`Scenario`]: gherkin::Scenario
type IsRetried = bool;
/// Default [`Runner`] implementation which follows [_order guarantees_][1] from
/// the [`Runner`] trait docs.
///
/// Executes [`Scenario`]s concurrently based on the custom function, which
/// returns [`ScenarioType`]. Also, can limit maximum number of concurrent
/// [`Scenario`]s.
///
/// [1]: Runner#order-guarantees
/// [`Scenario`]: gherkin::Scenario
pub struct Basic<
World,
F = WhichScenarioFn,
Before = BeforeHookFn<World>,
After = AfterHookFn<World>,
> {
/// Optional number of concurrently executed [`Scenario`]s.
///
/// [`Scenario`]: gherkin::Scenario
max_concurrent_scenarios: Option<usize>,
/// Optional number of retries of failed [`Scenario`]s.
///
/// [`Scenario`]: gherkin::Scenario
retries: Option<usize>,
/// Optional [`Duration`] between retries of failed [`Scenario`]s.
///
/// [`Scenario`]: gherkin::Scenario
retry_after: Option<Duration>,
/// Optional [`TagOperation`] filter for retries of failed [`Scenario`]s.
///
/// [`Scenario`]: gherkin::Scenario
retry_filter: Option<TagOperation>,
/// [`Collection`] of functions to match [`Step`]s.
///
/// [`Collection`]: step::Collection
steps: step::Collection<World>,
/// Function determining whether a [`Scenario`] is [`Concurrent`] or
/// a [`Serial`] one.
///
/// [`Concurrent`]: ScenarioType::Concurrent
/// [`Serial`]: ScenarioType::Serial
/// [`Scenario`]: gherkin::Scenario
which_scenario: F,
/// Function determining [`Scenario`]'s [`RetryOptions`].
///
/// [`Scenario`]: gherkin::Scenario
retry_options: RetryOptionsFn,
/// Function, executed on each [`Scenario`] before running all [`Step`]s,
/// including [`Background`] ones.
///
/// [`Background`]: gherkin::Background
/// [`Scenario`]: gherkin::Scenario
/// [`Step`]: gherkin::Step
before_hook: Option<Before>,
/// Function, executed on each [`Scenario`] after running all [`Step`]s.
///
/// [`Background`]: gherkin::Background
/// [`Scenario`]: gherkin::Scenario
/// [`Step`]: gherkin::Step
after_hook: Option<After>,
/// Indicates whether execution should be stopped after the first failure.
fail_fast: bool,
#[cfg(feature = "tracing")]
/// [`TracingCollector`] for [`event::Scenario::Log`]s forwarding.
pub(crate) logs_collector: Arc<AtomicCell<Box<Option<TracingCollector>>>>,
}
#[cfg(feature = "tracing")]
/// Assertion that [`Basic::logs_collector`] [`AtomicCell::is_lock_free`].
const _: () = {
assert!(
AtomicCell::<Box<Option<TracingCollector>>>::is_lock_free(),
"`AtomicCell::<Box<Option<TracingCollector>>>` is not lock-free",
);
};
// Implemented manually to omit redundant `World: Clone` trait bound, imposed by
// `#[derive(Clone)]`.
impl<World, F: Clone, B: Clone, A: Clone> Clone for Basic<World, F, B, A> {
fn clone(&self) -> Self {
Self {
max_concurrent_scenarios: self.max_concurrent_scenarios,
retries: self.retries,
retry_after: self.retry_after,
retry_filter: self.retry_filter.clone(),
steps: self.steps.clone(),
which_scenario: self.which_scenario.clone(),
retry_options: Arc::clone(&self.retry_options),
before_hook: self.before_hook.clone(),
after_hook: self.after_hook.clone(),
fail_fast: self.fail_fast,
#[cfg(feature = "tracing")]
logs_collector: Arc::clone(&self.logs_collector),
}
}
}
// Implemented manually to omit redundant trait bounds on `World` and to omit
// outputting `F`.
impl<World, F, B, A> fmt::Debug for Basic<World, F, B, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Basic")
.field("max_concurrent_scenarios", &self.max_concurrent_scenarios)
.field("retries", &self.retries)
.field("retry_after", &self.retry_after)
.field("retry_filter", &self.retry_filter)
.field("steps", &self.steps)
.field("fail_fast", &self.fail_fast)
.finish_non_exhaustive()
}
}
impl<World> Default for Basic<World> {
fn default() -> Self {
let which_scenario: WhichScenarioFn = |feature, rule, scenario| {
scenario
.tags
.iter()
.chain(rule.iter().flat_map(|r| &r.tags))
.chain(&feature.tags)
.find(|tag| *tag == "serial")
.map_or(ScenarioType::Concurrent, |_| ScenarioType::Serial)
};
Self {
max_concurrent_scenarios: Some(64),
retries: None,
retry_after: None,
retry_filter: None,
steps: step::Collection::new(),
which_scenario,
retry_options: Arc::new(RetryOptions::parse_from_tags),
before_hook: None,
after_hook: None,
fail_fast: false,
#[cfg(feature = "tracing")]
logs_collector: Arc::new(AtomicCell::new(Box::new(None))),
}
}
}
impl<World, Which, Before, After> Basic<World, Which, Before, After> {
/// If `max` is [`Some`], then 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.max_concurrent_scenarios = max.into();
self
}
/// If `retries` is [`Some`], then failed [`Scenario`]s will be retried
/// specified number of times.
///
/// [`Scenario`]: gherkin::Scenario
#[must_use]
pub fn retries(mut self, retries: impl Into<Option<usize>>) -> Self {
self.retries = retries.into();
self
}
/// If `after` is [`Some`], then failed [`Scenario`]s will be retried after
/// the specified [`Duration`].
///
/// [`Scenario`]: gherkin::Scenario
#[must_use]
pub fn retry_after(mut self, after: impl Into<Option<Duration>>) -> Self {
self.retry_after = after.into();
self
}
/// If `filter` is [`Some`], then failed [`Scenario`]s will be 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.retry_filter = tag_expression.into();
self
}
/// Makes stop running tests on the first failure.
///
/// __NOTE__: All the already started [`Scenario`]s at the moment of failure
/// will be finished.
///
/// __NOTE__: Retried [`Scenario`]s are considered as failed, only in case
/// they exhaust all retry attempts and still fail.
///
/// [`Scenario`]: gherkin::Scenario
#[must_use]
pub const fn fail_fast(mut self) -> Self {
self.fail_fast = true;
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<F>(self, func: F) -> Basic<World, F, Before, After>
where
F: Fn(
&gherkin::Feature,
Option<&gherkin::Rule>,
&gherkin::Scenario,
) -> ScenarioType
+ 'static,
{
let Self {
max_concurrent_scenarios,
retries,
retry_after,
retry_filter,
steps,
retry_options,
before_hook,
after_hook,
fail_fast,
#[cfg(feature = "tracing")]
logs_collector,
..
} = self;
Basic {
max_concurrent_scenarios,
retries,
retry_after,
retry_filter,
steps,
which_scenario: func,
retry_options,
before_hook,
after_hook,
fail_fast,
#[cfg(feature = "tracing")]
logs_collector,
}
}
/// Function determining [`Scenario`]'s [`RetryOptions`].
///
/// [`Scenario`]: gherkin::Scenario
#[must_use]
pub fn retry_options<R>(mut self, func: R) -> Self
where
R: Fn(
&gherkin::Feature,
Option<&gherkin::Rule>,
&gherkin::Scenario,
&Cli,
) -> Option<RetryOptions>
+ 'static,
{
self.retry_options = Arc::new(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<Func>(self, func: Func) -> Basic<World, Which, Func, After>
where
Func: for<'a> Fn(
&'a gherkin::Feature,
Option<&'a gherkin::Rule>,
&'a gherkin::Scenario,
&'a mut World,
) -> LocalBoxFuture<'a, ()>,
{
let Self {
max_concurrent_scenarios,
retries,
retry_after,
retry_filter,
steps,
which_scenario,
retry_options,
after_hook,
fail_fast,
#[cfg(feature = "tracing")]
logs_collector,
..
} = self;
Basic {
max_concurrent_scenarios,
retries,
retry_after,
retry_filter,
steps,
which_scenario,
retry_options,
before_hook: Some(func),
after_hook,
fail_fast,
#[cfg(feature = "tracing")]
logs_collector,
}
}
/// Sets hook, executed on each [`Scenario`] after running all its
/// [`Step`]s, even after [`Skipped`] of [`Failed`] ones.
///
/// 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<Func>(self, func: Func) -> Basic<World, Which, Before, Func>
where
Func: for<'a> Fn(
&'a gherkin::Feature,
Option<&'a gherkin::Rule>,
&'a gherkin::Scenario,
&'a event::ScenarioFinished,
Option<&'a mut World>,
) -> LocalBoxFuture<'a, ()>,
{
let Self {
max_concurrent_scenarios,
retries,
retry_after,
retry_filter,
steps,
which_scenario,
retry_options,
before_hook,
fail_fast,
#[cfg(feature = "tracing")]
logs_collector,
..
} = self;
Basic {
max_concurrent_scenarios,
retries,
retry_after,
retry_filter,
steps,
which_scenario,
retry_options,
before_hook,
after_hook: Some(func),
fail_fast,
#[cfg(feature = "tracing")]
logs_collector,
}
}
/// Sets the given [`Collection`] of [`Step`]s to this [`Runner`].
///
/// [`Collection`]: step::Collection
#[must_use]
pub fn steps(mut self, steps: step::Collection<World>) -> Self {
self.steps = steps;
self
}
/// Adds a [Given] [`Step`] matching the given `regex`.
///
/// [Given]: https://cucumber.io/docs/gherkin/reference#given
#[must_use]
pub fn given(mut self, regex: Regex, step: Step<World>) -> Self {
self.steps = mem::take(&mut self.steps).given(None, regex, step);
self
}
/// Adds a [When] [`Step`] matching the given `regex`.
///
/// [When]: https://cucumber.io/docs/gherkin/reference#given
#[must_use]
pub fn when(mut self, regex: Regex, step: Step<World>) -> Self {
self.steps = mem::take(&mut self.steps).when(None, regex, step);
self
}
/// Adds a [Then] [`Step`] matching the given `regex`.
///
/// [Then]: https://cucumber.io/docs/gherkin/reference#then
#[must_use]
pub fn then(mut self, regex: Regex, step: Step<World>) -> Self {
self.steps = mem::take(&mut self.steps).then(None, regex, step);
self
}
}
impl<W, Which, Before, After> Runner<W> for Basic<W, Which, Before, After>
where
W: World,
Which: Fn(
&gherkin::Feature,
Option<&gherkin::Rule>,
&gherkin::Scenario,
) -> ScenarioType
+ 'static,
Before: for<'a> Fn(
&'a gherkin::Feature,
Option<&'a gherkin::Rule>,
&'a gherkin::Scenario,
&'a mut W,
) -> LocalBoxFuture<'a, ()>
+ 'static,
After: for<'a> Fn(
&'a gherkin::Feature,
Option<&'a gherkin::Rule>,
&'a gherkin::Scenario,
&'a event::ScenarioFinished,
Option<&'a mut W>,
) -> LocalBoxFuture<'a, ()>
+ 'static,
{
type Cli = Cli;
type EventStream =
LocalBoxStream<'static, parser::Result<Event<event::Cucumber<W>>>>;
fn run<S>(self, features: S, mut cli: Cli) -> Self::EventStream
where
S: Stream<Item = parser::Result<gherkin::Feature>> + 'static,
{
#[cfg(feature = "tracing")]
let logs_collector = *self.logs_collector.swap(Box::new(None));
let Self {
max_concurrent_scenarios,
retries,
retry_after,
retry_filter,
steps,
which_scenario,
retry_options,
before_hook,
after_hook,
fail_fast,
..
} = self;
cli.retry = cli.retry.or(retries);
cli.retry_after = cli.retry_after.or(retry_after);
cli.retry_tag_filter = cli.retry_tag_filter.or(retry_filter);
let fail_fast = cli.fail_fast || fail_fast;
let concurrency = cli.concurrency.or(max_concurrent_scenarios);
let buffer = Features::default();
let (sender, receiver) = mpsc::unbounded();
let insert = insert_features(
buffer.clone(),
features,
which_scenario,
retry_options,
sender.clone(),
cli,
fail_fast,
);
let execute = execute(
buffer,
concurrency,
steps,
sender,
before_hook,
after_hook,
fail_fast,
#[cfg(feature = "tracing")]
logs_collector,
);
stream::select(
receiver.map(Either::Left),
future::join(insert, execute)
.into_stream()
.map(Either::Right),
)
.filter_map(|r| async {
match r {
Either::Left(ev) => Some(ev),
Either::Right(_) => None,
}
})
.boxed_local()
}
}
/// Stores [`Feature`]s for later use by [`execute()`].
///
/// [`Feature`]: gherkin::Feature
async fn insert_features<W, S, F>(
into: Features,
features_stream: S,
which_scenario: F,
retries: RetryOptionsFn,
sender: mpsc::UnboundedSender<parser::Result<Event<event::Cucumber<W>>>>,
cli: Cli,
fail_fast: bool,
) where
S: Stream<Item = parser::Result<gherkin::Feature>> + 'static,
F: Fn(
&gherkin::Feature,
Option<&gherkin::Rule>,
&gherkin::Scenario,
) -> ScenarioType
+ 'static,
{
let mut features = 0;
let mut rules = 0;
let mut scenarios = 0;
let mut steps = 0;
let mut parser_errors = 0;
pin_mut!(features_stream);
while let Some(feat) = features_stream.next().await {
match feat {
Ok(f) => {
features += 1;
rules += f.rules.len();
scenarios += f.count_scenarios();
steps += f.count_steps();
into.insert(f, &which_scenario, &retries, &cli).await;
}
Err(e) => {
parser_errors += 1;
// If the receiver end is dropped, then no one listens for the
// events, so we can just stop from here.
if sender.unbounded_send(Err(e)).is_err() || fail_fast {
break;
}
}
}
}
drop(sender.unbounded_send(Ok(Event::new(
event::Cucumber::ParsingFinished {
features,
rules,
scenarios,
steps,
parser_errors,
},
))));
into.finish();
}
/// Retrieves [`Feature`]s and executes them.
///
/// # Events
///
/// - [`Scenario`] events are emitted by [`Executor`].
/// - If [`Scenario`] was first or last for particular [`Rule`] or [`Feature`],
/// emits starting or finishing events for them.
///
/// [`Feature`]: gherkin::Feature
/// [`Rule`]: gherkin::Rule
/// [`Scenario`]: gherkin::Scenario
// TODO: Needs refactoring.
#[expect(clippy::too_many_lines, reason = "needs refactoring")]
#[cfg_attr(
feature = "tracing",
expect(clippy::too_many_arguments, reason = "needs refactoring")
)]
async fn execute<W, Before, After>(
features: Features,
max_concurrent_scenarios: Option<usize>,
collection: step::Collection<W>,
event_sender: mpsc::UnboundedSender<
parser::Result<Event<event::Cucumber<W>>>,
>,
before_hook: Option<Before>,
after_hook: Option<After>,
fail_fast: bool,
#[cfg(feature = "tracing")] mut logs_collector: Option<TracingCollector>,
) where
W: World,
Before: 'static
+ for<'a> Fn(
&'a gherkin::Feature,
Option<&'a gherkin::Rule>,
&'a gherkin::Scenario,
&'a mut W,
) -> LocalBoxFuture<'a, ()>,
After: 'static
+ for<'a> Fn(
&'a gherkin::Feature,
Option<&'a gherkin::Rule>,
&'a gherkin::Scenario,
&'a event::ScenarioFinished,
Option<&'a mut W>,
) -> LocalBoxFuture<'a, ()>,
{
// Those panic hook shenanigans are done to avoid console messages like
// "thread 'main' panicked at ..."
//
// 1. We obtain the current panic hook and replace it with an empty one.
// 2. We run tests, which can panic. In that case we pass all panic info
// down the line to the Writer, which will print it at a right time.
// 3. We restore original panic hook, because suppressing all panics doesn't
// sound like a very good idea.
let hook = panic::take_hook();
panic::set_hook(Box::new(|_| {}));
let (finished_sender, finished_receiver) = mpsc::unbounded();
let mut storage = FinishedRulesAndFeatures::new(finished_receiver);
let executor = Executor::new(
collection,
before_hook,
after_hook,
event_sender,
finished_sender,
features.clone(),
);
executor.send_event(event::Cucumber::Started);
#[cfg(feature = "tracing")]
let waiter = logs_collector
.as_ref()
.map(TracingCollector::scenario_span_event_waiter);
let mut started_scenarios = ControlFlow::Continue(max_concurrent_scenarios);
let mut run_scenarios = stream::FuturesUnordered::new();
loop {
let (runnable, sleep) = features
.get(started_scenarios.continue_value().unwrap_or(Some(0)))
.await;
if run_scenarios.is_empty() && runnable.is_empty() {
if features.is_finished(started_scenarios.is_break()).await {
break;
}
// To avoid busy-polling of `Features::get()`, in case there are no
// scenarios that are running or scheduled for execution, we spawn a
// thread, that sleeps for minimal deadline of all retried
// scenarios.
// TODO: Replace `thread::spawn` with async runtime agnostic sleep,
// once it's available.
if let Some(dur) = sleep {
let (sender, receiver) = oneshot::channel();
drop(thread::spawn(move || {
thread::sleep(dur);
sender.send(())
}));
_ = receiver.await.ok();
}
continue;
}
let started = storage.start_scenarios(&runnable);
executor.send_all_events(started);
{
#[cfg(feature = "tracing")]
let forward_logs = {
if let Some(coll) = logs_collector.as_mut() {
coll.start_scenarios(&runnable);
}
async {
#[expect( // intentional