Inline MQTT paho imports (#29177)

* Inline MQTT paho imports

* Address comments

* Fix patch paths

* Move other imports inline

* Fix test
This commit is contained in:
Paulus Schoutsen 2019-12-02 11:32:02 -08:00 committed by GitHub
parent 1804c6edc5
commit ffaa0e572a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 29 additions and 17 deletions

View File

@ -16,8 +16,6 @@ from typing import Any, Callable, List, Optional, Union
import attr import attr
import requests.certs import requests.certs
import voluptuous as vol import voluptuous as vol
import paho.mqtt.client as mqtt
from paho.mqtt.matcher import MQTTMatcher
from homeassistant import config_entries from homeassistant import config_entries
from homeassistant.components import websocket_api from homeassistant.components import websocket_api
@ -725,6 +723,11 @@ class MQTT:
tls_version: Optional[int], tls_version: Optional[int],
) -> None: ) -> None:
"""Initialize Home Assistant MQTT client.""" """Initialize Home Assistant MQTT client."""
# We don't import them on the top because some integrations
# should be able to optionally rely on MQTT.
# pylint: disable=import-outside-toplevel
import paho.mqtt.client as mqtt
self.hass = hass self.hass = hass
self.broker = broker self.broker = broker
self.port = port self.port = port
@ -786,6 +789,9 @@ class MQTT:
This method is a coroutine. This method is a coroutine.
""" """
# pylint: disable=import-outside-toplevel
import paho.mqtt.client as mqtt
result: int = None result: int = None
try: try:
result = await self.hass.async_add_job( result = await self.hass.async_add_job(
@ -877,6 +883,9 @@ class MQTT:
Resubscribe to all topics we were subscribed to and publish birth Resubscribe to all topics we were subscribed to and publish birth
message. message.
""" """
# pylint: disable=import-outside-toplevel
import paho.mqtt.client as mqtt
if result_code != mqtt.CONNACK_ACCEPTED: if result_code != mqtt.CONNACK_ACCEPTED:
_LOGGER.error( _LOGGER.error(
"Unable to connect to the MQTT broker: %s", "Unable to connect to the MQTT broker: %s",
@ -968,6 +977,9 @@ class MQTT:
def _raise_on_error(result_code: int) -> None: def _raise_on_error(result_code: int) -> None:
"""Raise error if error result.""" """Raise error if error result."""
# pylint: disable=import-outside-toplevel
import paho.mqtt.client as mqtt
if result_code != 0: if result_code != 0:
raise HomeAssistantError( raise HomeAssistantError(
"Error talking to MQTT: {}".format(mqtt.error_string(result_code)) "Error talking to MQTT: {}".format(mqtt.error_string(result_code))
@ -976,6 +988,9 @@ def _raise_on_error(result_code: int) -> None:
def _match_topic(subscription: str, topic: str) -> bool: def _match_topic(subscription: str, topic: str) -> bool:
"""Test if topic matches subscription.""" """Test if topic matches subscription."""
# pylint: disable=import-outside-toplevel
from paho.mqtt.matcher import MQTTMatcher
matcher = MQTTMatcher() matcher = MQTTMatcher()
matcher[subscription] = True matcher[subscription] = True
try: try:

View File

@ -3,7 +3,6 @@ from collections import OrderedDict
import queue import queue
import voluptuous as vol import voluptuous as vol
import paho.mqtt.client as mqtt
from homeassistant import config_entries from homeassistant import config_entries
from homeassistant.const import ( from homeassistant.const import (
@ -126,6 +125,8 @@ class FlowHandler(config_entries.ConfigFlow):
def try_connection(broker, port, username, password, protocol="3.1"): def try_connection(broker, port, username, password, protocol="3.1"):
"""Test if we can connect to an MQTT broker.""" """Test if we can connect to an MQTT broker."""
import paho.mqtt.client as mqtt
if protocol == "3.1": if protocol == "3.1":
proto = mqtt.MQTTv31 proto = mqtt.MQTTv31
else: else:

View File

@ -4,8 +4,6 @@ import logging
import tempfile import tempfile
import voluptuous as vol import voluptuous as vol
from hbmqtt.broker import Broker, BrokerException
from passlib.apps import custom_app_context
from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.const import EVENT_HOMEASSISTANT_STOP
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
@ -37,6 +35,9 @@ def async_start(hass, password, server_config):
This method is a coroutine. This method is a coroutine.
""" """
# pylint: disable=import-outside-toplevel
from hbmqtt.broker import Broker, BrokerException
passwd = tempfile.NamedTemporaryFile() passwd = tempfile.NamedTemporaryFile()
gen_server_config, client_config = generate_config(hass, passwd, password) gen_server_config, client_config = generate_config(hass, passwd, password)
@ -65,6 +66,9 @@ def async_start(hass, password, server_config):
def generate_config(hass, passwd, password): def generate_config(hass, passwd, password):
"""Generate a configuration based on current Home Assistant instance.""" """Generate a configuration based on current Home Assistant instance."""
# pylint: disable=import-outside-toplevel
from passlib.apps import custom_app_context
config = { config = {
"listeners": { "listeners": {
"default": { "default": {

View File

@ -19,13 +19,9 @@ class TestMQTT:
"""Stop everything that was started.""" """Stop everything that was started."""
self.hass.stop() self.hass.stop()
@patch( @patch("passlib.apps.custom_app_context", Mock(return_value=""))
"homeassistant.components.mqtt.server.custom_app_context", Mock(return_value="")
)
@patch("tempfile.NamedTemporaryFile", Mock(return_value=MagicMock())) @patch("tempfile.NamedTemporaryFile", Mock(return_value=MagicMock()))
@patch( @patch("hbmqtt.broker.Broker", Mock(return_value=MagicMock()))
"homeassistant.components.mqtt.server.Broker", Mock(return_value=MagicMock())
)
@patch("hbmqtt.broker.Broker.start", Mock(return_value=mock_coro())) @patch("hbmqtt.broker.Broker.start", Mock(return_value=mock_coro()))
@patch("homeassistant.components.mqtt.MQTT") @patch("homeassistant.components.mqtt.MQTT")
def test_creating_config_with_pass_and_no_http_pass(self, mock_mqtt): def test_creating_config_with_pass_and_no_http_pass(self, mock_mqtt):
@ -45,13 +41,9 @@ class TestMQTT:
assert mock_mqtt.mock_calls[1][2]["username"] == "homeassistant" assert mock_mqtt.mock_calls[1][2]["username"] == "homeassistant"
assert mock_mqtt.mock_calls[1][2]["password"] == password assert mock_mqtt.mock_calls[1][2]["password"] == password
@patch( @patch("passlib.apps.custom_app_context", Mock(return_value=""))
"homeassistant.components.mqtt.server.custom_app_context", Mock(return_value="")
)
@patch("tempfile.NamedTemporaryFile", Mock(return_value=MagicMock())) @patch("tempfile.NamedTemporaryFile", Mock(return_value=MagicMock()))
@patch( @patch("hbmqtt.broker.Broker", Mock(return_value=MagicMock()))
"homeassistant.components.mqtt.server.Broker", Mock(return_value=MagicMock())
)
@patch("hbmqtt.broker.Broker.start", Mock(return_value=mock_coro())) @patch("hbmqtt.broker.Broker.start", Mock(return_value=mock_coro()))
@patch("homeassistant.components.mqtt.MQTT") @patch("homeassistant.components.mqtt.MQTT")
def test_creating_config_with_pass_and_http_pass(self, mock_mqtt): def test_creating_config_with_pass_and_http_pass(self, mock_mqtt):