Rewrite vultr unittest to pytest (#63367)

* Rewrite vultr unittest to pytest

* Fix tests

* Fix annotations

* Don't check setup_platform return value

Co-authored-by: epenet <epenet@users.noreply.github.com>
This commit is contained in:
epenet 2022-01-06 21:44:53 +01:00 committed by GitHub
parent 5fa6ef2849
commit 442690b885
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 318 additions and 394 deletions

View File

@ -0,0 +1,30 @@
"""Test configuration for the Vultr tests."""
import json
from unittest.mock import patch
import pytest
from homeassistant.components import vultr
from homeassistant.core import HomeAssistant
from .const import VALID_CONFIG
from tests.common import load_fixture
@pytest.fixture(name="valid_config")
def valid_config(hass: HomeAssistant, requests_mock):
"""Load a valid config."""
requests_mock.get(
"https://api.vultr.com/v1/account/info?api_key=ABCDEFG1234567",
text=load_fixture("account_info.json", "vultr"),
)
with patch(
"vultr.Vultr.server_list",
return_value=json.loads(load_fixture("server_list.json", "vultr")),
):
# Setup hub
vultr.setup(hass, VALID_CONFIG)
yield

View File

@ -0,0 +1,3 @@
"""Constants for the Vultr tests."""
VALID_CONFIG = {"vultr": {"api_key": "ABCDEFG1234567"}}

View File

@ -1,10 +1,5 @@
"""Test the Vultr binary sensor platform.""" """Test the Vultr binary sensor platform."""
import json
import unittest
from unittest.mock import patch
import pytest import pytest
import requests_mock
import voluptuous as vol import voluptuous as vol
from homeassistant.components import vultr as base_vultr from homeassistant.components import vultr as base_vultr
@ -19,57 +14,33 @@ from homeassistant.components.vultr import (
binary_sensor as vultr, binary_sensor as vultr,
) )
from homeassistant.const import CONF_NAME, CONF_PLATFORM from homeassistant.const import CONF_NAME, CONF_PLATFORM
from homeassistant.core import HomeAssistant
from tests.common import get_test_home_assistant, load_fixture CONFIGS = [
from tests.components.vultr.test_init import VALID_CONFIG
class TestVultrBinarySensorSetup(unittest.TestCase):
"""Test the Vultr binary sensor platform."""
DEVICES = []
def add_entities(self, devices, action):
"""Mock add devices."""
for device in devices:
self.DEVICES.append(device)
def setUp(self):
"""Init values for this testcase class."""
self.hass = get_test_home_assistant()
self.configs = [
{CONF_SUBSCRIPTION: "576965", CONF_NAME: "A Server"}, {CONF_SUBSCRIPTION: "576965", CONF_NAME: "A Server"},
{CONF_SUBSCRIPTION: "123456", CONF_NAME: "Failed Server"}, {CONF_SUBSCRIPTION: "123456", CONF_NAME: "Failed Server"},
{CONF_SUBSCRIPTION: "555555", CONF_NAME: vultr.DEFAULT_NAME}, {CONF_SUBSCRIPTION: "555555", CONF_NAME: vultr.DEFAULT_NAME},
] ]
self.addCleanup(self.tear_down_cleanup)
def tear_down_cleanup(self):
"""Stop our started services."""
self.hass.stop()
@requests_mock.Mocker() @pytest.mark.usefixtures("valid_config")
def test_binary_sensor(self, mock): def test_binary_sensor(hass: HomeAssistant):
"""Test successful instance.""" """Test successful instance."""
mock.get( hass_devices = []
"https://api.vultr.com/v1/account/info?api_key=ABCDEFG1234567",
text=load_fixture("account_info.json", "vultr"),
)
with patch( def add_entities(devices, action):
"vultr.Vultr.server_list", """Mock add devices."""
return_value=json.loads(load_fixture("server_list.json", "vultr")), for device in devices:
): device.hass = hass
# Setup hub hass_devices.append(device)
base_vultr.setup(self.hass, VALID_CONFIG)
# Setup each of our test configs # Setup each of our test configs
for config in self.configs: for config in CONFIGS:
vultr.setup_platform(self.hass, config, self.add_entities, None) vultr.setup_platform(hass, config, add_entities, None)
assert len(self.DEVICES) == 3 assert len(hass_devices) == 3
for device in self.DEVICES: for device in hass_devices:
# Test pre data retrieval # Test pre data retrieval
if device.subscription == "555555": if device.subscription == "555555":
@ -103,41 +74,31 @@ class TestVultrBinarySensorSetup(unittest.TestCase):
assert device_attrs[ATTR_CREATED_AT] == "2014-10-13 14:45:41" assert device_attrs[ATTR_CREATED_AT] == "2014-10-13 14:45:41"
assert device_attrs[ATTR_SUBSCRIPTION_ID] == "123456" assert device_attrs[ATTR_SUBSCRIPTION_ID] == "123456"
def test_invalid_sensor_config(self):
def test_invalid_sensor_config():
"""Test config type failures.""" """Test config type failures."""
with pytest.raises(vol.Invalid): # No subs with pytest.raises(vol.Invalid): # No subs
vultr.PLATFORM_SCHEMA({CONF_PLATFORM: base_vultr.DOMAIN}) vultr.PLATFORM_SCHEMA({CONF_PLATFORM: base_vultr.DOMAIN})
@requests_mock.Mocker()
def test_invalid_sensors(self, mock):
"""Test the VultrBinarySensor fails."""
mock.get(
"https://api.vultr.com/v1/account/info?api_key=ABCDEFG1234567",
text=load_fixture("account_info.json", "vultr"),
)
with patch( @pytest.mark.usefixtures("valid_config")
"vultr.Vultr.server_list", def test_invalid_sensors(hass: HomeAssistant):
return_value=json.loads(load_fixture("server_list.json", "vultr")), """Test the VultrBinarySensor fails."""
): hass_devices = []
# Setup hub
base_vultr.setup(self.hass, VALID_CONFIG) def add_entities(devices, action):
"""Mock add devices."""
for device in devices:
device.hass = hass
hass_devices.append(device)
bad_conf = {} # No subscription bad_conf = {} # No subscription
no_subs_setup = vultr.setup_platform( vultr.setup_platform(hass, bad_conf, add_entities, None)
self.hass, bad_conf, self.add_entities, None
)
assert not no_subs_setup
bad_conf = { bad_conf = {
CONF_NAME: "Missing Server", CONF_NAME: "Missing Server",
CONF_SUBSCRIPTION: "555555", CONF_SUBSCRIPTION: "555555",
} # Sub not associated with API key (not in server_list) } # Sub not associated with API key (not in server_list)
wrong_subs_setup = vultr.setup_platform( vultr.setup_platform(hass, bad_conf, add_entities, None)
self.hass, bad_conf, self.add_entities, None
)
assert not wrong_subs_setup

View File

@ -1,44 +1,29 @@
"""The tests for the Vultr component.""" """The tests for the Vultr component."""
from copy import deepcopy from copy import deepcopy
import json import json
import unittest
from unittest.mock import patch from unittest.mock import patch
import requests_mock
from homeassistant import setup from homeassistant import setup
import homeassistant.components.vultr as vultr from homeassistant.components import vultr
from homeassistant.core import HomeAssistant
from tests.common import get_test_home_assistant, load_fixture from .const import VALID_CONFIG
VALID_CONFIG = {"vultr": {"api_key": "ABCDEFG1234567"}} from tests.common import load_fixture
class TestVultr(unittest.TestCase): def test_setup(hass: HomeAssistant):
"""Tests the Vultr component."""
def setUp(self):
"""Initialize values for this test case class."""
self.hass = get_test_home_assistant()
self.config = VALID_CONFIG
self.addCleanup(self.tear_down_cleanup)
def tear_down_cleanup(self):
"""Stop everything that we started."""
self.hass.stop()
@requests_mock.Mocker()
def test_setup(self, mock):
"""Test successful setup.""" """Test successful setup."""
with patch( with patch(
"vultr.Vultr.server_list", "vultr.Vultr.server_list",
return_value=json.loads(load_fixture("server_list.json", "vultr")), return_value=json.loads(load_fixture("server_list.json", "vultr")),
): ):
response = vultr.setup(self.hass, self.config) response = vultr.setup(hass, VALID_CONFIG)
assert response assert response
def test_setup_no_api_key(self):
async def test_setup_no_api_key(hass: HomeAssistant):
"""Test failed setup with missing API Key.""" """Test failed setup with missing API Key."""
conf = deepcopy(self.config) conf = deepcopy(VALID_CONFIG)
del conf["vultr"]["api_key"] del conf["vultr"]["api_key"]
assert not setup.setup_component(self.hass, vultr.DOMAIN, conf) assert not await setup.async_setup_component(hass, vultr.DOMAIN, conf)

View File

@ -1,10 +1,5 @@
"""The tests for the Vultr sensor platform.""" """The tests for the Vultr sensor platform."""
import json
import unittest
from unittest.mock import patch
import pytest import pytest
import requests_mock
import voluptuous as vol import voluptuous as vol
from homeassistant.components import vultr as base_vultr from homeassistant.components import vultr as base_vultr
@ -16,26 +11,9 @@ from homeassistant.const import (
CONF_PLATFORM, CONF_PLATFORM,
DATA_GIGABYTES, DATA_GIGABYTES,
) )
from homeassistant.core import HomeAssistant
from tests.common import get_test_home_assistant, load_fixture CONFIGS = [
from tests.components.vultr.test_init import VALID_CONFIG
class TestVultrSensorSetup(unittest.TestCase):
"""Test the Vultr platform."""
DEVICES = []
def add_entities(self, devices, action):
"""Mock add devices."""
for device in devices:
device.hass = self.hass
self.DEVICES.append(device)
def setUp(self):
"""Initialize values for this testcase class."""
self.hass = get_test_home_assistant()
self.configs = [
{ {
CONF_NAME: vultr.DEFAULT_NAME, CONF_NAME: vultr.DEFAULT_NAME,
CONF_SUBSCRIPTION: "576965", CONF_SUBSCRIPTION: "576965",
@ -51,34 +29,28 @@ class TestVultrSensorSetup(unittest.TestCase):
CONF_SUBSCRIPTION: "555555", CONF_SUBSCRIPTION: "555555",
CONF_MONITORED_CONDITIONS: ["pending_charges"], CONF_MONITORED_CONDITIONS: ["pending_charges"],
}, },
] ]
self.addCleanup(self.hass.stop)
@requests_mock.Mocker()
def test_sensor(self, mock): @pytest.mark.usefixtures("valid_config")
def test_sensor(hass: HomeAssistant):
"""Test the Vultr sensor class and methods.""" """Test the Vultr sensor class and methods."""
mock.get( hass_devices = []
"https://api.vultr.com/v1/account/info?api_key=ABCDEFG1234567",
text=load_fixture("account_info.json", "vultr"),
)
with patch( def add_entities(devices, action):
"vultr.Vultr.server_list", """Mock add devices."""
return_value=json.loads(load_fixture("server_list.json", "vultr")), for device in devices:
): device.hass = hass
# Setup hub hass_devices.append(device)
base_vultr.setup(self.hass, VALID_CONFIG)
for config in self.configs: for config in CONFIGS:
setup = vultr.setup_platform(self.hass, config, self.add_entities, None) vultr.setup_platform(hass, config, add_entities, None)
assert setup is None assert len(hass_devices) == 5
assert len(self.DEVICES) == 5
tested = 0 tested = 0
for device in self.DEVICES: for device in hass_devices:
# Test pre update # Test pre update
if device.subscription == "576965": if device.subscription == "576965":
@ -120,7 +92,8 @@ class TestVultrSensorSetup(unittest.TestCase):
assert tested == 5 assert tested == 5
def test_invalid_sensor_config(self):
def test_invalid_sensor_config():
"""Test config type failures.""" """Test config type failures."""
with pytest.raises(vol.Invalid): # No subscription with pytest.raises(vol.Invalid): # No subscription
vultr.PLATFORM_SCHEMA( vultr.PLATFORM_SCHEMA(
@ -138,20 +111,17 @@ class TestVultrSensorSetup(unittest.TestCase):
} }
) )
@requests_mock.Mocker()
def test_invalid_sensors(self, mock):
"""Test the VultrSensor fails."""
mock.get(
"https://api.vultr.com/v1/account/info?api_key=ABCDEFG1234567",
text=load_fixture("account_info.json", "vultr"),
)
with patch( @pytest.mark.usefixtures("valid_config")
"vultr.Vultr.server_list", def test_invalid_sensors(hass: HomeAssistant):
return_value=json.loads(load_fixture("server_list.json", "vultr")), """Test the VultrSensor fails."""
): hass_devices = []
# Setup hub
base_vultr.setup(self.hass, VALID_CONFIG) def add_entities(devices, action):
"""Mock add devices."""
for device in devices:
device.hass = hass
hass_devices.append(device)
bad_conf = { bad_conf = {
CONF_NAME: "Vultr {} {}", CONF_NAME: "Vultr {} {}",
@ -159,9 +129,6 @@ class TestVultrSensorSetup(unittest.TestCase):
CONF_MONITORED_CONDITIONS: vultr.SENSOR_KEYS, CONF_MONITORED_CONDITIONS: vultr.SENSOR_KEYS,
} # No subs at all } # No subs at all
no_sub_setup = vultr.setup_platform( vultr.setup_platform(hass, bad_conf, add_entities, None)
self.hass, bad_conf, self.add_entities, None
)
assert no_sub_setup is None assert len(hass_devices) == 0
assert len(self.DEVICES) == 0

View File

@ -1,10 +1,10 @@
"""Test the Vultr switch platform.""" """Test the Vultr switch platform."""
from __future__ import annotations
import json import json
import unittest
from unittest.mock import patch from unittest.mock import patch
import pytest import pytest
import requests_mock
import voluptuous as vol import voluptuous as vol
from homeassistant.components import vultr as base_vultr from homeassistant.components import vultr as base_vultr
@ -19,59 +19,44 @@ from homeassistant.components.vultr import (
switch as vultr, switch as vultr,
) )
from homeassistant.const import CONF_NAME, CONF_PLATFORM from homeassistant.const import CONF_NAME, CONF_PLATFORM
from homeassistant.core import HomeAssistant
from tests.common import get_test_home_assistant, load_fixture from tests.common import load_fixture
from tests.components.vultr.test_init import VALID_CONFIG
CONFIGS = [
class TestVultrSwitchSetup(unittest.TestCase):
"""Test the Vultr switch platform."""
DEVICES = []
def add_entities(self, devices, action):
"""Mock add devices."""
for device in devices:
self.DEVICES.append(device)
def setUp(self):
"""Init values for this testcase class."""
self.hass = get_test_home_assistant()
self.configs = [
{CONF_SUBSCRIPTION: "576965", CONF_NAME: "A Server"}, {CONF_SUBSCRIPTION: "576965", CONF_NAME: "A Server"},
{CONF_SUBSCRIPTION: "123456", CONF_NAME: "Failed Server"}, {CONF_SUBSCRIPTION: "123456", CONF_NAME: "Failed Server"},
{CONF_SUBSCRIPTION: "555555", CONF_NAME: vultr.DEFAULT_NAME}, {CONF_SUBSCRIPTION: "555555", CONF_NAME: vultr.DEFAULT_NAME},
] ]
self.addCleanup(self.tear_down_cleanup)
def tear_down_cleanup(self):
"""Stop our started services."""
self.hass.stop()
@requests_mock.Mocker() @pytest.fixture(name="hass_devices")
def test_switch(self, mock): def load_hass_devices(hass: HomeAssistant):
"""Test successful instance.""" """Load a valid config."""
mock.get( hass_devices = []
"https://api.vultr.com/v1/account/info?api_key=ABCDEFG1234567",
text=load_fixture("account_info.json", "vultr"),
)
with patch( def add_entities(devices, action):
"vultr.Vultr.server_list", """Mock add devices."""
return_value=json.loads(load_fixture("server_list.json", "vultr")), for device in devices:
): device.hass = hass
# Setup hub hass_devices.append(device)
base_vultr.setup(self.hass, VALID_CONFIG)
# Setup each of our test configs # Setup each of our test configs
for config in self.configs: for config in CONFIGS:
vultr.setup_platform(self.hass, config, self.add_entities, None) vultr.setup_platform(hass, config, add_entities, None)
assert len(self.DEVICES) == 3 yield hass_devices
@pytest.mark.usefixtures("valid_config")
def test_switch(hass: HomeAssistant, hass_devices: list[vultr.VultrSwitch]):
"""Test successful instance."""
assert len(hass_devices) == 3
tested = 0 tested = 0
for device in self.DEVICES: for device in hass_devices:
if device.subscription == "555555": if device.subscription == "555555":
assert device.name == "Vultr {}" assert device.name == "Vultr {}"
tested += 1 tested += 1
@ -109,69 +94,62 @@ class TestVultrSwitchSetup(unittest.TestCase):
assert tested == 4 assert tested == 4
@requests_mock.Mocker()
def test_turn_on(self, mock): @pytest.mark.usefixtures("valid_config")
def test_turn_on(hass: HomeAssistant, hass_devices: list[vultr.VultrSwitch]):
"""Test turning a subscription on.""" """Test turning a subscription on."""
with patch( with patch(
"vultr.Vultr.server_list", "vultr.Vultr.server_list",
return_value=json.loads(load_fixture("server_list.json", "vultr")), return_value=json.loads(load_fixture("server_list.json", "vultr")),
), patch("vultr.Vultr.server_start") as mock_start: ), patch("vultr.Vultr.server_start") as mock_start:
for device in self.DEVICES: for device in hass_devices:
if device.name == "Failed Server": if device.name == "Failed Server":
device.update()
device.turn_on() device.turn_on()
# Turn on # Turn on
assert mock_start.call_count == 1 assert mock_start.call_count == 1
@requests_mock.Mocker()
def test_turn_off(self, mock): @pytest.mark.usefixtures("valid_config")
def test_turn_off(hass: HomeAssistant, hass_devices: list[vultr.VultrSwitch]):
"""Test turning a subscription off.""" """Test turning a subscription off."""
with patch( with patch(
"vultr.Vultr.server_list", "vultr.Vultr.server_list",
return_value=json.loads(load_fixture("server_list.json", "vultr")), return_value=json.loads(load_fixture("server_list.json", "vultr")),
), patch("vultr.Vultr.server_halt") as mock_halt: ), patch("vultr.Vultr.server_halt") as mock_halt:
for device in self.DEVICES: for device in hass_devices:
if device.name == "A Server": if device.name == "A Server":
device.update()
device.turn_off() device.turn_off()
# Turn off # Turn off
assert mock_halt.call_count == 1 assert mock_halt.call_count == 1
def test_invalid_switch_config(self):
def test_invalid_switch_config():
"""Test config type failures.""" """Test config type failures."""
with pytest.raises(vol.Invalid): # No subscription with pytest.raises(vol.Invalid): # No subscription
vultr.PLATFORM_SCHEMA({CONF_PLATFORM: base_vultr.DOMAIN}) vultr.PLATFORM_SCHEMA({CONF_PLATFORM: base_vultr.DOMAIN})
@requests_mock.Mocker()
def test_invalid_switches(self, mock):
"""Test the VultrSwitch fails."""
mock.get(
"https://api.vultr.com/v1/account/info?api_key=ABCDEFG1234567",
text=load_fixture("account_info.json", "vultr"),
)
with patch( @pytest.mark.usefixtures("valid_config")
"vultr.Vultr.server_list", def test_invalid_switches(hass: HomeAssistant):
return_value=json.loads(load_fixture("server_list.json", "vultr")), """Test the VultrSwitch fails."""
): hass_devices = []
# Setup hub
base_vultr.setup(self.hass, VALID_CONFIG) def add_entities(devices, action):
"""Mock add devices."""
for device in devices:
hass_devices.append(device)
bad_conf = {} # No subscription bad_conf = {} # No subscription
no_subs_setup = vultr.setup_platform( vultr.setup_platform(hass, bad_conf, add_entities, None)
self.hass, bad_conf, self.add_entities, None
)
assert no_subs_setup is not None
bad_conf = { bad_conf = {
CONF_NAME: "Missing Server", CONF_NAME: "Missing Server",
CONF_SUBSCRIPTION: "665544", CONF_SUBSCRIPTION: "665544",
} # Sub not associated with API key (not in server_list) } # Sub not associated with API key (not in server_list)
wrong_subs_setup = vultr.setup_platform( vultr.setup_platform(hass, bad_conf, add_entities, None)
self.hass, bad_conf, self.add_entities, None
)
assert wrong_subs_setup is not None