Handle successful empty OCI list responses during discovery
This commit is contained in:
parent
77d4c1b53b
commit
f134b77bf1
|
|
@ -269,13 +269,39 @@ class OCI:
|
|||
self.compartments_cache = None
|
||||
|
||||
def call(self, *arguments):
|
||||
process = subprocess.run([self.binary, *self.options, *arguments, "--output", "json"],
|
||||
command = [self.binary, *self.options, *arguments, "--output", "json", "--query", "@"]
|
||||
label = shlex.join(command)
|
||||
is_list = "list" in arguments[:4]
|
||||
process = subprocess.run(command,
|
||||
capture_output=True, text=True, timeout=90)
|
||||
if process.returncode:
|
||||
# OCI deliberately conflates missing resources with denied access.
|
||||
# A 404 must never switch an entire foundation into create mode.
|
||||
raise ValueError(f"OCI {' '.join(arguments[:3])} failed: {process.stderr[-1800:]}")
|
||||
data = json.loads(process.stdout).get("data")
|
||||
raise ValueError(f"{label} failed: {process.stderr[-1800:]}")
|
||||
output = process.stdout.strip()
|
||||
if not output and is_list:
|
||||
# CLI 3.95.1 render() emits nothing for [] with no display headers.
|
||||
# Successful list calls are distinct from failed requests or gets.
|
||||
return []
|
||||
try:
|
||||
envelope = json.loads(output)
|
||||
except json.JSONDecodeError as error:
|
||||
raise ValueError(
|
||||
f"{label} returned invalid JSON (exit=0, stdout={len(output)} chars): "
|
||||
f"{output[:200]!r}; stderr={process.stderr[-500:]!r}"
|
||||
) from error
|
||||
if not isinstance(envelope, dict):
|
||||
raise ValueError(f"{label} did not return a JSON response object")
|
||||
if "data" not in envelope and not (is_list and envelope.get("opc-total-items") == 0):
|
||||
raise ValueError(f"{label} returned JSON without data (keys={sorted(envelope)})")
|
||||
data = envelope.get("data")
|
||||
if is_list:
|
||||
if data is None:
|
||||
data = []
|
||||
if isinstance(data, dict) and isinstance(data.get("items"), list):
|
||||
data = data["items"]
|
||||
if not isinstance(data, list):
|
||||
raise ValueError(f"{label} returned unexpected list data: {type(data).__name__}")
|
||||
if arguments[:2] == ("ons", "topic"):
|
||||
# Notifications calls this field topicId (topic-id in CLI JSON).
|
||||
# Normalize both get and list results before adoption/deduplication.
|
||||
|
|
|
|||
|
|
@ -119,6 +119,33 @@ class ResolverTests(unittest.TestCase):
|
|||
with self.assertRaisesRegex(ValueError, "no resource identifier"):
|
||||
resolver.OCI.unique([{"name": "invalid-resource"}], "resource")
|
||||
|
||||
def test_successful_empty_list_output_is_normalized(self):
|
||||
for output in ("", " \n", '{"data": []}', '{"data": null}',
|
||||
'{"data": {"items": []}}', '{"opc-total-items": 0}'):
|
||||
with self.subTest(output=output):
|
||||
response = SimpleNamespace(returncode=0, stdout=output, stderr="API key label warning")
|
||||
with patch("subprocess.run", return_value=response) as command:
|
||||
result = resolver.OCI().call("monitoring", "alarm", "list", "--all")
|
||||
self.assertEqual(result, [])
|
||||
self.assertEqual(command.call_args.args[0][-4:], ["--output", "json", "--query", "@"])
|
||||
|
||||
def test_empty_get_and_malformed_output_are_errors_with_command_context(self):
|
||||
for operation, output in (("get", ""), ("list", "<html>gateway error</html>"),
|
||||
("list", '{"unexpected": []}')):
|
||||
with self.subTest(operation=operation, output=output):
|
||||
response = SimpleNamespace(returncode=0, stdout=output, stderr="diagnostic")
|
||||
with patch("subprocess.run", return_value=response), self.assertRaisesRegex(
|
||||
ValueError, "monitoring alarm " + operation
|
||||
):
|
||||
resolver.OCI().call("monitoring", "alarm", operation)
|
||||
|
||||
def test_failed_empty_list_remains_an_error(self):
|
||||
response = SimpleNamespace(returncode=1, stdout="", stderr="NotAuthorizedOrNotFound")
|
||||
with patch("subprocess.run", return_value=response), self.assertRaisesRegex(
|
||||
ValueError, "NotAuthorizedOrNotFound"
|
||||
):
|
||||
resolver.OCI().call("monitoring", "alarm", "list")
|
||||
|
||||
def test_edge_separates_dns_and_ssh(self):
|
||||
client = SimpleNamespace(
|
||||
instance=lambda role: {"id": "ocid1.instance.current", "compartment-id": "owner",
|
||||
|
|
|
|||
Loading…
Reference in New Issue