Ensure diagnostics redaction can handle lists of lists ()

* Ensure diagnostics redaction can handle lists of lists

* Code review

* Update homeassistant/components/diagnostics/util.py

Co-authored-by: Paulus Schoutsen <paulus@home-assistant.io>

* Code review

* Typing

* Revert "Typing"

This reverts commit 8a57f772ca.

* New typing attempt

* Revert "New typing attempt"

This reverts commit e26e4aae69.

* Fix typing

* Fix typing again

* Add tests

Co-authored-by: Paulus Schoutsen <paulus@home-assistant.io>
pull/65167/head
Aaron Bach 2022-01-29 13:30:15 -07:00 committed by GitHub
parent d770a54881
commit cc6b0cc843
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 41 additions and 3 deletions
homeassistant/components/diagnostics
tests/components/diagnostics

View File

@ -2,19 +2,24 @@
from __future__ import annotations from __future__ import annotations
from collections.abc import Iterable, Mapping from collections.abc import Iterable, Mapping
from typing import Any from typing import Any, TypeVar, cast
from homeassistant.core import callback from homeassistant.core import callback
from .const import REDACTED from .const import REDACTED
T = TypeVar("T")
@callback @callback
def async_redact_data(data: Mapping, to_redact: Iterable[Any]) -> dict[str, Any]: def async_redact_data(data: T, to_redact: Iterable[Any]) -> T:
"""Redact sensitive data in a dict.""" """Redact sensitive data in a dict."""
if not isinstance(data, (Mapping, list)): if not isinstance(data, (Mapping, list)):
return data return data
if isinstance(data, list):
return cast(T, [async_redact_data(val, to_redact) for val in data])
redacted = {**data} redacted = {**data}
for key, value in redacted.items(): for key, value in redacted.items():
@ -25,4 +30,4 @@ def async_redact_data(data: Mapping, to_redact: Iterable[Any]) -> dict[str, Any]
elif isinstance(value, list): elif isinstance(value, list):
redacted[key] = [async_redact_data(item, to_redact) for item in value] redacted[key] = [async_redact_data(item, to_redact) for item in value]
return redacted return cast(T, redacted)

View File

@ -0,0 +1,33 @@
"""Test Diagnostics utils."""
from homeassistant.components.diagnostics import REDACTED, async_redact_data
def test_redact():
"""Test the async_redact_data helper."""
data = {
"key1": "value1",
"key2": ["value2_a", "value2_b"],
"key3": [["value_3a", "value_3b"], ["value_3c", "value_3d"]],
"key4": {
"key4_1": "value4_1",
"key4_2": ["value4_2a", "value4_2b"],
"key4_3": [["value4_3a", "value4_3b"], ["value4_3c", "value4_3d"]],
},
}
to_redact = {
"key1",
"key3",
"key4_1",
}
assert async_redact_data(data, to_redact) == {
"key1": REDACTED,
"key2": ["value2_a", "value2_b"],
"key3": REDACTED,
"key4": {
"key4_1": REDACTED,
"key4_2": ["value4_2a", "value4_2b"],
"key4_3": [["value4_3a", "value4_3b"], ["value4_3c", "value4_3d"]],
},
}