Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ruff] Reduce FastAPI false positives in unused-async (RUF029) #12938

Merged
merged 5 commits into from
Aug 17, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,7 @@ linter.pylint.max_public_methods = 20
linter.pylint.max_locals = 15
linter.pyupgrade.keep_runtime_typing = false
linter.ruff.parenthesize_tuple_in_subscript = false
linter.ruff.allow_fastapi_routes_unused_async = false

# Formatter Settings
formatter.exclude = []
Expand Down
AlexWaygood marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from fastapi import FastAPI

app = FastAPI()


@app.post("/count")
async def fastapi_route():
return 1
34 changes: 34 additions & 0 deletions crates/ruff_linter/src/rules/ruff/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,46 @@ mod tests {
Ok(())
}

#[test]
fn dont_allow_fastapi_routes_unused_async() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/RUF029_fastapi.py"),
&LinterSettings {
ruff: super::settings::Settings {
parenthesize_tuple_in_subscript: false,
allow_fastapi_routes_unused_async: false,
},
..LinterSettings::for_rule(Rule::UnusedAsync)
},
)?;
assert_messages!(diagnostics);
Ok(())
}

#[test]
fn allow_fastapi_routes_unused_async() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/RUF029_fastapi.py"),
&LinterSettings {
ruff: super::settings::Settings {
parenthesize_tuple_in_subscript: false,
allow_fastapi_routes_unused_async: true,
},
..LinterSettings::for_rule(Rule::UnusedAsync)
},
)?;
assert_messages!(diagnostics);
Ok(())
}

#[test]
fn prefer_parentheses_getitem_tuple() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/RUF031_prefer_parens.py"),
&LinterSettings {
ruff: super::settings::Settings {
parenthesize_tuple_in_subscript: true,
allow_fastapi_routes_unused_async: false,
},
..LinterSettings::for_rule(Rule::IncorrectlyParenthesizedTupleInSubscript)
},
Expand All @@ -90,6 +123,7 @@ mod tests {
&LinterSettings {
ruff: super::settings::Settings {
parenthesize_tuple_in_subscript: false,
allow_fastapi_routes_unused_async: false,
},
target_version: PythonVersion::Py310,
..LinterSettings::for_rule(Rule::IncorrectlyParenthesizedTupleInSubscript)
Expand Down
15 changes: 13 additions & 2 deletions crates/ruff_linter/src/rules/ruff/rules/unused_async.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use crate::checkers::ast::Checker;
use crate::rules::fastapi::rules::is_fastapi_route;
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::identifier::Identifier;
use ruff_python_ast::visitor::source_order;
use ruff_python_ast::{self as ast, AnyNodeRef, Expr, Stmt};
use ruff_python_semantic::analyze::function_type::is_stub;

use crate::checkers::ast::Checker;
use ruff_python_semantic::Modules;

/// ## What it does
/// Checks for functions declared `async` that do not await or otherwise use features requiring the
Expand All @@ -27,6 +28,9 @@ use crate::checkers::ast::Checker;
/// def foo():
/// bar()
/// ```
///
/// ## Options
/// - `lint.ruff.allow-fastapi-routes-unused-async`
#[violation]
pub struct UnusedAsync {
name: String,
Expand Down Expand Up @@ -173,6 +177,13 @@ pub(crate) fn unused_async(
return;
}

if checker.settings.ruff.allow_fastapi_routes_unused_async
&& checker.semantic().seen_module(Modules::FASTAPI)
&& is_fastapi_route(function_def, checker.semantic())
{
return;
}

let found_await_or_async = {
let mut visitor = AsyncExprVisitor::default();
source_order::walk_body(&mut visitor, body);
Expand Down
4 changes: 3 additions & 1 deletion crates/ruff_linter/src/rules/ruff/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::fmt;
#[derive(Debug, Clone, CacheKey, Default)]
pub struct Settings {
pub parenthesize_tuple_in_subscript: bool,
pub allow_fastapi_routes_unused_async: bool,
}

impl fmt::Display for Settings {
Expand All @@ -15,7 +16,8 @@ impl fmt::Display for Settings {
formatter = f,
namespace = "linter.ruff",
fields = [
self.parenthesize_tuple_in_subscript
self.parenthesize_tuple_in_subscript,
self.allow_fastapi_routes_unused_async
]
}
Ok(())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
source: crates/ruff_linter/src/rules/ruff/mod.rs
---

Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
source: crates/ruff_linter/src/rules/ruff/mod.rs
---
RUF029_fastapi.py:7:11: RUF029 Function `fastapi_route` is declared `async`, but doesn't `await` or use `async` features.
|
6 | @app.post("/count")
7 | async def fastapi_route():
| ^^^^^^^^^^^^^ RUF029
8 | return 1
|
15 changes: 15 additions & 0 deletions crates/ruff_workspace/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2986,6 +2986,18 @@ pub struct RuffOptions {
"#
)]
pub parenthesize_tuple_in_subscript: Option<bool>,

/// Whether to allow fastapi routes to be defined as async function, although they don't use
/// any asynchronous code (see `RUF029` and [FastAPI docs](https://fastapi.tiangolo.com/async/)).
#[option(
default = r#"false"#,
value_type = "bool",
example = r#"
# Make it a ok to have async functions in FastAPI routes that don't use await
parenthesize-tuple-in-subscript = true
"#
)]
pub allow_fastapi_routes_unused_async: Option<bool>,
}

impl RuffOptions {
Expand All @@ -2994,6 +3006,9 @@ impl RuffOptions {
parenthesize_tuple_in_subscript: self
.parenthesize_tuple_in_subscript
.unwrap_or_default(),
allow_fastapi_routes_unused_async: self
.allow_fastapi_routes_unused_async
.unwrap_or_default(),
}
}
}
Expand Down
7 changes: 7 additions & 0 deletions ruff.schema.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading