Skip to content
Open
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
42 changes: 40 additions & 2 deletions tests/integration/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
"regions",
"ssh",
"stackscripts",
"streams",
"tickets",
"tags",
"users",
Expand All @@ -63,6 +64,18 @@
]
BASE_CMDS = {module: ["linode-cli", module] for module in MODULES}

SENSITIVE_ARG_NAMES = {
"--access_key_secret",
"--access_key",
"--details.access_key_secret",
"--details.access_key_id",
"--token",
"--password",
"--secret",
"--secret_key",
"--bucket_access",
}


def get_random_text(length: int = 10):
return "".join(random.choice(ascii_lowercase) for _ in range(length))
Expand Down Expand Up @@ -90,7 +103,7 @@ def exec_test_command(args: List[str]):
if process.returncode != 0:
raise RuntimeError(
f"Command failed with exit code {process.returncode}\n"
f"Command: {' '.join(args)}\n"
f"Command: {' '.join(_redact_args(args))}\n"
f"Stdout:\n{process.stdout}\n"
f"Stderr:\n{process.stderr}"
)
Expand All @@ -105,7 +118,7 @@ def exec_failing_test_command(
if process.returncode != expected_code:
raise AssertionError(
f"Expected exit code {expected_code}, got {process.returncode}\n"
f"Command: {' '.join(args)}\n"
f"Command: {' '.join(_redact_args(args))}\n"
f"Stdout:\n{process.stdout}\n"
f"Stderr: {process.stderr}"
)
Expand Down Expand Up @@ -254,3 +267,28 @@ def check_attribute_value(
) -> bool:
result = view_command_attribute(command, action, item_id, attribute)
return expected_val in result


def _redact_args(args: List[str]) -> List[str]:
redacted = []
hide_next = False
for arg in args:
if hide_next:
redacted.append("***REDACTED***")
hide_next = False
continue

# handle `--flag value` form
if arg in SENSITIVE_ARG_NAMES:
redacted.append(arg)
hide_next = True
continue

# handle `--flag=value` form
if "=" in arg and arg.split("=", 1)[0] in SENSITIVE_ARG_NAMES:
flag = arg.split("=", 1)[0]
redacted.append(f"{flag}=***REDACTED***")
continue

redacted.append(arg)
return redacted
182 changes: 182 additions & 0 deletions tests/integration/streams/fixtures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
import json
import os
from typing import Any, Dict

import pytest
import requests

from linodecli.cli import logger
from tests.integration.helpers import (
BASE_CMDS,
delete_target_id,
exec_test_command,
get_random_region_with_caps,
get_random_text,
wait_for_condition,
)


def get_object_storage_buckets() -> Dict[str, Any]:
token = os.getenv("LINODE_CLI_TOKEN")
if token is None:
raise ValueError("LINODE_CLI_TOKEN environment variable is not set. ")
host = os.getenv("LINODE_CLI_API_HOST")
if host is None:
raise ValueError(
"LINODE_CLI_API_HOST environment variable is not set. "
)
version = os.getenv("LINODE_CLI_API_VERSION")
if version is None:
raise ValueError(
"LINODE_CLI_API_VERSION environment variable is not set. "
)

url = f"https://{host}/{version}/object-storage/buckets"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}

response = requests.get(url, headers=headers, timeout=30)
response.raise_for_status()

return response.json()


@pytest.fixture(scope="function")
def create_stream(create_destination_akamai_object_storage_type):
label = get_random_text(8) + "_stream_cli_test"
result_create = exec_test_command(
BASE_CMDS["streams"]
+ [
"create",
"--label",
label,
"--type",
"audit_logs",
"--destinations",
str(create_destination_akamai_object_storage_type["id"]),
"--json",
],
)
result_create_json = json.loads(result_create)[0]
yield result_create_json
wait_for_condition(
20,
3000,
is_expected_stream_status,
str(result_create_json["id"]),
"active",
)
delete_target_id(
"streams",
str(result_create_json["id"]),
)


@pytest.fixture
def create_object_storage_keys():
label = get_random_text(8) + "_destination_cli_test"
if get_object_storage_buckets()["data"][0] is None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It will fail if there is no buckets at all (then data=[] leads to 'list index out of range' error). Moreover, wouldnt be better to create a bucket instead of checking if there is any already? It would let you run the tests no matter if it exists or not

raise ValueError(
"There is no object storage bucket available in your account. Cannot run test."
)
test_bucket = get_object_storage_buckets()["data"][0]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

result_keys = exec_test_command(
BASE_CMDS["object-storage"]
+ [
"keys-create",
"--label",
label,
"--bucket_access",
'[{"region": "'
+ test_bucket["region"]
+ '", "bucket_name": "'
+ test_bucket["label"]
+ '", "permissions": "read_write" }]',
"--text",
"--no-headers",
"--delimiter",
",",
"--format",
"access_key,secret_key,id",
]
).split(",")
yield result_keys[0], result_keys[1], test_bucket["label"], test_bucket[
"s3_endpoint"
]
delete_target_id("object-storage", str(result_keys[2]), "keys-delete")


@pytest.fixture(scope="function")
def create_destination_akamai_object_storage_type(create_object_storage_keys):
get_random_region_with_caps(required_capabilities=["Linodes"])

label = get_random_text(8) + "_destination_cli_test"
result_create_destination = exec_test_command(
BASE_CMDS["streams"]
+ [
"destination-create",
"--label",
label,
"--type",
"akamai_object_storage",
"--details.host",
create_object_storage_keys[3],
"--details.bucket_name",
create_object_storage_keys[2],
"--details.path",
"audit-logs",
"--details.access_key_secret",
create_object_storage_keys[1],
Comment on lines +130 to +131

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"--details.access_key_id",
create_object_storage_keys[0],
"--delimiter",
",",
"--json",
]
)
create_destination_json = json.loads(result_create_destination)
yield create_destination_json[0]
try:
exec_test_command(
BASE_CMDS["streams"]
+ [
"destination-view",
str(create_destination_json[0]["id"]),
"--delimiter",
",",
"--text",
],
)
except RuntimeError as error:
if "Request failed: 404" not in str(error):
raise
logger.debug("Destination already deleted, skipping deletion.")
else:
delete_target_id(
"streams",
str(create_destination_json[0]["id"]),
"destination-delete",
)


def is_expected_stream_status(stream_id: "str", status: "str"):
try:
result = exec_test_command(
BASE_CMDS["streams"]
+ [
"view",
stream_id,
"--format",
"status",
"--text",
"--no-headers",
]
)
except RuntimeError as response_error:
if "Request failed: 404" not in str(response_error):
return False
else:
raise RuntimeError(response_error)
return status == result
Loading