diff --git a/README.md b/README.md index 2534464..0739d58 100644 --- a/README.md +++ b/README.md @@ -115,6 +115,19 @@ if __name__ == "__main__": asyncio.run(main()) ``` +### Updating devices one by one + +`update()` logs and skips a device that fails to update. To handle each device yourself, fetch the device list with `discover_devices()` and update the devices one by one: + +```python +await nintendo.discover_devices() +for device in nintendo.devices.values(): + try: + await device.update() + except Exception as err: + print(f"Updating {device.name} failed: {err}") +``` + ### The `NintendoParental` object The main entry point is the `NintendoParental` object. You create it using the asynchronous class method `create`: diff --git a/pynintendoparental/__init__.py b/pynintendoparental/__init__.py index 9ca2f89..c7cd186 100644 --- a/pynintendoparental/__init__.py +++ b/pynintendoparental/__init__.py @@ -38,6 +38,23 @@ async def update_device(dev: Device): except Exception as err: _LOGGER.exception("Error updating device %s: %s", dev.device_id, err) + await self.discover_devices() + coros = [update_device(d) for d in self.devices.values()] + await asyncio.gather(*coros) + + async def discover_devices(self) -> dict[str, Device]: + """Fetch the devices linked to the account without updating them. + + New devices are added to `devices`. Call `Device.update()` on each device + afterwards; unlike `update()`, its errors reach the caller. + + Returns: + The `devices` dictionary, keyed by device ID. + + Raises: + NoDevicesFoundException: If the account has no devices. + HttpException: If the device list could not be fetched. + """ try: response = await self._api.async_get_account_devices() except HttpException as err: @@ -51,9 +68,8 @@ async def update_device(dev: Device): if self.devices.get(device.device_id, None) is None: _LOGGER.debug("Creating new device %s", device.device_id) self.devices[device.device_id] = device - coros = [update_device(d) for d in self.devices.values()] - await asyncio.gather(*coros) _LOGGER.debug("Found %s device(s)", len(self.devices)) + return self.devices async def update(self): """Update module data. diff --git a/tests/test_init.py b/tests/test_init.py index 9f0f94c..498a874 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -53,6 +53,41 @@ async def test_device_fetch_http_exception(mock_authenticator: Authenticator, mo await NintendoParental.create(mock_authenticator) +async def test_discover_devices(mock_authenticator: Authenticator, mock_api_init: AsyncMock): + """Test discover_devices fetches the device list without updating the devices.""" + devices_fixture = await load_fixture("account_devices") + device_id = devices_fixture["ownedDevices"][0]["deviceId"] + mock_api_instance = mock_api_init.return_value + mock_api_instance.async_get_account_devices.return_value = {"json": devices_fixture} + parental = NintendoParental(mock_authenticator, "Europe/London", "en-GB") + + with patch("pynintendoparental.Device.update", autospec=True) as mock_update: + devices = await parental.discover_devices() + assert devices is parental.devices + assert list(devices) == [device_id] + device = devices[device_id] + + assert (await parental.discover_devices())[device_id] is device + + mock_update.assert_not_called() + assert mock_api_instance.async_get_account_devices.call_count == 2 + + +async def test_discover_devices_errors(mock_authenticator: Authenticator, mock_api_init: AsyncMock): + """Test discover_devices raises when the device list can't be fetched.""" + mock_api_instance = mock_api_init.return_value + parental = NintendoParental(mock_authenticator, "Europe/London", "en-GB") + + mock_api_instance.async_get_account_devices.side_effect = HttpException(404, "Not Found") + with pytest.raises(NoDevicesFoundException): + await parental.discover_devices() + + mock_api_instance.async_get_account_devices.side_effect = HttpException(500, "Internal Server Error") + with pytest.raises(HttpException): + await parental.discover_devices() + assert parental.devices == {} + + async def test_device_update_exception(mock_authenticator: Authenticator, mock_api_init: AsyncMock): """Test an exception during device update doesn't stop creation.""" devices_fixture = await load_fixture("account_devices")