Fix unspecified-encoding warnings in tests (#119405)

This commit is contained in:
epenet 2024-06-11 17:58:40 +02:00 committed by GitHub
parent 6bb9011db3
commit 7388271689
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 33 additions and 30 deletions

View File

@ -555,7 +555,7 @@ def get_fixture_path(filename: str, integration: str | None = None) -> pathlib.P
@lru_cache
def load_fixture(filename: str, integration: str | None = None) -> str:
"""Load a fixture."""
return get_fixture_path(filename, integration).read_text()
return get_fixture_path(filename, integration).read_text(encoding="utf8")
def load_json_value_fixture(

View File

@ -138,7 +138,7 @@ async def test_fetch_blueprint_from_github_url(
"https://raw.githubusercontent.com/balloob/home-assistant-config/main/blueprints/automation/motion_light.yaml",
text=Path(
hass.config.path("blueprints/automation/test_event_service.yaml")
).read_text(),
).read_text(encoding="utf8"),
)
imported_blueprint = await importer.fetch_blueprint_from_url(hass, url)
@ -181,7 +181,7 @@ async def test_fetch_blueprint_from_website_url(
"https://www.home-assistant.io/blueprints/awesome.yaml",
text=Path(
hass.config.path("blueprints/automation/test_event_service.yaml")
).read_text(),
).read_text(encoding="utf8"),
)
url = "https://www.home-assistant.io/blueprints/awesome.yaml"

View File

@ -100,7 +100,7 @@ async def test_import_blueprint(
"""Test importing blueprints."""
raw_data = Path(
hass.config.path("blueprints/automation/test_event_service.yaml")
).read_text()
).read_text(encoding="utf8")
aioclient_mock.get(
"https://raw.githubusercontent.com/balloob/home-assistant-config/main/blueprints/automation/motion_light.yaml",
@ -149,7 +149,7 @@ async def test_import_blueprint_update(
"""Test importing blueprints."""
raw_data = Path(
hass.config.path("blueprints/automation/in_folder/in_folder_blueprint.yaml")
).read_text()
).read_text(encoding="utf8")
aioclient_mock.get(
"https://raw.githubusercontent.com/in_folder/home-assistant-config/main/blueprints/automation/in_folder_blueprint.yaml",
@ -192,7 +192,7 @@ async def test_save_blueprint(
"""Test saving blueprints."""
raw_data = Path(
hass.config.path("blueprints/automation/test_event_service.yaml")
).read_text()
).read_text(encoding="utf8")
with patch("pathlib.Path.write_text") as write_mock:
client = await hass_ws_client(hass)

View File

@ -243,7 +243,7 @@ def _get_file_mock(file_path):
"""Convert file to BytesIO for testing due to PIL UnidentifiedImageError."""
_file = None
with open(file_path) as file_handler:
with open(file_path, encoding="utf8") as file_handler:
_file = io.BytesIO(file_handler.read())
_file.name = "color_extractor.jpg"

View File

@ -15,7 +15,7 @@ TEST_FILE = os.path.join(TEST_DIR, TEST_TXT)
def create_file(path):
"""Create a test file."""
with open(path, "w") as test_file:
with open(path, "w", encoding="utf8") as test_file:
test_file.write("test")

View File

@ -655,7 +655,7 @@ async def test_async_get_users(
)
path = hass.config.config_dir / ".storage" / GoogleConfigStore._STORAGE_KEY
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
with open(path, "w", encoding="utf8") as f:
f.write(store_data)
assert await async_get_users(hass) == expected_users

View File

@ -79,7 +79,7 @@ async def test_kira_creates_codes(work_dir) -> None:
async def test_load_codes(work_dir) -> None:
"""Kira should ignore invalid codes."""
code_path = os.path.join(work_dir, "codes.yaml")
with open(code_path, "w") as code_file:
with open(code_path, "w", encoding="utf8") as code_file:
code_file.write(KIRA_CODES)
res = kira.load_codes(code_path)
assert len(res) == 1, "Expected exactly 1 valid Kira code"

View File

@ -138,7 +138,7 @@ async def async_recorder_block_till_done(hass: HomeAssistant) -> None:
def corrupt_db_file(test_db_file):
"""Corrupt an sqlite3 database file."""
with open(test_db_file, "w+") as fhandle:
with open(test_db_file, "w+", encoding="utf8") as fhandle:
fhandle.seek(200)
fhandle.write("I am a corrupt db" * 100)

View File

@ -556,7 +556,7 @@ def test_delete_duplicates_non_identical(
isotime = dt_util.utcnow().isoformat()
backup_file_name = f".storage/deleted_statistics.{isotime}.json"
with open(hass.config.path(backup_file_name)) as backup_file:
with open(hass.config.path(backup_file_name), encoding="utf8") as backup_file:
backup = json.load(backup_file)
assert backup == [

View File

@ -684,7 +684,7 @@ async def test_loading_corrupt_core_file(
assert data == {"hello": "world"}
def _corrupt_store():
with open(store_file, "w") as f:
with open(store_file, "w", encoding="utf8") as f:
f.write("corrupt")
await hass.async_add_executor_job(_corrupt_store)
@ -745,7 +745,7 @@ async def test_loading_corrupt_file_known_domain(
assert data == {"hello": "world"}
def _corrupt_store():
with open(store_file, "w") as f:
with open(store_file, "w", encoding="utf8") as f:
f.write('{"valid":"json"}..with..corrupt')
await hass.async_add_executor_job(_corrupt_store)

View File

@ -208,7 +208,7 @@ async def test_protect_loop_open(caplog: pytest.LogCaptureFixture) -> None:
"""Test open of a file in /proc is not reported."""
block_async_io.enable()
with contextlib.suppress(FileNotFoundError):
open("/proc/does_not_exist").close()
open("/proc/does_not_exist", encoding="utf8").close()
assert "Detected blocking call to open with args" not in caplog.text
@ -216,7 +216,7 @@ async def test_protect_open(caplog: pytest.LogCaptureFixture) -> None:
"""Test opening a file in the event loop logs."""
block_async_io.enable()
with contextlib.suppress(FileNotFoundError):
open("/config/data_not_exist").close()
open("/config/data_not_exist", encoding="utf8").close()
assert "Detected blocking call to open with args" in caplog.text
@ -233,7 +233,7 @@ async def test_protect_open_path(path: Any, caplog: pytest.LogCaptureFixture) ->
"""Test opening a file by path in the event loop logs."""
block_async_io.enable()
with contextlib.suppress(FileNotFoundError):
open(path).close()
open(path, encoding="utf8").close()
assert "Detected blocking call to open with args" in caplog.text

View File

@ -74,7 +74,7 @@ SAFE_MODE_PATH = os.path.join(CONFIG_DIR, config_util.SAFE_MODE_FILENAME)
def create_file(path):
"""Create an empty file."""
with open(path, "w"):
with open(path, "w", encoding="utf8"):
pass
@ -414,7 +414,7 @@ async def test_ensure_config_exists_uses_existing_config(hass: HomeAssistant) ->
create_file(YAML_PATH)
await config_util.async_ensure_config_exists(hass)
with open(YAML_PATH) as fp:
with open(YAML_PATH, encoding="utf8") as fp:
content = fp.read()
# File created with create_file are empty
@ -427,7 +427,7 @@ async def test_ensure_existing_files_is_not_overwritten(hass: HomeAssistant) ->
await config_util.async_create_default_config(hass)
with open(SECRET_PATH) as fp:
with open(SECRET_PATH, encoding="utf8") as fp:
content = fp.read()
# File created with create_file are empty
@ -443,7 +443,7 @@ def test_load_yaml_config_converts_empty_files_to_dict() -> None:
def test_load_yaml_config_raises_error_if_not_dict() -> None:
"""Test error raised when YAML file is not a dict."""
with open(YAML_PATH, "w") as fp:
with open(YAML_PATH, "w", encoding="utf8") as fp:
fp.write("5")
with pytest.raises(HomeAssistantError):
@ -452,7 +452,7 @@ def test_load_yaml_config_raises_error_if_not_dict() -> None:
def test_load_yaml_config_raises_error_if_malformed_yaml() -> None:
"""Test error raised if invalid YAML."""
with open(YAML_PATH, "w") as fp:
with open(YAML_PATH, "w", encoding="utf8") as fp:
fp.write(":-")
with pytest.raises(HomeAssistantError):
@ -461,7 +461,7 @@ def test_load_yaml_config_raises_error_if_malformed_yaml() -> None:
def test_load_yaml_config_raises_error_if_unsafe_yaml() -> None:
"""Test error raised if unsafe YAML."""
with open(YAML_PATH, "w") as fp:
with open(YAML_PATH, "w", encoding="utf8") as fp:
fp.write("- !!python/object/apply:os.system []")
with (
@ -474,7 +474,10 @@ def test_load_yaml_config_raises_error_if_unsafe_yaml() -> None:
# Here we validate that the test above is a good test
# since previously the syntax was not valid
with open(YAML_PATH) as fp, patch.object(os, "system") as system_mock:
with (
open(YAML_PATH, encoding="utf8") as fp,
patch.object(os, "system") as system_mock,
):
list(yaml.unsafe_load_all(fp))
assert len(system_mock.mock_calls) == 1
@ -482,7 +485,7 @@ def test_load_yaml_config_raises_error_if_unsafe_yaml() -> None:
def test_load_yaml_config_preserves_key_order() -> None:
"""Test removal of library."""
with open(YAML_PATH, "w") as fp:
with open(YAML_PATH, "w", encoding="utf8") as fp:
fp.write("hello: 2\n")
fp.write("world: 1\n")

View File

@ -1997,7 +1997,7 @@ async def test_config_is_allowed_path() -> None:
config.allowlist_external_dirs = {os.path.realpath(tmp_dir)}
test_file = os.path.join(tmp_dir, "test.jpg")
with open(test_file, "w") as tmp_file:
with open(test_file, "w", encoding="utf8") as tmp_file:
tmp_file.write("test")
valid = [test_file, tmp_dir, os.path.join(tmp_dir, "notfound321")]

View File

@ -17,17 +17,17 @@ def test_write_utf8_file_atomic_private(tmpdir: py.path.local, func) -> None:
test_file = Path(test_dir / "test.json")
func(test_file, '{"some":"data"}', False)
with open(test_file) as fh:
with open(test_file, encoding="utf8") as fh:
assert fh.read() == '{"some":"data"}'
assert os.stat(test_file).st_mode & 0o777 == 0o644
func(test_file, '{"some":"data"}', True)
with open(test_file) as fh:
with open(test_file, encoding="utf8") as fh:
assert fh.read() == '{"some":"data"}'
assert os.stat(test_file).st_mode & 0o777 == 0o600
func(test_file, b'{"some":"data"}', True, mode="wb")
with open(test_file) as fh:
with open(test_file, encoding="utf8") as fh:
assert fh.read() == '{"some":"data"}'
assert os.stat(test_file).st_mode & 0o777 == 0o600

View File

@ -25,7 +25,7 @@ TEST_BAD_SERIALIED = "THIS IS NOT JSON\n"
def test_load_bad_data(tmp_path: Path) -> None:
"""Test error from trying to load unserializable data."""
fname = tmp_path / "test5.json"
with open(fname, "w") as fh:
with open(fname, "w", encoding="utf8") as fh:
fh.write(TEST_BAD_SERIALIED)
with pytest.raises(HomeAssistantError, match=re.escape(str(fname))) as err:
load_json(fname)