Repository: home-assistant/core
Pull request: SharkIQ Hotfix - Handle current installations by using default `REGION`
<!--
  You are amazing! Thanks for contributing to our project!
  Please, DO NOT DELETE ANY TEXT from this template! (unless instructed).
-->

## Proposed change
<!--
  Describe the big picture of your changes here to communicate to the
  maintainers why we should accept this pull request. If it fixes a bug
  or resolves a feature request, be sure to link to that issue in the
  additional information section.
-->
Add integration `REGION` default to setup function.  This is considered a safe default because all existing integrations are configured for the non-EU API.  This prevents existing integrations from breaking upon upgrading, while ensuring the EU region is now supported.  This is a BUG FIX for code introduced in #89349.

## Type of change
<!--
  What type of change does your PR introduce to Home Assistant?
  NOTE: Please, check only 1! box!
  If your PR requires multiple boxes to be checked, you'll most likely need to
  split it into multiple PRs. This makes things easier and faster to code review.
-->

- [ ] Dependency upgrade
- [x] Bugfix (non-breaking change which fixes an issue)
- [ ] New integration (thank you!)
- [ ] New feature (which adds functionality to an existing integration)
- [ ] Deprecation (breaking change to happen in the future)
- [ ] Breaking change (fix/feature causing existing functionality to break)
- [ ] Code quality improvements to existing code or addition of tests

## Additional information
<!--
  Details are important, and help maintainers processing your PR.
  Please be sure to fill out additional details, if applicable.
-->

- This PR fixes or closes issue: fixes #90672
- This PR is related to issue: #90672
- Link to documentation pull request: N/A

## Checklist
<!--
  Put an `x` in the boxes that apply. You can also fill these out after
  creating the PR. If you're unsure about any of them, don't hesitate to ask.
  We're here to help! This is simply a reminder of what we are going to look
  for before merging your code.
-->

- [x] The code change is tested and works locally.
- [x] Local tests pass. **Your PR cannot be merged unless tests pass**
- [x] There is no commented out code in this PR.
- [x] I have followed the [development checklist][dev-checklist]
- [x] I have followed the [perfect PR recommendations][perfect-pr]
- [x] The code has been formatted using Black (`black --fast homeassistant tests`)
- [ ] Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

- [ ] Documentation added/updated for [www.home-assistant.io][docs-repository]

If the code communicates with devices, web services, or third-party tools:

- [ ] The [manifest file][manifest-docs] has all fields filled out correctly.  
      Updated and included derived files by running: `python3 -m script.hassfest`.
- [ ] New or updated dependencies have been added to `requirements_all.txt`.  
      Updated by running `python3 -m script.gen_requirements_all`.
- [ ] For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description.
- [ ] Untested files have been added to `.coveragerc`.

<!--
  This project is very active and we have a high turnover of pull requests.

  Unfortunately, the number of incoming pull requests is higher than what our
  reviewers can review and merge so there is a long backlog of pull requests
  waiting for review. You can help here!
  
  By reviewing another pull request, you will help raise the code quality of
  that pull request and the final review will be faster. This way the general
  pace of pull request reviews will go up and your wait time will go down.
  
  When picking a pull request to review, try to choose one that hasn't yet
  been reviewed.

  Thanks for helping out!
-->

To help with the load of incoming pull requests:

- [ ] I have reviewed two other [open pull requests][prs] in this repository.

[prs]: https://github.com/home-assistant/core/pulls?q=is%3Aopen+is%3Apr+-author%3A%40me+-draft%3Atrue+-label%3Awaiting-for-upstream+sort%3Acreated-desc+review%3Anone+-status%3Afailure

<!--
  Thank you for contributing <3

  Below, some useful links you could explore:
-->
[dev-checklist]: https://developers.home-assistant.io/docs/en/development_checklist.html
[manifest-docs]: https://developers.home-assistant.io/docs/en/creating_integration_manifest.html
[quality-scale]: https://developers.home-assistant.io/docs/en/next/integration_quality_scale_index.html
[docs-repository]: https://github.com/home-assistant/home-assistant.io
[perfect-pr]: https://developers.home-assistant.io/docs/review-process/#creating-the-perfect-pr


Problem statement:
Existing SharkIQ instances break during upgrade - missing `region`
### The problem

The SharkIQ integration fails to run due to a region issue.

### What version of Home Assistant Core has the issue?

core-2023.4.0b4

### What was the last working version of Home Assistant Core?

core-2023.3.x

### What type of installation are you running?

Home Assistant OS

### Integration causing the issue

SharkIQ

### Link to integration documentation on our website

_No response_

### Diagnostics information

_No response_

### Example YAML snippet

_No response_

### Anything in the logs that might be useful for us?

```txt
2023-04-02 11:01:49.487 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry <redacted> for sharkiq
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 383, in async_setup
    result = await component.async_setup_entry(hass, self)
  File "/usr/src/homeassistant/homeassistant/components/sharkiq/__init__.py", line 50, in async_setup_entry
    europe=(config_entry.data[CONF_REGION] == SHARKIQ_REGION_EUROPE),
KeyError: 'region'
```


### Additional information

_No response_

Hints from issue discussion:
Hey there @jeffresc, @funkybunch, mind taking a look at this issue as it has been labeled with an integration (`sharkiq`) you are listed as a [code owner](https://github.com/home-assistant/core/blob/dev/CODEOWNERS#L1062) for? Thanks!

<details>
<summary>Code owner commands</summary>


Code owners of `sharkiq` can trigger bot actions by commenting:

- `@home-assistant close` Closes the issue.
- `@home-assistant rename Awesome new title` Renames the issue.
- `@home-assistant reopen` Reopen the issue.
- `@home-assistant unassign sharkiq` Removes the current integration label and assignees on the issue, add the integration domain after the command.

</details>


<sub><sup>(message by CodeOwnersMention)</sup></sub>

---

[sharkiq documentation](https://www.home-assistant.io/integrations/sharkiq)
[sharkiq source](https://github.com/home-assistant/core/tree/dev/homeassistant/components/sharkiq)
<sub><sup>(message by IssueLinks)</sup></sub>
@W-Floyd Can you tell us if this was a new instance of the integration or if it was an existing instance that broke upon upgrading?
Existing instance.
Okay, I have a suspicion of what might be going here.  My guess is if you reconfigured the integration it will work properly.  I'll work on a fix in the meantime so we hopefully don't risk breaking it during upgrades.  Let me know if reconfiguration works or not.
Yup, deleting and re-adding works.
@home-assistant rename Existing SharkIQ instances break during upgrade - missing `region`
@funkybunch  with #89349 you introduced the attribute `CONF_REGION` into config entry data for SharkIQ, but there is no migration for already existing config entries, which does not have this attribute.
The easiest should be in `async_setup_entry` to add the attribute `CONF_REGION` with value `SHARKIQ_REGION_DEFAULT` to a config entry, when it does not exists.
@mib1185 That was my thought as well.  I was able to reproduce this by installing the integration in 2023.3.x and then updated to `dev`.  Same test (in a fresh container) when updating to my test branch with the code fix was successful.

PR is up.  This is resolved by #90741

Commit message: Update Tests & Config setting method

Patch to review:
diff --git a/homeassistant/components/sharkiq/__init__.py b/homeassistant/components/sharkiq/__init__.py
index 738dd595a5a7b1..02d8986fbdbc09 100644
--- a/homeassistant/components/sharkiq/__init__.py
+++ b/homeassistant/components/sharkiq/__init__.py
@@ -17,7 +17,14 @@
 from homeassistant.core import HomeAssistant
 from homeassistant.helpers.aiohttp_client import async_get_clientsession
 
-from .const import API_TIMEOUT, DOMAIN, LOGGER, PLATFORMS, SHARKIQ_REGION_EUROPE
+from .const import (
+    API_TIMEOUT,
+    DOMAIN,
+    LOGGER,
+    PLATFORMS,
+    SHARKIQ_REGION_DEFAULT,
+    SHARKIQ_REGION_EUROPE,
+)
 from .update_coordinator import SharkIqUpdateCoordinator
 
 
@@ -43,11 +50,19 @@ async def async_connect_or_timeout(ayla_api: AylaApi) -> bool:
 
 async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
     """Initialize the sharkiq platform via config entry."""
+    ayla_region = SHARKIQ_REGION_DEFAULT
+    if not hasattr(config_entry.data, CONF_REGION):
+        new = {**config_entry.data}
+        new[CONF_REGION] = ayla_region
+        hass.config_entries.async_update_entry(config_entry, data=new)
+    else:
+        ayla_region = config_entry.data[CONF_REGION]
+
     ayla_api = get_ayla_api(
         username=config_entry.data[CONF_USERNAME],
         password=config_entry.data[CONF_PASSWORD],
         websession=async_get_clientsession(hass),
-        europe=(config_entry.data[CONF_REGION] == SHARKIQ_REGION_EUROPE),
+        europe=(ayla_region == SHARKIQ_REGION_EUROPE),
     )
 
     try:
diff --git a/tests/components/sharkiq/const.py b/tests/components/sharkiq/const.py
index 8ec7d424ffa164..b4f9d72dafddb7 100644
--- a/tests/components/sharkiq/const.py
+++ b/tests/components/sharkiq/const.py
@@ -76,4 +76,8 @@
     CONF_PASSWORD: TEST_PASSWORD,
     CONF_REGION: TEST_REGION,
 }
+CONFIG_NO_REGION = {
+    CONF_USERNAME: TEST_USERNAME,
+    CONF_PASSWORD: TEST_PASSWORD,
+}
 ENTRY_ID = "0123456789abcdef0123456789abcdef"
diff --git a/tests/components/sharkiq/test_config_flow.py b/tests/components/sharkiq/test_config_flow.py
index c7a0603f8651c4..248bb57f04c644 100644
--- a/tests/components/sharkiq/test_config_flow.py
+++ b/tests/components/sharkiq/test_config_flow.py
@@ -8,12 +8,32 @@
 from homeassistant import config_entries
 from homeassistant.components.sharkiq.const import DOMAIN
 from homeassistant.core import HomeAssistant
-
-from .const import CONFIG, TEST_PASSWORD, TEST_REGION, TEST_USERNAME, UNIQUE_ID
+from homeassistant.setup import async_setup_component
+
+from .const import (
+    CONFIG,
+    CONFIG_NO_REGION,
+    TEST_PASSWORD,
+    TEST_REGION,
+    TEST_USERNAME,
+    UNIQUE_ID,
+)
 
 from tests.common import MockConfigEntry
 
 
+async def test_setup_success_no_region(hass: HomeAssistant) -> None:
+    """Test reauth flow."""
+    mock_config = MockConfigEntry(
+        domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG_NO_REGION
+    )
+    mock_config.add_to_hass(hass)
+
+    result = await async_setup_component(hass=hass, domain=DOMAIN, config=mock_config)
+
+    assert result is True
+
+
 async def test_form(hass: HomeAssistant) -> None:
     """Test we get the form."""
 
@@ -39,6 +59,7 @@ async def test_form(hass: HomeAssistant) -> None:
         "password": TEST_PASSWORD,
         "region": TEST_REGION,
     }
+
     await hass.async_block_till_done()
     mock_setup_entry.assert_called_once()
 


Code review comments:
diff_hunk: @@ -43,11 +50,19 @@ async def async_connect_or_timeout(ayla_api: AylaApi) -> bool:
 
 async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
     """Initialize the sharkiq platform via config entry."""
+    ayla_region = SHARKIQ_REGION_DEFAULT
+    if not hasattr(config_entry.data, CONF_REGION):
+        new = {**config_entry.data}
+        new[CONF_REGION] = ayla_region
+        hass.config_entries.async_update_entry(config_entry, data=new)
+    else:
+        ayla_region = config_entry.data[CONF_REGION]
+
     ayla_api = get_ayla_api(
         username=config_entry.data[CONF_USERNAME],
         password=config_entry.data[CONF_PASSWORD],
         websession=async_get_clientsession(hass),
-        europe=(config_entry.data[CONF_REGION] == SHARKIQ_REGION_EUROPE),
+        europe=(ayla_region == SHARKIQ_REGION_EUROPE),
path: homeassistant/components/sharkiq/__init__.py
text: @user1:
```suggestion
        europe=(config_entry.data[CONF_REGION] == SHARKIQ_REGION_EUROPE),
```

diff_hunk: @@ -43,11 +50,19 @@ async def async_connect_or_timeout(ayla_api: AylaApi) -> bool:
 
 async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
     """Initialize the sharkiq platform via config entry."""
+    ayla_region = SHARKIQ_REGION_DEFAULT
+    if not hasattr(config_entry.data, CONF_REGION):
+        new = {**config_entry.data}
+        new[CONF_REGION] = ayla_region
+        hass.config_entries.async_update_entry(config_entry, data=new)
+    else:
+        ayla_region = config_entry.data[CONF_REGION]
path: homeassistant/components/sharkiq/__init__.py
text: @user1:
I think this can be reduced to:

```suggestion
    if CONF_REGION not in config_entry.data:
        hass.config_entries.async_update_entry(
            config_entry,
            data={**config_entry.data, CONF_REGION: SHARKIQ_REGION_DEFAULT}
        )
```