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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

UniFi - Try to discover local controller #31326

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 15 additions & 1 deletion homeassistant/components/unifi/config_flow.py
@@ -1,4 +1,6 @@
"""Config flow for UniFi."""
import socket

import voluptuous as vol

from homeassistant import config_entries
Expand Down Expand Up @@ -104,11 +106,15 @@ async def async_step_user(self, user_input=None):
)
return self.async_abort(reason="unknown")

host = ""
if await async_discover_unifi(self.hass):
host = "unifi"

return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_HOST): str,
vol.Required(CONF_HOST, default=host): str,
vol.Required(CONF_USERNAME): str,
vol.Required(CONF_PASSWORD): str,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): int,
Expand Down Expand Up @@ -235,3 +241,11 @@ async def async_step_statistics_sensors(self, user_input=None):
async def _update_options(self):
"""Update config entry options."""
return self.async_create_entry(title="", data=self.options)


async def async_discover_unifi(hass):
"""Discover UniFi address."""
try:
return await hass.async_add_executor_job(socket.gethostbyname, "unifi")
except socket.gaierror:
return None
13 changes: 13 additions & 0 deletions tests/components/unifi/conftest.py
@@ -0,0 +1,13 @@
"""Fixtures for UniFi methods."""
from asynctest import patch
import pytest


@pytest.fixture(autouse=True)
def mock_discovery():
"""No real network traffic allowed."""
with patch(
"homeassistant.components.unifi.config_flow.async_discover_unifi",
return_value=None,
) as mock:
yield mock
10 changes: 9 additions & 1 deletion tests/components/unifi/test_config_flow.py
Expand Up @@ -16,14 +16,22 @@
from tests.common import MockConfigEntry


async def test_flow_works(hass, aioclient_mock):
async def test_flow_works(hass, aioclient_mock, mock_discovery):
"""Test config flow."""
mock_discovery.return_value = "1"
result = await hass.config_entries.flow.async_init(
config_flow.DOMAIN, context={"source": "user"}
)

assert result["type"] == "form"
assert result["step_id"] == "user"
assert result["data_schema"]({CONF_USERNAME: "", CONF_PASSWORD: ""}) == {
CONF_HOST: "unifi",
CONF_USERNAME: "",
CONF_PASSWORD: "",
CONF_PORT: 8443,
CONF_VERIFY_SSL: False,
}

aioclient_mock.post(
"https://1.2.3.4:1234/api/login",
Expand Down