Migrate collection of component tests from coroutine to async/await (#30504)

This commit is contained in:
Franck Nijhof 2020-01-06 01:22:22 +01:00 committed by Martin Hjelmare
parent f400b77837
commit e642d95d0f
7 changed files with 45 additions and 69 deletions

View File

@ -1,18 +1,15 @@
"""Test intent_script component.""" """Test intent_script component."""
import asyncio
from homeassistant.bootstrap import async_setup_component from homeassistant.bootstrap import async_setup_component
from homeassistant.helpers import intent from homeassistant.helpers import intent
from tests.common import async_mock_service from tests.common import async_mock_service
@asyncio.coroutine async def test_intent_script(hass):
def test_intent_script(hass):
"""Test intent scripts work.""" """Test intent scripts work."""
calls = async_mock_service(hass, "test", "service") calls = async_mock_service(hass, "test", "service")
yield from async_setup_component( await async_setup_component(
hass, hass,
"intent_script", "intent_script",
{ {
@ -32,7 +29,7 @@ def test_intent_script(hass):
}, },
) )
response = yield from intent.async_handle( response = await intent.async_handle(
hass, "test", "HelloWorld", {"name": {"value": "Paulus"}} hass, "test", "HelloWorld", {"name": {"value": "Paulus"}}
) )

View File

@ -1,5 +1,4 @@
"""The tests the for Meraki device tracker.""" """The tests the for Meraki device tracker."""
import asyncio
import json import json
import pytest import pytest
@ -34,39 +33,38 @@ def meraki_client(loop, hass, hass_client):
yield loop.run_until_complete(hass_client()) yield loop.run_until_complete(hass_client())
@asyncio.coroutine async def test_invalid_or_missing_data(mock_device_tracker_conf, meraki_client):
def test_invalid_or_missing_data(mock_device_tracker_conf, meraki_client):
"""Test validator with invalid or missing data.""" """Test validator with invalid or missing data."""
req = yield from meraki_client.get(URL) req = await meraki_client.get(URL)
text = yield from req.text() text = await req.text()
assert req.status == 200 assert req.status == 200
assert text == "validator" assert text == "validator"
req = yield from meraki_client.post(URL, data=b"invalid") req = await meraki_client.post(URL, data=b"invalid")
text = yield from req.json() text = await req.json()
assert req.status == 400 assert req.status == 400
assert text["message"] == "Invalid JSON" assert text["message"] == "Invalid JSON"
req = yield from meraki_client.post(URL, data=b"{}") req = await meraki_client.post(URL, data=b"{}")
text = yield from req.json() text = await req.json()
assert req.status == 422 assert req.status == 422
assert text["message"] == "No secret" assert text["message"] == "No secret"
data = {"version": "1.0", "secret": "secret"} data = {"version": "1.0", "secret": "secret"}
req = yield from meraki_client.post(URL, data=json.dumps(data)) req = await meraki_client.post(URL, data=json.dumps(data))
text = yield from req.json() text = await req.json()
assert req.status == 422 assert req.status == 422
assert text["message"] == "Invalid version" assert text["message"] == "Invalid version"
data = {"version": "2.0", "secret": "invalid"} data = {"version": "2.0", "secret": "invalid"}
req = yield from meraki_client.post(URL, data=json.dumps(data)) req = await meraki_client.post(URL, data=json.dumps(data))
text = yield from req.json() text = await req.json()
assert req.status == 422 assert req.status == 422
assert text["message"] == "Invalid secret" assert text["message"] == "Invalid secret"
data = {"version": "2.0", "secret": "secret", "type": "InvalidType"} data = {"version": "2.0", "secret": "secret", "type": "InvalidType"}
req = yield from meraki_client.post(URL, data=json.dumps(data)) req = await meraki_client.post(URL, data=json.dumps(data))
text = yield from req.json() text = await req.json()
assert req.status == 422 assert req.status == 422
assert text["message"] == "Invalid device type" assert text["message"] == "Invalid device type"
@ -76,12 +74,11 @@ def test_invalid_or_missing_data(mock_device_tracker_conf, meraki_client):
"type": "BluetoothDevicesSeen", "type": "BluetoothDevicesSeen",
"data": {"observations": []}, "data": {"observations": []},
} }
req = yield from meraki_client.post(URL, data=json.dumps(data)) req = await meraki_client.post(URL, data=json.dumps(data))
assert req.status == 200 assert req.status == 200
@asyncio.coroutine async def test_data_will_be_saved(mock_device_tracker_conf, hass, meraki_client):
def test_data_will_be_saved(mock_device_tracker_conf, hass, meraki_client):
"""Test with valid data.""" """Test with valid data."""
data = { data = {
"version": "2.0", "version": "2.0",
@ -122,9 +119,9 @@ def test_data_will_be_saved(mock_device_tracker_conf, hass, meraki_client):
] ]
}, },
} }
req = yield from meraki_client.post(URL, data=json.dumps(data)) req = await meraki_client.post(URL, data=json.dumps(data))
assert req.status == 200 assert req.status == 200
yield from hass.async_block_till_done() await hass.async_block_till_done()
state_name = hass.states.get( state_name = hass.states.get(
"{}.{}".format("device_tracker", "00_26_ab_b8_a9_a4") "{}.{}".format("device_tracker", "00_26_ab_b8_a9_a4")
).state ).state

View File

@ -1,5 +1,4 @@
"""The tests for the MQTT component.""" """The tests for the MQTT component."""
import asyncio
import ssl import ssl
import unittest import unittest
from unittest import mock from unittest import mock
@ -593,8 +592,7 @@ class TestMQTTCallbacks(unittest.TestCase):
assert self.hass.data["mqtt"]._mqttc.subscribe.mock_calls == expected assert self.hass.data["mqtt"]._mqttc.subscribe.mock_calls == expected
@asyncio.coroutine async def test_setup_embedded_starts_with_no_config(hass):
def test_setup_embedded_starts_with_no_config(hass):
"""Test setting up embedded server with no config.""" """Test setting up embedded server with no config."""
client_config = ("localhost", 1883, "user", "pass", None, "3.1.1") client_config = ("localhost", 1883, "user", "pass", None, "3.1.1")
@ -602,12 +600,11 @@ def test_setup_embedded_starts_with_no_config(hass):
"homeassistant.components.mqtt.server.async_start", "homeassistant.components.mqtt.server.async_start",
return_value=mock_coro(return_value=(True, client_config)), return_value=mock_coro(return_value=(True, client_config)),
) as _start: ) as _start:
yield from async_mock_mqtt_client(hass, {}) await async_mock_mqtt_client(hass, {})
assert _start.call_count == 1 assert _start.call_count == 1
@asyncio.coroutine async def test_setup_embedded_with_embedded(hass):
def test_setup_embedded_with_embedded(hass):
"""Test setting up embedded server with no config.""" """Test setting up embedded server with no config."""
client_config = ("localhost", 1883, "user", "pass", None, "3.1.1") client_config = ("localhost", 1883, "user", "pass", None, "3.1.1")
@ -616,7 +613,7 @@ def test_setup_embedded_with_embedded(hass):
return_value=mock_coro(return_value=(True, client_config)), return_value=mock_coro(return_value=(True, client_config)),
) as _start: ) as _start:
_start.return_value = mock_coro(return_value=(True, client_config)) _start.return_value = mock_coro(return_value=(True, client_config))
yield from async_mock_mqtt_client(hass, {"embedded": None}) await async_mock_mqtt_client(hass, {"embedded": None})
assert _start.call_count == 1 assert _start.call_count == 1
@ -716,10 +713,9 @@ async def test_setup_with_tls_config_of_v1_under_python36_only_uses_v1(hass, moc
assert mock_MQTT.mock_calls[0][2]["tls_version"] == ssl.PROTOCOL_TLSv1 assert mock_MQTT.mock_calls[0][2]["tls_version"] == ssl.PROTOCOL_TLSv1
@asyncio.coroutine async def test_birth_message(hass):
def test_birth_message(hass):
"""Test sending birth message.""" """Test sending birth message."""
mqtt_client = yield from async_mock_mqtt_client( mqtt_client = await async_mock_mqtt_client(
hass, hass,
{ {
mqtt.CONF_BROKER: "mock-broker", mqtt.CONF_BROKER: "mock-broker",
@ -732,14 +728,13 @@ def test_birth_message(hass):
calls = [] calls = []
mqtt_client.publish.side_effect = lambda *args: calls.append(args) mqtt_client.publish.side_effect = lambda *args: calls.append(args)
hass.data["mqtt"]._mqtt_on_connect(None, None, 0, 0) hass.data["mqtt"]._mqtt_on_connect(None, None, 0, 0)
yield from hass.async_block_till_done() await hass.async_block_till_done()
assert calls[-1] == ("birth", "birth", 0, False) assert calls[-1] == ("birth", "birth", 0, False)
@asyncio.coroutine async def test_mqtt_subscribes_topics_on_connect(hass):
def test_mqtt_subscribes_topics_on_connect(hass):
"""Test subscription to topic on connect.""" """Test subscription to topic on connect."""
mqtt_client = yield from async_mock_mqtt_client(hass) mqtt_client = await async_mock_mqtt_client(hass)
hass.data["mqtt"].subscriptions = [ hass.data["mqtt"].subscriptions = [
mqtt.Subscription("topic/test", None), mqtt.Subscription("topic/test", None),
@ -751,7 +746,7 @@ def test_mqtt_subscribes_topics_on_connect(hass):
hass.add_job = mock.MagicMock() hass.add_job = mock.MagicMock()
hass.data["mqtt"]._mqtt_on_connect(None, None, 0, 0) hass.data["mqtt"]._mqtt_on_connect(None, None, 0, 0)
yield from hass.async_block_till_done() await hass.async_block_till_done()
assert mqtt_client.disconnect.call_count == 0 assert mqtt_client.disconnect.call_count == 0

View File

@ -1,5 +1,4 @@
"""Test the NamecheapDNS component.""" """Test the NamecheapDNS component."""
import asyncio
from datetime import timedelta from datetime import timedelta
import pytest import pytest
@ -33,8 +32,7 @@ def setup_namecheapdns(hass, aioclient_mock):
) )
@asyncio.coroutine async def test_setup(hass, aioclient_mock):
def test_setup(hass, aioclient_mock):
"""Test setup works if update passes.""" """Test setup works if update passes."""
aioclient_mock.get( aioclient_mock.get(
namecheapdns.UPDATE_URL, namecheapdns.UPDATE_URL,
@ -42,7 +40,7 @@ def test_setup(hass, aioclient_mock):
text="<interface-response><ErrCount>0</ErrCount></interface-response>", text="<interface-response><ErrCount>0</ErrCount></interface-response>",
) )
result = yield from async_setup_component( result = await async_setup_component(
hass, hass,
namecheapdns.DOMAIN, namecheapdns.DOMAIN,
{"namecheapdns": {"host": HOST, "domain": DOMAIN, "password": PASSWORD}}, {"namecheapdns": {"host": HOST, "domain": DOMAIN, "password": PASSWORD}},
@ -51,12 +49,11 @@ def test_setup(hass, aioclient_mock):
assert aioclient_mock.call_count == 1 assert aioclient_mock.call_count == 1
async_fire_time_changed(hass, utcnow() + timedelta(minutes=5)) async_fire_time_changed(hass, utcnow() + timedelta(minutes=5))
yield from hass.async_block_till_done() await hass.async_block_till_done()
assert aioclient_mock.call_count == 2 assert aioclient_mock.call_count == 2
@asyncio.coroutine async def test_setup_fails_if_update_fails(hass, aioclient_mock):
def test_setup_fails_if_update_fails(hass, aioclient_mock):
"""Test setup fails if first update fails.""" """Test setup fails if first update fails."""
aioclient_mock.get( aioclient_mock.get(
namecheapdns.UPDATE_URL, namecheapdns.UPDATE_URL,
@ -64,7 +61,7 @@ def test_setup_fails_if_update_fails(hass, aioclient_mock):
text="<interface-response><ErrCount>1</ErrCount></interface-response>", text="<interface-response><ErrCount>1</ErrCount></interface-response>",
) )
result = yield from async_setup_component( result = await async_setup_component(
hass, hass,
namecheapdns.DOMAIN, namecheapdns.DOMAIN,
{"namecheapdns": {"host": HOST, "domain": DOMAIN, "password": PASSWORD}}, {"namecheapdns": {"host": HOST, "domain": DOMAIN, "password": PASSWORD}},

View File

@ -1,5 +1,4 @@
"""The tests for the openalpr local platform.""" """The tests for the openalpr local platform."""
import asyncio
from unittest.mock import MagicMock, PropertyMock, patch from unittest.mock import MagicMock, PropertyMock, patch
import homeassistant.components.image_processing as ip import homeassistant.components.image_processing as ip
@ -11,13 +10,11 @@ from tests.common import assert_setup_component, get_test_home_assistant, load_f
from tests.components.image_processing import common from tests.components.image_processing import common
@asyncio.coroutine async def mock_async_subprocess():
def mock_async_subprocess():
"""Get a Popen mock back.""" """Get a Popen mock back."""
async_popen = MagicMock() async_popen = MagicMock()
@asyncio.coroutine async def communicate(input=None):
def communicate(input=None):
"""Communicate mock.""" """Communicate mock."""
fixture = bytes(load_fixture("alpr_stdout.txt"), "utf-8") fixture = bytes(load_fixture("alpr_stdout.txt"), "utf-8")
return (fixture, None) return (fixture, None)

View File

@ -1,6 +1,4 @@
"""The tests for the Prometheus exporter.""" """The tests for the Prometheus exporter."""
import asyncio
import pytest import pytest
from homeassistant import setup from homeassistant import setup
@ -51,14 +49,13 @@ async def prometheus_client(loop, hass, hass_client):
return await hass_client() return await hass_client()
@asyncio.coroutine async def test_view(prometheus_client): # pylint: disable=redefined-outer-name
def test_view(prometheus_client): # pylint: disable=redefined-outer-name
"""Test prometheus metrics view.""" """Test prometheus metrics view."""
resp = yield from prometheus_client.get(prometheus.API_ENDPOINT) resp = await prometheus_client.get(prometheus.API_ENDPOINT)
assert resp.status == 200 assert resp.status == 200
assert resp.headers["content-type"] == "text/plain" assert resp.headers["content-type"] == "text/plain"
body = yield from resp.text() body = await resp.text()
body = body.split("\n") body = body.split("\n")
assert len(body) > 3 assert len(body) > 3

View File

@ -1,6 +1,4 @@
"""The tests for the rss_feed_api component.""" """The tests for the rss_feed_api component."""
import asyncio
from defusedxml import ElementTree from defusedxml import ElementTree
import pytest import pytest
@ -28,24 +26,22 @@ def mock_http_client(loop, hass, hass_client):
return loop.run_until_complete(hass_client()) return loop.run_until_complete(hass_client())
@asyncio.coroutine async def test_get_nonexistant_feed(mock_http_client):
def test_get_nonexistant_feed(mock_http_client):
"""Test if we can retrieve the correct rss feed.""" """Test if we can retrieve the correct rss feed."""
resp = yield from mock_http_client.get("/api/rss_template/otherfeed") resp = await mock_http_client.get("/api/rss_template/otherfeed")
assert resp.status == 404 assert resp.status == 404
@asyncio.coroutine async def test_get_rss_feed(mock_http_client, hass):
def test_get_rss_feed(mock_http_client, hass):
"""Test if we can retrieve the correct rss feed.""" """Test if we can retrieve the correct rss feed."""
hass.states.async_set("test.test1", "a_state_1") hass.states.async_set("test.test1", "a_state_1")
hass.states.async_set("test.test2", "a_state_2") hass.states.async_set("test.test2", "a_state_2")
hass.states.async_set("test.test3", "a_state_3") hass.states.async_set("test.test3", "a_state_3")
resp = yield from mock_http_client.get("/api/rss_template/testfeed") resp = await mock_http_client.get("/api/rss_template/testfeed")
assert resp.status == 200 assert resp.status == 200
text = yield from resp.text() text = await resp.text()
xml = ElementTree.fromstring(text) xml = ElementTree.fromstring(text)
assert xml[0].text == "feed title is a_state_1" assert xml[0].text == "feed title is a_state_1"