diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index 7abdda185..9f0456230 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -1426,6 +1426,9 @@ pub struct PythonSettings { /// Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths), /// by interpreter executable; absolute or `~/`. pub interpreter_paths: BTreeMap>, + /// Default test runner (Settings › Python › Testing): `auto` (pytest when the project uses + /// it, else unittest), `pytest` or `unittest`. + pub test_runner: String, } impl Default for PythonSettings { @@ -1438,6 +1441,7 @@ impl Default for PythonSettings { hide_other_project_interpreters: false, show_interpreter_paths: true, interpreter_paths: BTreeMap::new(), + test_runner: "auto".into(), } } } diff --git a/crates/ide-host/src/mcp/run/targets.rs b/crates/ide-host/src/mcp/run/targets.rs index 6ef50e7ff..56fcf55d5 100644 --- a/crates/ide-host/src/mcp/run/targets.rs +++ b/crates/ide-host/src/mcp/run/targets.rs @@ -493,7 +493,7 @@ fn test_kinds(rel: &str) -> &'static [&'static str] { if JS_FILE.is_match(rel) { &["npm", "deno", "bun"] } else if rel.ends_with(".py") { - &["pytest", "python"] + &["pytest", "unittest", "python"] } else if rel.ends_with(".go") { &["go"] } else if rel.ends_with(".rs") { @@ -644,6 +644,11 @@ fn test_config_for(root: &Path, rel: &str, configs: &[RunConfig]) -> Option derived(&base, rel, with(&[file])), "npm" | "bun" => derived(&base, rel, with(&["--".into(), file])), "deno" | "pytest" | "python" => derived(&base, rel, with(&[file])), + // `python -m unittest `; a `discover` selection gives way to the file. + "unittest" => { + let end = base.args.iter().position(|a| a == "discover").unwrap_or(base.args.len()); + derived(&base, rel, [base.args[..end].to_vec(), vec![file]].concat()) + } "go" => { let dir = dir_of(&file); let target = if dir.is_empty() { ".".to_owned() } else { format!("./{dir}") }; @@ -790,6 +795,11 @@ pub fn target_config( "pytest" | "python" => { Some(named(replace_last(file.args.clone(), |f| format!("{f}::{}", target.path.join("::"))))) } + // unittest names tests by dotted module path: `tests.test_calc.TestCalc.test_add`. + "unittest" => Some(named(replace_last(file.args.clone(), |f| { + let module = f.strip_suffix(".py").unwrap_or(f).replace(['/', '\\'], "."); + format!("{module}.{}", target.path.join(".")) + }))), "go" => { let pattern = format!("^{}$", target.path.iter().map(|p| escape_regexp(p)).collect::>().join("$/^")); let benchmark = target.path.first().is_some_and(|p| p.starts_with("Benchmark")); @@ -921,6 +931,30 @@ mod tests { ); } + #[test] + fn narrows_unittest_configs_to_files_and_dotted_tests() { + let root = Path::new("/p"); + let mut unittest = + blank("unittest".into(), "unittest", "unittest", "python3".into(), vec!["-m".into(), "unittest".into()]); + unittest.is_test = true; + let mut discover = unittest.clone(); + discover.args.extend(["discover".into(), "-s".into(), "tests".into()]); + let src = "import unittest\n\nclass TestCalc(unittest.TestCase):\n def test_add(self):\n pass\n"; + let rel = "tests/test_calc.py"; + for configs in [vec![unittest], vec![discover]] { + let c = context_config(root, rel, &configs, src).unwrap(); + assert_eq!( + (c.kind.as_str(), c.args.as_slice()), + ("unittest", ["-m", "unittest", rel].map(String::from).as_slice()) + ); + let ts = detect(src, rel); + let c = target_config(root, &ts[1], rel, &configs, src).unwrap(); + assert_eq!(c.args, ["-m", "unittest", "tests.test_calc.TestCalc.test_add"]); + let c = target_config(root, &ts[0], rel, &configs, src).unwrap(); + assert_eq!(c.args, ["-m", "unittest", "tests.test_calc.TestCalc"]); + } + } + #[test] fn narrows_cargo_test_configs() { let root = Path::new("/p"); diff --git a/crates/ide-host/src/ops/run.rs b/crates/ide-host/src/ops/run.rs index 06247f3e2..47b54ffa0 100644 --- a/crates/ide-host/src/ops/run.rs +++ b/crates/ide-host/src/ops/run.rs @@ -493,7 +493,7 @@ async fn start_inner( } // A Python configuration pointing at a missing interpreter fails in the depth of // process spawn otherwise; name the cause and the fix like PyCharm's "Invalid SDK". - let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "django-test"); + let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test"); if is_python && Path::new(&config.command).components().count() > 1 { let cwd = project.root.join(config.cwd.as_deref().unwrap_or(Path::new(""))); let executable = ide_core::project_roots::resolve(&cwd, Path::new(&config.command)); diff --git a/crates/ide-remote/src/docker.rs b/crates/ide-remote/src/docker.rs index 5746082cc..c8235c910 100644 --- a/crates/ide-remote/src/docker.rs +++ b/crates/ide-remote/src/docker.rs @@ -78,7 +78,7 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult = run.file_env.clone(); - if matches!(config.kind.as_str(), "python" | "pytest" | "django-test") + if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test") && !command.env.contains_key("PYTHONUNBUFFERED") { env.insert("PYTHONUNBUFFERED".into(), "1".into()); diff --git a/crates/ide-run/src/detect.rs b/crates/ide-run/src/detect.rs index 050f52c3a..c04934396 100644 --- a/crates/ide-run/src/detect.rs +++ b/crates/ide-run/src/detect.rs @@ -1227,7 +1227,10 @@ fn uses_pytest(root: &Path) -> bool { if read(&root.join("setup.cfg")).is_some_and(|s| s.contains("[tool:pytest]")) { return true; } - if read(&root.join("pyproject.toml")).is_some_and(|py| py.contains("pytest") || root.join("tests").is_dir()) { + // A `tests` folder alone means pytest unless its tests are the standard library's unittest. + if read(&root.join("pyproject.toml")) + .is_some_and(|py| py.contains("pytest") || (root.join("tests").is_dir() && !uses_unittest(root))) + { return true; } ["requirements.txt", "requirements-dev.txt", "requirements_dev.txt", "dev-requirements.txt"] @@ -1235,6 +1238,34 @@ fn uses_pytest(root: &Path) -> bool { .any(|f| read(&root.join(f)).is_some_and(|s| s.contains("pytest"))) } +/// Whether the project's test modules (`test*.py` at the root and in `tests/` / `test/`) use the +/// standard library's unittest and none of them pytest. +fn uses_unittest(root: &Path) -> bool { + let mut found = false; + for dir in [root.to_path_buf(), root.join("tests"), root.join("test")] { + let Ok(entries) = fs::read_dir(&dir) else { continue }; + // ponytail: the first 50 modules of each folder decide; enough to tell a project's style. + for entry in entries.flatten().take(50) { + let name = entry.file_name().to_string_lossy().into_owned(); + if !name.starts_with("test") || !name.ends_with(".py") { + continue; + } + let Some(text) = read(&entry.path()) else { continue }; + if text + .lines() + .any(|l| l.trim_start().starts_with("import pytest") || l.trim_start().starts_with("from pytest")) + { + return false; + } + found |= text.lines().any(|l| { + let l = l.trim_start(); + l.starts_with("import unittest") || l.starts_with("from unittest") + }); + } + } + found +} + /// Python configurations of the project at `root`, a folder of the opened project `top`. fn detect_python(top: &Path, root: &Path, out: &mut Vec) { let markers = ["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "pytest.ini", "tox.ini", "manage.py"]; @@ -1280,6 +1311,11 @@ fn detect_python(top: &Path, root: &Path, out: &mut Vec) { let own_pytest = matches!(env, PyEnv::Venv(ref v) if !v.starts_with("../")) && env.has_tool(root, "pytest"); if uses_pytest(root) || own_pytest { out.push(py_config("pytest".into(), "pytest".into(), "pytest", env.tool(root, "pytest"), &[]).test()); + } else if !root.join("manage.py").is_file() && uses_unittest(root) { + out.push( + py_config("unittest".into(), "python -m unittest".into(), "unittest", env.python(), &["-m", "unittest"]) + .test(), + ); } // After pytest: a project set up for pytest (pytest-django) keeps it as the default test runner. if root.join("manage.py").is_file() { diff --git a/crates/ide-run/src/import/jetbrains.rs b/crates/ide-run/src/import/jetbrains.rs index 5ee6cc9f6..35905901a 100644 --- a/crates/ide-run/src/import/jetbrains.rs +++ b/crates/ide-run/src/import/jetbrains.rs @@ -341,6 +341,7 @@ impl Cx<'_> { DJANGO_SERVER => self.django_server(name, c, &mut ignored)?, DJANGO_TESTS => self.django_tests(name, c, &mut ignored)?, PYTHON_TESTS if matches!(factory, "py.test" | "pytest") => self.pytest(name, c, &mut ignored)?, + PYTHON_TESTS if factory == "Unittests" => self.unittest(name, c, &mut ignored)?, NPM => self.npm(name, c, &mut ignored)?, JEST | VITEST => self.js_tests(name, c, ty == VITEST, &mut ignored)?, NODE => self.node(name, c, &mut ignored)?, @@ -667,6 +668,38 @@ impl Cx<'_> { Ok(rc) } + /// PyCharm's Unittests: a Python target (`tests.test_money.TestRound`) as unittest's name, a + /// file as its path, a folder discovered (`discover -s`, with the configuration's pattern). + fn unittest(&self, name: &str, c: &El, ignored: &mut Vec) -> Res { + let (exe, mut args, dir, cwd) = self.interpreter(c, ignored)?; + args.extend(["-m".to_owned(), "unittest".to_owned()]); + let field = |key: &str| c.option(key).map(json_string).filter(|v| !v.trim().is_empty()); + if let Some(target) = field("_new_target") { + let target = self.expand(&target)?; + match field("_new_targetType").as_deref() { + Some("PYTHON") => args.push(target), + Some("CUSTOM") => {} + _ => { + let path = path_from(self.root, file_url_path(&target), &dir); + if path.ends_with(".py") { + args.push(path); + } else { + args.extend(["discover".to_owned(), "-s".to_owned(), path]); + if let Some(pattern) = field("_new_pattern") { + args.extend(["-p".to_owned(), strip_quotes(&pattern).to_owned()]); + } + } + } + } + } + args.extend(self.args_quoted(field("_new_additionalArguments").as_deref(), Quotes::Single, &dir)?); + let mut rc = config(name, "unittest", exe, args, Some("debugpy")); + rc.cwd = cwd.map(Into::into); + rc.is_test = true; + self.python_env(c, &mut rc, ignored)?; + Ok(rc) + } + /// A pytest Python target (`tests.test_money.TestRound.test_eur`) as the node id PyCharm /// passes (`tests/test_money.py::TestRound::test_eur`, intellij-community `PyTestsShared.kt:366-400`): /// the longest prefix that is a module on disk (`a/b.py` or `a/b/__init__.py`, from the working diff --git a/crates/ide-run/src/process.rs b/crates/ide-run/src/process.rs index 6182893e4..1ae80b1ee 100644 --- a/crates/ide-run/src/process.rs +++ b/crates/ide-run/src/process.rs @@ -426,7 +426,7 @@ impl ProcessManager { return Err(IdeError::invalid("input cannot be redirected from a file when emulating a terminal")); } let mut env = launch_env(root, config)?; - if matches!(config.kind.as_str(), "python" | "pytest" | "django-test") { + if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test") { crate::python_path::extend(&mut env.vars, &options.python_paths, !env.clear)?; } if let Some(dir) = options.ruby_reporter.as_deref().filter(|_| crate::ruby_reporter::applies(config)) { @@ -1087,7 +1087,7 @@ fn launch_env(root: &Path, config: &RunConfig) -> IdeResult { let paths: Vec = extras.env_files.iter().map(|f| resolve_cwd(root, Some(Path::new(f)))).collect(); crate::envfile::load(&paths, &base).map_err(|e| IdeError::not_found(format!("cannot read .env file: {e}")))? }; - if matches!(config.kind.as_str(), "python" | "pytest" | "django-test") + if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test") && !config.env.contains_key("PYTHONUNBUFFERED") && !vars.contains_key("PYTHONUNBUFFERED") { diff --git a/crates/ide-run/tests/detect.rs b/crates/ide-run/tests/detect.rs index 84b1a433c..e46b623ef 100644 --- a/crates/ide-run/tests/detect.rs +++ b/crates/ide-run/tests/detect.rs @@ -676,6 +676,34 @@ fn python_projects() { assert_eq!(ids(&c), ["python:module:app"]); } +#[test] +fn python_unittest_projects() { + const UNITTEST: &str = "import unittest\n\nclass T(unittest.TestCase):\n pass\n"; + // The standard library's unittest and no pytest: `python -m unittest`. + let dir = project(&[("pyproject.toml", "[project]\nname = 'x'\n"), ("tests/test_x.py", UNITTEST)]); + let c = detect(dir.path()); + assert_eq!(ids(&c), ["unittest"]); + let unittest = find(&c, "unittest"); + let python = if cfg!(windows) { "python" } else { "python3" }; + assert_eq!(cmdline(unittest), format!("{python} -m unittest")); + assert!(unittest.is_test); + assert_eq!(unittest.debug_adapter.as_deref(), Some("debugpy")); + let dir = project(&[("requirements.txt", ""), ("test_app.py", UNITTEST)]); + assert_eq!(ids(&detect(dir.path())), ["unittest"]); + // A module that imports pytest, a `tests` folder of pytest-style tests, or Django: as before. + let dir = project(&[ + ("pyproject.toml", "[project]\nname = 'x'\n"), + ("tests/test_x.py", UNITTEST), + ("tests/test_y.py", "import pytest\n"), + ]); + assert_eq!(ids(&detect(dir.path())), ["pytest"]); + let dir = + project(&[("pyproject.toml", "[project]\nname = 'x'\n"), ("tests/test_x.py", "def test_x():\n assert 1\n")]); + assert_eq!(ids(&detect(dir.path())), ["pytest"]); + let dir = project(&[("manage.py", ""), ("shop/tests.py", UNITTEST), ("test_x.py", UNITTEST)]); + assert_eq!(ids(&detect(dir.path())), ["django:runserver", "django:test"]); +} + #[cfg(unix)] #[test] fn python_virtualenv() { diff --git a/crates/ide-run/tests/import_jetbrains.rs b/crates/ide-run/tests/import_jetbrains.rs index 8f5596afc..9f76b842c 100644 --- a/crates/ide-run/tests/import_jetbrains.rs +++ b/crates/ide-run/tests/import_jetbrains.rs @@ -299,7 +299,16 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() { {PY_COMMON} - + + {PY_COMMON} + @@ -319,7 +328,7 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() { ); let r = import_from(dir.path(), &[]); let names: Vec<&str> = r.imported.iter().map(|c| c.config.name.as_str()).collect(); - assert_eq!(names, ["App", "Unit", "Case", "Path params", "Custom", "dev"]); + assert_eq!(names, ["App", "Unit", "Case", "Path params", "Custom", "Unittests in tests", "Unittest case", "dev"]); let app = get(&r, "App"); // `$USER_HOME$` is this machine's: the configuration goes to run.local.toml. @@ -343,7 +352,11 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() { assert_eq!(get(&r, "Path params").args, s(&["-m", "pytest", "tests/test_money.py", "-k", "slow or fast"])); assert_eq!(get(&r, "Custom").args, s(&["-m", "pytest", "tests/a.py", "--maxfail=2"])); - assert_eq!(reason(&r, "Unittests in tests"), &SkipReason::UnsupportedType { type_: "tests (Unittests)".into() }); + let unittests = get(&r, "Unittests in tests"); + assert_eq!(unittests.kind, "unittest"); + assert!(unittests.is_test); + assert_eq!(unittests.args, s(&["-m", "unittest", "discover", "-s", "tests", "-p", "check_*.py"])); + assert_eq!(get(&r, "Unittest case").args, s(&["-m", "unittest", "tests.test_money.RoundTests", "-f"])); assert_eq!(reason(&r, "Main"), &SkipReason::UnsupportedType { type_: "JUnit".into() }); let dev = get(&r, "dev"); @@ -366,7 +379,7 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() { ); assert_eq!(ignored(&r, "dev"), ["scripts"]); // Neither the template nor the temporary `build` is listed as skipped. - assert_eq!(r.skipped.len(), 2); + assert_eq!(r.skipped.len(), 1); } #[test] diff --git a/crates/ide-sdk/src/apply.rs b/crates/ide-sdk/src/apply.rs index 7351cf4c3..85f77b812 100644 --- a/crates/ide-sdk/src/apply.rs +++ b/crates/ide-sdk/src/apply.rs @@ -1954,7 +1954,7 @@ pub fn run_target<'a>(config: &RunConfig, settings: &'a Settings) -> Option<&'a } fn is_python_config(config: &RunConfig, program: &str) -> bool { - matches!(config.kind.as_str(), "python" | "pytest" | "django-test") || is_python_command(program) + matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test") || is_python_command(program) } /// Whether the configuration's `JAVA_HOME` is the one Settings choose (the Maven runner JRE, @@ -2067,7 +2067,7 @@ pub fn apply_to_run_configs_in(configs: &mut [RunConfig], root: &Path, fallback: resolve_run_command(c, root, s); let mut path_dirs: Vec = Vec::new(); match c.kind.as_str() { - "python" | "pytest" | "django-test" => { + "python" | "pytest" | "unittest" | "django-test" => { let command = Path::new(&c.command); let own = !c.detected && command.components().count() > 1 && is_python_command(&c.command); let python = if own { @@ -2085,7 +2085,7 @@ pub fn apply_to_run_configs_in(configs: &mut [RunConfig], root: &Path, fallback: let runner_options = runner && c.args.first().map(String::as_str) == Some("run") && c.args.get(1).is_some_and(|a| a.starts_with('-')); - if (c.kind == "python" || c.kind == "django-test") + if matches!(c.kind.as_str(), "python" | "unittest" | "django-test") && !runner_options && (runner || is_python_command(&c.command)) { diff --git a/crates/ide-sdk/src/tests.rs b/crates/ide-sdk/src/tests.rs index 6f53ffd50..0a8b5e71d 100644 --- a/crates/ide-sdk/src/tests.rs +++ b/crates/ide-sdk/src/tests.rs @@ -564,6 +564,7 @@ fn run_configs_use_selected_interpreter_and_package_manager() { run("django-test", "uv", &["run", "python", "manage.py", "test"]), run("django-test", ".venv/bin/python", &["manage.py", "test", "polls"]), run("python", "uv", &["run", "--with", "rich", "--no-sync", "main.py"]), + run("unittest", "uv", &["run", "python", "-m", "unittest", "tests"]), ]; apply_to_run_configs(&mut configs, tmp.path(), &s); assert_eq!(configs[0].command, python); @@ -581,6 +582,8 @@ fn run_configs_use_selected_interpreter_and_package_manager() { // uv's own options stay with uv (#5874). assert_eq!(configs[7].command, "uv"); assert_eq!(configs[7].args, ["run", "--with", "rich", "--no-sync", "main.py"]); + assert_eq!(configs[8].command, python); + assert_eq!(configs[8].args, ["-m", "unittest", "tests"]); } #[test] @@ -594,7 +597,7 @@ fn saved_python_configs_keep_their_explicit_interpreter() { settings.languages.python.interpreter = default.to_string_lossy().into_owned(); for command in [&override_python, relative_python] { - for kind in ["python", "pytest", "django-test"] { + for kind in ["python", "pytest", "unittest", "django-test"] { let command = command.to_string_lossy(); let mut config = run(kind, &command, &["main.py"]); config.detected = false; diff --git a/fixtures/README.md b/fixtures/README.md index 099471bc0..4ff48b63c 100644 --- a/fixtures/README.md +++ b/fixtures/README.md @@ -20,6 +20,7 @@ something to show. | `java-app/` | JDK 21, Maven 3.9 | `mvn compile exec:java` | `mvn test` | `mvn test -DopenideaFail=true` | unused variable in `App.java` | | `c-app/` | gcc / g++ 12+, make, GDB 14+ | `make all` | — | — | — | | `php-app/` | PHP 8.5, Composer | `composer quote` | `vendor/bin/pest` | `OPENIDEA_FAIL=1 vendor/bin/pest` | unused variable in `ThresholdCustoms.php` | +| `unittest-app/` | Python 3.10+ (standard library only) | — | `python -m unittest` | `OPENIDEA_FAIL=1 python -m unittest` | unused import in `inventory/stock.py` | | `django-app/` | Python 3.10+, Django 5.2+ | `python manage.py runserver` | `python manage.py test` | `OPENIDEA_FAIL=1 python manage.py test` | unused import in `shop/views.py` | | `tailwind-app/` | Node 22+, pnpm/npm, Tailwind CSS 4, React | `pnpm dev` | — | — | `flex` conflicting with `block` in `src/App.tsx` | | `zig-app/` | Zig 0.17 | `zig build run` | `zig build test` | — | — | diff --git a/fixtures/unittest-app/inventory/__init__.py b/fixtures/unittest-app/inventory/__init__.py new file mode 100644 index 000000000..44cb5f4e2 --- /dev/null +++ b/fixtures/unittest-app/inventory/__init__.py @@ -0,0 +1 @@ +"""A tiny stock keeper: the OpenIDEA unittest fixture.""" diff --git a/fixtures/unittest-app/inventory/stock.py b/fixtures/unittest-app/inventory/stock.py new file mode 100644 index 000000000..294dd3472 --- /dev/null +++ b/fixtures/unittest-app/inventory/stock.py @@ -0,0 +1,31 @@ +"""Items in stock and their quantities.""" + +import os # intentional warning: unused import + + +class OutOfStock(Exception): + """Raised when taking more than is in stock.""" + + +class Stock: + def __init__(self): + self._items: dict[str, int] = {} + + def add(self, name: str, quantity: int = 1) -> None: + if quantity <= 0: + raise ValueError("quantity must be positive") + self._items[name] = self._items.get(name, 0) + quantity + + def take(self, name: str, quantity: int = 1) -> int: + have = self._items.get(name, 0) + if quantity > have: + raise OutOfStock(f"{name}: {have} in stock, {quantity} asked") + self._items[name] = have - quantity + return self._items[name] + + def count(self, name: str) -> int: + return self._items.get(name, 0) + + # TODO: report the items running low + def total(self) -> int: + return sum(self._items.values()) diff --git a/fixtures/unittest-app/requirements.txt b/fixtures/unittest-app/requirements.txt new file mode 100644 index 000000000..2636e6b3a --- /dev/null +++ b/fixtures/unittest-app/requirements.txt @@ -0,0 +1 @@ +# Standard library only: the tests run with `python -m unittest`. diff --git a/fixtures/unittest-app/tests/__init__.py b/fixtures/unittest-app/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/fixtures/unittest-app/tests/test_stock.py b/fixtures/unittest-app/tests/test_stock.py new file mode 100644 index 000000000..0e4af0de8 --- /dev/null +++ b/fixtures/unittest-app/tests/test_stock.py @@ -0,0 +1,40 @@ +import os +import unittest + +from inventory.stock import OutOfStock, Stock + + +class StockTests(unittest.TestCase): + def setUp(self): + self.stock = Stock() + self.stock.add("apple", 3) + + def test_add(self): + self.stock.add("apple", 2) + self.assertEqual(self.stock.count("apple"), 5) + + def test_take(self): + print("taking one apple") + self.assertEqual(self.stock.take("apple"), 2) + + def test_take_too_many(self): + with self.assertRaises(OutOfStock): + self.stock.take("apple", 4) + + def test_rejects_bad_quantities(self): + for quantity in (0, -1, -5): + with self.subTest(quantity=quantity): + with self.assertRaises(ValueError): + self.stock.add("pear", quantity) + + @unittest.skip("FIXME: low-stock report not written yet") + def test_low_stock_report(self): + pass + + @unittest.expectedFailure + def test_negative_total(self): + self.assertLess(self.stock.total(), 0) + + @unittest.skipUnless(os.environ.get("OPENIDEA_FAIL"), "set OPENIDEA_FAIL=1 to run") + def test_failing(self): + self.assertEqual(self.stock.count("apple"), 4) diff --git a/fixtures/unittest-app/tests/test_total.py b/fixtures/unittest-app/tests/test_total.py new file mode 100644 index 000000000..60e20e084 --- /dev/null +++ b/fixtures/unittest-app/tests/test_total.py @@ -0,0 +1,14 @@ +import unittest + +from inventory.stock import Stock + + +class TotalTests(unittest.TestCase): + def test_empty(self): + self.assertEqual(Stock().total(), 0) + + def test_sums_every_item(self): + stock = Stock() + stock.add("apple", 2) + stock.add("pear", 3) + self.assertEqual(stock.total(), 5) diff --git a/smoke/run.test.ts b/smoke/run.test.ts index efedfc5b0..cd2c0342b 100644 --- a/smoke/run.test.ts +++ b/smoke/run.test.ts @@ -112,21 +112,35 @@ const CASES: Record = { }, }, ], - python: { - fixture: "python-app", - // A project venv with pytest, as the fixture's README sets it up. - setup: (root) => { - execFileSync("python3", ["-m", "venv", ".venv"], { cwd: root, stdio: "ignore" }); - execFileSync(join(root, ".venv", "bin", "pip"), ["install", "-q", "pytest"], { cwd: root, stdio: "ignore" }); + python: [ + { + fixture: "python-app", + // A project venv with pytest, as the fixture's README sets it up. + setup: (root) => { + execFileSync("python3", ["-m", "venv", ".venv"], { cwd: root, stdio: "ignore" }); + execFileSync(join(root, ".venv", "bin", "pip"), ["install", "-q", "pytest"], { cwd: root, stdio: "ignore" }); + }, + tests: { + config: "pytest", + failing: (c) => env(c, { OPENIDEA_FAIL: "1" }), + passed: 7, + failed: "test_intentionally_failing", + file: "tests/test_models.py", + }, }, - tests: { - config: "pytest", - failing: (c) => env(c, { OPENIDEA_FAIL: "1" }), - passed: 7, - failed: "test_intentionally_failing", - file: "tests/test_models.py", + { + // The standard library's unittest, no pytest: `python -m unittest` through the IDE's reporter. + fixture: "unittest-app", + tests: { + config: "unittest", + failing: (c) => env(c, { OPENIDEA_FAIL: "1" }), + // Three subtests, an expected failure and the other five tests; one skipped. + passed: 9, + failed: "test_failing", + file: "tests/test_stock.py", + }, }, - }, + ], rust: { fixture: "rust-app", run: { config: "cargo:run:inventory", prints: "Sold 3 mice, 9 left" }, diff --git a/src/bindings.ts b/src/bindings.ts index 58f1f68e0..df86e2bcc 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -12129,6 +12129,11 @@ export type PythonSettings = { * by interpreter executable; absolute or `~/`. */ interpreterPaths?: { [key in string]: string[] }, + /** + * Default test runner (Settings › Python › Testing): `auto` (pytest when the project uses + * it, else unittest), `pytest` or `unittest`. + */ + testRunner?: string, }; export type PythonStubLinks = { diff --git a/src/features/run/configSource.test.ts b/src/features/run/configSource.test.ts index 866cedf3b..29cb44baa 100644 --- a/src/features/run/configSource.test.ts +++ b/src/features/run/configSource.test.ts @@ -52,6 +52,27 @@ describe("configSource", () => { expect(await configSource(app)).toEqual({ path: `${ROOT}/api/src/main/java/com/acme/App.java`, line: 3 }); }); + it("opens a unittest target's module at the class or test it names", async () => { + files.set( + `${ROOT}/tests/test_models.py`, + "import unittest\n\nclass ModelTests(unittest.TestCase):\n def test_save(self):\n pass\n", + ); + const unittest = (target: string) => config({ kind: "unittest", params: { target } }); + expect(await configSource(unittest("tests.test_models.ModelTests.test_save"))).toEqual({ + path: `${ROOT}/tests/test_models.py`, + line: 3, + }); + expect(await configSource(unittest("tests.test_models.ModelTests"))).toEqual({ + path: `${ROOT}/tests/test_models.py`, + line: 2, + }); + expect(await configSource(unittest("tests/test_models.py"))).toEqual({ + path: `${ROOT}/tests/test_models.py`, + line: 0, + }); + expect(await configSource(unittest("discover -s tests"))).toBeNull(); + }); + it("opens a Kotlin file class at its main function", async () => { files.set(`${ROOT}/src/main/kotlin/demo/Main.kt`, "package demo\n\nfun main() {}\n"); const app = config({ kind: "application", params: { mainClass: "demo.MainKt" } }); diff --git a/src/features/run/configSource.ts b/src/features/run/configSource.ts index f607d2966..3bec8210e 100644 --- a/src/features/run/configSource.ts +++ b/src/features/run/configSource.ts @@ -22,6 +22,7 @@ const SOURCE_KINDS = new Set([ "spring-boot", "python", "pytest", + "unittest", "ruby", "shell", "npm", @@ -60,6 +61,27 @@ async function file(path: string | null, pattern?: RegExp): Promise { + const name = target?.trim().split(/\s+/)[0]; + if (!name || name === "discover" || name.startsWith("-")) return null; + if (name.endsWith(".py")) return file(joinPath(cwd, name)); + const parts = name.split("."); + for (let n = parts.length; n > 0; n--) { + const rest = parts.slice(n); + const pattern = rest.length + ? new RegExp(String.raw`^[ \t]*(?:async\s+)?(?:class|def)\s+${escape(rest[rest.length - 1]!)}\b`, "m") + : undefined; + // oxlint-disable-next-line no-await-in-loop -- longest module prefix first + const found = await file(joinPath(cwd, `${parts.slice(0, n).join("/")}.py`), pattern); + if (found) return found; + } + return null; +} + async function firstFile(dir: string, names: string[], pattern?: RegExp): Promise { for (const name of names) { // oxlint-disable-next-line no-await-in-loop -- candidate names are priority ordered; stop at the first file that exists @@ -114,6 +136,8 @@ export async function configSource(config: RunConfig): Promise = { go: "Go", python: "Python", pytest: "pytest", + unittest: "Python unittest", phpunit: "PHPUnit", composer: "Composer", make: "Make", @@ -72,6 +73,7 @@ export const KIND_CATEGORIES: Record = { cypress: "JavaScript", python: "Python", pytest: "Python", + unittest: "Python", cargo: "Rust", rustc: "Rust", go: "Go", @@ -181,6 +183,7 @@ export function configIcon(config: Pick): string { return "file-binary"; case "python": case "pytest": + case "unittest": return "file-python"; case "phpunit": case "composer": diff --git a/src/features/run/context.ts b/src/features/run/context.ts index 87cdc9811..5410e9d3f 100644 --- a/src/features/run/context.ts +++ b/src/features/run/context.ts @@ -4,6 +4,8 @@ * direct interpreter invocation for main files. Best effort, IDEA-style. */ import type { RunConfig } from "@/platform/ipc"; +import { validateLanguages, type PythonTestRunner } from "@/platform/languageSettings"; +import { useProject } from "@/platform/project"; import { jvmModuleDir } from "@/platform/javaLaunch"; import { djangoLabel, djangoTestsOf, hasDjangoTests } from "./djangoTypes"; import { inGradleModule } from "./gradleModuleTests"; @@ -57,7 +59,7 @@ const stem = (p: string) => (p.split("/").pop() ?? p).replace(/\.[^.]+$/, ""); function testKinds(relPath: string): string[] { if (/\.cs$/i.test(relPath)) return ["dotnet-test"]; if (/\.[cm]?[jt]sx?$/.test(relPath)) return ["npm", "deno", "bun", "node", "cypress"]; - if (/\.py$/.test(relPath)) return ["pytest", "python", "django-test"]; + if (/\.py$/.test(relPath)) return ["pytest", "unittest", "python", "django-test"]; if (/\.php$/.test(relPath)) return ["phpunit"]; if (/_spec\.rb$/.test(relPath)) return ["rspec", "rake", "ruby"]; if (/(^|\/)test_[^/]*\.rb$|_test\.rb$/.test(relPath)) return ["rake", "rspec", "ruby"]; @@ -127,11 +129,14 @@ function derived(base: RunConfig, relPath: string, patch: Partial): R export function projectPython(configs: RunConfig[], relPath?: string): { command: string; prefix: string[] } | null { if (relPath !== undefined) configs = allClosest( - configs.filter((c) => ["python", "pytest", "django-test"].includes(c.kind)), + configs.filter((c) => PYTHON_KINDS.includes(c.kind)), relPath, ); // A detected configuration says what the project uses; one made by hand only what it runs itself. - const py = configs.find((c) => c.kind === "python" && c.detected) ?? configs.find((c) => c.kind === "python"); + const py = + configs.find((c) => c.kind === "python" && c.detected) ?? + configs.find((c) => c.kind === "python") ?? + configs.find((c) => c.kind === "unittest"); if (py) { // The interpreter part ends where the program starts: `-m`, or the script (`manage.py`). What follows // (`runserver`, `test`…) belongs to that program, never to the interpreter. @@ -153,25 +158,46 @@ export function projectPython(configs: RunConfig[], relPath?: string): { command return null; } +/** Kinds of a Python project's configurations. */ +export const PYTHON_KINDS = ["python", "pytest", "unittest", "django-test"]; + +/** Settings › Python › Testing › Default test runner. */ +export function pythonTestRunner(): PythonTestRunner { + return validateLanguages(useProject.getState().settings?.languages).python.testRunner; +} + +/** A module of unittest tests (and not pytest's): Autodetect runs it with unittest. */ +const isUnittestModule = (content: string) => + /^[ \t]*(?:import|from)[ \t]+unittest\b/m.test(content) && !/^[ \t]*(?:import|from)[ \t]+pytest\b/m.test(content); + /** - * PyCharm runs pytest for a `test_*.py` file even when the project declares no - * test setup: `python -m pytest`, with the project's interpreter when detected. - * The "Edit configuration templates…" › pytest values win over both the - * interpreter and the runner arguments, like a template a new config inherits. + * The test runner of a Python file with no test configuration for it, like PyCharm's "Default + * test runner": the setting, or with Autodetect, unittest for a module of unittest tests, else pytest. */ -function implicitPytest(relPath: string, configs: RunConfig[]): RunConfig | null { - if (!relPath.endsWith(".py")) return null; +function implicitPythonRunner(content: string): "pytest" | "unittest" { + const runner = pythonTestRunner(); + if (runner !== "auto") return runner; + return isUnittestModule(content) ? "unittest" : "pytest"; +} + +/** + * PyCharm runs a `test_*.py` file even when the project declares no test setup: `python -m pytest` + * (or `python -m unittest`, by `implicitPythonRunner`), with the project's interpreter when + * detected. The "Edit configuration templates…" › pytest values win over both the interpreter and + * the runner arguments, like a template a new config inherits. + */ +export function implicitPythonTests(relPath: string, configs: RunConfig[], runner: "pytest" | "unittest"): RunConfig { const owners = allClosest( - configs.filter((c) => ["python", "pytest", "django-test"].includes(c.kind)), + configs.filter((c) => PYTHON_KINDS.includes(c.kind)), relPath, ); const py = projectPython(owners); const base: RunConfig = { - id: "pytest:implicit", - name: "pytest", - kind: "pytest", + id: `${runner}:implicit`, + name: runner === "pytest" ? "pytest" : "python -m unittest", + kind: runner, command: py?.command ?? systemPython(), - args: [...(py?.prefix ?? []), "-m", "pytest"], + args: [...(py?.prefix ?? []), "-m", runner], cwd: owners[0]?.cwd ?? null, module: owners[0]?.module, env: { ...owners[0]?.env }, @@ -179,7 +205,7 @@ function implicitPytest(relPath: string, configs: RunConfig[]): RunConfig | null isTest: true, debugAdapter: "debugpy", }; - return applyPytestTemplate(base); + return runner === "pytest" ? applyPytestTemplate(base) : base; } /** @@ -229,16 +255,18 @@ function byCypress(candidates: RunConfig[], relPath: string): RunConfig[] { */ export function testBasesFor(relPath: string, configs: RunConfig[], content?: string): RunConfig[] { const kinds = testKinds(relPath); + // The chosen default test runner sets the other one's configurations aside (Autodetect keeps both). + const runner = pythonTestRunner(); + const other = runner === "pytest" ? "unittest" : runner === "unittest" ? "pytest" : null; // Configurations produced from a test or file are results of narrowing, never bases for it. const candidates = configs - .filter((c) => c.isTest && kinds.includes(c.kind) && !c.id.startsWith("context:")) + .filter((c) => c.isTest && kinds.includes(c.kind) && c.kind !== other && !c.id.startsWith("context:")) // `node` configurations run a file of their own; only Playwright's (`npx playwright test`) take a test file. .filter((c) => c.kind !== "node" || frameworkFor(c) === "playwright") .sort((a, b) => kinds.indexOf(a.kind) - kinds.indexOf(b.kind)); const best = allClosest(byCypress(candidates, relPath), relPath); if (best.length) return content === undefined ? best : byRunner(best, content); - const fallback = implicitPytest(relPath, configs); - return fallback ? [fallback] : []; + return /\.py$/.test(relPath) ? [implicitPythonTests(relPath, configs, implicitPythonRunner(content ?? ""))] : []; } /** @@ -284,6 +312,9 @@ export function testConfigFor( case "python": case "rspec": return derived(base, relPath, { args: [...base.args, file] }); + case "unittest": + // unittest's dotted name of the module, which also runs a module of a namespace package. + return derived(base, relPath, { args: [...base.args, djangoLabel(file)] }); case "phpunit": return derived(base, relPath, { args: phpunitArgs(base.args, { target: file }) }); case "rake": { diff --git a/src/features/run/producers.ts b/src/features/run/producers.ts index abce3affb..0e837fdce 100644 --- a/src/features/run/producers.ts +++ b/src/features/run/producers.ts @@ -22,7 +22,10 @@ import { allClosest, contextConfig, fileRole, + implicitPythonTests, projectPython, + PYTHON_KINDS, + pythonTestRunner, testBasesFor, testConfigFor, relToCwd as relativeToCwd, @@ -445,7 +448,7 @@ function site(input: ContextInput): FileSite { const kinds: Record = { js: ["npm", "deno", "bun", "node"], ts: ["npm", "deno", "bun", "node"], - python: ["python", "pytest", "django-test"], + python: PYTHON_KINDS, ruby: ["ruby", "rake", "rspec"], php: ["php", "phpunit", "composer"], zig: ["zig", "zig-application"], @@ -522,7 +525,7 @@ function pythonCommand(input: ContextInput, env: ToolEnv, s: FileSite): { comman if (py) { // A venv-relative interpreter is relative to the project root. const owner = allClosest( - input.configs.filter((c) => ["python", "pytest", "django-test"].includes(c.kind)), + input.configs.filter((c) => PYTHON_KINDS.includes(c.kind)), relTo(input.path, input.root), )[0]; const cwd = owner?.cwd ?? ""; @@ -1369,12 +1372,29 @@ export function produceDirectory(input: ContextInput): Produced | null { const js = closest(["npm", "bun", "deno"]); const ruby = marked && !js && rubyDirectory(closest, relToCwd, make, testsIn, root); if (ruby) return ruby; - const py = closest(["pytest"]); + // The chosen default test runner sets the other one's configurations aside (Autodetect keeps both). + const runner = pythonTestRunner(); + const py = runner === "unittest" ? undefined : closest(["pytest"]); const django = closest(["django-test"]); + const unittest = + runner === "pytest" + ? undefined + : (closest(["unittest"]) ?? + (!py && + !django && + allClosest( + input.configs.filter((c) => PYTHON_KINDS.includes(c.kind)), + rel, + ).length + ? implicitPythonTests(rel, [...input.configs], "unittest") + : undefined)); const go = closest(["go"]); const cargo = closest(["cargo"]); if (cargo && /(^|\/)tests$/.test(rel) && !js && !py) return make(cargo, "All Tests", [...cargo.args, "--tests"]); if (py && (!js || /(^|\/)tests?$/.test(rel))) return make(py, testsIn, [...py.args, relToCwd(py)]); + // unittest discovers the folder's `test*.py` modules (the reporter adds `-t` inside a package). + if (unittest && (!js || /(^|\/)tests?$/.test(rel)) && relToCwd(unittest)) + return make(unittest, testsIn, [...unittest.args, "discover", "-s", relToCwd(unittest)]); // Django runs a test package by its dotted label (`polls/tests` → `polls.tests`). if (django && !js && relToCwd(django)) { const tests = djangoTestsOf(django, [djangoLabel(relToCwd(django))]); diff --git a/src/features/run/pythonTypes.ts b/src/features/run/pythonTypes.ts index f2636d5d3..e17eb871c 100644 --- a/src/features/run/pythonTypes.ts +++ b/src/features/run/pythonTypes.ts @@ -171,3 +171,71 @@ export const pythonType: RunConfigTypeContribution = { }; }, }; + +/** + * Python unittest (PyCharm's "Python tests › Unittests"): `python -m unittest` with a target + * (dotted test names, a file, or `discover -s `) and further options. The command is the + * interpreter, the runner args its leading arguments (`run python` for uv / poetry). + */ +export const unittestType: RunConfigTypeContribution = { + id: "unittest", + label: "Python unittest", + icon: "file-python", + description: "Run Python tests with python -m unittest", + get defaults() { + return { command: systemPython() }; + }, + debugAdapter: "debugpy", + fields: [ + { + key: "target", + label: "Target", + mono: true, + placeholder: "tests.test_models", + hint: "Modules, classes or tests (tests.test_models.ModelTests.test_save), a file, or discover -s ; empty discovers every test", + }, + { key: "options", label: "Options", mono: true, placeholder: "e.g. -f --locals" }, + { + key: "command", + label: "Command", + mono: true, + placeholder: "python3", + required: true, + hint: "e.g. python3, .venv/bin/python, uv, poetry", + }, + { + key: "runnerArgs", + label: "Runner arguments", + mono: true, + placeholder: "run python", + hint: "e.g. `run python` for uv/poetry; empty calls the interpreter itself", + }, + ], + commandLine(p) { + return { + command: p.command?.trim() || systemPython(), + args: [ + ...parseArgs(p.runnerArgs ?? ""), + "-m", + "unittest", + ...parseArgs(p.target ?? ""), + ...parseArgs(p.options ?? ""), + ], + }; + }, + paramsFrom(c) { + if (c.kind !== "unittest") return null; + const at = c.args.findIndex((a, i) => a === "-m" && c.args[i + 1] === "unittest"); + if (at < 0) return null; + const rest = c.args.slice(at + 2); + // `discover` takes its own options: all of it is the target. + const n = rest[0] === "discover" ? rest.length : rest.findIndex((a) => a.startsWith("-")); + const end = n < 0 ? rest.length : n; + return { + command: c.command, + runnerArgs: formatArgs(c.args.slice(0, at)), + target: formatArgs(rest.slice(0, end)), + options: formatArgs(rest.slice(end)), + }; + }, +}; diff --git a/src/features/run/services.test.ts b/src/features/run/services.test.ts index 7ad81f60a..4a00fe469 100644 --- a/src/features/run/services.test.ts +++ b/src/features/run/services.test.ts @@ -491,6 +491,7 @@ describe("add service categories", () => { go: "Go", python: "Python", pytest: "Python", + unittest: "Python", phpunit: "Others", composer: "Others", cc: "C/C++", diff --git a/src/features/run/store.ts b/src/features/run/store.ts index f5c8757e1..aeaf86c85 100644 --- a/src/features/run/store.ts +++ b/src/features/run/store.ts @@ -809,7 +809,7 @@ function newRuntime(config: RunConfig): SessionRuntime { }; const framework = tests && parser ? frameworkFor(config) : null; // PHPUnit `--teamcity` and Gradle's test init script report through service messages, Minitest, - // node:test, Mocha and Jasmine through the IDE's own reporters (RSpec has none: its progress dots must show as they come). + // node:test, Mocha, Jasmine and Python's unittest through the IDE's own reporters (RSpec has none: its progress dots must show as they come). const stdout = framework === "go" ? new GoTestOutput(feed) @@ -817,7 +817,10 @@ function newRuntime(config: RunConfig): SessionRuntime { ? new TeamcityOutput(feed, framework !== "phpunit") : framework === "ruby" && config.kind !== "rspec" ? new RubyTestOutput(feed) - : framework === "node-test" || framework === "mocha" || framework === "jasmine" + : framework === "node-test" || + framework === "mocha" || + framework === "jasmine" || + framework === "python-unittest" ? new RecordsOutput(feed) : null; const runtime: SessionRuntime = { diff --git a/src/features/run/targets.ts b/src/features/run/targets.ts index 3feda9c8b..52ba38bd0 100644 --- a/src/features/run/targets.ts +++ b/src/features/run/targets.ts @@ -535,6 +535,9 @@ export function targetConfig( : pestFilter(target.path.slice(0, -1), target.path[target.path.length - 1]); return named(phpunitArgs(file.args, { target: relToCwd(relPath, file), filter })); } + case "unittest": + // The file's run ends with the module's dotted name: the class or test follows it. + return target.unittest ? named(withLast(file.args, (m) => `${m}.${target.path.join(".")}`)) : null; case "django-test": { // unittest's loader would call a module-level `test_*` function (or a plain class) to build the suite. if (!target.unittest) return null; diff --git a/src/features/run/testing/index.ts b/src/features/run/testing/index.ts index 1b1dc745f..18d448761 100644 --- a/src/features/run/testing/index.ts +++ b/src/features/run/testing/index.ts @@ -13,6 +13,7 @@ import { recordsParser } from "./records"; import { phpunitParser, withTeamcity } from "./phpunit"; import { playwrightParser } from "./playwright"; import { pytestParser } from "./pytest"; +import { withUnittestReporter } from "./pythonUnittest"; import { rubyParser } from "./ruby"; import { unittestParser } from "./unittest"; import { zigParser } from "./zig"; @@ -53,7 +54,10 @@ export type Framework = | "mocha" | "jasmine" | "pytest" + /** Django's `manage.py test`: unittest's text runner. */ | "unittest" + /** `python -m unittest`: the IDE's reporter. */ + | "python-unittest" | "phpunit" | "go" | "jvm" @@ -86,9 +90,12 @@ export function frameworkFor(config: FrameworkConfig): Framework { return "js"; case "pytest": return "pytest"; + case "unittest": + return "python-unittest"; case "python": // `manage.py test` made as a Python configuration before the Django tests type existed. - return /\bmanage\.py test\b/.test(cmd) ? "unittest" : "pytest"; + if (/\bmanage\.py test\b/.test(cmd)) return "unittest"; + return /(^|\s)-m unittest(\s|$)/.test(cmd) ? "python-unittest" : "pytest"; case "django-test": return "unittest"; case "phpunit": @@ -141,6 +148,7 @@ export function withTestReporting(config: T): T { if (frameworkFor(config) === "node-test") return { ...config, env: withNodeTestReporter(config.env ?? {}) }; if (frameworkFor(config) === "mocha") return { ...config, env: withMochaHook(config.env ?? {}) }; if (frameworkFor(config) === "jasmine") return { ...config, env: withJasmineHook(config.env ?? {}) }; + if (frameworkFor(config) === "python-unittest") return withUnittestReporter(config); if (frameworkFor(config) === "playwright") { // The list reporter prints a line per test; a project's own (`html`, `dot` on CI) may print none. const chosen = config.args.some((a) => a === "--reporter" || a.startsWith("--reporter=")); @@ -195,6 +203,7 @@ export function createTestParser(config: FrameworkConfig): TestOutputParser { case "node-test": case "mocha": case "jasmine": + case "python-unittest": return recordsParser(); case "pytest": return pytestParser(); diff --git a/src/features/run/testing/pythonUnittest.test.ts b/src/features/run/testing/pythonUnittest.test.ts new file mode 100644 index 000000000..2359e592a --- /dev/null +++ b/src/features/run/testing/pythonUnittest.test.ts @@ -0,0 +1,156 @@ +import { afterEach, describe, expect, it } from "vitest"; +import type { RunConfig } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { testBasesFor, testConfigFor } from "../context"; +import { produceDirectory } from "../producers"; +import { unittestType } from "../pythonTypes"; +import { detectRunTargets, targetConfig } from "../targets"; +import { createTestParser, frameworkFor, parseAll, TestResults, withTestReporting } from "./index"; +import { REPORTER_VAR, unittestRerunArgs, withUnittestReporter } from "./pythonUnittest"; +import { failedTestPaths, rerunFailedConfig } from "./rerun"; +import REPORTER from "./unittestReporter.py?raw"; + +const cfg = (over: Partial & { id: string; kind: string }): RunConfig => ({ + name: over.id, + command: "python3", + args: [], + cwd: null, + env: {}, + detected: true, + isTest: true, + debugAdapter: "debugpy", + ...over, +}); +const unittest = cfg({ id: "unittest", kind: "unittest", args: ["-m", "unittest"] }); +const pytest = cfg({ id: "pytest", kind: "pytest", command: "pytest" }); +const runner = (testRunner: string) => + useProject.setState({ settings: { languages: { python: { testRunner } } } } as never); + +afterEach(() => useProject.setState({ settings: null } as never)); + +describe("python -m unittest", () => { + it("runs through the IDE's reporter with the same arguments", () => { + expect(frameworkFor(unittest)).toBe("python-unittest"); + expect(frameworkFor(cfg({ id: "p", kind: "python", args: ["-m", "unittest", "-v"] }))).toBe("python-unittest"); + const bootstrap = `import os; exec(os.environ.pop("${REPORTER_VAR}"))`; + expect(withUnittestReporter({ args: ["run", "python", "-m", "unittest", "tests", "-f"], env: { A: "1" } })).toEqual( + { + args: ["run", "python", "-c", bootstrap, "tests", "-f"], + env: { A: "1", [REPORTER_VAR]: REPORTER }, + }, + ); + const launch = withTestReporting({ ...unittest, args: ["-m", "unittest", "discover", "-s", "tests"] }); + expect(launch.args).toEqual(["-c", bootstrap, "discover", "-s", "tests"]); + expect(launch.env?.[REPORTER_VAR]).toBe(REPORTER); + }); + + it("reads the reporter's records into the tree", () => { + const mark = "@@openidea:test@@"; + const out = [ + ".taking one apple", + `${mark}{"path": ["tests.test_stock", "StockTests", "test_take"], "status": "passed", "ms": 0.2, "file": "tests/test_stock.py", "line": 16, "error": "taking one apple"}`, + `${mark}{"path": ["tests.test_stock", "StockTests", "test_sub", "(i=1)"], "status": "failed", "file": "tests/test_stock.py", "line": 30, "error": "AssertionError: 1 != 0"}`, + `${mark}{"path": ["tests.test_broken"], "status": "failed", "error": "ImportError: Failed to import test module: tests.test_broken"}`, + ].join("\n"); + const results = new TestResults(); + results.apply(parseAll(createTestParser(unittest), out)); + const take = results.get(["tests.test_stock", "StockTests", "test_take"].join("\u0000")); + expect(take?.own).toBe("passed"); + expect(take?.output).toEqual(["taking one apple"]); + // Named by module: the file comes with the record. + expect(take?.location).toEqual({ path: "tests/test_stock.py", line: 16, resolve: "path" }); + expect(results.counts()).toMatchObject({ passed: 1, failed: 2, total: 3 }); + expect(failedTestPaths(results)).toEqual([ + ["tests.test_stock", "StockTests", "test_sub", "(i=1)"], + ["tests.test_broken"], + ]); + }); + + it("reruns failed tests with -k patterns in place of the run's own", () => { + expect( + unittestRerunArgs( + ["-m", "unittest", "discover", "-s", "tests", "-k", "old", "-kother"], + [ + ["tests.test_stock", "StockTests", "test_a", "(i=1)"], + ["tests.test_stock", "StockTests", "test_a", "(i=2)"], + ["tests.test_stock", "Fixture"], + ["tests.test_broken"], + ], + ), + ).toEqual([ + "-m", + "unittest", + "discover", + "-s", + "tests", + "-k", + "*tests.test_stock.StockTests.test_a", + "-k", + "*tests.test_stock.Fixture.*", + "-k", + "*tests.test_broken.*", + ]); + const rerun = rerunFailedConfig(unittest, [["m", "C", "t"]]) as RunConfig; + expect(rerun.args).toEqual(["-m", "unittest", "-k", "*m.C.t"]); + }); + + it("has a run configuration type", () => { + const params = { command: "uv", runnerArgs: "run python", target: "tests.test_stock", options: "-f" }; + const line = unittestType.commandLine(params)!; + expect(line).toEqual({ command: "uv", args: ["run", "python", "-m", "unittest", "tests.test_stock", "-f"] }); + expect(unittestType.paramsFrom!(cfg({ id: "u", kind: "unittest", ...line }))).toEqual(params); + const discover = ["-m", "unittest", "discover", "-s", "tests", "-p", "check_*.py"]; + expect(unittestType.paramsFrom!(cfg({ id: "u", kind: "unittest", args: discover }))).toMatchObject({ + target: "discover -s tests -p check_*.py", + options: "", + }); + }); +}); + +describe("running unittest tests from the editor", () => { + const module = "import unittest\n\nclass StockTests(unittest.TestCase):\n def test_add(self):\n pass\n"; + + it("narrows the project's unittest run to a module, class or test", () => { + expect(testConfigFor("tests/test_stock.py", [unittest])!.args).toEqual(["-m", "unittest", "tests.test_stock"]); + const [cls, test] = detectRunTargets(module, "tests/test_stock.py"); + expect(targetConfig(cls!, "tests/test_stock.py", [unittest], module)!.args).toEqual([ + "-m", + "unittest", + "tests.test_stock.StockTests", + ]); + expect(targetConfig(test!, "tests/test_stock.py", [unittest], module)!.args).toEqual([ + "-m", + "unittest", + "tests.test_stock.StockTests.test_add", + ]); + // A module-level function is pytest's: unittest can't run it. + const fn = detectRunTargets("def test_x():\n pass\n", "tests/test_x.py")[0]!; + expect(targetConfig(fn, "tests/test_x.py", [unittest])).toBeNull(); + }); + + it("discovers a folder's tests", () => { + const produced = produceDirectory({ path: "/p/tests", root: "/p", configs: [unittest] } as never); + expect(produced?.config?.args).toEqual(["-m", "unittest", "discover", "-s", "tests"]); + }); + + it("picks the runner by the Default test runner setting", () => { + const python = cfg({ id: "python:module:app", kind: "python", args: ["-m", "app"], isTest: false }); + // Autodetect without a test configuration: unittest for a module of unittest tests, else pytest. + expect(testBasesFor("tests/test_stock.py", [python], module)[0]).toMatchObject({ + kind: "unittest", + args: ["-m", "unittest"], + }); + expect(testBasesFor("tests/test_x.py", [python], "def test_x():\n pass\n")[0]?.kind).toBe("pytest"); + expect(testBasesFor("tests/test_x.py", [python], `import pytest\n${module}`)[0]?.kind).toBe("pytest"); + // A project's pytest configuration wins under Autodetect… + expect(testBasesFor("tests/test_stock.py", [pytest, unittest], module)[0]?.id).toBe("pytest"); + // …and the chosen runner sets the other one's aside. + runner("unittest"); + expect(testBasesFor("tests/test_stock.py", [pytest], module)[0]).toMatchObject({ id: "unittest:implicit" }); + expect(produceDirectory({ path: "/p/tests", root: "/p", configs: [pytest] } as never)?.config?.kind).toBe( + "unittest", + ); + runner("pytest"); + expect(testBasesFor("tests/test_stock.py", [unittest], module)[0]?.kind).toBe("pytest"); + }); +}); diff --git a/src/features/run/testing/pythonUnittest.ts b/src/features/run/testing/pythonUnittest.ts new file mode 100644 index 000000000..4a4dfd958 --- /dev/null +++ b/src/features/run/testing/pythonUnittest.ts @@ -0,0 +1,42 @@ +/** + * Python's `python -m unittest`: the IDE's reporter (`unittestReporter.py`, handed over in an + * environment variable) runs in its place with the same arguments, and prints a record per + * finished test and subtest (`records.ts`) next to unittest's own console output. Tests are + * reported as `[module, Class, test, subtest]`; reruns select them with unittest's own `-k` patterns. + */ +import REPORTER_SOURCE from "./unittestReporter.py?raw"; + +/** Index of `-m` when `unittest` follows it, else -1. */ +function unittestAt(args: readonly string[]): number { + return args.findIndex((a, i) => a === "-m" && args[i + 1] === "unittest"); +} + +/** The environment variable the reporter's source reaches Python in; the command line stays short. */ +export const REPORTER_VAR = "OPENIDEA_UNITTEST_REPORTER"; +const BOOTSTRAP = `import os; exec(os.environ.pop("${REPORTER_VAR}"))`; + +/** `config` with `-m unittest` replaced by the IDE's reporter; unchanged when it doesn't run unittest. */ +export function withUnittestReporter }>(config: T): T { + const at = unittestAt(config.args); + if (at < 0) return config; + return { + ...config, + args: [...config.args.slice(0, at), "-c", BOOTSTRAP, ...config.args.slice(at + 2)], + env: { ...config.env, [REPORTER_VAR]: REPORTER_SOURCE }, + }; +} + +/** + * `args` running only the tests at `paths` (tree paths): a `-k` pattern per test in place of the + * run's own. A pattern with a wildcard matches the whole test id (`module.Class.test`), so + * `*.test_a` doesn't also run `test_ab`; a class or module fixture runs all of its tests. + */ +export function unittestRerunArgs(args: readonly string[], paths: readonly string[][]): string[] { + const kept: string[] = []; + for (let i = 0; i < args.length; i++) { + if (args[i] === "-k") i++; + else if (!args[i]!.startsWith("-k")) kept.push(args[i]!); + } + const ids = [...new Set(paths.map((p) => p.slice(0, 3).join(".") + (p.length < 3 ? ".*" : "")))]; + return [...kept, ...ids.flatMap((id) => ["-k", `*${id}`])]; +} diff --git a/src/features/run/testing/records.ts b/src/features/run/testing/records.ts index 5f398302f..270f8d540 100644 --- a/src/features/run/testing/records.ts +++ b/src/features/run/testing/records.ts @@ -11,6 +11,8 @@ interface TestRecord { path: string[]; status: "passed" | "failed" | "skipped"; ms?: number; + /** Where `line` is, when `path` doesn't start with the file (Python's unittest names modules). */ + file?: string; /** 1-based declaration line and column. */ line?: number; col?: number; @@ -30,11 +32,12 @@ export function recordsParser(): TestOutputParser { } if (!Array.isArray(r.path) || !r.path.length) return []; const events: TestEvent[] = [{ type: "result", path: r.path, status: r.status, durationMs: r.ms }]; - if (r.line !== undefined && r.path.length > 1) + const file = r.file ?? (r.path.length > 1 ? r.path[0] : undefined); + if (r.line !== undefined && file) events.push({ type: "location", path: r.path, - location: { path: r.path[0]!, line: r.line, col: r.col, resolve: "path" }, + location: { path: file, line: r.line, col: r.col, resolve: "path" }, }); for (const text of r.error?.split("\n") ?? []) events.push({ type: "output", path: r.path, line: text }); return events; diff --git a/src/features/run/testing/rerun.ts b/src/features/run/testing/rerun.ts index eed11befe..bcaccfd7b 100644 --- a/src/features/run/testing/rerun.ts +++ b/src/features/run/testing/rerun.ts @@ -18,6 +18,7 @@ import { pytestNodeId } from "./pytest"; import { cypressSelection } from "./cypress"; import { playwrightProject, playwrightTitles } from "./playwright"; import { withNodeTestNamePattern } from "./nodeTest"; +import { unittestRerunArgs } from "./pythonUnittest"; import { nodeStatus, type TestNode, type TestResults } from "./results"; /** Paths of failed tests: failed leaves, plus failed suites without any failed children reported. */ @@ -319,6 +320,9 @@ function builtinTestsConfig(config: RunConfig, paths: string[][], name: string): if (!tests) return null; return { ...config, ...tests, name, detected: true, env: { ...config.env } }; } + case "python-unittest": + args = unittestRerunArgs(config.args, paths); + break; case "phpunit": args = phpunitArgs(config.args, { filter: phpunitFilter(paths) }); break; diff --git a/src/features/run/testing/unittestReporter.py b/src/features/run/testing/unittestReporter.py new file mode 100644 index 000000000..aaf7eb8cd --- /dev/null +++ b/src/features/run/testing/unittestReporter.py @@ -0,0 +1,214 @@ +# The IDE's unittest reporter: `python -c [python -m unittest arguments]` runs unittest's +# own main program and text runner, with a result class that also prints one record per finished +# test and subtest (`records.ts`), with what the test printed. Standard library only, Python 3.8+. +import inspect +import json +import os +import re +import sys +import time +import traceback +import unittest + +MARK = "@@openidea:test@@" +_out = sys.stdout +# Whether the last text written to stdout left its line open. +_open_line = False + + +class _Tee: + """A test's stdout or stderr: written through, and kept for its record.""" + + def __init__(self, stream, kept, stdout): + self._stream = stream + self._kept = kept + self._stdout = stdout + + def write(self, text): + global _open_line + self._kept.append(text) + if self._stdout and text: + _open_line = not text.endswith("\n") + return self._stream.write(text) + + def __getattr__(self, name): + return getattr(self._stream, name) + + +def _emit(record): + global _open_line + sys.stderr.flush() + # A record starts its own line, after output that didn't end one. + _out.write(("\n" if _open_line else "") + MARK + json.dumps(record) + "\n") + _out.flush() + _open_line = False + + +def _path(test): + """The tree path: module, class (its qualified name) and method; fixtures and failed imports shorter.""" + if isinstance(test, unittest.case._SubTest): + return _path(test.test_case) + [test._subDescription()] + name = type(test).__name__ + if name in ("_FailedTest", "ModuleImportFailure"): + return [test._testMethodName] + if name == "_ErrorHolder": + # `setUpClass (pkg.mod.Class)`, `setUpModule (pkg.mod)`. + m = re.match(r"^(\w+) \((.+)\)$", test.description) + target = m.group(2) if m else test.description + if m and m.group(1) in ("setUpClass", "tearDownClass"): + module, _, cls = target.rpartition(".") + return [module, cls] if module else [target] + return [target] + cls = type(test) + return [cls.__module__, cls.__qualname__, getattr(test, "_testMethodName", str(test))] + + +def _source(test): + """File and 1-based line of a test method, else of its class; (None, None) when unknown.""" + if isinstance(test, unittest.case._SubTest): + test = test.test_case + if type(test).__name__ in ("_ErrorHolder", "_FailedTest", "ModuleImportFailure"): + return None, None + method = getattr(test, getattr(test, "_testMethodName", ""), None) + # `@skip` and other decorators wrap the method: its own code is the test's. + code = getattr(inspect.unwrap(getattr(method, "__func__", method)), "__code__", None) + if code is not None: + return code.co_filename, code.co_firstlineno + return None, None + + +def _relative(file): + try: + return os.path.relpath(file).replace(os.sep, "/") + except ValueError: + return file.replace(os.sep, "/") + + +def _failure(err, file): + """File and line of the error: its innermost frame in `file`, else in a file of the project.""" + here = os.getcwd() + frames = [(f.filename, f.lineno) for f in traceback.extract_tb(err[2])] + # A module that failed to import carries its traceback as text (`_FailedTest`). + frames += [(m.group(1), int(m.group(2))) for m in re.finditer(r'File "([^"]+)", line (\d+)', str(err[1]))] + inside = None + for name, line in frames: + path = os.path.abspath(name) + if file and os.path.normcase(path) == os.path.normcase(os.path.abspath(file)): + inside = (name, line) + elif not file and path.startswith(here + os.sep) and "site-packages" not in path: + inside = (name, line) + return inside + + +class _Result(unittest.TextTestResult): + def startTest(self, test): + self._started = time.perf_counter() + self._kept = [] + self._status = "passed" + self._notes = [] + self._at = None + self._streams = sys.stdout, sys.stderr + sys.stdout = _Tee(sys.stdout, self._kept, True) + sys.stderr = _Tee(sys.stderr, self._kept, False) + super().startTest(test) + + def stopTest(self, test): + super().stopTest(test) + if hasattr(self, "_streams"): + sys.stdout, sys.stderr = self._streams + del self._streams + ms = (time.perf_counter() - self._started) * 1000 + self._record(test, self._status, "".join(self._kept), self._notes, self._at, ms) + + def _record(self, test, status, out, notes, at=None, ms=None): + file, line = _source(test) + if at: + file, line = at + record = {"path": _path(test), "status": status} + if ms is not None: + record["ms"] = round(ms, 3) + if file: + record["file"] = _relative(file) + record["line"] = line + text = "\n".join(t for t in [out.rstrip("\n")] + notes if t) + if text: + record["error"] = text + _emit(record) + + def _trace(self, test, err): + return self._exc_info_to_string(err, test).rstrip("\n") + + def _failed(self, test, err): + if not hasattr(self, "_streams"): + # A class or module fixture, or a module that failed to import: outside startTest / stopTest. + self._record(test, "failed", "", [self._trace(test, err)], _failure(err, None)) + return + self._status = "failed" + self._notes.append(self._trace(test, err)) + self._at = self._at or _failure(err, _source(test)[0]) + + def addError(self, test, err): + super().addError(test, err) + self._failed(test, err) + + def addFailure(self, test, err): + super().addFailure(test, err) + self._failed(test, err) + + def addSkip(self, test, reason): + super().addSkip(test, reason) + if not hasattr(self, "_streams"): + # A skipped class (`@skip` on it, or `SkipTest` in `setUpClass`). + self._record(test, "skipped", "", ["Skipped: " + reason]) + return + self._status = "skipped" + self._notes.append("Skipped: " + reason) + + def addExpectedFailure(self, test, err): + super().addExpectedFailure(test, err) + self._notes.append("Expected failure:\n" + self._trace(test, err)) + + def addUnexpectedSuccess(self, test): + super().addUnexpectedSuccess(test) + self._status = "failed" + self._notes.append("Unexpected success: the test is marked @expectedFailure but passed") + + def addSubTest(self, test, subtest, err): + super().addSubTest(test, subtest, err) + if err is None: + self._record(subtest, "passed", "", []) + return + at = _failure(err, _source(test)[0]) + self._status = "failed" + self._at = self._at or at + self._record(subtest, "failed", "", [self._trace(test, err)], at) + + +class _Runner(unittest.TextTestRunner): + resultclass = _Result + + def __init__(self, *args, **kwargs): + # What a test prints reaches the console and its record anyway. + kwargs["buffer"] = False + super().__init__(*args, **kwargs) + + +def _top_level(args): + """`discover -s ` inside a package: import its modules from above the outermost package.""" + if not args or args[0] != "discover" or "-t" in args or "--top-level-directory" in args: + return args + start = None + for i, a in enumerate(args): + if a in ("-s", "--start-directory") and i + 1 < len(args): + start = args[i + 1] + if not start or not os.path.isfile(os.path.join(start, "__init__.py")): + return args + top = os.path.abspath(start) + while os.path.isfile(os.path.join(top, "__init__.py")): + top = os.path.dirname(top) + return args + ["-t", top] + + +if __name__ == "__main__": + sys.argv[0] = "python -m unittest" + unittest.main(module=None, argv=[sys.argv[0]] + _top_level(sys.argv[1:]), testRunner=_Runner) diff --git a/src/features/run/types.ts b/src/features/run/types.ts index 761f225b2..71748bfd5 100644 --- a/src/features/run/types.ts +++ b/src/features/run/types.ts @@ -29,7 +29,7 @@ import { goBuildType, goTestType } from "./goTypes"; import { dotnetProjectType, dotnetTestType } from "./dotnetTypes"; import { rakeType, rspecType, rubyScriptType } from "./rubyTypes"; import { djangoTestType } from "./djangoTypes"; -import { pythonType } from "./pythonTypes"; +import { pythonType, unittestType } from "./pythonTypes"; import { phpunitType } from "./phpunitTypes"; import { cypressType } from "./cypressType"; import { UNITY_CONFIG_KIND } from "./unity"; @@ -620,6 +620,7 @@ export const BUILTIN_TYPES: readonly RunConfigTypeContribution[] = [ unreal, pythonType, pytest, + unittestType, rubyScriptType, rakeType, rspecType, @@ -684,6 +685,7 @@ export function withParams(config: RunConfig, params: Record, ty ...(config.kind === "cypress" || config.kind === "dotnet-test" || config.kind === "django-test" || + config.kind === "unittest" || config.kind === "phpunit" || config.kind === "junit" || config.kind === "rspec" diff --git a/src/features/settings/__tests__/languages.test.ts b/src/features/settings/__tests__/languages.test.ts index ae0ff52d2..c9eb404e0 100644 --- a/src/features/settings/__tests__/languages.test.ts +++ b/src/features/settings/__tests__/languages.test.ts @@ -411,6 +411,7 @@ describe("language pages", () => { "All Interpreters", "Dependencies", "Docstrings", + "Testing", "Ruff", "Black formatter", ]); @@ -418,6 +419,7 @@ describe("language pages", () => { "python.interpreters", "python.interpreter", "python.docstrings", + "python.testing", "python.ruff", "python.black", ]); diff --git a/src/features/settings/languages/PythonTestingPage.tsx b/src/features/settings/languages/PythonTestingPage.tsx new file mode 100644 index 000000000..68e5ec54a --- /dev/null +++ b/src/features/settings/languages/PythonTestingPage.tsx @@ -0,0 +1,24 @@ +/** + * Settings › Python › Testing: the test runner of gutter and context-menu runs in projects + * without a test configuration of their own (PyCharm's "Default test runner"). + */ +import { Section, SettingSelect } from "../components/Form"; + +const RUNNERS = [ + { value: "auto", label: "Autodetect" }, + { value: "pytest", label: "pytest" }, + { value: "unittest", label: "unittest" }, +] as const; + +export function PythonTestingPage() { + return ( +
+ +
+ ); +} diff --git a/src/features/settings/pages/languages.tsx b/src/features/settings/pages/languages.tsx index 2e3c39031..6695a8f2d 100644 --- a/src/features/settings/pages/languages.tsx +++ b/src/features/settings/pages/languages.tsx @@ -26,6 +26,9 @@ const PrettierPage = lazyPage("languages.prettier", () => const OxfmtPage = lazyPage("languages.oxfmt", () => import("../languages/FormatterPage").then((m) => m.OxfmtPage)); const BiomePage = lazyPage("languages.biome", () => import("../languages/FormatterPage").then((m) => m.BiomePage)); const DprintPage = lazyPage("languages.dprint", () => import("../languages/FormatterPage").then((m) => m.DprintPage)); +const PythonTestingPage = lazyPage("python.testing", () => + import("../languages/PythonTestingPage").then((m) => m.PythonTestingPage), +); const DocstringsPage = lazyPage("python.docstrings", () => import("../languages/DocstringsPage").then((m) => m.DocstringsPage), ); @@ -254,6 +257,16 @@ export const LANGUAGE_PAGES: PageSpec[] = [ ], component: DocstringsPage, }, + { + id: "python.testing", + projectScope: true, + defaultScope: "project", + title: "Testing", + group: LANGUAGES_GROUP, + order: 403.25, + keywords: ["default test runner", "test runner", "pytest", "unittest", "testing", "integrated tools"], + component: PythonTestingPage, + }, { id: "python.ruff", projectScope: true, diff --git a/src/platform/i18n.test.ts b/src/platform/i18n.test.ts index 23b55e654..bd448d3f1 100644 --- a/src/platform/i18n.test.ts +++ b/src/platform/i18n.test.ts @@ -332,6 +332,9 @@ describe("catalogs", () => { "JavaScript", "TypeScript", "Vue Router", + // Python unittest: the runner's name and a dotted module placeholder. + "unittest", + "tests.test_models", "Pinia", "Vitest", "ESLint", diff --git a/src/platform/languageSettings.ts b/src/platform/languageSettings.ts index 3e5998569..5d129b5b5 100644 --- a/src/platform/languageSettings.ts +++ b/src/platform/languageSettings.ts @@ -178,6 +178,8 @@ export interface LanguagesValid { showInterpreterPaths: boolean; /** Folders added to an interpreter's `sys.path`, by interpreter executable. */ interpreterPaths: Record; + /** Default test runner of gutter and context-menu runs (Settings › Python › Testing). */ + testRunner: PythonTestRunner; }; ruby: { interpreter: string }; zig: { zig: string }; @@ -305,6 +307,9 @@ export type FolderListKey = | "excluded" | "unmarked"; +export const PYTHON_TEST_RUNNERS = ["auto", "pytest", "unittest"] as const; +export type PythonTestRunner = (typeof PYTHON_TEST_RUNNERS)[number]; + export const DEFAULT_LANGUAGES: LanguagesValid = { pluginFormatters: {}, python: { @@ -315,6 +320,7 @@ export const DEFAULT_LANGUAGES: LanguagesValid = { hideOtherProjectInterpreters: false, showInterpreterPaths: true, interpreterPaths: {}, + testRunner: "auto", }, ruby: { interpreter: "" }, zig: { zig: "" }, @@ -471,6 +477,7 @@ export function validateLanguages(raw: unknown): LanguagesValid { interpreterPaths: Object.fromEntries( Object.entries(obj(py.interpreterPaths)).map(([python, paths]) => [python, strings(paths)]), ), + testRunner: oneOf(py.testRunner, PYTHON_TEST_RUNNERS, d.python.testRunner), }, ruby: { interpreter: text(ruby.interpreter, d.ruby.interpreter) }, zig: { zig: text(zig.zig, d.zig.zig) }, diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index b0b88cd82..0b9fac4b7 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -4264,5 +4264,15 @@ "Files matching these globs, e.g. **/index.ts.": "Files matching these globs, e.g. **/index.ts.", "Regular expressions for the import path, e.g. ^node: or /index$.": "Regular expressions for the import path, e.g. ^node: or /index$.", "No expressions": "No expressions", - "Expression": "Expression" + "Expression": "Expression", + "Python unittest": "Python unittest", + "Run Python tests with python -m unittest": "Run Python tests with python -m unittest", + "Modules, classes or tests (tests.test_models.ModelTests.test_save), a file, or discover -s ; empty discovers every test": "Modules, classes or tests (tests.test_models.ModelTests.test_save), a file, or discover -s ; empty discovers every test", + "e.g. -f --locals": "e.g. -f --locals", + "Default test runner": "Default test runner", + "Autodetect": "Autodetect", + "Testing": "Testing", + "Runs tests from the gutter and the context menu. Autodetect uses pytest when the project uses it, else unittest, except for modules that don't import unittest.": "Runs tests from the gutter and the context menu. Autodetect uses pytest when the project uses it, else unittest, except for modules that don't import unittest.", + "tests.test_models": "tests.test_models", + "unittest": "unittest" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 121c9cdda..0fbb627f3 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10726,5 +10726,15 @@ "For the imports the TypeScript server adds.": "用于 TypeScript 服务器添加的导入。", "Files matching these globs, e.g. **/index.ts.": "匹配这些 glob 的文件,例如 **/index.ts。", "Regular expressions for the import path, e.g. ^node: or /index$.": "匹配导入路径的正则表达式,例如 ^node: 或 /index$。", - "No expressions": "没有表达式" + "No expressions": "没有表达式", + "Python unittest": "Python unittest 测试", + "Run Python tests with python -m unittest": "使用 python -m unittest 运行 Python 测试", + "Modules, classes or tests (tests.test_models.ModelTests.test_save), a file, or discover -s ; empty discovers every test": "模块、类或测试(tests.test_models.ModelTests.test_save)、文件,或 discover -s <文件夹>;留空则发现所有测试", + "e.g. -f --locals": "例如 -f --locals", + "Default test runner": "默认测试运行器", + "Autodetect": "自动检测", + "Testing": "测试", + "Runs tests from the gutter and the context menu. Autodetect uses pytest when the project uses it, else unittest, except for modules that don't import unittest.": "从边栏和上下文菜单运行测试时使用。自动检测:项目使用 pytest 时用 pytest,否则用 unittest;未导入 unittest 的模块仍用 pytest。", + "tests.test_models": "tests.test_models", + "unittest": "unittest" }