pytest-language-server 0.23.0

A blazingly fast Language Server Protocol implementation for pytest
Documentation
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
//! Unit tests for decorator analysis utilities.
//!
//! All tests have a 30-second timeout to prevent hangs from blocking CI.

use ntest::timeout;
use pytest_language_server::fixtures::decorators;
use rustpython_parser::{parse, Mode};

#[test]
#[timeout(30000)]
fn test_is_fixture_decorator_simple() {
    let code = "@fixture\ndef my_fixture(): pass";
    let parsed = parse(code, Mode::Module, "").unwrap();

    if let rustpython_parser::ast::Mod::Module(module) = parsed {
        if let rustpython_parser::ast::Stmt::FunctionDef(func_def) = &module.body[0] {
            assert!(decorators::is_fixture_decorator(
                &func_def.decorator_list[0]
            ));
        }
    }
}

#[test]
#[timeout(30000)]
fn test_is_fixture_decorator_pytest_dot() {
    let code = "@pytest.fixture\ndef my_fixture(): pass";
    let parsed = parse(code, Mode::Module, "").unwrap();

    if let rustpython_parser::ast::Mod::Module(module) = parsed {
        if let rustpython_parser::ast::Stmt::FunctionDef(func_def) = &module.body[0] {
            assert!(decorators::is_fixture_decorator(
                &func_def.decorator_list[0]
            ));
        }
    }
}

#[test]
#[timeout(30000)]
fn test_is_fixture_decorator_with_args() {
    let code = "@pytest.fixture(scope='session')\ndef my_fixture(): pass";
    let parsed = parse(code, Mode::Module, "").unwrap();

    if let rustpython_parser::ast::Mod::Module(module) = parsed {
        if let rustpython_parser::ast::Stmt::FunctionDef(func_def) = &module.body[0] {
            assert!(decorators::is_fixture_decorator(
                &func_def.decorator_list[0]
            ));
        }
    }
}

#[test]
#[timeout(30000)]
fn test_is_fixture_decorator_pytest_asyncio() {
    // Test @pytest_asyncio.fixture (no parens)
    let code = "@pytest_asyncio.fixture\nasync def my_fixture(): pass";
    let parsed = parse(code, Mode::Module, "").unwrap();

    if let rustpython_parser::ast::Mod::Module(module) = parsed {
        if let rustpython_parser::ast::Stmt::AsyncFunctionDef(func_def) = &module.body[0] {
            assert!(decorators::is_fixture_decorator(
                &func_def.decorator_list[0]
            ));
        }
    }
}

#[test]
#[timeout(30000)]
fn test_is_fixture_decorator_pytest_asyncio_with_args() {
    // Test @pytest_asyncio.fixture(scope='session')
    let code = "@pytest_asyncio.fixture(scope='session')\nasync def my_fixture(): pass";
    let parsed = parse(code, Mode::Module, "").unwrap();

    if let rustpython_parser::ast::Mod::Module(module) = parsed {
        if let rustpython_parser::ast::Stmt::AsyncFunctionDef(func_def) = &module.body[0] {
            assert!(decorators::is_fixture_decorator(
                &func_def.decorator_list[0]
            ));
        }
    }
}

#[test]
#[timeout(30000)]
fn test_not_fixture_decorator() {
    let code = "@property\ndef my_prop(): pass";
    let parsed = parse(code, Mode::Module, "").unwrap();

    if let rustpython_parser::ast::Mod::Module(module) = parsed {
        if let rustpython_parser::ast::Stmt::FunctionDef(func_def) = &module.body[0] {
            assert!(!decorators::is_fixture_decorator(
                &func_def.decorator_list[0]
            ));
        }
    }
}

#[test]
#[timeout(30000)]
fn test_extract_custom_fixture_name() {
    let code = "@pytest.fixture(name='custom')\ndef my_fixture(): pass";
    let parsed = parse(code, Mode::Module, "").unwrap();

    if let rustpython_parser::ast::Mod::Module(module) = parsed {
        if let rustpython_parser::ast::Stmt::FunctionDef(func_def) = &module.body[0] {
            let name = decorators::extract_fixture_name_from_decorator(&func_def.decorator_list[0]);
            assert_eq!(name, Some("custom".to_string()));
        }
    }
}

#[test]
#[timeout(30000)]
fn test_is_usefixtures_decorator() {
    let code = "@pytest.mark.usefixtures('f1')\ndef test_x(): pass";
    let parsed = parse(code, Mode::Module, "").unwrap();

    if let rustpython_parser::ast::Mod::Module(module) = parsed {
        if let rustpython_parser::ast::Stmt::FunctionDef(func_def) = &module.body[0] {
            assert!(decorators::is_usefixtures_decorator(
                &func_def.decorator_list[0]
            ));
        }
    }
}

#[test]
#[timeout(30000)]
fn test_extract_usefixtures() {
    let code = "@pytest.mark.usefixtures('f1', 'f2')\ndef test_x(): pass";
    let parsed = parse(code, Mode::Module, "").unwrap();

    if let rustpython_parser::ast::Mod::Module(module) = parsed {
        if let rustpython_parser::ast::Stmt::FunctionDef(func_def) = &module.body[0] {
            let names = decorators::extract_usefixtures_names(&func_def.decorator_list[0]);
            assert_eq!(names.len(), 2);
            assert_eq!(names[0].0, "f1");
            assert_eq!(names[1].0, "f2");
        }
    }
}

#[test]
#[timeout(30000)]
fn test_extract_usefixtures_from_expr_direct_call() {
    let code = "pytestmark = pytest.mark.usefixtures('f1', 'f2')";
    let parsed = parse(code, Mode::Module, "").unwrap();

    if let rustpython_parser::ast::Mod::Module(module) = parsed {
        if let rustpython_parser::ast::Stmt::Assign(assign) = &module.body[0] {
            let names = decorators::extract_usefixtures_from_expr(&assign.value);
            assert_eq!(names.len(), 2);
            assert_eq!(names[0].0, "f1");
            assert_eq!(names[1].0, "f2");
        }
    }
}

#[test]
#[timeout(30000)]
fn test_extract_usefixtures_from_expr_list() {
    let code = "pytestmark = [pytest.mark.usefixtures('f1'), pytest.mark.skip, pytest.mark.usefixtures('f2')]";
    let parsed = parse(code, Mode::Module, "").unwrap();

    if let rustpython_parser::ast::Mod::Module(module) = parsed {
        if let rustpython_parser::ast::Stmt::Assign(assign) = &module.body[0] {
            let names = decorators::extract_usefixtures_from_expr(&assign.value);
            assert_eq!(names.len(), 2);
            assert_eq!(names[0].0, "f1");
            assert_eq!(names[1].0, "f2");
        }
    }
}

#[test]
#[timeout(30000)]
fn test_extract_usefixtures_from_expr_tuple() {
    let code = "pytestmark = (pytest.mark.usefixtures('f1'), pytest.mark.usefixtures('f2'))";
    let parsed = parse(code, Mode::Module, "").unwrap();

    if let rustpython_parser::ast::Mod::Module(module) = parsed {
        if let rustpython_parser::ast::Stmt::Assign(assign) = &module.body[0] {
            let names = decorators::extract_usefixtures_from_expr(&assign.value);
            assert_eq!(names.len(), 2);
            assert_eq!(names[0].0, "f1");
            assert_eq!(names[1].0, "f2");
        }
    }
}

#[test]
#[timeout(30000)]
fn test_extract_usefixtures_from_expr_no_usefixtures() {
    let code = "pytestmark = [pytest.mark.skip, pytest.mark.slow]";
    let parsed = parse(code, Mode::Module, "").unwrap();

    if let rustpython_parser::ast::Mod::Module(module) = parsed {
        if let rustpython_parser::ast::Stmt::Assign(assign) = &module.body[0] {
            let names = decorators::extract_usefixtures_from_expr(&assign.value);
            assert_eq!(names.len(), 0);
        }
    }
}

#[test]
#[timeout(30000)]
fn test_is_parametrize_decorator() {
    let code = "@pytest.mark.parametrize('x', [1])\ndef test_x(x): pass";
    let parsed = parse(code, Mode::Module, "").unwrap();

    if let rustpython_parser::ast::Mod::Module(module) = parsed {
        if let rustpython_parser::ast::Stmt::FunctionDef(func_def) = &module.body[0] {
            assert!(decorators::is_parametrize_decorator(
                &func_def.decorator_list[0]
            ));
        }
    }
}

#[test]
#[timeout(30000)]
fn test_extract_parametrize_indirect() {
    let code = "@pytest.mark.parametrize('f1', ['a'], indirect=True)\ndef test_x(f1): pass";
    let parsed = parse(code, Mode::Module, "").unwrap();

    if let rustpython_parser::ast::Mod::Module(module) = parsed {
        if let rustpython_parser::ast::Stmt::FunctionDef(func_def) = &module.body[0] {
            let fixtures =
                decorators::extract_parametrize_indirect_fixtures(&func_def.decorator_list[0]);
            assert_eq!(fixtures.len(), 1);
            assert_eq!(fixtures[0].0, "f1");
        }
    }
}

/// Parse a single decorated function and return `(name, source_slice)` pairs from
/// `extract_parametrize_argnames`, where `source_slice` is the exact substring the returned
/// range points at — so tests can confirm ranges land on the identifier, not quotes/whitespace.
fn argnames_with_slices(code: &str) -> Vec<(String, String)> {
    let parsed = parse(code, Mode::Module, "").unwrap();
    let rustpython_parser::ast::Mod::Module(module) = parsed else {
        panic!("expected module");
    };
    let rustpython_parser::ast::Stmt::FunctionDef(func_def) = &module.body[0] else {
        panic!("expected function def");
    };
    func_def
        .decorator_list
        .iter()
        .flat_map(|dec| decorators::extract_parametrize_argnames(dec, code))
        .map(|(name, range)| {
            let slice = code[range.start().to_usize()..range.end().to_usize()].to_string();
            (name, slice)
        })
        .collect()
}

#[test]
#[timeout(30000)]
fn test_extract_parametrize_argnames_single() {
    let got = argnames_with_slices("@pytest.mark.parametrize('x', [1])\ndef test_x(x): pass");
    assert_eq!(got, vec![("x".to_string(), "x".to_string())]);
}

#[test]
#[timeout(30000)]
fn test_extract_parametrize_argnames_comma_no_space() {
    let got =
        argnames_with_slices("@pytest.mark.parametrize('a,b', [(1, 2)])\ndef test_x(a, b): pass");
    assert_eq!(
        got,
        vec![
            ("a".to_string(), "a".to_string()),
            ("b".to_string(), "b".to_string())
        ]
    );
}

#[test]
#[timeout(30000)]
fn test_extract_parametrize_argnames_comma_with_spaces() {
    // The ranges must skip the surrounding whitespace and land on the identifiers.
    let got = argnames_with_slices(
        "@pytest.mark.parametrize('a,  b ', [(1, 2)])\ndef test_x(a, b): pass",
    );
    assert_eq!(
        got,
        vec![
            ("a".to_string(), "a".to_string()),
            ("b".to_string(), "b".to_string())
        ]
    );
}

#[test]
#[timeout(30000)]
fn test_extract_parametrize_argnames_list() {
    let got = argnames_with_slices(
        "@pytest.mark.parametrize(['a', 'b'], [(1, 2)])\ndef test_x(a, b): pass",
    );
    assert_eq!(
        got,
        vec![
            ("a".to_string(), "a".to_string()),
            ("b".to_string(), "b".to_string())
        ]
    );
}

#[test]
#[timeout(30000)]
fn test_extract_parametrize_argnames_tuple() {
    let got = argnames_with_slices(
        "@pytest.mark.parametrize(('a', 'b'), [(1, 2)])\ndef test_x(a, b): pass",
    );
    assert_eq!(
        got,
        vec![
            ("a".to_string(), "a".to_string()),
            ("b".to_string(), "b".to_string())
        ]
    );
}

#[test]
#[timeout(30000)]
fn test_extract_parametrize_argnames_keyword() {
    let got = argnames_with_slices(
        "@pytest.mark.parametrize(argnames='x', argvalues=[1])\ndef test_x(x): pass",
    );
    assert_eq!(got, vec![("x".to_string(), "x".to_string())]);
}

#[test]
#[timeout(30000)]
fn test_extract_parametrize_argnames_stacked() {
    let code = "@pytest.mark.parametrize('a', [1])\n@pytest.mark.parametrize('b', [2])\ndef test_x(a, b): pass";
    let got = argnames_with_slices(code);
    assert_eq!(
        got,
        vec![
            ("a".to_string(), "a".to_string()),
            ("b".to_string(), "b".to_string())
        ]
    );
}

#[test]
#[timeout(30000)]
fn test_extract_parametrize_argnames_not_parametrize() {
    let got = argnames_with_slices("@pytest.mark.usefixtures('x')\ndef test_x(): pass");
    assert!(got.is_empty());
}

#[test]
#[timeout(30000)]
fn test_extract_parametrize_argnames_triple_quoted() {
    // The range must skip all three opening quotes and land on the identifier.
    let got = argnames_with_slices(
        "@pytest.mark.parametrize('''a, b''', [(1, 2)])\ndef test_x(a, b): pass",
    );
    assert_eq!(
        got,
        vec![
            ("a".to_string(), "a".to_string()),
            ("b".to_string(), "b".to_string())
        ]
    );
}

#[test]
#[timeout(30000)]
fn test_extract_parametrize_argnames_raw_string_prefix() {
    // The `r` prefix must be skipped along with the quote.
    let got =
        argnames_with_slices("@pytest.mark.parametrize(r\"foo\", [1])\ndef test_x(foo): pass");
    assert_eq!(got, vec![("foo".to_string(), "foo".to_string())]);
}

#[test]
#[timeout(30000)]
fn test_extract_parametrize_argnames_rejects_non_identifier() {
    // Implicitly concatenated literals can't be cleanly located, so nothing is returned rather
    // than a corrupting range.
    let got = argnames_with_slices("@pytest.mark.parametrize('a' 'b', [1])\ndef test_x(ab): pass");
    assert!(got.is_empty());
}

#[test]
#[timeout(30000)]
fn test_indirect_names_keyword_argnames() {
    let code = "@pytest.mark.parametrize(argnames='a,b', argvalues=[(1, 2)], indirect=True)\ndef test_x(a, b): pass";
    let parsed = parse(code, Mode::Module, "").unwrap();
    let rustpython_parser::ast::Mod::Module(module) = parsed else {
        panic!("expected module");
    };
    let rustpython_parser::ast::Stmt::FunctionDef(func_def) = &module.body[0] else {
        panic!("expected function def");
    };
    let dec = &func_def.decorator_list[0];
    let names: Vec<String> = decorators::extract_parametrize_argnames(dec, code)
        .into_iter()
        .map(|(n, _)| n)
        .collect();
    let indirect = decorators::extract_parametrize_indirect_names(dec, &names);
    assert!(indirect.contains("a"));
    assert!(indirect.contains("b"));
}

#[test]
#[timeout(30000)]
fn test_indirect_names_partial_list() {
    let code = "@pytest.mark.parametrize('a,b', [(1, 2)], indirect=['a'])\ndef test_x(a, b): pass";
    let parsed = parse(code, Mode::Module, "").unwrap();
    let rustpython_parser::ast::Mod::Module(module) = parsed else {
        panic!("expected module");
    };
    let rustpython_parser::ast::Stmt::FunctionDef(func_def) = &module.body[0] else {
        panic!("expected function def");
    };
    let dec = &func_def.decorator_list[0];
    let names: Vec<String> = decorators::extract_parametrize_argnames(dec, code)
        .into_iter()
        .map(|(n, _)| n)
        .collect();
    let indirect = decorators::extract_parametrize_indirect_names(dec, &names);
    assert!(indirect.contains("a"));
    assert!(!indirect.contains("b"));
}

/// Returns the indirect-name set for the first decorator of a single decorated function.
fn indirect_names(code: &str) -> std::collections::HashSet<String> {
    let parsed = parse(code, Mode::Module, "").unwrap();
    let rustpython_parser::ast::Mod::Module(module) = parsed else {
        panic!("expected module");
    };
    let dec = match &module.body[0] {
        rustpython_parser::ast::Stmt::FunctionDef(f) => &f.decorator_list[0],
        rustpython_parser::ast::Stmt::AsyncFunctionDef(f) => &f.decorator_list[0],
        _ => panic!("expected function def"),
    };
    let names: Vec<String> = decorators::extract_parametrize_argnames(dec, code)
        .into_iter()
        .map(|(n, _)| n)
        .collect();
    decorators::extract_parametrize_indirect_names(dec, &names)
}

#[test]
#[timeout(30000)]
fn test_indirect_names_tuple_form() {
    let names = indirect_names(
        "@pytest.mark.parametrize('a,b', [(1, 2)], indirect=('a', 'b'))\ndef test_x(a, b): pass",
    );
    assert!(names.contains("a"));
    assert!(names.contains("b"));
}

#[test]
#[timeout(30000)]
fn test_indirect_names_positional() {
    // indirect passed as the third positional argument.
    let names = indirect_names("@pytest.mark.parametrize('a', [1], True)\ndef test_x(a): pass");
    assert!(names.contains("a"));
}

#[test]
#[timeout(30000)]
fn test_indirect_names_absent_or_false() {
    assert!(indirect_names("@pytest.mark.parametrize('a', [1])\ndef test_x(a): pass").is_empty());
    assert!(indirect_names(
        "@pytest.mark.parametrize('a', [1], indirect=False)\ndef test_x(a): pass"
    )
    .is_empty());
}

#[test]
#[timeout(30000)]
fn test_argnames_non_string_forms_ignored() {
    // A non-string/list/tuple argnames expression (e.g. a variable) yields nothing.
    assert!(
        argnames_with_slices("@pytest.mark.parametrize(NAMES, [1])\ndef test_x(a): pass")
            .is_empty()
    );
    // List elements that are not string literals are skipped, whether they are non-constant
    // expressions or non-string constants.
    let got =
        argnames_with_slices("@pytest.mark.parametrize([NAME, 'b'], [1])\ndef test_x(a, b): pass");
    assert_eq!(got, vec![("b".to_string(), "b".to_string())]);
    let got =
        argnames_with_slices("@pytest.mark.parametrize([1, 'b'], [1])\ndef test_x(a, b): pass");
    assert_eq!(got, vec![("b".to_string(), "b".to_string())]);
}

#[test]
#[timeout(30000)]
fn test_indirect_names_ignores_non_string_list_elements() {
    // Non-string entries in an indirect list are ignored.
    let names = indirect_names(
        "@pytest.mark.parametrize('a,b', [(1, 2)], indirect=[1, other])\ndef test_x(a, b): pass",
    );
    assert!(names.is_empty());
}