mirror of
https://github.com/astral-sh/ruff.git
synced 2026-12-04 02:03:58 +08:00
## Summary Today, a line break in a diagnostic message ends the annotation in GitHub Actions and Azure Pipelines. For example, an [invalid `requires-python` value and the caret pointing to it](https://github.com/astral-sh/ruff/pull/29768#discussion_r4665837003) appear on separate log lines outside the annotation. A comma in a filename can also truncate the path in GitHub Actions. This PR updates Ruff and ty to escape line breaks and percent signs in diagnostic messages and command properties. It also escapes delimiters in property values such as file paths, following the rules in the [GitHub Actions toolkit](https://github.com/actions/toolkit/blob/0c3a9c332b678ff1e776f93d728a4ad279803abe/packages/core/src/command.ts#L103-L117) and [Azure Pipelines task library](https://github.com/microsoft/azure-pipelines-task-lib/blob/43673c958dc5fb40b898c5c7b5b7b5bf0ebd14bd/node/taskcommand.ts#L93-L110). This keeps the full message in one annotation and preserves literal text like `%0A`. ## Notes to reviewers Escaping adds about 14–27 ns per short diagnostic in a local rendering benchmark. I measured median wall time in ns per diagnostic over 24 runs per variant in alternating order on an M5 Max with the profiling profile. Each run rendered 2,048 prebuilt diagnostics into a reusable string 64 times, excluding analysis and I/O. | Message | GitHub main | GitHub PR | Azure main | Azure PR | |---|---:|---:|---:|---:| | Short | 147 | 174 | 68 | 82 | | Headline and primary label | 157 | 185 | 78 | 93 | | Long (492 bytes) | 152 | 183 | 73 | 93 | | Multiline with literal `%0A` | 156 | 223 | 70 | 124 | The renderer tests, full Ruff and ty CLI test suites, and Clippy passed locally.
1113 lines
31 KiB
Rust
1113 lines
31 KiB
Rust
mod analysis_options;
|
|
mod baseline;
|
|
mod config_option;
|
|
mod exit_code;
|
|
mod file_selection;
|
|
mod fixes;
|
|
mod python_environment;
|
|
mod rule;
|
|
mod rule_selection;
|
|
mod scripts;
|
|
mod server;
|
|
mod uv_workspace;
|
|
|
|
#[path = "../common/mod.rs"]
|
|
pub mod common;
|
|
|
|
use std::fmt::Write;
|
|
|
|
use insta_cmd::assert_cmd_snapshot;
|
|
use test_case::test_case;
|
|
|
|
use common::{CliTest, user_config_directory_env_var};
|
|
|
|
#[test]
|
|
fn test_quiet_output() -> anyhow::Result<()> {
|
|
let case = CliTest::with_file("test.py", "x: int = 1")?;
|
|
|
|
// By default, we emit an "all checks passed" message
|
|
assert_cmd_snapshot!(case.command(), @"
|
|
success: true
|
|
exit_code: 0
|
|
----- stdout -----
|
|
All checks passed!
|
|
|
|
----- stderr -----
|
|
");
|
|
|
|
// With `quiet`, the message is not displayed
|
|
assert_cmd_snapshot!(case.command().arg("--quiet"), @"
|
|
success: true
|
|
exit_code: 0
|
|
----- stdout -----
|
|
|
|
----- stderr -----
|
|
");
|
|
|
|
let case = CliTest::with_file("test.py", "x: int = 'foo'")?;
|
|
|
|
// By default, we emit a diagnostic
|
|
assert_cmd_snapshot!(case.command(), @r#"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
error[invalid-assignment]: Object of type `Literal["foo"]` is not assignable to `int`
|
|
--> test.py:1:10
|
|
|
|
|
1 | x: int = 'foo'
|
|
| --- ^^^^^ Incompatible value of type `Literal["foo"]`
|
|
| |
|
|
| Declared type
|
|
|
|
Found 1 diagnostic
|
|
|
|
----- stderr -----
|
|
"#);
|
|
|
|
// With `quiet`, the diagnostic is not displayed, just the summary message
|
|
assert_cmd_snapshot!(case.command().arg("--quiet"), @"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
Found 1 diagnostic
|
|
|
|
----- stderr -----
|
|
");
|
|
|
|
// We allow `-q`
|
|
assert_cmd_snapshot!(case.command().arg("-q"), @"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
Found 1 diagnostic
|
|
|
|
----- stderr -----
|
|
");
|
|
|
|
// And repeated `-qq`
|
|
assert_cmd_snapshot!(case.command().arg("-qq"), @"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
|
|
----- stderr -----
|
|
");
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[test]
|
|
fn test_output_format_env() -> anyhow::Result<()> {
|
|
let case = CliTest::with_file(
|
|
"test.py",
|
|
r#"
|
|
print(x) # [unresolved-reference]
|
|
print(4[1]) # [not-subscriptable]
|
|
from typing_extensions import reveal_type
|
|
reveal_type('str'.lower()) # [revealed-type]
|
|
"#,
|
|
)?
|
|
.with_filter(r",file=[^,\n]+[\\/]", ",file=<temp_dir>/");
|
|
assert_cmd_snapshot!(case.command().env("TY_OUTPUT_FORMAT", "github").arg("--warn").arg("unresolved-reference"), @"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
::warning title=ty (unresolved-reference),file=<temp_dir>/test.py,line=2,col=7,endLine=2,endColumn=8::test.py:2:7: unresolved-reference: Name `x` used when not defined
|
|
::error title=ty (not-subscriptable),file=<temp_dir>/test.py,line=3,col=7,endLine=3,endColumn=11::test.py:3:7: not-subscriptable: Cannot subscript object of type `Literal[4]` with no `__getitem__` method
|
|
::notice title=ty (revealed-type),file=<temp_dir>/test.py,line=5,col=13,endLine=5,endColumn=26::test.py:5:13: revealed-type: Revealed type: `LiteralString`
|
|
|
|
----- stderr -----
|
|
");
|
|
Ok(())
|
|
}
|
|
|
|
#[test]
|
|
fn test_run_in_sub_directory() -> anyhow::Result<()> {
|
|
let case = CliTest::with_files([("test.py", "~"), ("subdir/nothing", "")])?;
|
|
assert_cmd_snapshot!(case.command().current_dir(case.root().join("subdir")).arg(".."), @"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
error[invalid-syntax]: Expected an expression
|
|
--> <temp_dir>/test.py:1:2
|
|
|
|
|
1 | ~
|
|
| ^
|
|
|
|
Found 1 diagnostic
|
|
|
|
----- stderr -----
|
|
");
|
|
Ok(())
|
|
}
|
|
|
|
#[test]
|
|
fn test_include_hidden_files_by_default() -> anyhow::Result<()> {
|
|
let case = CliTest::with_files([(".test.py", "~")])?;
|
|
assert_cmd_snapshot!(case.command(), @"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
error[invalid-syntax]: Expected an expression
|
|
--> .test.py:1:2
|
|
|
|
|
1 | ~
|
|
| ^
|
|
|
|
Found 1 diagnostic
|
|
|
|
----- stderr -----
|
|
");
|
|
Ok(())
|
|
}
|
|
|
|
#[test]
|
|
fn test_respect_ignore_files() -> anyhow::Result<()> {
|
|
// First test that the default option works correctly (the file is skipped)
|
|
let case = CliTest::with_files([(".ignore", "test.py"), ("test.py", "~")])?;
|
|
assert_cmd_snapshot!(case.command(), @"
|
|
success: true
|
|
exit_code: 0
|
|
----- stdout -----
|
|
All checks passed!
|
|
|
|
----- stderr -----
|
|
WARN No python files found under the given path(s)
|
|
");
|
|
|
|
// Test that we can set to false via CLI
|
|
assert_cmd_snapshot!(case.command().arg("--no-respect-ignore-files"), @"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
error[invalid-syntax]: Expected an expression
|
|
--> test.py:1:2
|
|
|
|
|
1 | ~
|
|
| ^
|
|
|
|
Found 1 diagnostic
|
|
|
|
----- stderr -----
|
|
");
|
|
|
|
// Test that we can set to false via config file
|
|
case.write_file("ty.toml", "src.respect-ignore-files = false")?;
|
|
assert_cmd_snapshot!(case.command(), @"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
error[invalid-syntax]: Expected an expression
|
|
--> test.py:1:2
|
|
|
|
|
1 | ~
|
|
| ^
|
|
|
|
Found 1 diagnostic
|
|
|
|
----- stderr -----
|
|
");
|
|
|
|
// Ensure CLI takes precedence
|
|
case.write_file("ty.toml", "src.respect-ignore-files = true")?;
|
|
assert_cmd_snapshot!(case.command().arg("--no-respect-ignore-files"), @"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
error[invalid-syntax]: Expected an expression
|
|
--> test.py:1:2
|
|
|
|
|
1 | ~
|
|
| ^
|
|
|
|
Found 1 diagnostic
|
|
|
|
----- stderr -----
|
|
");
|
|
Ok(())
|
|
}
|
|
|
|
/// Paths specified on the CLI are relative to the current working directory and not the project root.
|
|
///
|
|
/// We test this by adding an extra search path from the CLI to the libs directory when
|
|
/// running the CLI from the child directory (using relative paths).
|
|
///
|
|
/// Project layout:
|
|
/// ```
|
|
/// - libs
|
|
/// |- utils.py
|
|
/// - child
|
|
/// | - test.py
|
|
/// - pyproject.toml
|
|
/// ```
|
|
///
|
|
/// And the command is run in the `child` directory.
|
|
#[test]
|
|
fn cli_arguments_are_relative_to_the_current_directory() -> anyhow::Result<()> {
|
|
let case = CliTest::with_files([
|
|
(
|
|
"pyproject.toml",
|
|
r#"
|
|
[tool.ty.environment]
|
|
python-version = "3.11"
|
|
"#,
|
|
),
|
|
(
|
|
"libs/utils.py",
|
|
r#"
|
|
def add(a: int, b: int) -> int:
|
|
return a + b
|
|
"#,
|
|
),
|
|
(
|
|
"child/test.py",
|
|
r#"
|
|
from utils import add
|
|
|
|
stat = add(10, 15)
|
|
"#,
|
|
),
|
|
])?;
|
|
|
|
// Make sure that the CLI fails when the `libs` directory is not in the search path.
|
|
assert_cmd_snapshot!(case.command().current_dir(case.root().join("child")), @"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
error[import-not-found]: Cannot resolve imported module `utils`
|
|
--> test.py:2:6
|
|
|
|
|
2 | from utils import add
|
|
| ^^^^^
|
|
info: Searched in the following paths during module resolution:
|
|
info: 1. <temp_dir>/ (first-party code)
|
|
info: 2. vendored://stdlib (stdlib typeshed stubs vendored by ty)
|
|
info: make sure your Python environment is properly configured: https://docs.astral.sh/ty/modules/#python-environment
|
|
|
|
Found 1 diagnostic
|
|
|
|
----- stderr -----
|
|
");
|
|
|
|
assert_cmd_snapshot!(case.command().current_dir(case.root().join("child")).arg("--extra-search-path").arg("../libs"), @"
|
|
success: true
|
|
exit_code: 0
|
|
----- stdout -----
|
|
All checks passed!
|
|
|
|
----- stderr -----
|
|
");
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Paths specified in a configuration file are relative to the project root.
|
|
///
|
|
/// We test this by adding `libs` (as a relative path) to the extra search path in the configuration and run
|
|
/// the CLI from a subdirectory.
|
|
///
|
|
/// Project layout:
|
|
/// ```
|
|
/// - libs
|
|
/// |- utils.py
|
|
/// - child
|
|
/// | - test.py
|
|
/// - pyproject.toml
|
|
/// ```
|
|
#[test]
|
|
fn paths_in_configuration_files_are_relative_to_the_project_root() -> anyhow::Result<()> {
|
|
let case = CliTest::with_files([
|
|
(
|
|
"pyproject.toml",
|
|
r#"
|
|
[tool.ty.environment]
|
|
python-version = "3.11"
|
|
extra-paths = ["libs"]
|
|
"#,
|
|
),
|
|
(
|
|
"libs/utils.py",
|
|
r#"
|
|
def add(a: int, b: int) -> int:
|
|
return a + b
|
|
"#,
|
|
),
|
|
(
|
|
"child/test.py",
|
|
r#"
|
|
from utils import add
|
|
|
|
stat = add(10, 15)
|
|
"#,
|
|
),
|
|
])?;
|
|
|
|
assert_cmd_snapshot!(case.command().current_dir(case.root().join("child")), @"
|
|
success: true
|
|
exit_code: 0
|
|
----- stdout -----
|
|
All checks passed!
|
|
|
|
----- stderr -----
|
|
");
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[test]
|
|
fn user_configuration() -> anyhow::Result<()> {
|
|
let case = CliTest::with_files([
|
|
(
|
|
"project/ty.toml",
|
|
r#"
|
|
[rules]
|
|
division-by-zero = "warn"
|
|
"#,
|
|
),
|
|
(
|
|
"project/main.py",
|
|
r#"
|
|
y = 4 / 0
|
|
|
|
for a in range(0, int(y)):
|
|
x = a
|
|
|
|
prin(x)
|
|
"#,
|
|
),
|
|
])?;
|
|
|
|
let config_directory = case.user_config_directory();
|
|
let config_env_var = user_config_directory_env_var();
|
|
|
|
assert_cmd_snapshot!(
|
|
case.command().arg("--verbose").current_dir(case.root().join("project")).env(config_env_var, config_directory.as_os_str()),
|
|
@"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
warning[division-by-zero]: Cannot divide object of type `Literal[4]` by zero
|
|
--> main.py:2:5
|
|
|
|
|
2 | y = 4 / 0
|
|
| ^^^^^
|
|
info: rule `division-by-zero` was selected in the configuration file
|
|
|
|
error[unresolved-reference]: Name `prin` used when not defined
|
|
--> main.py:7:1
|
|
|
|
|
7 | prin(x)
|
|
| ^^^^
|
|
info: rule `unresolved-reference` is enabled by default
|
|
|
|
Found 2 diagnostics
|
|
|
|
----- stderr -----
|
|
INFO Indexed 1 file(s) in 0.000s
|
|
"
|
|
);
|
|
|
|
// The user-level configuration sets the severity for `unresolved-reference` to warn.
|
|
// Changing the level for `division-by-zero` has no effect, because the project-level configuration
|
|
// has higher precedence.
|
|
case.write_file(
|
|
config_directory.join("ty/ty.toml"),
|
|
r#"
|
|
[rules]
|
|
division-by-zero = "error"
|
|
unresolved-reference = "warn"
|
|
"#,
|
|
)?;
|
|
|
|
assert_cmd_snapshot!(
|
|
case.command().arg("--verbose").current_dir(case.root().join("project")).env(config_env_var, config_directory.as_os_str()),
|
|
@"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
warning[division-by-zero]: Cannot divide object of type `Literal[4]` by zero
|
|
--> main.py:2:5
|
|
|
|
|
2 | y = 4 / 0
|
|
| ^^^^^
|
|
info: rule `division-by-zero` was selected in the configuration file
|
|
|
|
warning[unresolved-reference]: Name `prin` used when not defined
|
|
--> main.py:7:1
|
|
|
|
|
7 | prin(x)
|
|
| ^^^^
|
|
info: rule `unresolved-reference` was selected in the configuration file
|
|
|
|
Found 2 diagnostics
|
|
|
|
----- stderr -----
|
|
INFO Indexed 1 file(s) in 0.000s
|
|
"
|
|
);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[test]
|
|
fn check_specific_paths() -> anyhow::Result<()> {
|
|
let case = CliTest::with_files([
|
|
(
|
|
"project/main.py",
|
|
r#"
|
|
y = 4 / 0 # error: division-by-zero
|
|
"#,
|
|
),
|
|
(
|
|
"project/tests/test_main.py",
|
|
r#"
|
|
import does_not_exist # error: import-not-found
|
|
"#,
|
|
),
|
|
(
|
|
"project/other.py",
|
|
r#"
|
|
from main2 import z # error: import-not-found
|
|
|
|
print(z)
|
|
"#,
|
|
),
|
|
])?;
|
|
|
|
assert_cmd_snapshot!(
|
|
case.command(),
|
|
@"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
error[import-not-found]: Cannot resolve imported module `main2`
|
|
--> project/other.py:2:6
|
|
|
|
|
2 | from main2 import z # error: import-not-found
|
|
| ^^^^^
|
|
info: Searched in the following paths during module resolution:
|
|
info: 1. <temp_dir>/ (first-party code)
|
|
info: 2. vendored://stdlib (stdlib typeshed stubs vendored by ty)
|
|
info: make sure your Python environment is properly configured: https://docs.astral.sh/ty/modules/#python-environment
|
|
|
|
error[import-not-found]: Cannot resolve imported module `does_not_exist`
|
|
--> project/tests/test_main.py:2:8
|
|
|
|
|
2 | import does_not_exist # error: import-not-found
|
|
| ^^^^^^^^^^^^^^
|
|
info: Searched in the following paths during module resolution:
|
|
info: 1. <temp_dir>/ (first-party code)
|
|
info: 2. vendored://stdlib (stdlib typeshed stubs vendored by ty)
|
|
info: make sure your Python environment is properly configured: https://docs.astral.sh/ty/modules/#python-environment
|
|
|
|
Found 2 diagnostics
|
|
|
|
----- stderr -----
|
|
"
|
|
);
|
|
|
|
// Now check only the `tests` and `other.py` files.
|
|
// We should no longer see any diagnostics related to `main.py`.
|
|
assert_cmd_snapshot!(
|
|
case.command().arg("project/tests").arg("project/other.py"),
|
|
@"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
error[import-not-found]: Cannot resolve imported module `main2`
|
|
--> project/other.py:2:6
|
|
|
|
|
2 | from main2 import z # error: import-not-found
|
|
| ^^^^^
|
|
info: Searched in the following paths during module resolution:
|
|
info: 1. <temp_dir>/ (first-party code)
|
|
info: 2. vendored://stdlib (stdlib typeshed stubs vendored by ty)
|
|
info: make sure your Python environment is properly configured: https://docs.astral.sh/ty/modules/#python-environment
|
|
|
|
error[import-not-found]: Cannot resolve imported module `does_not_exist`
|
|
--> project/tests/test_main.py:2:8
|
|
|
|
|
2 | import does_not_exist # error: import-not-found
|
|
| ^^^^^^^^^^^^^^
|
|
info: Searched in the following paths during module resolution:
|
|
info: 1. <temp_dir>/ (first-party code)
|
|
info: 2. vendored://stdlib (stdlib typeshed stubs vendored by ty)
|
|
info: make sure your Python environment is properly configured: https://docs.astral.sh/ty/modules/#python-environment
|
|
|
|
Found 2 diagnostics
|
|
|
|
----- stderr -----
|
|
"
|
|
);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[test]
|
|
fn check_non_existing_path() -> anyhow::Result<()> {
|
|
let case = CliTest::with_files([])?;
|
|
|
|
let mut settings = insta::Settings::clone_current();
|
|
settings.add_filter(
|
|
®ex::escape("The system cannot find the path specified. (os error 3)"),
|
|
"No such file or directory (os error 2)",
|
|
);
|
|
let _s = settings.bind_to_scope();
|
|
|
|
assert_cmd_snapshot!(
|
|
case.command().arg("project/main.py").arg("project/tests"),
|
|
@"
|
|
success: false
|
|
exit_code: 2
|
|
----- stdout -----
|
|
error[io]: `<temp_dir>/project/main.py`: No such file or directory (os error 2)
|
|
|
|
error[io]: `<temp_dir>/project/tests`: No such file or directory (os error 2)
|
|
|
|
Found 2 diagnostics
|
|
|
|
----- stderr -----
|
|
WARN No python files found under the given path(s)
|
|
"
|
|
);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[test]
|
|
fn check_file_without_extension() -> anyhow::Result<()> {
|
|
let case = CliTest::with_file("main", "a = b")?;
|
|
|
|
assert_cmd_snapshot!(
|
|
case.command().arg("main"),
|
|
@"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
error[unresolved-reference]: Name `b` used when not defined
|
|
--> main:1:5
|
|
|
|
|
1 | a = b
|
|
| ^
|
|
|
|
Found 1 diagnostic
|
|
|
|
----- stderr -----
|
|
"
|
|
);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[test]
|
|
fn check_file_without_extension_in_subfolder() -> anyhow::Result<()> {
|
|
let case = CliTest::with_file("src/main", "a = b")?;
|
|
|
|
assert_cmd_snapshot!(
|
|
case.command().arg("src"),
|
|
@"
|
|
success: true
|
|
exit_code: 0
|
|
----- stdout -----
|
|
All checks passed!
|
|
|
|
----- stderr -----
|
|
WARN No python files found under the given path(s)
|
|
"
|
|
);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[test]
|
|
fn concise_diagnostics() -> anyhow::Result<()> {
|
|
let case = CliTest::with_file(
|
|
"test.py",
|
|
r#"
|
|
print(x) # [unresolved-reference]
|
|
print(4[1]) # [not-subscriptable]
|
|
"#,
|
|
)?;
|
|
|
|
assert_cmd_snapshot!(case.command().arg("--output-format=concise").arg("--warn").arg("unresolved-reference"), @"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
test.py:2:7: warning[unresolved-reference] Name `x` used when not defined
|
|
test.py:3:7: error[not-subscriptable] Cannot subscript object of type `Literal[4]` with no `__getitem__` method
|
|
Found 2 diagnostics
|
|
|
|
----- stderr -----
|
|
");
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Check which CLI and environment settings force ANSI styling in a piped diagnostic.
|
|
#[test_case(None, &[] => false; "automatic detection")]
|
|
#[test_case(None, &[("FORCE_COLOR", "0")] => true; "force color")]
|
|
#[test_case(None, &[("FORCE_COLOR", ""), ("CLICOLOR_FORCE", "0")] => true; "empty force color defers")]
|
|
#[test_case(None, &[("CLICOLOR_FORCE", "")] => false; "empty clicolor force")]
|
|
#[test_case(None, &[("CLICOLOR", "1")] => false; "clicolor requires a terminal")]
|
|
#[test_case(None, &[("NO_COLOR", "0"), ("CLICOLOR_FORCE", "1")] => false; "no color beats clicolor force")]
|
|
#[test_case(None, &[("NO_COLOR", "0"), ("FORCE_COLOR", "0")] => false; "no color wins")]
|
|
#[test_case(Some("auto"), &[("NO_COLOR", ""), ("FORCE_COLOR", "0")] => true; "empty no color")]
|
|
#[test_case(Some("always"), &[("NO_COLOR", "0")] => true; "explicit always")]
|
|
#[test_case(Some("never"), &[("FORCE_COLOR", "0")] => false; "explicit never")]
|
|
fn color_in_piped_diagnostics(flag: Option<&str>, env: &[(&str, &str)]) -> bool {
|
|
let case = CliTest::with_file("test.py", "x: int = 'wrong'").unwrap();
|
|
let mut command = case.command();
|
|
if let Some(flag) = flag {
|
|
command.args(["--color", flag]);
|
|
}
|
|
let output = command
|
|
.arg("--output-format=concise")
|
|
.envs(env.iter().copied())
|
|
.output()
|
|
.unwrap();
|
|
|
|
assert_eq!(output.status.code(), Some(1));
|
|
let stdout = String::from_utf8(output.stdout).unwrap();
|
|
let diagnostic = stdout
|
|
.lines()
|
|
.find(|line| line.contains("invalid-assignment"))
|
|
.unwrap();
|
|
diagnostic.contains("\x1b[")
|
|
}
|
|
|
|
#[test]
|
|
fn gitlab_diagnostics() -> anyhow::Result<()> {
|
|
let case = CliTest::with_file(
|
|
"test.py",
|
|
r#"
|
|
print(x) # [unresolved-reference]
|
|
print(4[1]) # [not-subscriptable]
|
|
from typing_extensions import reveal_type
|
|
reveal_type('str'.lower()) # [revealed-type]
|
|
"#,
|
|
)?;
|
|
|
|
let mut settings = insta::Settings::clone_current();
|
|
settings.add_filter(r#"("fingerprint": ")[a-z0-9]+(",)"#, "$1[FINGERPRINT]$2");
|
|
let _s = settings.bind_to_scope();
|
|
|
|
assert_cmd_snapshot!(case.command().arg("--output-format=gitlab").arg("--warn").arg("unresolved-reference")
|
|
.env("CI_PROJECT_DIR", case.project_dir), @r#"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
[
|
|
{
|
|
"check_name": "unresolved-reference",
|
|
"description": "unresolved-reference: Name `x` used when not defined",
|
|
"severity": "minor",
|
|
"fingerprint": "[FINGERPRINT]",
|
|
"location": {
|
|
"path": "test.py",
|
|
"positions": {
|
|
"begin": {
|
|
"line": 2,
|
|
"column": 7
|
|
},
|
|
"end": {
|
|
"line": 2,
|
|
"column": 8
|
|
}
|
|
}
|
|
}
|
|
},
|
|
{
|
|
"check_name": "not-subscriptable",
|
|
"description": "not-subscriptable: Cannot subscript object of type `Literal[4]` with no `__getitem__` method",
|
|
"severity": "major",
|
|
"fingerprint": "[FINGERPRINT]",
|
|
"location": {
|
|
"path": "test.py",
|
|
"positions": {
|
|
"begin": {
|
|
"line": 3,
|
|
"column": 7
|
|
},
|
|
"end": {
|
|
"line": 3,
|
|
"column": 11
|
|
}
|
|
}
|
|
}
|
|
},
|
|
{
|
|
"check_name": "revealed-type",
|
|
"description": "revealed-type: Revealed type: `LiteralString`",
|
|
"severity": "info",
|
|
"fingerprint": "[FINGERPRINT]",
|
|
"location": {
|
|
"path": "test.py",
|
|
"positions": {
|
|
"begin": {
|
|
"line": 5,
|
|
"column": 13
|
|
},
|
|
"end": {
|
|
"line": 5,
|
|
"column": 26
|
|
}
|
|
}
|
|
}
|
|
}
|
|
]
|
|
----- stderr -----
|
|
"#);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[test]
|
|
fn gitlab_empty_diagnostics() -> anyhow::Result<()> {
|
|
let case = CliTest::with_file("test.py", "1")?;
|
|
|
|
assert_cmd_snapshot!(case.command().arg("--output-format=gitlab"), @"
|
|
success: true
|
|
exit_code: 0
|
|
----- stdout -----
|
|
[]
|
|
----- stderr -----
|
|
");
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[test]
|
|
fn github_diagnostics() -> anyhow::Result<()> {
|
|
let case = CliTest::with_file(
|
|
"test.py",
|
|
r#"
|
|
print(x) # [unresolved-reference]
|
|
print(4[1]) # [not-subscriptable]
|
|
from typing_extensions import reveal_type
|
|
reveal_type('str'.lower()) # [revealed-type]
|
|
"#,
|
|
)?
|
|
.with_filter(r",file=[^,\n]+[\\/]", ",file=<temp_dir>/");
|
|
|
|
assert_cmd_snapshot!(case.command().arg("--output-format=github").arg("--warn").arg("unresolved-reference"), @"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
::warning title=ty (unresolved-reference),file=<temp_dir>/test.py,line=2,col=7,endLine=2,endColumn=8::test.py:2:7: unresolved-reference: Name `x` used when not defined
|
|
::error title=ty (not-subscriptable),file=<temp_dir>/test.py,line=3,col=7,endLine=3,endColumn=11::test.py:3:7: not-subscriptable: Cannot subscript object of type `Literal[4]` with no `__getitem__` method
|
|
::notice title=ty (revealed-type),file=<temp_dir>/test.py,line=5,col=13,endLine=5,endColumn=26::test.py:5:13: revealed-type: Revealed type: `LiteralString`
|
|
|
|
----- stderr -----
|
|
");
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[test]
|
|
fn sarif_diagnostics() -> anyhow::Result<()> {
|
|
let case = CliTest::with_files([
|
|
(
|
|
"ty.toml",
|
|
r#"
|
|
[rules]
|
|
division-by-zero = "warn"
|
|
unused-ignore-comment = "error"
|
|
|
|
[[overrides]]
|
|
include = ["a.py"]
|
|
|
|
[overrides.rules]
|
|
unresolved-reference = "warn"
|
|
"#,
|
|
),
|
|
("a.py", "print(x)"),
|
|
(
|
|
"b.py",
|
|
r#"
|
|
print(x)
|
|
1 / 0 # ty: ignore[unresolved-reference]
|
|
"#,
|
|
),
|
|
])?
|
|
.with_filter(
|
|
r#"("fullDescription": \{\s*"text": ")[^\n]*(")"#,
|
|
"$1[DESCRIPTION]$2",
|
|
)
|
|
.with_filter(r#"(?m)^(\s{10}"version": ")[^"]+"#, "$1[VERSION]")
|
|
.with_filter(r#"file://[^"]*/project/"#, "file://<temp_dir>/");
|
|
|
|
assert_cmd_snapshot!(case.command().arg("--output-format=sarif"), @r#"
|
|
success: false
|
|
exit_code: 1
|
|
----- stdout -----
|
|
{
|
|
"$schema": "https://json.schemastore.org/sarif-2.1.0.json",
|
|
"runs": [
|
|
{
|
|
"results": [
|
|
{
|
|
"level": "warning",
|
|
"locations": [
|
|
{
|
|
"physicalLocation": {
|
|
"artifactLocation": {
|
|
"uri": "file://<temp_dir>/a.py"
|
|
},
|
|
"region": {
|
|
"endColumn": 8,
|
|
"endLine": 1,
|
|
"startColumn": 7,
|
|
"startLine": 1
|
|
}
|
|
}
|
|
}
|
|
],
|
|
"message": {
|
|
"text": "Name `x` used when not defined"
|
|
},
|
|
"ruleId": "unresolved-reference"
|
|
},
|
|
{
|
|
"level": "error",
|
|
"locations": [
|
|
{
|
|
"physicalLocation": {
|
|
"artifactLocation": {
|
|
"uri": "file://<temp_dir>/b.py"
|
|
},
|
|
"region": {
|
|
"endColumn": 8,
|
|
"endLine": 2,
|
|
"startColumn": 7,
|
|
"startLine": 2
|
|
}
|
|
}
|
|
}
|
|
],
|
|
"message": {
|
|
"text": "Name `x` used when not defined"
|
|
},
|
|
"ruleId": "unresolved-reference"
|
|
},
|
|
{
|
|
"level": "warning",
|
|
"locations": [
|
|
{
|
|
"physicalLocation": {
|
|
"artifactLocation": {
|
|
"uri": "file://<temp_dir>/b.py"
|
|
},
|
|
"region": {
|
|
"endColumn": 6,
|
|
"endLine": 3,
|
|
"startColumn": 1,
|
|
"startLine": 3
|
|
}
|
|
}
|
|
}
|
|
],
|
|
"message": {
|
|
"text": "Cannot divide object of type `Literal[1]` by zero"
|
|
},
|
|
"ruleId": "division-by-zero"
|
|
},
|
|
{
|
|
"fixes": [
|
|
{
|
|
"artifactChanges": [
|
|
{
|
|
"artifactLocation": {
|
|
"uri": "file://<temp_dir>/b.py"
|
|
},
|
|
"replacements": [
|
|
{
|
|
"deletedRegion": {
|
|
"endColumn": 42,
|
|
"endLine": 3,
|
|
"startColumn": 6,
|
|
"startLine": 3
|
|
}
|
|
}
|
|
]
|
|
}
|
|
],
|
|
"description": {
|
|
"text": "Remove the unused suppression comment"
|
|
}
|
|
}
|
|
],
|
|
"level": "error",
|
|
"locations": [
|
|
{
|
|
"physicalLocation": {
|
|
"artifactLocation": {
|
|
"uri": "file://<temp_dir>/b.py"
|
|
},
|
|
"region": {
|
|
"endColumn": 42,
|
|
"endLine": 3,
|
|
"startColumn": 8,
|
|
"startLine": 3
|
|
}
|
|
}
|
|
}
|
|
],
|
|
"message": {
|
|
"text": "Unused `ty: ignore` directive"
|
|
},
|
|
"ruleId": "unused-ignore-comment"
|
|
}
|
|
],
|
|
"tool": {
|
|
"driver": {
|
|
"informationUri": "https://github.com/astral-sh/ty",
|
|
"name": "ty",
|
|
"rules": [
|
|
{
|
|
"defaultConfiguration": {
|
|
"enabled": false
|
|
},
|
|
"fullDescription": {
|
|
"text": "[DESCRIPTION]"
|
|
},
|
|
"help": {
|
|
"text": "detects division by zero"
|
|
},
|
|
"helpUri": "https://ty.dev/rules#division-by-zero",
|
|
"id": "division-by-zero",
|
|
"properties": {
|
|
"id": "division-by-zero",
|
|
"kind": null,
|
|
"name": "division-by-zero",
|
|
"problem.severity": "warning"
|
|
},
|
|
"shortDescription": {
|
|
"text": "detects division by zero"
|
|
}
|
|
},
|
|
{
|
|
"defaultConfiguration": {
|
|
"enabled": true,
|
|
"level": "error"
|
|
},
|
|
"fullDescription": {
|
|
"text": "[DESCRIPTION]"
|
|
},
|
|
"help": {
|
|
"text": "detects references to names that are not defined"
|
|
},
|
|
"helpUri": "https://ty.dev/rules#unresolved-reference",
|
|
"id": "unresolved-reference",
|
|
"properties": {
|
|
"id": "unresolved-reference",
|
|
"kind": null,
|
|
"name": "unresolved-reference",
|
|
"problem.severity": "error"
|
|
},
|
|
"shortDescription": {
|
|
"text": "detects references to names that are not defined"
|
|
}
|
|
},
|
|
{
|
|
"defaultConfiguration": {
|
|
"enabled": true,
|
|
"level": "warning"
|
|
},
|
|
"fullDescription": {
|
|
"text": "[DESCRIPTION]"
|
|
},
|
|
"help": {
|
|
"text": "detects unused `ty: ignore` comments"
|
|
},
|
|
"helpUri": "https://ty.dev/rules#unused-ignore-comment",
|
|
"id": "unused-ignore-comment",
|
|
"properties": {
|
|
"id": "unused-ignore-comment",
|
|
"kind": null,
|
|
"name": "unused-ignore-comment",
|
|
"problem.severity": "error"
|
|
},
|
|
"shortDescription": {
|
|
"text": "detects unused `ty: ignore` comments"
|
|
}
|
|
}
|
|
],
|
|
"version": "[VERSION]"
|
|
}
|
|
}
|
|
}
|
|
],
|
|
"version": "2.1.0"
|
|
}
|
|
----- stderr -----
|
|
"#);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// This tests the diagnostic format for revealed type.
|
|
///
|
|
/// This test was introduced because changes were made to
|
|
/// how the revealed type diagnostic was constructed and
|
|
/// formatted in "verbose" mode. But it required extra
|
|
/// logic to ensure the concise version didn't regress on
|
|
/// information content. So this test was introduced to
|
|
/// capture that.
|
|
#[test]
|
|
fn concise_revealed_type() -> anyhow::Result<()> {
|
|
let case = CliTest::with_file(
|
|
"test.py",
|
|
r#"
|
|
from typing_extensions import reveal_type
|
|
|
|
x = "hello"
|
|
reveal_type(x)
|
|
"#,
|
|
)?;
|
|
|
|
assert_cmd_snapshot!(case.command().arg("--output-format=concise"), @r#"
|
|
success: true
|
|
exit_code: 0
|
|
----- stdout -----
|
|
test.py:5:13: info[revealed-type] Revealed type: `Literal["hello"]`
|
|
Found 1 diagnostic
|
|
|
|
----- stderr -----
|
|
"#);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[test]
|
|
fn can_handle_large_binop_expressions() -> anyhow::Result<()> {
|
|
let mut content = String::new();
|
|
writeln!(
|
|
&mut content,
|
|
"
|
|
from typing_extensions import reveal_type
|
|
total = 1{plus_one_repeated}
|
|
reveal_type(total)
|
|
",
|
|
plus_one_repeated = " + 1".repeat(2000 - 1)
|
|
)?;
|
|
|
|
let case = CliTest::with_file("test.py", &ruff_python_trivia::textwrap::dedent(&content))?;
|
|
|
|
assert_cmd_snapshot!(case.command(), @"
|
|
success: true
|
|
exit_code: 0
|
|
----- stdout -----
|
|
info[revealed-type]: Revealed type
|
|
--> test.py:4:13
|
|
|
|
|
4 | reveal_type(total)
|
|
| ^^^^^ `Literal[2000]`
|
|
|
|
Found 1 diagnostic
|
|
|
|
----- stderr -----
|
|
");
|
|
|
|
Ok(())
|
|
}
|