def test_parse_links_presents_warning_on_missing_doctype( caplog: pytest.LogCaptureFixture, ) -> None: html = b'<a href="/pkg1-1.0.tar.gz"></a><a href="/pkg1-2.0.tar.gz"></a>' url = "https://example.com/simple/" page = HTMLPage(html, encoding=None, url=url, cache_link_parsing=False) with caplog.at_level(logging.WARN): parsed_links = list(parse_links(page, use_deprecated_html5lib=False)) assert len(parsed_links) == 2, parsed_links assert "pkg1-1.0" in parsed_links[0].url assert "pkg1-2.0" in parsed_links[1].url assert len(caplog.records) == 1
def test_log_warning_if_python_event_callback( self, caplog: pytest.LogCaptureFixture) -> None: d = Document() m1 = EmbedTestUtilModel() c1 = _GoodEventCallback() d.add_root(m1) m1.on_event(Tap, c1) assert len(m1._event_callbacks) != 0 with caplog.at_level(logging.WARN): beu.standalone_docs_json_and_render_items(m1) assert len(caplog.records) == 1 assert caplog.text != ''
async def test_document_on_session_destroyed_exceptions(self, caplog: pytest.LogCaptureFixture) -> None: doc = Document() def blowup(session_context): raise ValueError("boom!") doc.on_session_destroyed(blowup) handler = bahd.DocumentLifecycleHandler() session_context = MockSessionContext(doc) with caplog.at_level(logging.WARN): await handler.on_session_destroyed(session_context) assert len(caplog.records) == 1 assert "boom!" in caplog.text
async def test_repeated_connect( caplog: pytest.LogCaptureFixture, connected_source_mock: DmsDeviceSource, upnp_factory_mock: Mock, ) -> None: """Test trying to connect an already connected device is safely ignored.""" upnp_factory_mock.async_create_device.reset_mock() # Calling internal function directly to skip trying to time 2 SSDP messages carefully with caplog.at_level(logging.DEBUG): await connected_source_mock.device_connect() assert ( "Trying to connect when device already connected" == caplog.records[-1].message ) assert not upnp_factory_mock.async_create_device.await_count
async def test_send_message_raises(caplog: pytest.LogCaptureFixture) -> None: class ExcMessage: def send(self, handler): raise WebSocketClosedError() assert len(caplog.records) == 0 with caplog.at_level(logging.WARN): # fake self not great but much easier than setting up a real view ret = await WSHandler.send_message("self", ExcMessage()) assert len(caplog.records) == 1 assert caplog.text.endswith( "Failed sending message as connection was closed\n") assert ret is None
def test_deploy_stack_wait(self, cfngin_context: MockCFNginContext, caplog: LogCaptureFixture) -> None: """Test for deploy_stack with wait.""" hook = Hook(cfngin_context, MagicMock()) stack = MagicMock() stack.name = "test-stack" with caplog.at_level(logging.DEBUG, logger="runway.cfngin.hooks.base"): assert hook.deploy_stack(stack=stack, wait=True) == COMPLETE assert caplog.records[0].message == "%s:%s" % (stack.name, SUBMITTED.name) assert caplog.records[1].message == "waiting for stack to complete..." assert caplog.records[2].message == "%s:%s" % (stack.name, COMPLETE.name)
def test_send_message_with_bad_data_throws_vol_error( signal_notification_service: SignalNotificationService, signal_requests_mock_factory: Mocker, caplog: pytest.LogCaptureFixture, ) -> None: """Test sending a message with bad data throws an error.""" with caplog.at_level( logging.DEBUG, logger="homeassistant.components.signal_messenger.notify"): with pytest.raises(vol.Invalid) as exc: data = {"test": "test"} signal_notification_service.send_message(MESSAGE, **{"data": data}) assert "Sending signal message" in caplog.text assert "extra keys not allowed" in str(exc.value)
def test_send_message( signal_notification_service: SignalNotificationService, signal_requests_mock_factory: Mocker, caplog: pytest.LogCaptureFixture, ) -> None: """Test send message.""" signal_requests_mock = signal_requests_mock_factory() with caplog.at_level( logging.DEBUG, logger="homeassistant.components.signal_messenger.notify"): signal_notification_service.send_message(MESSAGE) assert "Sending signal message" in caplog.text assert signal_requests_mock.called assert signal_requests_mock.call_count == 2 assert_sending_requests(signal_requests_mock)
def test_reload_dir_is_set(reload_directory_structure: Path, caplog: pytest.LogCaptureFixture) -> None: app_dir = reload_directory_structure / "app" with caplog.at_level(logging.INFO): config = Config(app="tests.test_config:asgi_app", reload=True, reload_dirs=[str(app_dir)]) assert len(caplog.records) == 1 assert ( caplog.records[-1].message == f"Will watch for changes in these directories: {[str(app_dir)]}") assert config.reload_dirs == [app_dir] config = Config(app="tests.test_config:asgi_app", reload=True, reload_dirs=str(app_dir)) assert config.reload_dirs == [app_dir]
def test_parse_links_presents_warning_on_html4_doctype( caplog: pytest.LogCaptureFixture, ) -> None: html = (b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" ' b'"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">' b'<a href="/pkg1-1.0.tar.gz"></a><a href="/pkg1-2.0.tar.gz"></a>') url = "https://example.com/simple/" page = HTMLPage(html, encoding=None, url=url, cache_link_parsing=False) with caplog.at_level(logging.WARN): parsed_links = list(parse_links(page, use_deprecated_html5lib=False)) assert len(parsed_links) == 2, parsed_links assert "pkg1-1.0" in parsed_links[0].url assert "pkg1-2.0" in parsed_links[1].url assert len(caplog.records) == 1
def test_get_attachments_not_on_allowlist( signal_notification_service: SignalNotificationService, caplog: pytest.LogCaptureFixture, hass: HomeAssistant, ) -> None: """Test getting attachments as URL that aren't on the allowlist.""" url = "http://dodgyurl.com" data = {"urls": [url]} with caplog.at_level( logging.ERROR, logger="homeassistant.components.signal_messenger.notify"): result = signal_notification_service.get_attachments_as_bytes( data, len(CONTENT), hass) assert f"URL '{url}' not in allow list" in caplog.text assert result is None
def test_core_logic( installed_version: str, remote_version: str, stored_version: Optional[str], installed_by_pip: bool, should_show_prompt: bool, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch, ) -> None: # GIVEN monkeypatch.setattr(self_outdated_check, "was_installed_by_pip", lambda _: installed_by_pip) mock_state = Mock() mock_state.get.return_value = stored_version fake_time = datetime.datetime(2000, 1, 1, 0, 0, 0) version_that_should_be_checked = stored_version or remote_version # WHEN with caplog.at_level(logging.DEBUG): return_value = self_outdated_check._self_version_check_logic( state=mock_state, current_time=fake_time, local_version=Version(installed_version), get_remote_version=lambda: remote_version, ) # THEN mock_state.get.assert_called_once_with(fake_time) assert caplog.messages == [ f"Remote version of pip: {version_that_should_be_checked}", f"Local version of pip: {installed_version}", f"Was pip installed by pip? {installed_by_pip}", ] if stored_version: mock_state.set.assert_not_called() else: mock_state.set.assert_called_once_with(version_that_should_be_checked, fake_time) if not should_show_prompt: assert return_value is None return # the remaining assertions are for the other case. assert return_value is not None assert return_value.old == installed_version assert return_value.new == remote_version
def test_suppress_warnings(self, caplog: pytest.LogCaptureFixture) -> None: d = Document() m1 = EmbedTestUtilModel() c1 = _GoodPropertyCallback() c2 = _GoodEventCallback() d.add_root(m1) m1.on_change('name', c1) assert len(m1._callbacks) != 0 m1.on_event(Tap, c2) assert len(m1._event_callbacks) != 0 with caplog.at_level(logging.WARN): beu.standalone_docs_json_and_render_items(m1, suppress_callback_warning=True) assert len(caplog.records) == 0 assert caplog.text == ''
def test_send_message_to_api_with_bad_data_throws_error( signal_notification_service: SignalNotificationService, signal_requests_mock_factory: Mocker, caplog: pytest.LogCaptureFixture, ) -> None: """Test sending a message with bad data to the API throws an error.""" signal_requests_mock = signal_requests_mock_factory(False) with caplog.at_level( logging.DEBUG, logger="homeassistant.components.signal_messenger.notify"): with pytest.raises(SignalCliRestApiError) as exc: signal_notification_service.send_message(MESSAGE) assert "Sending signal message" in caplog.text assert signal_requests_mock.called assert signal_requests_mock.call_count == 2 assert "Couldn't send signal message" in str(exc.value)
async def test_repeated_connect( caplog: pytest.LogCaptureFixture, hass: HomeAssistant, upnp_factory_mock: Mock, connected_source_mock: None, ) -> None: """Test trying to connect an already connected device is safely ignored.""" upnp_factory_mock.async_create_device.reset_mock() # Calling internal function directly to skip trying to time 2 SSDP messages carefully domain_data = get_domain_data(hass) device_source = domain_data.sources[MOCK_SOURCE_ID] with caplog.at_level(logging.DEBUG): await device_source.device_connect() assert not upnp_factory_mock.async_create_device.await_count await assert_source_available(hass)
def test_get_html_page_invalid_scheme(caplog: pytest.LogCaptureFixture, url: str, vcs_scheme: str) -> None: """`_get_html_page()` should error if an invalid scheme is given. Only file:, http:, https:, and ftp: are allowed. """ with caplog.at_level(logging.WARNING): page = _get_html_page(Link(url), session=mock.Mock(PipSession)) assert page is None assert caplog.record_tuples == [ ( "pip._internal.index.collector", logging.WARNING, "Cannot look at {} URL {} because it does not support " "lookup as web pages.".format(vcs_scheme, url), ), ]
def test_send_message_with_attachment_as_url( signal_notification_service: SignalNotificationService, signal_requests_mock_factory: Mocker, caplog: pytest.LogCaptureFixture, ) -> None: """Test send message with attachment as URL.""" signal_requests_mock = signal_requests_mock_factory( True, str(len(CONTENT))) with caplog.at_level( logging.DEBUG, logger="homeassistant.components.signal_messenger.notify"): data = {"urls": [URL_ATTACHMENT]} signal_notification_service.send_message(MESSAGE, **{"data": data}) assert "Sending signal message" in caplog.text assert signal_requests_mock.called assert signal_requests_mock.call_count == 3 assert_sending_requests(signal_requests_mock, 1)
def test_dist_get_direct_url_invalid_json( mock_read_text: mock.Mock, caplog: pytest.LogCaptureFixture ) -> None: class FakeDistribution(BaseDistribution): canonical_name = cast(NormalizedName, "whatever") # Needed for error logging. dist = FakeDistribution() with caplog.at_level(logging.WARNING): assert dist.direct_url is None mock_read_text.assert_called_once_with(DIRECT_URL_METADATA_NAME) assert ( caplog.records[-1] .getMessage() .startswith( "Error parsing direct_url.json for whatever:", ) )
def test_rehold(self, first, second, caplog: pytest.LogCaptureFixture) -> None: d = document.Document() with caplog.at_level(logging.WARN): d.hold(first) assert caplog.text == "" assert len(caplog.records) == 0 d.hold(first) assert caplog.text == "" assert len(caplog.records) == 0 d.hold(second) assert caplog.text.strip().endswith("hold already active with '%s', ignoring '%s'" % (first, second)) assert len(caplog.records) == 1 d.unhold() d.hold(second) assert len(caplog.records) == 1
def test_hold_rehold(self, first: HoldPolicyType, second: HoldPolicyType, caplog: pytest.LogCaptureFixture) -> None: d = Document() cm = bdc.DocumentCallbackManager(d) with caplog.at_level(logging.WARN): cm.hold(first) assert caplog.text == "" assert len(caplog.records) == 0 cm.hold(first) assert caplog.text == "" assert len(caplog.records) == 0 cm.hold(second) assert caplog.text.strip().endswith(f"hold already active with {first!r}, ignoring {second!r}") assert len(caplog.records) == 1 cm.unhold() cm.hold(second) assert len(caplog.records) == 1
async def test_sensors( hass: HomeAssistant, config_entry: ConfigEntry, owproxy: MagicMock, device_id: str, caplog: pytest.LogCaptureFixture, ): """Test for 1-Wire device. As they would be on a clean setup: all binary-sensors and switches disabled. """ device_registry = mock_device_registry(hass) entity_registry = mock_registry(hass) mock_device = MOCK_OWPROXY_DEVICES[device_id] expected_entities = mock_device.get(Platform.SENSOR, []) if "branches" in mock_device: for branch_details in mock_device["branches"].values(): for sub_device in branch_details.values(): expected_entities += sub_device[Platform.SENSOR] expected_devices = ensure_list(mock_device.get(ATTR_DEVICE_INFO)) setup_owproxy_mock_devices(owproxy, Platform.SENSOR, [device_id]) with caplog.at_level(logging.WARNING, logger="homeassistant.components.onewire"): await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() if mock_device.get(ATTR_UNKNOWN_DEVICE): assert "Ignoring unknown device family/type" in caplog.text else: assert "Ignoring unknown device family/type" not in caplog.text check_device_registry(device_registry, expected_devices) assert len(entity_registry.entities) == len(expected_entities) check_and_enable_disabled_entities(entity_registry, expected_entities) setup_owproxy_mock_devices(owproxy, Platform.SENSOR, [device_id]) await hass.config_entries.async_reload(config_entry.entry_id) await hass.async_block_till_done() check_entities(hass, entity_registry, expected_entities)
def test_send_message_with_attachment( signal_notification_service: SignalNotificationService, signal_requests_mock_factory: Mocker, caplog: pytest.LogCaptureFixture, ) -> None: """Test send message with attachment.""" signal_requests_mock = signal_requests_mock_factory() with caplog.at_level( logging.DEBUG, logger="homeassistant.components.signal_messenger.notify"): with tempfile.NamedTemporaryFile( mode="w", suffix=".png", prefix=os.path.basename(__file__)) as temp_file: temp_file.write("attachment_data") data = {"attachments": [temp_file.name]} signal_notification_service.send_message(MESSAGE, **{"data": data}) assert "Sending signal message" in caplog.text assert signal_requests_mock.called assert signal_requests_mock.call_count == 2 assert_sending_requests(signal_requests_mock, 1)
def test_set_values( self, slider_kwargs: SliderKwargs, caplog: pytest.LogCaptureFixture ) -> None: sliders = deepcopy(slider_kwargs) assert sliders["n"].value == 2 assert sliders["alpha"].value == 0.3 assert sliders["Dummy"].value == 1.5 # Using identifiers as kwargs with caplog.at_level(logging.WARNING): sliders.set_values(non_existent=0) sliders.set_values(n=1, Dummy=2) assert sliders["n"].value == 1 assert sliders["Dummy"].value == 2 # Using a symbol mapping n, alpha, theta = sp.symbols(R"n, alpha, \theta_12") sliders.set_values({n: 5, alpha: 2.1, theta: 1.57}) assert sliders["n"].value == 5 assert sliders["alpha"].value == 2.1 assert sliders["Dummy"].value == 1.57
def test_env_file( web_concurrency: int, forwarded_allow_ips: str, caplog: pytest.LogCaptureFixture, tmp_path: Path, ) -> None: """ Test that one can load environment variables using an env file. """ fp = tmp_path / ".env" content = (f"WEB_CONCURRENCY={web_concurrency}\n" f"FORWARDED_ALLOW_IPS={forwarded_allow_ips}\n") fp.write_text(content) with caplog.at_level(logging.INFO): config = Config(app=asgi_app, env_file=fp) config.load() assert config.workers == int(str(os.getenv("WEB_CONCURRENCY"))) assert config.forwarded_allow_ips == os.getenv("FORWARDED_ALLOW_IPS") assert len(caplog.records) == 1 assert f"Loading environment from '{fp}'" in caplog.records[0].message
def test_reload_includes_exclude_dir_patterns_are_matched( reload_directory_structure: Path, caplog: pytest.LogCaptureFixture) -> None: with caplog.at_level(logging.INFO): first_app_dir = reload_directory_structure / "app_first" / "src" second_app_dir = reload_directory_structure / "app_second" / "src" with as_cwd(reload_directory_structure): config = Config( app="tests.test_config:asgi_app", reload=True, reload_includes=["*/src"], reload_excludes=["app", "*third*"], ) assert len(caplog.records) == 1 assert (caplog.records[-1].message == "Will watch for changes in these directories: " f"{sorted([str(first_app_dir), str(second_app_dir)])}") assert frozenset(config.reload_dirs) == frozenset( [first_app_dir, second_app_dir]) assert config.reload_includes == ["*/src"]
def test_app_factory(caplog: pytest.LogCaptureFixture) -> None: def create_app() -> ASGIApplication: return asgi_app config = Config(app=create_app, factory=True, proxy_headers=False) config.load() assert config.loaded_app is asgi_app # Flag not passed. In this case, successfully load the app, but issue a warning # to indicate that an explicit flag is preferred. caplog.clear() config = Config(app=create_app, proxy_headers=False) with caplog.at_level(logging.WARNING): config.load() assert config.loaded_app is asgi_app assert len(caplog.records) == 1 assert "--factory" in caplog.records[0].message # App not a no-arguments callable. config = Config(app=asgi_app, factory=True) with pytest.raises(SystemExit): config.load()
def test_virtualenv_no_global_with_pep_405_virtual_environment( monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, pyvenv_cfg_lines: Optional[List[str]], under_venv: bool, expected: bool, expect_warning: bool, ) -> None: monkeypatch.setattr(virtualenv, "_running_under_regular_virtualenv", lambda: False) monkeypatch.setattr(virtualenv, "_get_pyvenv_cfg_lines", lambda: pyvenv_cfg_lines) monkeypatch.setattr(virtualenv, "_running_under_venv", lambda: under_venv) with caplog.at_level(logging.WARNING): assert virtualenv.virtualenv_no_global() == expected if expect_warning: assert caplog.records # Check for basic information message = caplog.records[-1].getMessage().lower() assert "could not access 'pyvenv.cfg'" in message assert "assuming global site-packages is not accessible" in message
def test_add_trusted_host__logging( self, caplog: pytest.LogCaptureFixture) -> None: """ Test logging when add_trusted_host() is called. """ trusted_hosts = ["host0", "host1"] session = PipSession(trusted_hosts=trusted_hosts) with caplog.at_level(logging.INFO): # Test adding an existing host. session.add_trusted_host("host1", source="somewhere") session.add_trusted_host("host2") # Test calling add_trusted_host() on the same host twice. session.add_trusted_host("host2") actual = [(r.levelname, r.message) for r in caplog.records] # Observe that "host0" isn't included in the logs. expected = [ ("INFO", "adding trusted host: 'host1' (from somewhere)"), ("INFO", "adding trusted host: 'host2'"), ("INFO", "adding trusted host: 'host2'"), ] assert actual == expected
def test_exception_handler_response_was_sent( app: Sanic, caplog: LogCaptureFixture, message_in_records: Callable[[List[logging.LogRecord], str], bool], ): exception_handler_ran = False @app.exception(ServerError) async def exception_handler(request, exception): nonlocal exception_handler_ran exception_handler_ran = True return text("Error") @app.route("/1") async def handler1(request: Request): response = await request.respond() await response.send("some text") raise ServerError("Exception") @app.route("/2") async def handler2(request: Request): response = await request.respond() raise ServerError("Exception") with caplog.at_level(logging.WARNING): _, response = app.test_client.get("/1") assert "some text" in response.text # Change to assert warning not in the records in the future version. message_in_records( caplog.records, ("An error occurred while handling the request after at " "least some part of the response was sent to the client. " "Therefore, the response from your custom exception "), ) _, response = app.test_client.get("/2") assert "Error" in response.text
async def test_binary_sensors( hass: HomeAssistant, config_entry: ConfigEntry, owproxy: MagicMock, device_id: str, caplog: pytest.LogCaptureFixture, ): """Test for 1-Wire binary sensor. This test forces all entities to be enabled. """ device_registry = mock_device_registry(hass) entity_registry = mock_registry(hass) mock_device = MOCK_OWPROXY_DEVICES[device_id] expected_entities = mock_device.get(Platform.BINARY_SENSOR, []) expected_devices = ensure_list(mock_device.get(ATTR_DEVICE_INFO)) setup_owproxy_mock_devices(owproxy, Platform.BINARY_SENSOR, [device_id]) with caplog.at_level(logging.WARNING, logger="homeassistant.components.onewire"): await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() if mock_device.get(ATTR_UNKNOWN_DEVICE): assert "Ignoring unknown device family/type" in caplog.text else: assert "Ignoring unknown device family/type" not in caplog.text check_device_registry(device_registry, expected_devices) assert len(entity_registry.entities) == len(expected_entities) check_and_enable_disabled_entities(entity_registry, expected_entities) setup_owproxy_mock_devices(owproxy, Platform.BINARY_SENSOR, [device_id]) await hass.config_entries.async_reload(config_entry.entry_id) await hass.async_block_till_done() check_entities(hass, entity_registry, expected_entities)