-
Notifications
You must be signed in to change notification settings - Fork 903
/
fixture.rs
983 lines (926 loc) · 27.3 KB
/
fixture.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
use std::fmt;
use ruff_diagnostics::{AlwaysAutofixableViolation, Violation};
use ruff_diagnostics::{Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::call_path::collect_call_path;
use ruff_python_ast::identifier::Identifier;
use ruff_python_ast::visitor;
use ruff_python_ast::visitor::Visitor;
use ruff_python_ast::Decorator;
use ruff_python_ast::{self as ast, Expr, ParameterWithDefault, Parameters, Stmt};
use ruff_python_semantic::analyze::visibility::is_abstract;
use ruff_python_semantic::SemanticModel;
use ruff_text_size::Ranged;
use ruff_text_size::{TextLen, TextRange};
use crate::autofix::edits;
use crate::checkers::ast::Checker;
use crate::registry::{AsRule, Rule};
use super::helpers::{
get_mark_decorators, is_pytest_fixture, is_pytest_yield_fixture, keyword_is_literal,
};
/// ## What it does
/// Checks for argument-free `@pytest.fixture()` decorators with or without
/// parentheses, depending on the `flake8-pytest-style.fixture-parentheses`
/// setting.
///
/// ## Why is this bad?
/// If a `@pytext.fixture()` doesn't take any arguments, the parentheses are
/// optional.
///
/// Either removing those unnecessary parentheses _or_ requiring them for all
/// fixtures is fine, but it's best to be consistent.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.fixture
/// def my_fixture():
/// ...
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def my_fixture():
/// ...
/// ```
///
/// ## Options
/// - `flake8-pytest-style.fixture-parentheses`
///
/// ## References
/// - [`pytest` documentation: API Reference: Fixtures](https://docs.pytest.org/en/latest/reference/reference.html#fixtures-api)
#[violation]
pub struct PytestFixtureIncorrectParenthesesStyle {
expected: Parentheses,
actual: Parentheses,
}
impl AlwaysAutofixableViolation for PytestFixtureIncorrectParenthesesStyle {
#[derive_message_formats]
fn message(&self) -> String {
let PytestFixtureIncorrectParenthesesStyle { expected, actual } = self;
format!("Use `@pytest.fixture{expected}` over `@pytest.fixture{actual}`")
}
fn autofix_title(&self) -> String {
let PytestFixtureIncorrectParenthesesStyle { expected, .. } = self;
match expected {
Parentheses::None => "Remove parentheses".to_string(),
Parentheses::Empty => "Add parentheses".to_string(),
}
}
}
/// ## What it does
/// Checks for `pytest.fixture` calls with positional arguments.
///
/// ## Why is this bad?
/// For clarity and consistency, prefer using keyword arguments to specify
/// fixture configuration.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.fixture("module")
/// def my_fixture():
/// ...
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.fixture(scope="module")
/// def my_fixture():
/// ...
/// ```
///
/// ## References
/// - [`pytest` documentation: `@pytest.fixture` functions](https://docs.pytest.org/en/latest/reference/reference.html#pytest-fixture)
#[violation]
pub struct PytestFixturePositionalArgs {
function: String,
}
impl Violation for PytestFixturePositionalArgs {
#[derive_message_formats]
fn message(&self) -> String {
let PytestFixturePositionalArgs { function } = self;
format!("Configuration for fixture `{function}` specified via positional args, use kwargs")
}
}
/// ## What it does
/// Checks for `pytest.fixture` calls with `scope="function"`.
///
/// ## Why is this bad?
/// `scope="function"` can be omitted, as it is the default.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.fixture(scope="function")
/// def my_fixture():
/// ...
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def my_fixture():
/// ...
/// ```
///
/// ## References
/// - [`pytest` documentation: `@pytest.fixture` functions](https://docs.pytest.org/en/latest/reference/reference.html#pytest-fixture)
#[violation]
pub struct PytestExtraneousScopeFunction;
impl AlwaysAutofixableViolation for PytestExtraneousScopeFunction {
#[derive_message_formats]
fn message(&self) -> String {
format!("`scope='function'` is implied in `@pytest.fixture()`")
}
fn autofix_title(&self) -> String {
"Remove implied `scope` argument".to_string()
}
}
/// ## What it does
/// Checks for `pytest` fixtures that do not return a value, but are not named
/// with a leading underscore.
///
/// ## Why is this bad?
/// By convention, fixtures that don't return a value should be named with a
/// leading underscore, while fixtures that do return a value should not.
///
/// This rule ignores abstract fixtures and generators.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def patch_something(mocker):
/// mocker.patch("module.object")
///
///
/// @pytest.fixture()
/// def use_context():
/// with create_context():
/// yield
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def _patch_something(mocker):
/// mocker.patch("module.object")
///
///
/// @pytest.fixture()
/// def _use_context():
/// with create_context():
/// yield
/// ```
///
/// ## References
/// - [`pytest` documentation: `@pytest.fixture` functions](https://docs.pytest.org/en/latest/reference/reference.html#pytest-fixture)
#[violation]
pub struct PytestMissingFixtureNameUnderscore {
function: String,
}
impl Violation for PytestMissingFixtureNameUnderscore {
#[derive_message_formats]
fn message(&self) -> String {
let PytestMissingFixtureNameUnderscore { function } = self;
format!("Fixture `{function}` does not return anything, add leading underscore")
}
}
/// ## What it does
/// Checks for `pytest` fixtures that return a value, but are named with a
/// leading underscore.
///
/// ## Why is this bad?
/// By convention, fixtures that don't return a value should be named with a
/// leading underscore, while fixtures that do return a value should not.
///
/// This rule ignores abstract fixtures.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def _some_object():
/// return SomeClass()
///
///
/// @pytest.fixture()
/// def _some_object_with_cleanup():
/// obj = SomeClass()
/// yield obj
/// obj.cleanup()
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def some_object():
/// return SomeClass()
///
///
/// @pytest.fixture()
/// def some_object_with_cleanup():
/// obj = SomeClass()
/// yield obj
/// obj.cleanup()
/// ```
///
/// ## References
/// - [`pytest` documentation: `@pytest.fixture` functions](https://docs.pytest.org/en/latest/reference/reference.html#pytest-fixture)
#[violation]
pub struct PytestIncorrectFixtureNameUnderscore {
function: String,
}
impl Violation for PytestIncorrectFixtureNameUnderscore {
#[derive_message_formats]
fn message(&self) -> String {
let PytestIncorrectFixtureNameUnderscore { function } = self;
format!("Fixture `{function}` returns a value, remove leading underscore")
}
}
/// ## What it does
/// Checks for `pytest` test functions that should be decorated with
/// `@pytest.mark.usefixtures`.
///
/// ## Why is this bad?
/// In `pytest`, fixture injection is used to activate fixtures in a test
/// function.
///
/// Fixtures can be injected either by passing them as parameters to the test
/// function, or by using the `@pytest.mark.usefixtures` decorator.
///
/// If the test function depends on the fixture being activated, but does not
/// use it in the test body or otherwise rely on its return value, prefer
/// the `@pytest.mark.usefixtures` decorator, to make the dependency explicit
/// and avoid the confusion caused by unused arguments.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.fixture
/// def _patch_something():
/// ...
///
///
/// def test_foo(_patch_something):
/// ...
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.fixture
/// def _patch_something():
/// ...
///
///
/// @pytest.mark.usefixtures("_patch_something")
/// def test_foo():
/// ...
/// ```
///
/// ## References
/// - [`pytest` documentation: `pytest.mark.usefixtures`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-mark-usefixtures)
#[violation]
pub struct PytestFixtureParamWithoutValue {
name: String,
}
impl Violation for PytestFixtureParamWithoutValue {
#[derive_message_formats]
fn message(&self) -> String {
let PytestFixtureParamWithoutValue { name } = self;
format!(
"Fixture `{name}` without value is injected as parameter, use \
`@pytest.mark.usefixtures` instead"
)
}
}
/// ## What it does
/// Checks for `pytest.yield_fixture` usage.
///
/// ## Why is this bad?
/// `pytest.yield_fixture` is deprecated. `pytest.fixture` should be used instead.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.yield_fixture()
/// def my_fixture():
/// obj = SomeClass()
/// yield obj
/// obj.cleanup()
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def my_fixture():
/// obj = SomeClass()
/// yield obj
/// obj.cleanup()
/// ```
///
/// ## References
/// - [`pytest` documentation: `yield_fixture` functions](https://docs.pytest.org/en/latest/yieldfixture.html)
#[violation]
pub struct PytestDeprecatedYieldFixture;
impl Violation for PytestDeprecatedYieldFixture {
#[derive_message_formats]
fn message(&self) -> String {
format!("`@pytest.yield_fixture` is deprecated, use `@pytest.fixture`")
}
}
/// ## What it does
/// Checks for unnecessary `request.addfinalizer` usages in `pytest` fixtures.
///
/// ## Why is this bad?
/// `pytest` offers two ways to perform cleanup in fixture code. The first is
/// sequential (via the `yield` statement), the second callback-based (via
/// `request.addfinalizer`).
///
/// The sequential approach is more readable and should be preferred, unless
/// the fixture uses the "factory as fixture" pattern.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def my_fixture(request):
/// resource = acquire_resource()
/// request.addfinalizer(resource.release)
/// return resource
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def my_fixture():
/// resource = acquire_resource()
/// yield resource
/// resource.release()
///
///
/// # "factory-as-fixture" pattern
/// @pytest.fixture()
/// def my_factory(request):
/// def create_resource(arg):
/// resource = acquire_resource(arg)
/// request.addfinalizer(resource.release)
/// return resource
///
/// return create_resource
/// ```
///
/// ## References
/// - [`pytest` documentation: Adding finalizers directly](https://docs.pytest.org/en/latest/how-to/fixtures.html#adding-finalizers-directly)
/// - [`pytest` documentation: Factories as fixtures](https://docs.pytest.org/en/latest/how-to/fixtures.html#factories-as-fixtures)
#[violation]
pub struct PytestFixtureFinalizerCallback;
impl Violation for PytestFixtureFinalizerCallback {
#[derive_message_formats]
fn message(&self) -> String {
format!("Use `yield` instead of `request.addfinalizer`")
}
}
/// ## What it does
/// Checks for unnecessary `yield` expressions in `pytest` fixtures.
///
/// ## Why is this bad?
/// In `pytest` fixtures, the `yield` expression should only be used for fixtures
/// that include teardown code, to clean up the fixture after the test function
/// has finished executing.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def my_fixture():
/// resource = acquire_resource()
/// yield resource
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def my_fixture_with_teardown():
/// resource = acquire_resource()
/// yield resource
/// resource.release()
///
///
/// @pytest.fixture()
/// def my_fixture_without_teardown():
/// resource = acquire_resource()
/// return resource
/// ```
///
/// ## References
/// - [`pytest` documentation: Teardown/Cleanup](https://docs.pytest.org/en/latest/how-to/fixtures.html#teardown-cleanup-aka-fixture-finalization)
#[violation]
pub struct PytestUselessYieldFixture {
name: String,
}
impl AlwaysAutofixableViolation for PytestUselessYieldFixture {
#[derive_message_formats]
fn message(&self) -> String {
let PytestUselessYieldFixture { name } = self;
format!("No teardown in fixture `{name}`, use `return` instead of `yield`")
}
fn autofix_title(&self) -> String {
"Replace `yield` with `return`".to_string()
}
}
/// ## What it does
/// Checks for `pytest.mark.usefixtures` decorators applied to `pytest`
/// fixtures.
///
/// ## Why is this bad?
/// The `pytest.mark.usefixtures` decorator has no effect on `pytest` fixtures.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def a():
/// pass
///
///
/// @pytest.mark.usefixtures("a")
/// @pytest.fixture()
/// def b(a):
/// pass
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// def a():
/// pass
///
///
/// @pytest.fixture()
/// def b(a):
/// pass
/// ```
///
/// ## References
/// - [`pytest` documentation: `pytest.mark.usefixtures`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-mark-usefixtures)
#[violation]
pub struct PytestErroneousUseFixturesOnFixture;
impl AlwaysAutofixableViolation for PytestErroneousUseFixturesOnFixture {
#[derive_message_formats]
fn message(&self) -> String {
format!("`pytest.mark.usefixtures` has no effect on fixtures")
}
fn autofix_title(&self) -> String {
"Remove `pytest.mark.usefixtures`".to_string()
}
}
/// ## What it does
/// Checks for unnecessary `@pytest.mark.asyncio` decorators applied to fixtures.
///
/// ## Why is this bad?
/// `pytest.mark.asyncio` is unnecessary for fixtures.
///
/// ## Example
/// ```python
/// import pytest
///
///
/// @pytest.mark.asyncio()
/// @pytest.fixture()
/// async def my_fixture():
/// return 0
/// ```
///
/// Use instead:
/// ```python
/// import pytest
///
///
/// @pytest.fixture()
/// async def my_fixture():
/// return 0
/// ```
///
/// ## References
/// - [`pytest-asyncio`](https://pypi.org/project/pytest-asyncio/)
#[violation]
pub struct PytestUnnecessaryAsyncioMarkOnFixture;
impl AlwaysAutofixableViolation for PytestUnnecessaryAsyncioMarkOnFixture {
#[derive_message_formats]
fn message(&self) -> String {
format!("`pytest.mark.asyncio` is unnecessary for fixtures")
}
fn autofix_title(&self) -> String {
"Remove `pytest.mark.asyncio`".to_string()
}
}
#[derive(Debug, PartialEq, Eq)]
enum Parentheses {
None,
Empty,
}
impl fmt::Display for Parentheses {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
Parentheses::None => fmt.write_str(""),
Parentheses::Empty => fmt.write_str("()"),
}
}
}
/// Visitor that skips functions
#[derive(Debug, Default)]
struct SkipFunctionsVisitor<'a> {
has_return_with_value: bool,
has_yield_from: bool,
yield_statements: Vec<&'a Expr>,
addfinalizer_call: Option<&'a Expr>,
}
impl<'a, 'b> Visitor<'b> for SkipFunctionsVisitor<'a>
where
'b: 'a,
{
fn visit_stmt(&mut self, stmt: &'b Stmt) {
match stmt {
Stmt::Return(ast::StmtReturn { value, range: _ }) => {
if value.is_some() {
self.has_return_with_value = true;
}
}
Stmt::FunctionDef(_) => {}
_ => visitor::walk_stmt(self, stmt),
}
}
fn visit_expr(&mut self, expr: &'b Expr) {
match expr {
Expr::YieldFrom(_) => {
self.has_yield_from = true;
}
Expr::Yield(ast::ExprYield { value, range: _ }) => {
self.yield_statements.push(expr);
if value.is_some() {
self.has_return_with_value = true;
}
}
Expr::Call(ast::ExprCall { func, .. }) => {
if collect_call_path(func).is_some_and(|call_path| {
matches!(call_path.as_slice(), ["request", "addfinalizer"])
}) {
self.addfinalizer_call = Some(expr);
};
visitor::walk_expr(self, expr);
}
_ => {}
}
}
}
fn fixture_decorator<'a>(
decorators: &'a [Decorator],
semantic: &SemanticModel,
) -> Option<&'a Decorator> {
decorators.iter().find(|decorator| {
is_pytest_fixture(decorator, semantic) || is_pytest_yield_fixture(decorator, semantic)
})
}
fn pytest_fixture_parentheses(
checker: &mut Checker,
decorator: &Decorator,
fix: Fix,
expected: Parentheses,
actual: Parentheses,
) {
let mut diagnostic = Diagnostic::new(
PytestFixtureIncorrectParenthesesStyle { expected, actual },
decorator.range(),
);
if checker.patch(diagnostic.kind.rule()) {
diagnostic.set_fix(fix);
}
checker.diagnostics.push(diagnostic);
}
/// PT001, PT002, PT003
fn check_fixture_decorator(checker: &mut Checker, func_name: &str, decorator: &Decorator) {
match &decorator.expression {
Expr::Call(ast::ExprCall {
func,
arguments,
range: _,
}) => {
if checker.enabled(Rule::PytestFixtureIncorrectParenthesesStyle) {
if !checker.settings.flake8_pytest_style.fixture_parentheses
&& arguments.args.is_empty()
&& arguments.keywords.is_empty()
{
let fix = Fix::automatic(Edit::deletion(func.end(), decorator.end()));
pytest_fixture_parentheses(
checker,
decorator,
fix,
Parentheses::None,
Parentheses::Empty,
);
}
}
if checker.enabled(Rule::PytestFixturePositionalArgs) {
if !arguments.args.is_empty() {
checker.diagnostics.push(Diagnostic::new(
PytestFixturePositionalArgs {
function: func_name.to_string(),
},
decorator.range(),
));
}
}
if checker.enabled(Rule::PytestExtraneousScopeFunction) {
if let Some(keyword) = arguments.find_keyword("scope") {
if keyword_is_literal(keyword, "function") {
let mut diagnostic =
Diagnostic::new(PytestExtraneousScopeFunction, keyword.range());
if checker.patch(diagnostic.kind.rule()) {
diagnostic.try_set_fix(|| {
edits::remove_argument(
keyword,
arguments,
edits::Parentheses::Preserve,
checker.locator().contents(),
)
.map(Fix::suggested)
});
}
checker.diagnostics.push(diagnostic);
}
}
}
}
_ => {
if checker.enabled(Rule::PytestFixtureIncorrectParenthesesStyle) {
if checker.settings.flake8_pytest_style.fixture_parentheses {
let fix = Fix::automatic(Edit::insertion(
Parentheses::Empty.to_string(),
decorator.end(),
));
pytest_fixture_parentheses(
checker,
decorator,
fix,
Parentheses::Empty,
Parentheses::None,
);
}
}
}
}
}
/// PT004, PT005, PT022
fn check_fixture_returns(
checker: &mut Checker,
stmt: &Stmt,
name: &str,
body: &[Stmt],
returns: Option<&Expr>,
) {
let mut visitor = SkipFunctionsVisitor::default();
for stmt in body {
visitor.visit_stmt(stmt);
}
if checker.enabled(Rule::PytestIncorrectFixtureNameUnderscore)
&& visitor.has_return_with_value
&& name.starts_with('_')
{
checker.diagnostics.push(Diagnostic::new(
PytestIncorrectFixtureNameUnderscore {
function: name.to_string(),
},
stmt.identifier(),
));
} else if checker.enabled(Rule::PytestMissingFixtureNameUnderscore)
&& !visitor.has_return_with_value
&& !visitor.has_yield_from
&& !name.starts_with('_')
{
checker.diagnostics.push(Diagnostic::new(
PytestMissingFixtureNameUnderscore {
function: name.to_string(),
},
stmt.identifier(),
));
}
if checker.enabled(Rule::PytestUselessYieldFixture) {
let Some(stmt) = body.last() else {
return;
};
let Stmt::Expr(ast::StmtExpr { value, .. }) = stmt else {
return;
};
if !value.is_yield_expr() {
return;
}
if visitor.yield_statements.len() != 1 {
return;
}
let mut diagnostic = Diagnostic::new(
PytestUselessYieldFixture {
name: name.to_string(),
},
stmt.range(),
);
if checker.patch(diagnostic.kind.rule()) {
let yield_edit = Edit::range_replacement(
"return".to_string(),
TextRange::at(stmt.start(), "yield".text_len()),
);
let return_type_edit = returns.and_then(|returns| {
let ast::ExprSubscript { value, slice, .. } = returns.as_subscript_expr()?;
let ast::ExprTuple { elts, .. } = slice.as_tuple_expr()?;
let [first, ..] = elts.as_slice() else {
return None;
};
if !checker.semantic().match_typing_expr(value, "Generator") {
return None;
}
Some(Edit::range_replacement(
checker.generator().expr(first),
returns.range(),
))
});
if let Some(return_type_edit) = return_type_edit {
diagnostic.set_fix(Fix::automatic_edits(yield_edit, [return_type_edit]));
} else {
diagnostic.set_fix(Fix::automatic(yield_edit));
}
}
checker.diagnostics.push(diagnostic);
}
}
/// PT019
fn check_test_function_args(checker: &mut Checker, parameters: &Parameters) {
parameters
.posonlyargs
.iter()
.chain(¶meters.args)
.chain(¶meters.kwonlyargs)
.for_each(
|ParameterWithDefault {
parameter,
default: _,
range: _,
}| {
let name = ¶meter.name;
if name.starts_with('_') {
checker.diagnostics.push(Diagnostic::new(
PytestFixtureParamWithoutValue {
name: name.to_string(),
},
parameter.range(),
));
}
},
);
}
/// PT020
fn check_fixture_decorator_name(checker: &mut Checker, decorator: &Decorator) {
if is_pytest_yield_fixture(decorator, checker.semantic()) {
checker.diagnostics.push(Diagnostic::new(
PytestDeprecatedYieldFixture,
decorator.range(),
));
}
}
/// PT021
fn check_fixture_addfinalizer(checker: &mut Checker, parameters: &Parameters, body: &[Stmt]) {
if !parameters.includes("request") {
return;
}
let mut visitor = SkipFunctionsVisitor::default();
for stmt in body {
visitor.visit_stmt(stmt);
}
if let Some(addfinalizer) = visitor.addfinalizer_call {
checker.diagnostics.push(Diagnostic::new(
PytestFixtureFinalizerCallback,
addfinalizer.range(),
));
}
}
/// PT024, PT025
fn check_fixture_marks(checker: &mut Checker, decorators: &[Decorator]) {
for (expr, call_path) in get_mark_decorators(decorators) {
let name = call_path.last().expect("Expected a mark name");
if checker.enabled(Rule::PytestUnnecessaryAsyncioMarkOnFixture) {
if *name == "asyncio" {
let mut diagnostic =
Diagnostic::new(PytestUnnecessaryAsyncioMarkOnFixture, expr.range());
if checker.patch(diagnostic.kind.rule()) {
let range = checker.locator().full_lines_range(expr.range());
diagnostic.set_fix(Fix::automatic(Edit::range_deletion(range)));
}
checker.diagnostics.push(diagnostic);
}
}
if checker.enabled(Rule::PytestErroneousUseFixturesOnFixture) {
if *name == "usefixtures" {
let mut diagnostic =
Diagnostic::new(PytestErroneousUseFixturesOnFixture, expr.range());
if checker.patch(diagnostic.kind.rule()) {
let line_range = checker.locator().full_lines_range(expr.range());
diagnostic.set_fix(Fix::automatic(Edit::range_deletion(line_range)));
}
checker.diagnostics.push(diagnostic);
}
}
}
}
pub(crate) fn fixture(
checker: &mut Checker,
stmt: &Stmt,
name: &str,
parameters: &Parameters,
returns: Option<&Expr>,
decorators: &[Decorator],
body: &[Stmt],
) {
let decorator = fixture_decorator(decorators, checker.semantic());
if let Some(decorator) = decorator {
if checker.enabled(Rule::PytestFixtureIncorrectParenthesesStyle)
|| checker.enabled(Rule::PytestFixturePositionalArgs)
|| checker.enabled(Rule::PytestExtraneousScopeFunction)
{
check_fixture_decorator(checker, name, decorator);
}
if checker.enabled(Rule::PytestDeprecatedYieldFixture)
&& checker.settings.flake8_pytest_style.fixture_parentheses
{
check_fixture_decorator_name(checker, decorator);
}
if (checker.enabled(Rule::PytestMissingFixtureNameUnderscore)
|| checker.enabled(Rule::PytestIncorrectFixtureNameUnderscore)
|| checker.enabled(Rule::PytestUselessYieldFixture))
&& !is_abstract(decorators, checker.semantic())
{
check_fixture_returns(checker, stmt, name, body, returns);
}
if checker.enabled(Rule::PytestFixtureFinalizerCallback) {
check_fixture_addfinalizer(checker, parameters, body);
}
if checker.enabled(Rule::PytestUnnecessaryAsyncioMarkOnFixture)
|| checker.enabled(Rule::PytestErroneousUseFixturesOnFixture)
{
check_fixture_marks(checker, decorators);
}
}
if checker.enabled(Rule::PytestFixtureParamWithoutValue) && name.starts_with("test_") {
check_test_function_args(checker, parameters);
}
}