|
1 | 1 | """Test REST data module logging improvements.""" |
2 | 2 |
|
| 3 | +from datetime import timedelta |
3 | 4 | import logging |
| 5 | +from unittest.mock import patch |
4 | 6 |
|
| 7 | +from freezegun.api import FrozenDateTimeFactory |
5 | 8 | import pytest |
6 | 9 |
|
7 | 10 | from homeassistant.components.rest import DOMAIN |
8 | 11 | from homeassistant.core import HomeAssistant |
9 | 12 | from homeassistant.setup import async_setup_component |
10 | 13 |
|
| 14 | +from tests.common import async_fire_time_changed |
11 | 15 | from tests.test_util.aiohttp import AiohttpClientMocker |
12 | 16 |
|
13 | 17 |
|
@@ -89,6 +93,59 @@ async def test_rest_data_no_warning_on_200_with_wrong_content_type( |
89 | 93 | ) |
90 | 94 |
|
91 | 95 |
|
| 96 | +async def test_rest_data_with_incorrect_charset_in_header( |
| 97 | + hass: HomeAssistant, |
| 98 | + aioclient_mock: AiohttpClientMocker, |
| 99 | + caplog: pytest.LogCaptureFixture, |
| 100 | + freezer: FrozenDateTimeFactory, |
| 101 | +) -> None: |
| 102 | + """Test that we can handle sites which provides an incorrect charset.""" |
| 103 | + aioclient_mock.get( |
| 104 | + "http://example.com/api", |
| 105 | + status=200, |
| 106 | + text="<p>Some html</p>", |
| 107 | + headers={"Content-Type": "text/html; charset=utf-8"}, |
| 108 | + ) |
| 109 | + |
| 110 | + assert await async_setup_component( |
| 111 | + hass, |
| 112 | + DOMAIN, |
| 113 | + { |
| 114 | + DOMAIN: { |
| 115 | + "resource": "http://example.com/api", |
| 116 | + "method": "GET", |
| 117 | + "encoding": "windows-1250", |
| 118 | + "sensor": [ |
| 119 | + { |
| 120 | + "name": "test_sensor", |
| 121 | + "value_template": "{{ value }}", |
| 122 | + } |
| 123 | + ], |
| 124 | + } |
| 125 | + }, |
| 126 | + ) |
| 127 | + await hass.async_block_till_done() |
| 128 | + |
| 129 | + with patch( |
| 130 | + "tests.test_util.aiohttp.AiohttpClientMockResponse.text", |
| 131 | + side_effect=UnicodeDecodeError("utf-8", b"", 1, 0, ""), |
| 132 | + ): |
| 133 | + freezer.tick(timedelta(minutes=1)) |
| 134 | + async_fire_time_changed(hass) |
| 135 | + await hass.async_block_till_done() |
| 136 | + |
| 137 | + log_text = "Response charset came back as utf-8 but could not be decoded, continue with configured encoding windows-1250." |
| 138 | + assert log_text in caplog.text |
| 139 | + |
| 140 | + caplog.clear() |
| 141 | + freezer.tick(timedelta(minutes=1)) |
| 142 | + async_fire_time_changed(hass) |
| 143 | + await hass.async_block_till_done() |
| 144 | + |
| 145 | + # Only log once as we only try once with automatic decoding |
| 146 | + assert log_text not in caplog.text |
| 147 | + |
| 148 | + |
92 | 149 | async def test_rest_data_no_warning_on_success_json( |
93 | 150 | hass: HomeAssistant, |
94 | 151 | aioclient_mock: AiohttpClientMocker, |
|
0 commit comments