Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
holtgrewe committed Nov 1, 2023
1 parent b668a60 commit fbcd143
Show file tree
Hide file tree
Showing 4 changed files with 152 additions and 1 deletion.
58 changes: 58 additions & 0 deletions tests/cli/test_projects.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,61 @@ def test_project_retrieve(

assert result.exit_code == 0, result.output
snapshot.assert_match(result.output, "result_output")


def test_project_load_config(
runner: CliRunner,
fake_fs_configured: FakeFs,
requests_mock: RequestsMocker,
fake_conn: typing.Tuple[str, str],
project_retrieve_result,
snapshot: Snapshot,
mocker: MockerFixture,
):
mocker.patch("varfish_cli.config.open", fake_fs_configured.open_, create=True)
mocker.patch("varfish_cli.config.os", fake_fs_configured.os)

responses = {
"import_data_host": ("STRING", "http-host.example.com"),
"import_data_password": ("STRING", "http-password"),
"import_data_path": ("STRING", "http-prefix/"),
"import_data_port": ("INTEGER", 80),
"import_data_protocol": ("STRING", "http"),
"import_data_user": ("STRING", "http-user"),
}

project_uuid = str(uuid.uuid4())
host, token = fake_conn
req_mocks = []
for setting_name, (setting_type, setting_value) in responses.items():
req_mocks.append(
requests_mock.get(
(
f"{host}/project/api/retrieve/{project_uuid}?app_name=cases_import"
f"&setting_name={setting_name}"
),
request_headers={"Authorization": f"Token {token}"},
json={
"project": project_uuid,
"user": None,
"name": setting_name,
"type": setting_type,
"value": setting_value,
"user_modifiable": True,
"app_name": "cases_import",
},
)
)
result = runner.invoke(app, ["--verbose", "projects", "project-load-config", project_uuid])

rc_path = fake_fs_configured.os.path.expanduser("~/.varfishrc.toml")
with fake_fs_configured.open_(rc_path, "rt") as inputf:
fcontents = inputf.read()

mocker.stopall()

for req_mock in req_mocks:
assert req_mock.called_once, req_mock._netloc

assert result.exit_code == 0, result.output
snapshot.assert_match(fcontents, "result_output")
19 changes: 19 additions & 0 deletions varfish_cli/api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,3 +341,22 @@ class VarAnnoSetEntryV1(pydantic.BaseModel):
alternative: str
#: Data, the set's fields are the keys.
payload: typing.Dict[str, str]


class SettingsEntry(pydantic.BaseModel):
"""Configuration entry from server"""

#: Project UUID.
project: typing.Optional[uuid.UUID]
#: User UUID, if any.
user: typing.Optional[uuid.UUID]
#: Name of the app.
app_name: str
#: Name of the setting.
name: str
#: Type of the setting.
type: typing.Literal["STRING", "INTEGER", "BOOLEAN"]
#: Value of the setting.
value: typing.Any
#: Whether the user can modify the setting.
user_modifiable: bool
30 changes: 29 additions & 1 deletion varfish_cli/api/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import requests

from varfish_cli.api.common import raise_for_status
from varfish_cli.api.models import Project
from varfish_cli.api.models import Project, SettingsEntry
from varfish_cli.common import strip_trailing_slash

ACCEPT_API_VARFISH = ""
Expand All @@ -17,6 +17,8 @@
ENDPOINT_PROJECT_LIST = "/project/api/list"
#: End point for retrieving projects.
ENDPOINT_PROJECT_RETRIEVE = "/project/api/retrieve/{project_uuid}"
#: End point for retrieving projects settings.
ENDPOINT_PROJECT_RETRIEVE = "/project/api/settings/retrieve/{project_uuid}"


def project_list(
Expand Down Expand Up @@ -48,3 +50,29 @@ def project_retrieve(
result = requests.get(endpoint, headers=headers, verify=verify_ssl)
raise_for_status(result)
return pydantic.TypeAdapter(Project).validate_python(result.json())


def project_settings_retrieve(
server_url: str,
api_token: str,
project_uuid: typing.Union[str, uuid.UUID],
app_name: typing.Optional[str],
setting_name: typing.Optional[str],
verify_ssl: bool = True,
) -> SettingsEntry:
server_url = strip_trailing_slash(server_url)
queries = []
if app_name:
queries.append(f"app_name={app_name}")
if setting_name:
queries.append(f"setting_name={setting_name}")
query = "&".join(queries)
if query:
query = f"?{query}"
endpoint = f"{server_url}{ENDPOINT_PROJECT_RETRIEVE}{query}".format(project_uuid=project_uuid)
logger.debug("Sending GET request to end point %s", endpoint)
headers = {"Authorization": "Token %s" % api_token}
result = requests.get(endpoint, headers=headers, verify=verify_ssl)
raise_for_status(result)
print(result.json())
return pydantic.TypeAdapter(SettingsEntry).validate_python(result.json())
46 changes: 46 additions & 0 deletions varfish_cli/cli/projects.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
import typing
import uuid

from logzero import logger
import typer

from varfish_cli import api, common
from varfish_cli.cli.common import ListObjects, RetrieveObject
from varfish_cli.common import OutputFormat
from varfish_cli.config import CommonOptions

#: Default fields for projects.
DEFAULT_FIELDS_PROJECT: typing.Dict[OutputFormat, typing.Optional[typing.Tuple[str, ...]]] = {
Expand Down Expand Up @@ -76,3 +78,47 @@ def cli_project_retrieve(
object_uuid=object_uuid,
output_file=output_file,
)


@app.command("project-load-config")
def cli_project_load_config(
ctx: typer.Context,
project_uuid: typing.Annotated[
uuid.UUID, typer.Argument(..., help="UUID of the object to retrieve")
],
output_file: typing.Annotated[
str, typer.Option("--output-file", help="Path to file to write to")
] = "-",
):
"""Load project configuration for import and store in ~/.varfishrc.toml"""
common_options: common.CommonOptions = ctx.obj
logger.info("Retrieving project configuration...")

fields_types = {
"import_data_host": str,
"import_data_password": str,
"import_data_path": str,
"import_data_port": int,
"import_data_protocol": str,
"import_data_user": str,
}

kwargs = {}
for field_name, field_type in fields_types.items():
logger.debug(" - retrieving %s", field_name)
setting_entry = api.project_settings_retrieve(
server_url=common_options.varfish_server_url,
api_token=common_options.varfish_api_token.get_secret_value(),
project_uuid=project_uuid,
app_name="cases_import",
setting_name=field_name,
verify_ssl=common_options.verify_ssl,
)
print(setting_entry)
if setting_entry.value:
kwargs[field_name] = field_type(setting_entry.value)
print(kwargs)

logger.info("... all data retrieved, updating config...")

print(kwargs)

0 comments on commit fbcd143

Please sign in to comment.