Skip to content

Commit

Permalink
Activate ruff B rules (#5527)
Browse files Browse the repository at this point in the history
* Activate ruff B007 rule.

* Activate ruff B009 rule.

* Activate ruff B010 rule.

* Activate ruff B008 rule.

* Activate ruff B904 rule.

* Updates per pr review.
  • Loading branch information
PhillSimonds authored Jan 22, 2025
1 parent b1e5bf4 commit 3952c75
Show file tree
Hide file tree
Showing 20 changed files with 49 additions and 53 deletions.
2 changes: 1 addition & 1 deletion backend/infrahub/api/artifact.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ async def generate_artifact(
request: Request,
artifact_definition_id: str,
payload: ArtifactGeneratePayload = Body(
ArtifactGeneratePayload(),
ArtifactGeneratePayload(), # noqa: B008
description="Payload of the request, can be used to limit the scope of the query to a specific list of hosts",
),
db: InfrahubDatabase = Depends(get_db),
Expand Down
3 changes: 2 additions & 1 deletion backend/infrahub/api/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,8 @@ async def execute_query(
async def graphql_query_post(
request: Request,
payload: QueryPayload = Body(
QueryPayload(), description="Payload of the request, must be used to provide the variables"
QueryPayload(), # noqa: B008
description="Payload of the request, must be used to provide the variables",
),
query_id: str = Path(description="ID or Name of the GraphQL query to execute"),
subscribers: list[str] = Query(
Expand Down
2 changes: 1 addition & 1 deletion backend/infrahub/cli/git_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ async def start(
await client.branch.all()
except SdkError as exc:
log.error(f"Error in communication with Infrahub: {exc.message}")
raise typer.Exit(1)
raise typer.Exit(1) from None

# Initialize trace
if config.SETTINGS.trace.enable:
Expand Down
4 changes: 2 additions & 2 deletions backend/infrahub/core/attribute.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,8 +527,8 @@ async def to_graphql(
elif isinstance(field, (int, bool, dict, list)):
response[field_name] = field

if related_node_ids and self.is_from_profile and getattr(self, "source_id"):
related_node_ids.add(getattr(self, "source_id"))
if related_node_ids and self.is_from_profile and self.source_id:
related_node_ids.add(self.source_id)

return response

Expand Down
6 changes: 3 additions & 3 deletions backend/infrahub/core/branch/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ def get_query_filter_relationships(

for rel in rel_labels:
filters_per_rel = []
for idx, (branch_name, time_to_query) in enumerate(branches_times.items()):
for idx in range(len(branches_times)):
filters_per_rel.append(
f"({rel}.branch IN $branch{idx} AND {rel}.from <= $time{idx} AND {rel}.to IS NULL)"
)
Expand Down Expand Up @@ -324,7 +324,7 @@ def get_query_filter_path(
params[f"time{idx}"] = time_to_query

filters = []
for idx, (branch_name, time_to_query) in enumerate(branches_times.items()):
for idx in range(len(branches_times)):
filters.append(
f"({variable_name}.branch IN $branch{idx} AND {variable_name}.from <= $time{idx} AND {variable_name}.to IS NULL)"
)
Expand Down Expand Up @@ -404,7 +404,7 @@ def get_query_filter_relationships_diff(

for rel in rel_labels:
filters_per_rel = []
for idx, branch_name in enumerate(start_times.keys()):
for idx in range(len(start_times)):
filters_per_rel.extend(
[
f"""({rel}.branch = $branch{idx}
Expand Down
2 changes: 1 addition & 1 deletion backend/infrahub/core/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def get_schema(
) -> MainSchemaTypes:
if isinstance(node_schema, str):
return db.schema.get(name=node_schema, branch=branch.name)
if hasattr(node_schema, "_is_runtime_protocol") and getattr(node_schema, "_is_runtime_protocol"):
if hasattr(node_schema, "_is_runtime_protocol") and node_schema._is_runtime_protocol:
return db.schema.get(name=node_schema.__name__, branch=branch.name)
if not isinstance(node_schema, (MainSchemaTypes)):
raise ValueError(f"Invalid schema provided {node_schema}")
Expand Down
2 changes: 1 addition & 1 deletion backend/infrahub/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ def init(cls, diff: SchemaDiff, schema: SchemaBranch, enforce_update_support: bo
return obj

def process_diff(self, schema: SchemaBranch) -> None:
for schema_name, schema_diff in self.diff.removed.items():
for schema_name in self.diff.removed.keys():
self.migrations.append(
SchemaUpdateMigrationInfo(
path=SchemaPath( # type: ignore[call-arg]
Expand Down
2 changes: 1 addition & 1 deletion backend/infrahub/core/node/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ async def init(
elif isinstance(schema, str):
# TODO need to raise a proper exception for this, right now it will raise a generic ValueError
attrs["schema"] = db.schema.get(name=schema, branch=branch)
elif hasattr(schema, "_is_runtime_protocol") and getattr(schema, "_is_runtime_protocol"):
elif hasattr(schema, "_is_runtime_protocol") and schema._is_runtime_protocol:
attrs["schema"] = db.schema.get(name=schema.__name__, branch=branch)
else:
raise ValueError(f"Invalid schema provided {type(schema)}, expected NodeSchema or ProfileSchema")
Expand Down
4 changes: 2 additions & 2 deletions backend/infrahub/core/schema/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ async def update_schema_to_db(

added_nodes = []
added_generics = []
for item_kind, item_diff in diff.added.items():
for item_kind in diff.added.keys():
item = schema.get(name=item_kind, duplicate=False)
node = await self.load_node_to_db(node=item, branch=branch, db=db)
schema.set(name=item_kind, schema=node)
Expand All @@ -218,7 +218,7 @@ async def update_schema_to_db(

removed_nodes = []
removed_generics = []
for item_kind, item_diff in diff.removed.items():
for item_kind in diff.removed.keys():
item = schema.get(name=item_kind, duplicate=False)
node = await self.delete_node_in_db(node=item, branch=branch, db=db)
schema.delete(name=item_kind)
Expand Down
16 changes: 8 additions & 8 deletions backend/infrahub/graphql/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,8 +479,8 @@ async def _get_operation_from_request(request: Request) -> Union[dict[str, Any],
if content_type == "application/json":
try:
return cast(Union[dict[str, Any], list[Any]], await request.json())
except (TypeError, ValueError):
raise ValueError("Request body is not a valid JSON")
except (TypeError, ValueError) as err:
raise ValueError("Request body is not a valid JSON") from err
elif content_type == "multipart/form-data":
return await _get_operation_from_multipart(request)
else:
Expand All @@ -490,24 +490,24 @@ async def _get_operation_from_request(request: Request) -> Union[dict[str, Any],
async def _get_operation_from_multipart(request: Request) -> Union[dict[str, Any], list[Any]]:
try:
request_body = await request.form()
except Exception:
raise ValueError("Request body is not a valid multipart/form-data")
except Exception as err:
raise ValueError("Request body is not a valid multipart/form-data") from err

try:
operations_value = request_body.get("operations")
operations_data = operations_value if isinstance(operations_value, str) else ""
operations = ujson.loads(operations_data)
except (TypeError, ValueError):
raise ValueError("'operations' must be a valid JSON")
except (TypeError, ValueError) as err:
raise ValueError("'operations' must be a valid JSON") from err
if not isinstance(operations, (dict, list)):
raise ValueError("'operations' field must be an Object or an Array")

try:
map_value = request_body.get("map")
map_data = map_value if isinstance(map_value, str) else ""
name_path_map = ujson.loads(map_data)
except (TypeError, ValueError):
raise ValueError("'map' field must be a valid JSON")
except (TypeError, ValueError) as err:
raise ValueError("'map' field must be a valid JSON") from err
if not isinstance(name_path_map, dict):
raise ValueError("'map' field must be an Object")

Expand Down
4 changes: 2 additions & 2 deletions backend/infrahub/graphql/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ def generate_object_types(self) -> None:
full_schema = self.schema.get_all(duplicate=False)

# Generate all GraphQL Interface Object first and store them in the registry
for node_name, node_schema in full_schema.items():
for node_schema in full_schema.values():
if not isinstance(node_schema, GenericSchema):
continue
interface = self.generate_interface_object(schema=node_schema, populate_cache=True)
Expand Down Expand Up @@ -389,7 +389,7 @@ def generate_object_types(self) -> None:
self.set_type(name=nested_edged_interface._meta.name, graphql_type=nested_edged_interface)

# Generate all GraphQL ObjectType, Nested, Paginated & NestedPaginated and store them in the registry
for node_name, node_schema in full_schema.items():
for node_schema in full_schema.values():
if isinstance(node_schema, (NodeSchema, ProfileSchema)):
node_type = self.generate_graphql_object(schema=node_schema, populate_cache=True)
node_type_edged = self.generate_graphql_edged_object(
Expand Down
4 changes: 2 additions & 2 deletions backend/infrahub/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,5 @@ def retrieve(self, identifier: str) -> str:
try:
with self._storage.open(identifier) as f:
return f.read().decode()
except (FileNotFoundError, botocore.exceptions.ClientError):
raise NodeNotFoundError(node_type="StorageObject", identifier=identifier)
except (FileNotFoundError, botocore.exceptions.ClientError) as err:
raise NodeNotFoundError(node_type="StorageObject", identifier=identifier) from err
6 changes: 3 additions & 3 deletions backend/infrahub/workers/infrahub_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,9 +169,9 @@ async def _init_infrahub_client(self, client: InfrahubClient | None = None) -> I

try:
await client.branch.all()
except SdkError as exc:
self._logger.error(f"Error in communication with Infrahub: {exc.message}")
raise typer.Exit(1)
except SdkError as err:
self._logger.error(f"Error in communication with Infrahub: {err.message}")
raise typer.Exit(1) from err

return client

Expand Down
2 changes: 1 addition & 1 deletion backend/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def pytest_configure(config):
markexpr = f"not neo4j and ({markexpr})"

if not config.option.neo4j:
setattr(config.option, "markexpr", markexpr)
config.option.markexpr = markexpr

log_level = config.option.log_level
log_level = log_level if log_level is not None else DEFAULT_TESTING_LOG_LEVEL
Expand Down
18 changes: 3 additions & 15 deletions backend/tests/scale/common/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,21 +30,9 @@ def random_ascii_string(length: int = 10) -> str:

def get_container_resource_usage(container_id: str) -> ContainerStats:
client = docker.from_env()

try:
stats = client.containers.get(container_id).stats(stream=False)
except docker.errors.NotFound:
raise Exception

try:
cpu_usage = get_cpu_usage(stats)
except KeyError:
raise Exception

try:
memory_usage = get_memory_usage(stats)
except KeyError:
raise Exception
stats = client.containers.get(container_id).stats(stream=False)
cpu_usage = get_cpu_usage(stats)
memory_usage = get_memory_usage(stats)

return ContainerStats(cpu_usage, memory_usage)

Expand Down
2 changes: 1 addition & 1 deletion backend/tests/unit/core/test_protocols.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@


def test_sanity_protocol_defined():
assert getattr(protocols, "CoreNode")
assert protocols.CoreNode
4 changes: 2 additions & 2 deletions backend/tests/unit/git/test_git_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -936,7 +936,7 @@ async def test_create_python_check_definition(
repo = git_repo_03_w_client

module = helper.import_module_in_fixtures(module="checks/check01")
check_class = getattr(module, "Check01")
check_class = module.Check01

gql_schema = await repo.client.schema.get(kind=InfrahubKind.GRAPHQLQUERY)

Expand Down Expand Up @@ -967,7 +967,7 @@ async def test_compare_python_check(
repo = git_repo_03_w_client

module = helper.import_module_in_fixtures(module="checks/check01")
check_class = getattr(module, "Check01")
check_class = module.Check01

gql_schema = await repo.client.schema.get(kind=InfrahubKind.GRAPHQLQUERY)
check_schema = await repo.client.schema.get(kind=InfrahubKind.CHECKDEFINITION)
Expand Down
1 change: 1 addition & 0 deletions changelog/2193.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Activate ruff B rules.
2 changes: 1 addition & 1 deletion models/infrastructure_edge.py
Original file line number Diff line number Diff line change
Expand Up @@ -1095,7 +1095,7 @@ async def generate_site(
}

# Here we need as much prefix as we have edge device
for i in range(site_design.num_edge_device):
for _ in range(site_design.num_edge_device):
peer_networks.append(
await client.allocate_next_ip_prefix(resource_pool=interconnection_pool, kind=IpamIPPrefix, branch=branch)
)
Expand Down
16 changes: 11 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -405,11 +405,6 @@ ignore = [
# like this so that we can reactivate them one by one. Alternatively ignored after further #
# investigation if they are deemed to not make sense. #
##################################################################################################
"B007", # Loop control variable not used within loop body
"B008", # Do not perform function call `Depends` in argument defaults;
"B009", # [*] Do not call `getattr` with a constant attribute value. It is not any safer than normal property access.
"B010", # [*] Do not call `setattr` with a constant attribute value. It is not any safer than normal property access.
"B904", # Within an `except` clause, raise exceptions with `raise ... from err` or `raise ... from None` to distinguish them from errors in exception handling
"FURB113", # Use `networks.extend(...)` instead of repeatedly calling `networks.append()`
"FURB118", # Use `operator.itemgetter(1)` instead of defining a lambda
"FURB140", # Use `itertools.starmap` instead of the generator
Expand Down Expand Up @@ -473,6 +468,17 @@ ignore = [
"UP035", # `typing.List` is deprecated, use `list` instead
]

[tool.ruff.lint.flake8-bugbear]
extend-immutable-calls = [
"fastapi.Body",
"fastapi.Depends",
"fastapi.params.Depends",
"fastapi.File",
"fastapi.Query",
"fastapi.params.Query",
"typer.Argument",
]

#https://docs.astral.sh/ruff/formatter/black/
[tool.ruff.format]
quote-style = "double"
Expand Down

0 comments on commit 3952c75

Please sign in to comment.