Use tmp_path in tests (#91203)

* Use tmp_path in tests

* Use joinpath

* Prefer / operator

* Cleanup
This commit is contained in:
epenet 2023-04-12 08:19:01 +02:00 committed by GitHub
parent 4e78bcb236
commit e277bbb513
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 69 additions and 75 deletions

View file

@ -4,11 +4,10 @@ from datetime import timedelta
from http import HTTPStatus
from ipaddress import ip_network
import logging
import pathlib
from pathlib import Path
import time
from unittest.mock import MagicMock, Mock, patch
import py
import pytest
from homeassistant.auth.providers.legacy_api_password import (
@ -26,22 +25,24 @@ from tests.test_util.aiohttp import AiohttpClientMockResponse
from tests.typing import ClientSessionGenerator
def _setup_broken_ssl_pem_files(tmpdir):
test_dir = tmpdir.mkdir("test_broken_ssl")
cert_path = pathlib.Path(test_dir) / "cert.pem"
def _setup_broken_ssl_pem_files(tmp_path: Path) -> tuple[Path, Path]:
test_dir = tmp_path / "test_broken_ssl"
test_dir.mkdir()
cert_path = test_dir / "cert.pem"
cert_path.write_text("garbage")
key_path = pathlib.Path(test_dir) / "key.pem"
key_path = test_dir / "key.pem"
key_path.write_text("garbage")
return cert_path, key_path
def _setup_empty_ssl_pem_files(tmpdir):
test_dir = tmpdir.mkdir("test_empty_ssl")
cert_path = pathlib.Path(test_dir) / "cert.pem"
def _setup_empty_ssl_pem_files(tmp_path: Path) -> tuple[Path, Path, Path]:
test_dir = tmp_path / "test_empty_ssl"
test_dir.mkdir()
cert_path = test_dir / "cert.pem"
cert_path.write_text("-")
peer_cert_path = pathlib.Path(test_dir) / "peer_cert.pem"
peer_cert_path = test_dir / "peer_cert.pem"
peer_cert_path.write_text("-")
key_path = pathlib.Path(test_dir) / "key.pem"
key_path = test_dir / "key.pem"
key_path.write_text("-")
return cert_path, key_path, peer_cert_path
@ -154,13 +155,11 @@ async def test_proxy_config_only_trust_proxies(hass: HomeAssistant) -> None:
)
async def test_ssl_profile_defaults_modern(
hass: HomeAssistant, tmpdir: py.path.local
) -> None:
async def test_ssl_profile_defaults_modern(hass: HomeAssistant, tmp_path: Path) -> None:
"""Test default ssl profile."""
cert_path, key_path, _ = await hass.async_add_executor_job(
_setup_empty_ssl_pem_files, tmpdir
_setup_empty_ssl_pem_files, tmp_path
)
with patch("ssl.SSLContext.load_cert_chain"), patch(
@ -182,12 +181,12 @@ async def test_ssl_profile_defaults_modern(
async def test_ssl_profile_change_intermediate(
hass: HomeAssistant, tmpdir: py.path.local
hass: HomeAssistant, tmp_path: Path
) -> None:
"""Test setting ssl profile to intermediate."""
cert_path, key_path, _ = await hass.async_add_executor_job(
_setup_empty_ssl_pem_files, tmpdir
_setup_empty_ssl_pem_files, tmp_path
)
with patch("ssl.SSLContext.load_cert_chain"), patch(
@ -214,13 +213,11 @@ async def test_ssl_profile_change_intermediate(
assert len(mock_context.mock_calls) == 1
async def test_ssl_profile_change_modern(
hass: HomeAssistant, tmpdir: py.path.local
) -> None:
async def test_ssl_profile_change_modern(hass: HomeAssistant, tmp_path: Path) -> None:
"""Test setting ssl profile to modern."""
cert_path, key_path, _ = await hass.async_add_executor_job(
_setup_empty_ssl_pem_files, tmpdir
_setup_empty_ssl_pem_files, tmp_path
)
with patch("ssl.SSLContext.load_cert_chain"), patch(
@ -247,10 +244,10 @@ async def test_ssl_profile_change_modern(
assert len(mock_context.mock_calls) == 1
async def test_peer_cert(hass: HomeAssistant, tmpdir: py.path.local) -> None:
async def test_peer_cert(hass: HomeAssistant, tmp_path: Path) -> None:
"""Test required peer cert."""
cert_path, key_path, peer_cert_path = await hass.async_add_executor_job(
_setup_empty_ssl_pem_files, tmpdir
_setup_empty_ssl_pem_files, tmp_path
)
with patch("ssl.SSLContext.load_cert_chain"), patch(
@ -282,12 +279,12 @@ async def test_peer_cert(hass: HomeAssistant, tmpdir: py.path.local) -> None:
async def test_emergency_ssl_certificate_when_invalid(
hass: HomeAssistant, tmpdir: py.path.local, caplog: pytest.LogCaptureFixture
hass: HomeAssistant, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test http can startup with an emergency self signed cert when the current one is broken."""
cert_path, key_path = await hass.async_add_executor_job(
_setup_broken_ssl_pem_files, tmpdir
_setup_broken_ssl_pem_files, tmp_path
)
hass.config.safe_mode = True
@ -313,12 +310,12 @@ async def test_emergency_ssl_certificate_when_invalid(
async def test_emergency_ssl_certificate_not_used_when_not_safe_mode(
hass: HomeAssistant, tmpdir: py.path.local, caplog: pytest.LogCaptureFixture
hass: HomeAssistant, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test an emergency cert is only used in safe mode."""
cert_path, key_path = await hass.async_add_executor_job(
_setup_broken_ssl_pem_files, tmpdir
_setup_broken_ssl_pem_files, tmp_path
)
assert (
@ -330,14 +327,14 @@ async def test_emergency_ssl_certificate_not_used_when_not_safe_mode(
async def test_emergency_ssl_certificate_when_invalid_get_url_fails(
hass: HomeAssistant, tmpdir: py.path.local, caplog: pytest.LogCaptureFixture
hass: HomeAssistant, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test http falls back to no ssl when an emergency cert cannot be created when the configured one is broken.
Ensure we can still start of we cannot determine the external url as well.
"""
cert_path, key_path = await hass.async_add_executor_job(
_setup_broken_ssl_pem_files, tmpdir
_setup_broken_ssl_pem_files, tmp_path
)
hass.config.safe_mode = True
@ -367,12 +364,12 @@ async def test_emergency_ssl_certificate_when_invalid_get_url_fails(
async def test_invalid_ssl_and_cannot_create_emergency_cert(
hass: HomeAssistant, tmpdir: py.path.local, caplog: pytest.LogCaptureFixture
hass: HomeAssistant, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test http falls back to no ssl when an emergency cert cannot be created when the configured one is broken."""
cert_path, key_path = await hass.async_add_executor_job(
_setup_broken_ssl_pem_files, tmpdir
_setup_broken_ssl_pem_files, tmp_path
)
hass.config.safe_mode = True
@ -398,7 +395,7 @@ async def test_invalid_ssl_and_cannot_create_emergency_cert(
async def test_invalid_ssl_and_cannot_create_emergency_cert_with_ssl_peer_cert(
hass: HomeAssistant, tmpdir: py.path.local, caplog: pytest.LogCaptureFixture
hass: HomeAssistant, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Test http falls back to no ssl when an emergency cert cannot be created when the configured one is broken.
@ -409,7 +406,7 @@ async def test_invalid_ssl_and_cannot_create_emergency_cert_with_ssl_peer_cert(
"""
cert_path, key_path = await hass.async_add_executor_job(
_setup_broken_ssl_pem_files, tmpdir
_setup_broken_ssl_pem_files, tmp_path
)
hass.config.safe_mode = True

View file

@ -1,9 +1,9 @@
"""Test the Lutron Caseta config flow."""
import asyncio
from pathlib import Path
import ssl
from unittest.mock import AsyncMock, patch
import py
from pylutron_caseta.pairing import PAIR_CA, PAIR_CERT, PAIR_KEY
from pylutron_caseta.smartbridge import Smartbridge
import pytest
@ -193,12 +193,11 @@ async def test_already_configured_with_ignored(hass: HomeAssistant) -> None:
assert result["type"] == "form"
async def test_form_user(hass: HomeAssistant, tmpdir: py.path.local) -> None:
async def test_form_user(hass: HomeAssistant, tmp_path: Path) -> None:
"""Test we get the form and can pair."""
hass.config.config_dir = await hass.async_add_executor_job(
tmpdir.mkdir, "tls_assets"
)
config_dir = tmp_path / "tls_assets"
await hass.async_add_executor_job(config_dir.mkdir)
hass.config.config_dir = str(config_dir)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -244,14 +243,11 @@ async def test_form_user(hass: HomeAssistant, tmpdir: py.path.local) -> None:
assert len(mock_setup_entry.mock_calls) == 1
async def test_form_user_pairing_fails(
hass: HomeAssistant, tmpdir: py.path.local
) -> None:
async def test_form_user_pairing_fails(hass: HomeAssistant, tmp_path: Path) -> None:
"""Test we get the form and we handle pairing failure."""
hass.config.config_dir = await hass.async_add_executor_job(
tmpdir.mkdir, "tls_assets"
)
config_dir = tmp_path / "tls_assets"
await hass.async_add_executor_job(config_dir.mkdir)
hass.config.config_dir = str(config_dir)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -292,13 +288,12 @@ async def test_form_user_pairing_fails(
async def test_form_user_reuses_existing_assets_when_pairing_again(
hass: HomeAssistant, tmpdir: py.path.local
hass: HomeAssistant, tmp_path: Path
) -> None:
"""Test the tls assets saved on disk are reused when pairing again."""
hass.config.config_dir = await hass.async_add_executor_job(
tmpdir.mkdir, "tls_assets"
)
config_dir = tmp_path / "tls_assets"
await hass.async_add_executor_job(config_dir.mkdir)
hass.config.config_dir = str(config_dir)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
@ -394,13 +389,12 @@ async def test_form_user_reuses_existing_assets_when_pairing_again(
async def test_zeroconf_host_already_configured(
hass: HomeAssistant, tmpdir: py.path.local
hass: HomeAssistant, tmp_path: Path
) -> None:
"""Test starting a flow from discovery when the host is already configured."""
hass.config.config_dir = await hass.async_add_executor_job(
tmpdir.mkdir, "tls_assets"
)
config_dir = tmp_path / "tls_assets"
await hass.async_add_executor_job(config_dir.mkdir)
hass.config.config_dir = str(config_dir)
config_entry = MockConfigEntry(domain=DOMAIN, data={CONF_HOST: "1.1.1.1"})
@ -479,12 +473,11 @@ async def test_zeroconf_not_lutron_device(hass: HomeAssistant) -> None:
@pytest.mark.parametrize(
"source", (config_entries.SOURCE_ZEROCONF, config_entries.SOURCE_HOMEKIT)
)
async def test_zeroconf(hass: HomeAssistant, source, tmpdir: py.path.local) -> None:
async def test_zeroconf(hass: HomeAssistant, source, tmp_path: Path) -> None:
"""Test starting a flow from discovery."""
hass.config.config_dir = await hass.async_add_executor_job(
tmpdir.mkdir, "tls_assets"
)
config_dir = tmp_path / "tls_assets"
await hass.async_add_executor_job(config_dir.mkdir)
hass.config.config_dir = str(config_dir)
result = await hass.config_entries.flow.async_init(
DOMAIN,

View file

@ -2,11 +2,11 @@
from datetime import timedelta
from functools import lru_cache
import os
from pathlib import Path
import sys
from unittest.mock import patch
from lru import LRU # pylint: disable=no-name-in-module
import py
import pytest
from homeassistant.components.profiler import (
@ -33,9 +33,10 @@ import homeassistant.util.dt as dt_util
from tests.common import MockConfigEntry, async_fire_time_changed
async def test_basic_usage(hass: HomeAssistant, tmpdir: py.path.local) -> None:
async def test_basic_usage(hass: HomeAssistant, tmp_path: Path) -> None:
"""Test we can setup and the service is registered."""
test_dir = tmpdir.mkdir("profiles")
test_dir = tmp_path / "profiles"
test_dir.mkdir()
entry = MockConfigEntry(domain=DOMAIN)
entry.add_to_hass(hass)
@ -47,9 +48,9 @@ async def test_basic_usage(hass: HomeAssistant, tmpdir: py.path.local) -> None:
last_filename = None
def _mock_path(filename):
def _mock_path(filename: str) -> str:
nonlocal last_filename
last_filename = f"{test_dir}/{filename}"
last_filename = str(test_dir / filename)
return last_filename
with patch("cProfile.Profile"), patch.object(hass.config, "path", _mock_path):
@ -66,9 +67,10 @@ async def test_basic_usage(hass: HomeAssistant, tmpdir: py.path.local) -> None:
@pytest.mark.skipif(
sys.version_info >= (3, 11), reason="not yet available on python 3.11"
)
async def test_memory_usage(hass: HomeAssistant, tmpdir: py.path.local) -> None:
async def test_memory_usage(hass: HomeAssistant, tmp_path: Path) -> None:
"""Test we can setup and the service is registered."""
test_dir = tmpdir.mkdir("profiles")
test_dir = tmp_path / "profiles"
test_dir.mkdir()
entry = MockConfigEntry(domain=DOMAIN)
entry.add_to_hass(hass)
@ -80,9 +82,9 @@ async def test_memory_usage(hass: HomeAssistant, tmpdir: py.path.local) -> None:
last_filename = None
def _mock_path(filename):
def _mock_path(filename: str) -> str:
nonlocal last_filename
last_filename = f"{test_dir}/{filename}"
last_filename = str(test_dir / filename)
return last_filename
with patch("guppy.hpy") as mock_hpy, patch.object(hass.config, "path", _mock_path):
@ -97,7 +99,7 @@ async def test_memory_usage(hass: HomeAssistant, tmpdir: py.path.local) -> None:
@pytest.mark.skipif(sys.version_info < (3, 11), reason="still works on python 3.10")
async def test_memory_usage_py311(hass: HomeAssistant, tmpdir: py.path.local) -> None:
async def test_memory_usage_py311(hass: HomeAssistant) -> None:
"""Test raise an error on python3.11."""
entry = MockConfigEntry(domain=DOMAIN)
entry.add_to_hass(hass)

View file

@ -3,6 +3,7 @@ import asyncio
from datetime import timedelta
from io import BytesIO
import os
from pathlib import Path
from unittest.mock import patch
import av
@ -39,9 +40,9 @@ async def stream_component(hass):
@pytest.fixture
def filename(tmpdir):
def filename(tmp_path: Path) -> str:
"""Use this filename for the tests."""
return f"{tmpdir}/test.mp4"
return str(tmp_path / "test.mp4")
async def test_record_stream(hass: HomeAssistant, filename, h264_video) -> None:

View file

@ -17,6 +17,7 @@ import fractions
import io
import logging
import math
from pathlib import Path
import threading
from unittest.mock import patch
@ -75,9 +76,9 @@ TIMEOUT = 15
@pytest.fixture
def filename(tmpdir):
def filename(tmp_path: Path) -> str:
"""Use this filename for the tests."""
return f"{tmpdir}/test.mp4"
return str(tmp_path / "test.mp4")
@pytest.fixture(autouse=True)