From 73882716898b94f82a002ddf4c60092ba6e05776 Mon Sep 17 00:00:00 2001 From: epenet <6771947+epenet@users.noreply.github.com> Date: Tue, 11 Jun 2024 17:58:40 +0200 Subject: [PATCH] Fix unspecified-encoding warnings in tests (#119405) --- tests/common.py | 2 +- tests/components/blueprint/test_importer.py | 4 ++-- .../blueprint/test_websocket_api.py | 6 +++--- .../color_extractor/test_service.py | 2 +- tests/components/folder/test_sensor.py | 2 +- .../components/google_assistant/test_http.py | 2 +- tests/components/kira/test_init.py | 2 +- tests/components/recorder/common.py | 2 +- .../recorder/test_statistics_v23_migration.py | 2 +- tests/helpers/test_storage.py | 4 ++-- tests/test_block_async_io.py | 6 +++--- tests/test_config.py | 19 +++++++++++-------- tests/test_core.py | 2 +- tests/util/test_file.py | 6 +++--- tests/util/test_json.py | 2 +- 15 files changed, 33 insertions(+), 30 deletions(-) diff --git a/tests/common.py b/tests/common.py index 1e53242c961..2606b510430 100644 --- a/tests/common.py +++ b/tests/common.py @@ -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( diff --git a/tests/components/blueprint/test_importer.py b/tests/components/blueprint/test_importer.py index 2b1d697fce5..f135bbf23b8 100644 --- a/tests/components/blueprint/test_importer.py +++ b/tests/components/blueprint/test_importer.py @@ -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" diff --git a/tests/components/blueprint/test_websocket_api.py b/tests/components/blueprint/test_websocket_api.py index 21387f7763c..4052e7c3316 100644 --- a/tests/components/blueprint/test_websocket_api.py +++ b/tests/components/blueprint/test_websocket_api.py @@ -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) diff --git a/tests/components/color_extractor/test_service.py b/tests/components/color_extractor/test_service.py index 941a0710067..7b603420bdf 100644 --- a/tests/components/color_extractor/test_service.py +++ b/tests/components/color_extractor/test_service.py @@ -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" diff --git a/tests/components/folder/test_sensor.py b/tests/components/folder/test_sensor.py index ad0969c6a0f..e71f1b3addc 100644 --- a/tests/components/folder/test_sensor.py +++ b/tests/components/folder/test_sensor.py @@ -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") diff --git a/tests/components/google_assistant/test_http.py b/tests/components/google_assistant/test_http.py index 416d569b286..b041f69828f 100644 --- a/tests/components/google_assistant/test_http.py +++ b/tests/components/google_assistant/test_http.py @@ -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 diff --git a/tests/components/kira/test_init.py b/tests/components/kira/test_init.py index a200c25d2a3..e57519667ce 100644 --- a/tests/components/kira/test_init.py +++ b/tests/components/kira/test_init.py @@ -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" diff --git a/tests/components/recorder/common.py b/tests/components/recorder/common.py index 2ded3513a7e..c72b1ac830b 100644 --- a/tests/components/recorder/common.py +++ b/tests/components/recorder/common.py @@ -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) diff --git a/tests/components/recorder/test_statistics_v23_migration.py b/tests/components/recorder/test_statistics_v23_migration.py index ac48f0d0994..af784692612 100644 --- a/tests/components/recorder/test_statistics_v23_migration.py +++ b/tests/components/recorder/test_statistics_v23_migration.py @@ -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 == [ diff --git a/tests/helpers/test_storage.py b/tests/helpers/test_storage.py index 577e81d1a44..651c7ce5cbc 100644 --- a/tests/helpers/test_storage.py +++ b/tests/helpers/test_storage.py @@ -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) diff --git a/tests/test_block_async_io.py b/tests/test_block_async_io.py index eab8033e37d..d011bdccdbe 100644 --- a/tests/test_block_async_io.py +++ b/tests/test_block_async_io.py @@ -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 diff --git a/tests/test_config.py b/tests/test_config.py index 1178b41398c..27ef8059fd8 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -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") diff --git a/tests/test_core.py b/tests/test_core.py index f8e96640fd1..71e6cb3f3b6 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -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")] diff --git a/tests/util/test_file.py b/tests/util/test_file.py index 2371998b1b9..efa3c1ab0d9 100644 --- a/tests/util/test_file.py +++ b/tests/util/test_file.py @@ -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 diff --git a/tests/util/test_json.py b/tests/util/test_json.py index c973ed1a91c..3a314bb5a1b 100644 --- a/tests/util/test_json.py +++ b/tests/util/test_json.py @@ -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) -- GitLab