Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve backup manager backup creation tests #130916

Merged
merged 2 commits into from
Nov 19, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Improve backup manager backup creation tests
  • Loading branch information
emontnemery committed Nov 18, 2024
commit 2d8e4b8bcc4fb8b8d44c2e6274a62df087512707
2 changes: 1 addition & 1 deletion homeassistant/components/backup/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -564,7 +564,7 @@ def _mkdir_and_generate_backup_contents(
if tar_file_paths:
tar_file_path = tar_file_paths[0]
else:
tar_file_path = self.temp_backup_dir / f"{backup_data['backup_id']}.tar"
tar_file_path = self.temp_backup_dir / f"{backup_data['slug']}.tar"
if not (backup_dir := tar_file_path.parent).exists():
LOGGER.debug("Creating backup directory %s", backup_dir)
backup_dir.mkdir()
Expand Down
7 changes: 7 additions & 0 deletions tests/components/backup/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,13 @@ async def async_upload_backup(
**kwargs: Any,
) -> None:
"""Upload a backup."""
self._backups[metadata.backup_id] = BaseBackup(
backup_id=metadata.backup_id,
date=metadata.date,
name=metadata.name,
protected=metadata.protected,
size=metadata.size,
)

async def async_list_backups(self, **kwargs: Any) -> list[BaseBackup]:
"""List backups."""
Expand Down
6 changes: 5 additions & 1 deletion tests/components/backup/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,11 @@ def _mock_iterdir(path: Path) -> list[Path]:
),
patch(
"pathlib.Path.exists",
lambda x: x != Path(hass.config.path("backups")),
lambda x: x
not in (
Path(hass.config.path("backups")),
Path(hass.config.path("tmp_backups")),
),
),
patch(
"pathlib.Path.is_symlink",
Expand Down
84 changes: 73 additions & 11 deletions tests/components/backup/test_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
BackupAgentPlatformProtocol,
BackupManager,
BackupPlatformProtocol,
BaseBackup,
backup as local_backup_platform,
)
from homeassistant.components.backup.manager import BackupProgress
Expand Down Expand Up @@ -44,12 +45,14 @@
mocked_json_bytes: Mock,
mocked_tarfile: Mock,
*,
agent_ids: list[str] | None = None,
database_included: bool = True,
name: str | None = "Core 2025.1.0",
password: str | None = None,
) -> None:
) -> BaseBackup:
"""Mock backup generator."""

agent_ids = agent_ids or [LOCAL_AGENT_ID]
progress: list[BackupProgress] = []

def on_progress(_progress: BackupProgress) -> None:
Expand All @@ -59,7 +62,7 @@
assert manager.backup_task is None
await manager.async_create_backup(
addons_included=[],
agent_ids=[LOCAL_AGENT_ID],
agent_ids=agent_ids,
database_included=database_included,
folders_included=[],
name=name,
Expand Down Expand Up @@ -88,10 +91,24 @@
"slug": ANY,
"type": "partial",
}
local_agent = manager.backup_agents[LOCAL_AGENT_ID]
assert local_agent._backup_dir.as_posix() in str(
mocked_tarfile.call_args_list[0][0][0]
assert isinstance(backup, BaseBackup)
assert backup == BaseBackup(
backup_id=ANY,
date=ANY,
name=name,
protected=bool(password),
size=ANY,
)
for agent_id in agent_ids:
agent = manager.backup_agents[agent_id]
assert len(agent._backups) == 1
agent_backup = agent._backups[backup.backup_id]
assert agent_backup.backup_id == backup.backup_id
assert agent_backup.date == backup.date
assert agent_backup.name == backup.name
assert agent_backup.protected == backup.protected
assert agent_backup.size == backup.size

outer_tar = mocked_tarfile.return_value
core_tar = outer_tar.create_inner_tar.return_value.__enter__.return_value
expected_files = [call(hass.config.path(), arcname="data", recursive=False)] + [
Expand Down Expand Up @@ -248,7 +265,39 @@
event.set()


@pytest.mark.parametrize(
("agent_ids", "expected_error"),
[
([], "At least one agent must be selected"),
(["non_existing"], "Invalid agent selected"),
],
)
async def test_async_create_backup_wrong_agent_id(
hass: HomeAssistant, agent_ids: list[str], expected_error: str
) -> None:
"""Test generate backup."""
manager = BackupManager(hass)
with pytest.raises(HomeAssistantError, match=expected_error):
await manager.async_create_backup(
addons_included=[],
agent_ids=agent_ids,
database_included=True,
folders_included=[],
name=None,
on_progress=None,
password=None,
)


@pytest.mark.usefixtures("mock_backup_generation")
@pytest.mark.parametrize(
("agent_ids", "backup_directory"),
[
([LOCAL_AGENT_ID], "backups"),
(["test.remote"], "tmp_backups"),
([LOCAL_AGENT_ID, "test.remote"], "backups"),
],
)
@pytest.mark.parametrize(
"params",
[
Expand All @@ -264,28 +313,41 @@
mocked_json_bytes: Mock,
mocked_tarfile: Mock,
params: dict,
agent_ids: list[str],
backup_directory: str,
) -> None:
"""Test generate backup."""
manager = BackupManager(hass)

await _setup_backup_platform(hass, domain=DOMAIN, platform=local_backup_platform)
await _setup_backup_platform(
hass,
domain="test",
platform=Mock(
async_get_backup_agents=AsyncMock(
return_value=[BackupAgentTest("remote", backups=[])]

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.12 (3)

test_async_create_backup[params0-agent_ids0-backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.12 (3)

test_async_create_backup[params0-agent_ids1-tmp_backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.12 (3)

test_async_create_backup[params0-agent_ids2-backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.12 (3)

test_async_create_backup[params1-agent_ids0-backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.12 (3)

test_async_create_backup[params1-agent_ids1-tmp_backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.12 (3)

test_async_create_backup[params1-agent_ids2-backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.12 (3)

test_async_create_backup[params2-agent_ids0-backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.12 (3)

test_async_create_backup[params2-agent_ids1-tmp_backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.12 (3)

test_async_create_backup[params2-agent_ids2-backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.12 (3)

test_async_create_backup[params3-agent_ids0-backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.13 (3)

test_async_create_backup[params0-agent_ids0-backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.13 (3)

test_async_create_backup[params0-agent_ids1-tmp_backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.13 (3)

test_async_create_backup[params0-agent_ids2-backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.13 (3)

test_async_create_backup[params1-agent_ids0-backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.13 (3)

test_async_create_backup[params1-agent_ids1-tmp_backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.13 (3)

test_async_create_backup[params1-agent_ids2-backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.13 (3)

test_async_create_backup[params2-agent_ids0-backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.13 (3)

test_async_create_backup[params2-agent_ids1-tmp_backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.13 (3)

test_async_create_backup[params2-agent_ids2-backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'

Check failure on line 328 in tests/components/backup/test_manager.py

View workflow job for this annotation

GitHub Actions / Run tests Python 3.13 (3)

test_async_create_backup[params3-agent_ids0-backups] TypeError: BackupAgentTest.__init__() got an unexpected keyword argument 'backups'
),
spec_set=BackupAgentPlatformProtocol,
),
)
await manager.load_platforms()

local_agent = manager.backup_agents[LOCAL_AGENT_ID]
local_agent._loaded_backups = True

await _mock_backup_generation(
hass, manager, mocked_json_bytes, mocked_tarfile, **params
backup = await _mock_backup_generation(
hass, manager, mocked_json_bytes, mocked_tarfile, agent_ids=agent_ids, **params
)

assert "Generated new backup with backup_id " in caplog.text
assert "Creating backup directory" in caplog.text
assert "Loaded 0 platforms" in caplog.text
assert "Loaded 1 agents" in caplog.text
assert "Loaded 2 agents" in caplog.text

assert len(local_agent._backups) == 1
backup = list(local_agent._backups.values())[0]
assert backup.protected is bool(params.get("password"))
tar_file_path = str(mocked_tarfile.call_args_list[0][0][0])
backup_directory = hass.config.path(backup_directory)
assert tar_file_path == f"{backup_directory}/{backup.backup_id}.tar"
assert isinstance(tar_file_path, str)


async def test_loading_platforms(
Expand Down