Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
12 changes: 12 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.11.0
hooks:
# Run the linter.
- id: ruff
args: [ --fix ]
files: ^chk/.*\.py$
# Run the formatter.
- id: ruff-format
files: ^chk/.*\.py$
4 changes: 1 addition & 3 deletions chk/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
"""
chk command-line app
"""
"""chk command-line app"""
24 changes: 6 additions & 18 deletions chk/console/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@
# root command
@click.group()
@click.version_option()
@click.option(
"--debug/--no-debug", is_flag=True, default=True, help="Enable debug logging"
)
@click.option("--debug/--no-debug", is_flag=True, default=True, help="Enable debug logging")
@click.pass_context
def chk(ctx: click.Context, debug: bool) -> None:
"""\b
Expand All @@ -50,9 +48,7 @@ def chk(ctx: click.Context, debug: bool) -> None:
# run fetch sub-command
@chk.command()
@click.argument("file", type=click.Path(exists=True))
@click.option(
"-nf", "--no-format", is_flag=True, help="No formatting to show the output"
)
@click.option("-nf", "--no-format", is_flag=True, help="No formatting to show the output")
@click.option("-V", "--variables", type=str, help="Pass variable(s) as JSON object")
@click.pass_context
def fetch(cctx: click.Context, file: str, no_format: bool, variables: str) -> None:
Expand Down Expand Up @@ -85,9 +81,7 @@ def fetch(cctx: click.Context, file: str, no_format: bool, variables: str) -> No
# run validate sub-command
@chk.command()
@click.argument("file", type=click.Path(exists=True))
@click.option(
"-nf", "--no-format", is_flag=True, help="No formatting to show the output"
)
@click.option("-nf", "--no-format", is_flag=True, help="No formatting to show the output")
@click.option("-V", "--variables", type=str, help="Pass variable(s) as JSON object")
@click.option("-D", "--data", type=str, help="Pass data as JSON")
@click.option("-Di", "--data-in", is_flag=True, help="Pass data as JSON [from pipe]")
Expand All @@ -111,13 +105,9 @@ def validate(

with with_catch_log():
_data = (
load_variables_as_dict(
get_stdin(), except_msg="-Di, --data-in: Pass data as JSON [from pipe]"
)
load_variables_as_dict(get_stdin(), except_msg="-Di, --data-in: Pass data as JSON [from pipe]")
if data_in
else load_variables_as_dict(
data, except_msg="-D, --data: Pass data as JSON"
)
else load_variables_as_dict(data, except_msg="-D, --data: Pass data as JSON")
)

execution_ctx = ExecuteContext(
Expand All @@ -141,9 +131,7 @@ def validate(
# run validate sub-command
@chk.command()
@click.argument("file", type=click.Path(exists=True))
@click.option(
"-nf", "--no-format", is_flag=True, help="No formatting to show the output"
)
@click.option("-nf", "--no-format", is_flag=True, help="No formatting to show the output")
@click.option("-V", "--variables", type=str, help="Pass variable(s) as JSON object")
@click.pass_context
def workflow(cctx: click.Context, file: str, no_format: bool, variables: str) -> None:
Expand Down
12 changes: 3 additions & 9 deletions chk/infrastructure/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ class VersionedDocumentSupport:
"""DocumentVersionSupport"""

@staticmethod
def validate_with_schema(
schema: dict, doc: VersionedDocument | VersionedDocumentV2
) -> bool:
def validate_with_schema(schema: dict, doc: VersionedDocument | VersionedDocumentV2) -> bool:
"""Validate a document with given schema

Args:
Expand All @@ -54,12 +52,8 @@ def validate_with_schema(

try:
if not validator.validate(file_ctx.document, schema):
raise RuntimeError(
f"File exception: Validation failed: {str(validator.errors)}"
)
raise RuntimeError(f"File exception: Validation failed: {str(validator.errors)}")
except cerberus.validator.DocumentError as doc_err:
raise RuntimeError(
f"Document exception: `version` string not found: {str(doc_err)}"
) from doc_err
raise RuntimeError(f"Document exception: `version` string not found: {str(doc_err)}") from doc_err

return True
12 changes: 3 additions & 9 deletions chk/infrastructure/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ def data_set(data: dict | list, keymap: str, value: Any) -> Any:

if isinstance(data, dict):
if current_item.isnumeric():
raise IndexError(
f"Trying to set numeric key `{current_item}` on dict `{data}`"
)
raise IndexError(f"Trying to set numeric key `{current_item}` on dict `{data}`")

if len(keymap_list) == 0:
data[current_item] = value
Expand All @@ -42,9 +40,7 @@ def data_set(data: dict | list, keymap: str, value: Any) -> Any:

if isinstance(data, list):
if not current_item.isnumeric():
raise IndexError(
f"Trying to set non-numeric index `{current_item}` on list `{data}`"
)
raise IndexError(f"Trying to set non-numeric index `{current_item}` on list `{data}`")
current_item_i = int(current_item)

if len(data) < current_item_i:
Expand Down Expand Up @@ -170,9 +166,7 @@ def try_dict(to_dict: Any, say_exception: bool = False) -> dict | Any:
return to_dict


def formatter(
message: object, cb: Callable = str, dump: bool = True, is_err: bool = False
) -> str:
def formatter(message: object, cb: Callable = str, dump: bool = True, is_err: bool = False) -> str:
"""Format message with given callback

Args:
Expand Down
15 changes: 4 additions & 11 deletions chk/infrastructure/symbol_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,17 +189,13 @@ def handle_composite(
composite_values[key] = val

if composite_values:
replaced_values: dict = replace_callback(
composite_values, variable_doc.data
)
replaced_values: dict = replace_callback(composite_values, variable_doc.data)

cls.handle_absolute(variable_doc, replaced_values)
cls.handle_composite(variable_doc, replaced_values)

@classmethod
def handle_execute_context(
cls, variable_doc: Variables, exec_ctx: ExecuteContext
) -> None:
def handle_execute_context(cls, variable_doc: Variables, exec_ctx: ExecuteContext) -> None:
"""Handle variables passed from external context

Args:
Expand Down Expand Up @@ -276,12 +272,9 @@ def get_exposed_replaced_data(document: VersionedDocumentV2, store: dict) -> dic

if expose_doc := ExposeManager.get_expose_doc(file_ctx.document):
exposed_doc_t = copy.copy(expose_doc)
exposed_doc_t = [
str(key).replace("%>", "").replace("<%", "").strip()
for key in exposed_doc_t
]
exposed_doc_t = [str(key).replace("%>", "").replace("<%", "").strip() for key in exposed_doc_t]

expose_val = ExposeManager.replace_values(expose_doc, store)
return dict(zip(exposed_doc_t, expose_val))
return dict(zip(exposed_doc_t, expose_val, strict=False))

return {}
4 changes: 2 additions & 2 deletions chk/infrastructure/templating.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def render(env: NativeEnvironment, template: str, data: dict) -> typing.Any:
# handle undefined vars
undeclared_vars = find_undeclared_variables(env.parse(template))

if all([_var in data for _var in undeclared_vars]):
if all(_var in data for _var in undeclared_vars):
return env.from_string(template).render(data)
else:
return template
Expand All @@ -76,7 +76,7 @@ def is_template_str(tpl: str) -> bool:
"""Check given string is templated string or not"""

_dm_sets = [("<%", "%>"), ("<@", "@>"), ("<#", "#>")]
return any([_dm_set[0] in tpl and _dm_set[1] in tpl for _dm_set in _dm_sets])
return any(_dm_set[0] in tpl and _dm_set[1] in tpl for _dm_set in _dm_sets)


######################################
Expand Down
6 changes: 1 addition & 5 deletions chk/infrastructure/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,7 @@ def parse(self) -> None:
ver_l[-1],
)

if (
len(self.provider) == 0
or len(self.doc_type) == 0
or len(self.doc_type_ver) == 0
):
if len(self.provider) == 0 or len(self.doc_type) == 0 or len(self.doc_type_ver) == 0:
raise ValueError("Invalid version string")

def validate(self) -> bool:
Expand Down
4 changes: 1 addition & 3 deletions chk/infrastructure/view.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,7 @@ def display(
formatter(wfp.dump_json(), dump=exec_ctx.options["dump"])


def die_with_error(
err: Exception, Presenter: type[PresentationBuilder], is_fmt: bool
) -> None:
def die_with_error(err: Exception, Presenter: type[PresentationBuilder], is_fmt: bool) -> None:
"""die_with_error"""

prs = Presenter(data=None)
Expand Down
8 changes: 2 additions & 6 deletions chk/modules/fetch/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,7 @@ def call(file_ctx: FileContext, exec_ctx: ExecuteContext) -> ExecResponse:
http_doc = HttpDocumentSupport.from_file_context(file_ctx)
debug(http_doc.model_dump_json())

VersionedDocumentSupport.validate_with_schema(
HttpDocumentSupport.build_schema(), http_doc
)
VersionedDocumentSupport.validate_with_schema(HttpDocumentSupport.build_schema(), http_doc)
except Exception as ex:
error_trace(exception=sys.exc_info()).error(ex)
return ExecResponse(
Expand Down Expand Up @@ -96,9 +94,7 @@ def call(file_ctx: FileContext, exec_ctx: ExecuteContext) -> ExecResponse:


@with_catch_log
def execute(
ctx: FileContext, exec_ctx: ExecuteContext, cb: abc.Callable = lambda *args: ...
) -> None:
def execute(ctx: FileContext, exec_ctx: ExecuteContext, cb: abc.Callable = lambda *args: ...) -> None:
"""Call with a http document

Args:
Expand Down
21 changes: 4 additions & 17 deletions chk/modules/fetch/entities.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,9 +177,7 @@ def __bool__(self) -> bool:
@computed_field # type: ignore
@property
def info(self) -> str:
return (
f"{Http_V10 if self.version == 10 else Http_V11} {self.code} {self.reason}"
)
return f"{Http_V10 if self.version == 10 else Http_V11} {self.code} {self.reason}"

@computed_field # type: ignore
@property
Expand Down Expand Up @@ -248,26 +246,19 @@ def from_response(response: requests.Response) -> ApiResponseModel:
ApiResponseModel: _description_
"""

arm = ApiResponseModel(
return ApiResponseModel(
code=response.status_code,
version=11 if response.raw.version == 0 else response.raw.version,
reason=response.reason,
headers=dict(response.headers),
body=response.text,
)

if arm:
arm.body_content_type

return arm

@staticmethod
def from_dict(**kwargs: dict) -> ApiResponseModel:
"""Construct from dict"""

if not all(
[item in kwargs.keys() for item in ["code", "info", "headers", "body"]]
):
if not all(item in kwargs.keys() for item in ["code", "info", "headers", "body"]):
raise KeyError("Expected keys to make ApiResponseModel not found")

if not isinstance(kwargs["code"], int):
Expand Down Expand Up @@ -311,11 +302,7 @@ def as_fmt_str(self) -> str:
presentation += "\r\n".join(f"{k}: {v}" for k, v in self.headers.items())
presentation += "\r\n\r\n"

presentation += (
json.dumps(self.body_as_dict())
if self.body_content_type == CTYPE_JSON
else self.body
)
presentation += json.dumps(self.body_as_dict()) if self.body_content_type == CTYPE_JSON else self.body

return presentation

Expand Down
32 changes: 7 additions & 25 deletions chk/modules/fetch/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def allowed_method(value: str) -> bool:
ValueError: When unsupported method found
"""

if value not in set(method for method in HttpMethod):
if value not in set(HttpMethod):
raise ValueError("Unsupported method")

return True
Expand Down Expand Up @@ -105,9 +105,7 @@ def add_authorization(request_data: dict, request_arg: dict) -> None:

# handle bearer auth
if (tag_be := request_data.get(RequestConfigNode.AUTH_BE)) is not None:
request_arg["auth"] = BearerAuthentication(
tag_be.get(RequestConfigNode.AUTH_BE_TOK)
)
request_arg["auth"] = BearerAuthentication(tag_be.get(RequestConfigNode.AUTH_BE_TOK))

@staticmethod
def add_body(request_data: dict, request_arg: dict) -> None:
Expand Down Expand Up @@ -141,21 +139,15 @@ def add_body(request_data: dict, request_arg: dict) -> None:
if "headers" not in request_arg:
request_arg["headers"] = {}

if (
"content-type" not in request_arg["headers"]
and "Content-Type" not in request_arg["headers"]
):
if "content-type" not in request_arg["headers"] and "Content-Type" not in request_arg["headers"]:
request_arg["headers"]["content-type"] = CTYPE_XML

request_arg["data"] = body
elif (body := request_data.get(RequestConfigNode.BODY_TXT)) is not None:
if "headers" not in request_arg:
request_arg["headers"] = {}

if (
"content-type" not in request_arg["headers"]
and "Content-Type" not in request_arg["headers"]
):
if "content-type" not in request_arg["headers"] and "Content-Type" not in request_arg["headers"]:
request_arg["headers"]["content-type"] = "text/plain"

request_arg["data"] = str(body)
Expand Down Expand Up @@ -252,11 +244,7 @@ def dump_error_fmt(self, err: object = None) -> str:
if not err:
err = self.data.exception

return (
f"Fetch error\n------\n{repr(err)}"
if err
else "Fetch error\n------\nUnspecified error"
)
return f"Fetch error\n------\n{repr(err)}" if err else "Fetch error\n------\nUnspecified error"

def dump_json(self) -> str:
"""dump json"""
Expand All @@ -265,10 +253,7 @@ def dump_json(self) -> str:

for key, expose_item in self.data.exposed.items():
if key == RequestConfigNode.LOCAL and all(
[
item in expose_item.keys()
for item in ["code", "info", "headers", "body"]
]
item in expose_item.keys() for item in ("code", "info", "headers", "body")
):
resp = ApiResponseModel.from_dict(**expose_item)
displayables.append(resp.model_dump())
Expand All @@ -284,10 +269,7 @@ def dump_fmt(self) -> str:

for key, expose_item in self.data.exposed.items():
if key == RequestConfigNode.LOCAL and all(
[
item in expose_item.keys()
for item in ["code", "info", "headers", "body"]
]
item in expose_item.keys() for item in ("code", "info", "headers", "body")
):
resp = ApiResponseModel.from_dict(**expose_item)
displayables.append(resp.as_fmt_str())
Expand Down
Loading
Loading