Handle Unifi Protect BadRequest exception during API key creation (#150223)

This commit is contained in:
Raphael Hehl
2025-08-08 15:26:02 +02:00
committed by Franck Nijhof
parent 3ef332e168
commit 8afe3fed74
2 changed files with 26 additions and 3 deletions

View File

@@ -8,7 +8,7 @@ import logging
from aiohttp.client_exceptions import ServerDisconnectedError
from uiprotect.api import DEVICE_UPDATE_INTERVAL
from uiprotect.data import Bootstrap
from uiprotect.exceptions import ClientError, NotAuthorized
from uiprotect.exceptions import BadRequest, ClientError, NotAuthorized
# Import the test_util.anonymize module from the uiprotect package
# in __init__ to ensure it gets imported in the executor since the
@@ -100,7 +100,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: UFPConfigEntry) -> bool:
new_api_key = await protect.create_api_key(
name=f"Home Assistant ({hass.config.location_name})"
)
except NotAuthorized as err:
except (NotAuthorized, BadRequest) as err:
_LOGGER.error("Failed to create API key: %s", err)
else:
protect.set_api_key(new_api_key)

View File

@@ -5,9 +5,10 @@ from __future__ import annotations
from unittest.mock import AsyncMock, Mock, patch
import pytest
from uiprotect import NotAuthorized, NvrError, ProtectApiClient
from uiprotect import NvrError, ProtectApiClient
from uiprotect.api import DEVICE_UPDATE_INTERVAL
from uiprotect.data import NVR, Bootstrap, CloudAccount, Light
from uiprotect.exceptions import BadRequest, NotAuthorized
from homeassistant.components.unifiprotect.const import (
AUTH_RETRIES,
@@ -414,6 +415,28 @@ async def test_setup_handles_api_key_creation_failure(
ufp.api.set_api_key.assert_not_called()
@pytest.mark.parametrize("mock_user_can_write_nvr", [True], indirect=True)
async def test_setup_handles_api_key_creation_bad_request(
hass: HomeAssistant, ufp: MockUFPFixture, mock_user_can_write_nvr: Mock
) -> None:
"""Test handling of API key creation BadRequest error."""
# Setup: API key is not set, user has write permissions, but creation fails with BadRequest
ufp.api.is_api_key_set.return_value = False
ufp.api.create_api_key = AsyncMock(
side_effect=BadRequest("Invalid API key creation request")
)
# Should fail with auth error due to API key creation failure
await hass.config_entries.async_setup(ufp.entry.entry_id)
await hass.async_block_till_done()
assert ufp.entry.state is ConfigEntryState.SETUP_ERROR
# Verify API key creation was attempted but set_api_key was not called
ufp.api.create_api_key.assert_called_once_with(name="Home Assistant (test home)")
ufp.api.set_api_key.assert_not_called()
async def test_setup_with_existing_api_key(
hass: HomeAssistant, ufp: MockUFPFixture
) -> None: