Use snapshots in analytics tests (#110704)

This commit is contained in:
Joakim Sørensen 2024-02-16 15:47:41 +01:00 committed by GitHub
parent 2d74dafd3f
commit 23e81a45c8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 401 additions and 118 deletions

View File

@ -0,0 +1,224 @@
# serializer version: 1
# name: test_custom_integrations
dict({
'certificate': False,
'custom_integrations': list([
dict({
'domain': 'test_package',
'version': <AwesomeVersion SemVer '1.2.3'>,
}),
]),
'installation_type': 'Home Assistant Tests',
'integrations': list([
]),
'uuid': 'abcdefg',
'version': '1970.1.0',
})
# ---
# name: test_not_check_config_entries_if_yaml
dict({
'automation_count': 0,
'certificate': True,
'custom_integrations': list([
]),
'installation_type': 'Home Assistant Tests',
'integration_count': 1,
'integrations': list([
'default_config',
]),
'state_count': 0,
'user_count': 0,
'uuid': 'abcdefg',
'version': '1970.1.0',
})
# ---
# name: test_send_base
dict({
'installation_type': 'Home Assistant Tests',
'uuid': 'abcdefg',
'version': '1970.1.0',
})
# ---
# name: test_send_base_with_supervisor
dict({
'installation_type': 'Home Assistant Supervised',
'operating_system': dict({
'board': 'blue',
'version': '123',
}),
'supervisor': dict({
'arch': 'amd64',
'healthy': True,
'supported': True,
}),
'uuid': 'abcdefg',
'version': '1970.1.0',
})
# ---
# name: test_send_statistics
dict({
'automation_count': 0,
'installation_type': 'Home Assistant Tests',
'integration_count': 1,
'state_count': 0,
'user_count': 0,
'uuid': 'abcdefg',
'version': '1970.1.0',
})
# ---
# name: test_send_statistics_disabled_integration
dict({
'automation_count': 0,
'installation_type': 'Home Assistant Tests',
'integration_count': 0,
'state_count': 0,
'user_count': 0,
'uuid': 'abcdefg',
'version': '1970.1.0',
})
# ---
# name: test_send_statistics_ignored_integration
dict({
'automation_count': 0,
'installation_type': 'Home Assistant Tests',
'integration_count': 0,
'state_count': 0,
'user_count': 0,
'uuid': 'abcdefg',
'version': '1970.1.0',
})
# ---
# name: test_send_statistics_with_supervisor
dict({
'addon_count': 1,
'automation_count': 0,
'installation_type': 'Home Assistant Supervised',
'integration_count': 0,
'state_count': 0,
'supervisor': dict({
'arch': 'amd64',
'healthy': True,
'supported': True,
}),
'user_count': 0,
'uuid': 'abcdefg',
'version': '1970.1.0',
})
# ---
# name: test_send_usage
dict({
'certificate': False,
'custom_integrations': list([
]),
'installation_type': 'Home Assistant Tests',
'integrations': list([
'default_config',
]),
'uuid': 'abcdefg',
'version': '1970.1.0',
})
# ---
# name: test_send_usage_with_certificate
dict({
'certificate': True,
'custom_integrations': list([
]),
'installation_type': 'Home Assistant Tests',
'integrations': list([
]),
'uuid': 'abcdefg',
'version': '1970.1.0',
})
# ---
# name: test_send_usage_with_supervisor
dict({
'addons': list([
dict({
'auto_update': False,
'protected': True,
'slug': 'test_addon',
'version': '1',
}),
]),
'certificate': False,
'custom_integrations': list([
]),
'installation_type': 'Home Assistant Supervised',
'integrations': list([
]),
'supervisor': dict({
'arch': 'amd64',
'healthy': True,
'supported': True,
}),
'uuid': 'abcdefg',
'version': '1970.1.0',
})
# ---
# name: test_send_with_energy_config
dict({
'certificate': False,
'custom_integrations': list([
]),
'energy': dict({
'configured': True,
}),
'installation_type': 'Home Assistant Tests',
'integrations': list([
]),
'recorder': dict({
'engine': 'sqlite',
'version': AwesomeVersion,
}),
'uuid': 'abcdefg',
'version': '1970.1.0',
})
# ---
# name: test_send_with_no_energy
dict({
'certificate': False,
'custom_integrations': list([
]),
'installation_type': 'Home Assistant Tests',
'integrations': list([
]),
'uuid': 'abcdefg',
'version': '1970.1.0',
})
# ---
# name: test_send_with_no_energy_config
dict({
'certificate': False,
'custom_integrations': list([
]),
'energy': dict({
'configured': False,
}),
'installation_type': 'Home Assistant Tests',
'integrations': list([
]),
'recorder': dict({
'engine': 'sqlite',
'version': AwesomeVersion,
}),
'uuid': 'abcdefg',
'version': '1970.1.0',
})
# ---
# name: test_send_with_recorder
dict({
'certificate': True,
'custom_integrations': list([
]),
'installation_type': 'Home Assistant Tests',
'integrations': list([
'recorder',
]),
'recorder': dict({
'engine': 'sqlite',
'version': AwesomeVersion,
}),
'uuid': 'abcdefg',
'version': '1970.1.0',
})
# ---

View File

@ -1,9 +1,13 @@
"""The tests for the analytics .""" """The tests for the analytics ."""
from collections.abc import Generator
from typing import Any from typing import Any
from unittest.mock import ANY, AsyncMock, Mock, PropertyMock, patch from unittest.mock import AsyncMock, Mock, PropertyMock, patch
import aiohttp import aiohttp
from awesomeversion import AwesomeVersion
import pytest import pytest
from syrupy import SnapshotAssertion
from syrupy.matchers import path_type
from homeassistant.components.analytics.analytics import Analytics from homeassistant.components.analytics.analytics import Analytics
from homeassistant.components.analytics.const import ( from homeassistant.components.analytics.const import (
@ -16,7 +20,6 @@ from homeassistant.components.analytics.const import (
) )
from homeassistant.components.recorder import Recorder from homeassistant.components.recorder import Recorder
from homeassistant.config_entries import ConfigEntryState from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import ATTR_DOMAIN
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.loader import IntegrationNotFound from homeassistant.loader import IntegrationNotFound
@ -31,6 +34,34 @@ MOCK_VERSION_DEV = "1970.1.0.dev0"
MOCK_VERSION_NIGHTLY = "1970.1.0.dev19700101" MOCK_VERSION_NIGHTLY = "1970.1.0.dev19700101"
@pytest.fixture(autouse=True)
def uuid_mock() -> Generator[Any, Any, None]:
"""Mock the UUID."""
with patch("uuid.UUID.hex", new_callable=PropertyMock) as hex_mock:
hex_mock.return_value = MOCK_UUID
yield
@pytest.fixture(autouse=True)
def ha_version_mock() -> Generator[Any, Any, None]:
"""Mock the core version."""
with patch(
"homeassistant.components.analytics.analytics.HA_VERSION",
MOCK_VERSION,
):
yield
@pytest.fixture
def installation_type_mock() -> Generator[Any, Any, None]:
"""Mock the async_get_system_info."""
with patch(
"homeassistant.components.analytics.analytics.async_get_system_info",
return_value={"installation_type": "Home Assistant Tests"},
):
yield
def _last_call_payload(aioclient: AiohttpClientMocker) -> dict[str, Any]: def _last_call_payload(aioclient: AiohttpClientMocker) -> dict[str, Any]:
"""Return the payload of the last call.""" """Return the payload of the last call."""
return aioclient.mock_calls[-1][2] return aioclient.mock_calls[-1][2]
@ -100,8 +131,7 @@ async def test_failed_to_send(
await analytics.save_preferences({ATTR_BASE: True}) await analytics.save_preferences({ATTR_BASE: True})
assert analytics.preferences[ATTR_BASE] assert analytics.preferences[ATTR_BASE]
with patch("homeassistant.components.analytics.analytics.HA_VERSION", MOCK_VERSION): await analytics.send_analytics()
await analytics.send_analytics()
assert ( assert (
f"Sending analytics failed with statuscode 400 from {ANALYTICS_ENDPOINT_URL}" f"Sending analytics failed with statuscode 400 from {ANALYTICS_ENDPOINT_URL}"
in caplog.text in caplog.text
@ -119,8 +149,7 @@ async def test_failed_to_send_raises(
await analytics.save_preferences({ATTR_BASE: True}) await analytics.save_preferences({ATTR_BASE: True})
assert analytics.preferences[ATTR_BASE] assert analytics.preferences[ATTR_BASE]
with patch("homeassistant.components.analytics.analytics.HA_VERSION", MOCK_VERSION): await analytics.send_analytics()
await analytics.send_analytics()
assert "Error sending analytics" in caplog.text assert "Error sending analytics" in caplog.text
@ -128,6 +157,8 @@ async def test_send_base(
hass: HomeAssistant, hass: HomeAssistant,
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
installation_type_mock: Generator[Any, Any, None],
snapshot: SnapshotAssertion,
) -> None: ) -> None:
"""Test send base preferences are defined.""" """Test send base preferences are defined."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200) aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
@ -136,23 +167,20 @@ async def test_send_base(
await analytics.save_preferences({ATTR_BASE: True}) await analytics.save_preferences({ATTR_BASE: True})
assert analytics.preferences[ATTR_BASE] assert analytics.preferences[ATTR_BASE]
with patch("uuid.UUID.hex", new_callable=PropertyMock) as hex, patch( await analytics.send_analytics()
"homeassistant.components.analytics.analytics.HA_VERSION", MOCK_VERSION
):
hex.return_value = MOCK_UUID
await analytics.send_analytics()
assert f"'uuid': '{MOCK_UUID}'" in caplog.text logged_data = caplog.records[-1].args
assert f"'version': '{MOCK_VERSION}'" in caplog.text submitted_data = _last_call_payload(aioclient_mock)
assert "'installation_type':" in caplog.text
assert "'integration_count':" not in caplog.text assert submitted_data == logged_data
assert "'integrations':" not in caplog.text assert snapshot == submitted_data
async def test_send_base_with_supervisor( async def test_send_base_with_supervisor(
hass: HomeAssistant, hass: HomeAssistant,
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
snapshot: SnapshotAssertion,
) -> None: ) -> None:
"""Test send base preferences are defined.""" """Test send base preferences are defined."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200) aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
@ -178,34 +206,24 @@ async def test_send_base_with_supervisor(
), patch( ), patch(
"homeassistant.components.hassio.is_hassio", "homeassistant.components.hassio.is_hassio",
side_effect=Mock(return_value=True), side_effect=Mock(return_value=True),
), patch(
"uuid.UUID.hex",
new_callable=PropertyMock,
) as hex, patch(
"homeassistant.components.analytics.analytics.HA_VERSION",
MOCK_VERSION,
): ):
hex.return_value = MOCK_UUID
await analytics.load() await analytics.load()
await analytics.send_analytics() await analytics.send_analytics()
assert f"'uuid': '{MOCK_UUID}'" in caplog.text logged_data = caplog.records[-1].args
assert f"'version': '{MOCK_VERSION}'" in caplog.text submitted_data = _last_call_payload(aioclient_mock)
assert (
"'supervisor': {'healthy': True, 'supported': True, 'arch': 'amd64'}" assert submitted_data == logged_data
in caplog.text assert snapshot == submitted_data
)
assert "'operating_system': {'board': 'blue', 'version': '123'}" in caplog.text
assert "'installation_type':" in caplog.text
assert "'integration_count':" not in caplog.text
assert "'integrations':" not in caplog.text
async def test_send_usage( async def test_send_usage(
hass: HomeAssistant, hass: HomeAssistant,
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
installation_type_mock: Generator[Any, Any, None],
snapshot: SnapshotAssertion,
) -> None: ) -> None:
"""Test send usage preferences are defined.""" """Test send usage preferences are defined."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200) aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
@ -218,13 +236,8 @@ async def test_send_usage(
hass.config.components = ["default_config"] hass.config.components = ["default_config"]
with patch( with patch(
"homeassistant.components.analytics.analytics.HA_VERSION", MOCK_VERSION
), patch(
"homeassistant.config.load_yaml_config_file", "homeassistant.config.load_yaml_config_file",
return_value={"default_config": {}}, return_value={"default_config": {}},
), patch(
"homeassistant.components.analytics.analytics.async_get_system_info",
return_value={"installation_type": "Home Assistant Tests"},
): ):
await analytics.send_analytics() await analytics.send_analytics()
@ -232,14 +245,12 @@ async def test_send_usage(
"Submitted analytics to Home Assistant servers. Information submitted includes" "Submitted analytics to Home Assistant servers. Information submitted includes"
in caplog.text in caplog.text
) )
assert _last_call_payload(aioclient_mock) == {
"uuid": ANY, logged_data = caplog.records[-1].args
"version": MOCK_VERSION, submitted_data = _last_call_payload(aioclient_mock)
"installation_type": "Home Assistant Tests",
"certificate": False, assert submitted_data == logged_data
"integrations": ["default_config"], assert snapshot == submitted_data
"custom_integrations": [],
}
async def test_send_usage_with_supervisor( async def test_send_usage_with_supervisor(
@ -247,6 +258,7 @@ async def test_send_usage_with_supervisor(
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
mock_hass_config: None, mock_hass_config: None,
snapshot: SnapshotAssertion,
) -> None: ) -> None:
"""Test send usage with supervisor preferences are defined.""" """Test send usage with supervisor preferences are defined."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200) aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
@ -289,22 +301,22 @@ async def test_send_usage_with_supervisor(
), patch( ), patch(
"homeassistant.components.hassio.is_hassio", "homeassistant.components.hassio.is_hassio",
side_effect=Mock(return_value=True), side_effect=Mock(return_value=True),
), patch(
"homeassistant.components.analytics.analytics.HA_VERSION",
MOCK_VERSION,
): ):
await analytics.send_analytics() await analytics.send_analytics()
assert (
"'addons': [{'slug': 'test_addon', 'protected': True, 'version': '1'," logged_data = caplog.records[-1].args
" 'auto_update': False}]" submitted_data = _last_call_payload(aioclient_mock)
) in caplog.text
assert "'addon_count':" not in caplog.text assert submitted_data == logged_data
assert snapshot == submitted_data
async def test_send_statistics( async def test_send_statistics(
hass: HomeAssistant, hass: HomeAssistant,
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
installation_type_mock: Generator[Any, Any, None],
snapshot: SnapshotAssertion,
) -> None: ) -> None:
"""Test send statistics preferences are defined.""" """Test send statistics preferences are defined."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200) aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
@ -315,17 +327,16 @@ async def test_send_statistics(
hass.config.components = ["default_config"] hass.config.components = ["default_config"]
with patch( with patch(
"homeassistant.components.analytics.analytics.HA_VERSION", MOCK_VERSION
), patch(
"homeassistant.config.load_yaml_config_file", "homeassistant.config.load_yaml_config_file",
return_value={"default_config": {}}, return_value={"default_config": {}},
): ):
await analytics.send_analytics() await analytics.send_analytics()
assert (
"'state_count': 0, 'automation_count': 0, 'integration_count': 1," logged_data = caplog.records[-1].args
" 'user_count': 0" submitted_data = _last_call_payload(aioclient_mock)
) in caplog.text
assert "'integrations':" not in caplog.text assert submitted_data == logged_data
assert snapshot == submitted_data
async def test_send_statistics_one_integration_fails( async def test_send_statistics_one_integration_fails(
@ -345,7 +356,7 @@ async def test_send_statistics_one_integration_fails(
with patch( with patch(
"homeassistant.components.analytics.analytics.async_get_integrations", "homeassistant.components.analytics.analytics.async_get_integrations",
return_value={"any": IntegrationNotFound("any")}, return_value={"any": IntegrationNotFound("any")},
), patch("homeassistant.components.analytics.analytics.HA_VERSION", MOCK_VERSION): ):
await analytics.send_analytics() await analytics.send_analytics()
post_call = aioclient_mock.mock_calls[0] post_call = aioclient_mock.mock_calls[0]
@ -358,6 +369,8 @@ async def test_send_statistics_disabled_integration(
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
mock_hass_config: None, mock_hass_config: None,
installation_type_mock: Generator[Any, Any, None],
snapshot: SnapshotAssertion,
) -> None: ) -> None:
"""Test send statistics with disabled integration.""" """Test send statistics with disabled integration."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200) aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
@ -379,12 +392,14 @@ async def test_send_statistics_disabled_integration(
), ),
) )
}, },
), patch("homeassistant.components.analytics.analytics.HA_VERSION", MOCK_VERSION): ):
await analytics.send_analytics() await analytics.send_analytics()
payload = _last_call_payload(aioclient_mock) logged_data = caplog.records[-1].args
assert "uuid" in payload submitted_data = _last_call_payload(aioclient_mock)
assert payload["integration_count"] == 0
assert submitted_data == logged_data
assert snapshot == submitted_data
async def test_send_statistics_ignored_integration( async def test_send_statistics_ignored_integration(
@ -392,6 +407,8 @@ async def test_send_statistics_ignored_integration(
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
mock_hass_config: None, mock_hass_config: None,
installation_type_mock: Generator[Any, Any, None],
snapshot: SnapshotAssertion,
) -> None: ) -> None:
"""Test send statistics with ignored integration.""" """Test send statistics with ignored integration."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200) aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
@ -419,12 +436,14 @@ async def test_send_statistics_ignored_integration(
), ),
), ),
}, },
), patch("homeassistant.components.analytics.analytics.HA_VERSION", MOCK_VERSION): ):
await analytics.send_analytics() await analytics.send_analytics()
payload = _last_call_payload(aioclient_mock) logged_data = caplog.records[-1].args
assert "uuid" in payload submitted_data = _last_call_payload(aioclient_mock)
assert payload["integration_count"] == 0
assert submitted_data == logged_data
assert snapshot == submitted_data
async def test_send_statistics_async_get_integration_unknown_exception( async def test_send_statistics_async_get_integration_unknown_exception(
@ -444,7 +463,7 @@ async def test_send_statistics_async_get_integration_unknown_exception(
with pytest.raises(ValueError), patch( with pytest.raises(ValueError), patch(
"homeassistant.components.analytics.analytics.async_get_integrations", "homeassistant.components.analytics.analytics.async_get_integrations",
return_value={"any": ValueError()}, return_value={"any": ValueError()},
), patch("homeassistant.components.analytics.analytics.HA_VERSION", MOCK_VERSION): ):
await analytics.send_analytics() await analytics.send_analytics()
@ -453,6 +472,7 @@ async def test_send_statistics_with_supervisor(
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
mock_hass_config: None, mock_hass_config: None,
snapshot: SnapshotAssertion,
) -> None: ) -> None:
"""Test send statistics preferences are defined.""" """Test send statistics preferences are defined."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200) aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
@ -493,17 +513,19 @@ async def test_send_statistics_with_supervisor(
), patch( ), patch(
"homeassistant.components.hassio.is_hassio", "homeassistant.components.hassio.is_hassio",
side_effect=Mock(return_value=True), side_effect=Mock(return_value=True),
), patch(
"homeassistant.components.analytics.analytics.HA_VERSION",
MOCK_VERSION,
): ):
await analytics.send_analytics() await analytics.send_analytics()
assert "'addon_count': 1" in caplog.text
assert "'integrations':" not in caplog.text logged_data = caplog.records[-1].args
submitted_data = _last_call_payload(aioclient_mock)
assert submitted_data == logged_data
assert snapshot == submitted_data
async def test_reusing_uuid( async def test_reusing_uuid(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
) -> None: ) -> None:
"""Test reusing the stored UUID.""" """Test reusing the stored UUID."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200) aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
@ -512,12 +534,8 @@ async def test_reusing_uuid(
await analytics.save_preferences({ATTR_BASE: True}) await analytics.save_preferences({ATTR_BASE: True})
with patch("uuid.UUID.hex", new_callable=PropertyMock) as hex, patch( # This is not actually called but that in itself prove the test
"homeassistant.components.analytics.analytics.HA_VERSION", MOCK_VERSION await analytics.send_analytics()
):
# This is not actually called but that in itself prove the test
hex.return_value = MOCK_UUID
await analytics.send_analytics()
assert analytics.uuid == "NOT_MOCK_UUID" assert analytics.uuid == "NOT_MOCK_UUID"
@ -526,6 +544,9 @@ async def test_custom_integrations(
hass: HomeAssistant, hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
enable_custom_integrations: None, enable_custom_integrations: None,
caplog: pytest.LogCaptureFixture,
installation_type_mock: Generator[Any, Any, None],
snapshot: SnapshotAssertion,
) -> None: ) -> None:
"""Test sending custom integrations.""" """Test sending custom integrations."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200) aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
@ -535,15 +556,16 @@ async def test_custom_integrations(
await analytics.save_preferences({ATTR_BASE: True, ATTR_USAGE: True}) await analytics.save_preferences({ATTR_BASE: True, ATTR_USAGE: True})
with patch( with patch(
"homeassistant.components.analytics.analytics.HA_VERSION", MOCK_VERSION
), patch(
"homeassistant.config.load_yaml_config_file", "homeassistant.config.load_yaml_config_file",
return_value={"test_package": {}}, return_value={"test_package": {}},
): ):
await analytics.send_analytics() await analytics.send_analytics()
payload = aioclient_mock.mock_calls[0][2] logged_data = caplog.records[-1].args
assert payload["custom_integrations"][0][ATTR_DOMAIN] == "test_package" submitted_data = _last_call_payload(aioclient_mock)
assert submitted_data == logged_data
assert snapshot == submitted_data
async def test_dev_url( async def test_dev_url(
@ -607,6 +629,9 @@ async def test_send_with_no_energy(
hass: HomeAssistant, hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
mock_hass_config: None, mock_hass_config: None,
caplog: pytest.LogCaptureFixture,
installation_type_mock: Generator[Any, Any, None],
snapshot: SnapshotAssertion,
) -> None: ) -> None:
"""Test send base preferences are defined.""" """Test send base preferences are defined."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200) aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
@ -615,18 +640,22 @@ async def test_send_with_no_energy(
await analytics.save_preferences({ATTR_BASE: True, ATTR_USAGE: True}) await analytics.save_preferences({ATTR_BASE: True, ATTR_USAGE: True})
with patch("uuid.UUID.hex", new_callable=PropertyMock) as hex, patch( with patch(
"homeassistant.components.analytics.analytics.HA_VERSION", MOCK_VERSION
), patch(
"homeassistant.components.analytics.analytics.energy_is_configured", AsyncMock() "homeassistant.components.analytics.analytics.energy_is_configured", AsyncMock()
) as energy_is_configured: ) as energy_is_configured, patch(
"homeassistant.components.analytics.analytics.get_recorder_instance",
Mock(),
) as get_recorder_instance:
energy_is_configured.return_value = False energy_is_configured.return_value = False
hex.return_value = MOCK_UUID get_recorder_instance.return_value = Mock(database_engine=Mock())
await analytics.send_analytics() await analytics.send_analytics()
postdata = aioclient_mock.mock_calls[-1][2] logged_data = caplog.records[-1].args
submitted_data = _last_call_payload(aioclient_mock)
assert "energy" not in postdata assert "energy" not in submitted_data
assert submitted_data == logged_data
assert snapshot == submitted_data
async def test_send_with_no_energy_config( async def test_send_with_no_energy_config(
@ -634,6 +663,9 @@ async def test_send_with_no_energy_config(
hass: HomeAssistant, hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
mock_hass_config: None, mock_hass_config: None,
caplog: pytest.LogCaptureFixture,
installation_type_mock: Generator[Any, Any, None],
snapshot: SnapshotAssertion,
) -> None: ) -> None:
"""Test send base preferences are defined.""" """Test send base preferences are defined."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200) aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
@ -642,18 +674,21 @@ async def test_send_with_no_energy_config(
await analytics.save_preferences({ATTR_BASE: True, ATTR_USAGE: True}) await analytics.save_preferences({ATTR_BASE: True, ATTR_USAGE: True})
assert await async_setup_component(hass, "energy", {}) assert await async_setup_component(hass, "energy", {})
with patch("uuid.UUID.hex", new_callable=PropertyMock) as hex, patch( with patch(
"homeassistant.components.analytics.analytics.HA_VERSION", MOCK_VERSION
), patch(
"homeassistant.components.analytics.analytics.energy_is_configured", AsyncMock() "homeassistant.components.analytics.analytics.energy_is_configured", AsyncMock()
) as energy_is_configured: ) as energy_is_configured:
energy_is_configured.return_value = False energy_is_configured.return_value = False
hex.return_value = MOCK_UUID
await analytics.send_analytics() await analytics.send_analytics()
postdata = aioclient_mock.mock_calls[-1][2] logged_data = caplog.records[-1].args
submitted_data = _last_call_payload(aioclient_mock)
assert not postdata["energy"]["configured"] assert submitted_data["energy"]["configured"] is False
assert submitted_data == logged_data
assert (
snapshot(matcher=path_type({"recorder.version": (AwesomeVersion,)}))
== submitted_data
)
async def test_send_with_energy_config( async def test_send_with_energy_config(
@ -661,6 +696,9 @@ async def test_send_with_energy_config(
hass: HomeAssistant, hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
mock_hass_config: None, mock_hass_config: None,
caplog: pytest.LogCaptureFixture,
installation_type_mock: Generator[Any, Any, None],
snapshot: SnapshotAssertion,
) -> None: ) -> None:
"""Test send base preferences are defined.""" """Test send base preferences are defined."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200) aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
@ -669,18 +707,21 @@ async def test_send_with_energy_config(
await analytics.save_preferences({ATTR_BASE: True, ATTR_USAGE: True}) await analytics.save_preferences({ATTR_BASE: True, ATTR_USAGE: True})
assert await async_setup_component(hass, "energy", {}) assert await async_setup_component(hass, "energy", {})
with patch("uuid.UUID.hex", new_callable=PropertyMock) as hex, patch( with patch(
"homeassistant.components.analytics.analytics.HA_VERSION", MOCK_VERSION
), patch(
"homeassistant.components.analytics.analytics.energy_is_configured", AsyncMock() "homeassistant.components.analytics.analytics.energy_is_configured", AsyncMock()
) as energy_is_configured: ) as energy_is_configured:
energy_is_configured.return_value = True energy_is_configured.return_value = True
hex.return_value = MOCK_UUID
await analytics.send_analytics() await analytics.send_analytics()
postdata = aioclient_mock.mock_calls[-1][2] logged_data = caplog.records[-1].args
submitted_data = _last_call_payload(aioclient_mock)
assert postdata["energy"]["configured"] assert submitted_data["energy"]["configured"] is True
assert submitted_data == logged_data
assert (
snapshot(matcher=path_type({"recorder.version": (AwesomeVersion,)}))
== submitted_data
)
async def test_send_usage_with_certificate( async def test_send_usage_with_certificate(
@ -688,6 +729,8 @@ async def test_send_usage_with_certificate(
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
mock_hass_config: None, mock_hass_config: None,
installation_type_mock: Generator[Any, Any, None],
snapshot: SnapshotAssertion,
) -> None: ) -> None:
"""Test send usage preferences with certificate.""" """Test send usage preferences with certificate."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200) aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
@ -698,16 +741,23 @@ async def test_send_usage_with_certificate(
assert analytics.preferences[ATTR_BASE] assert analytics.preferences[ATTR_BASE]
assert analytics.preferences[ATTR_USAGE] assert analytics.preferences[ATTR_USAGE]
with patch("homeassistant.components.analytics.analytics.HA_VERSION", MOCK_VERSION): await analytics.send_analytics()
await analytics.send_analytics()
assert "'certificate': True" in caplog.text logged_data = caplog.records[-1].args
submitted_data = _last_call_payload(aioclient_mock)
assert submitted_data["certificate"] is True
assert submitted_data == logged_data
assert snapshot == submitted_data
async def test_send_with_recorder( async def test_send_with_recorder(
recorder_mock: Recorder, recorder_mock: Recorder,
hass: HomeAssistant, hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
installation_type_mock: Generator[Any, Any, None],
snapshot: SnapshotAssertion,
) -> None: ) -> None:
"""Test recorder information.""" """Test recorder information."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200) aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
@ -717,15 +767,20 @@ async def test_send_with_recorder(
await analytics.save_preferences({ATTR_BASE: True, ATTR_USAGE: True}) await analytics.save_preferences({ATTR_BASE: True, ATTR_USAGE: True})
with patch( with patch(
"homeassistant.components.analytics.analytics.HA_VERSION", MOCK_VERSION
), patch(
"homeassistant.config.load_yaml_config_file", "homeassistant.config.load_yaml_config_file",
return_value={"recorder": {}}, return_value={"recorder": {}},
): ):
await analytics.send_analytics() await analytics.send_analytics()
postdata = _last_call_payload(aioclient_mock) logged_data = caplog.records[-1].args
assert postdata["recorder"]["engine"] == "sqlite" submitted_data = _last_call_payload(aioclient_mock)
assert submitted_data["recorder"]["engine"] == "sqlite"
assert submitted_data == logged_data
assert (
snapshot(matcher=path_type({"recorder.version": (AwesomeVersion,)}))
== submitted_data
)
async def test_send_with_problems_loading_yaml( async def test_send_with_problems_loading_yaml(
@ -770,6 +825,8 @@ async def test_not_check_config_entries_if_yaml(
hass: HomeAssistant, hass: HomeAssistant,
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker, aioclient_mock: AiohttpClientMocker,
installation_type_mock: Generator[Any, Any, None],
snapshot: SnapshotAssertion,
) -> None: ) -> None:
"""Test skip config entry check if defined in yaml.""" """Test skip config entry check if defined in yaml."""
aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200) aioclient_mock.post(ANALYTICS_ENDPOINT_URL, status=200)
@ -803,14 +860,16 @@ async def test_not_check_config_entries_if_yaml(
), ),
), ),
}, },
), patch(
"homeassistant.components.analytics.analytics.HA_VERSION", MOCK_VERSION
), patch( ), patch(
"homeassistant.config.load_yaml_config_file", "homeassistant.config.load_yaml_config_file",
return_value={"default_config": {}}, return_value={"default_config": {}},
): ):
await analytics.send_analytics() await analytics.send_analytics()
payload = _last_call_payload(aioclient_mock) logged_data = caplog.records[-1].args
assert payload["integration_count"] == 1 submitted_data = _last_call_payload(aioclient_mock)
assert payload["integrations"] == ["default_config"]
assert submitted_data["integration_count"] == 1
assert submitted_data["integrations"] == ["default_config"]
assert submitted_data == logged_data
assert snapshot == submitted_data