def test_read_metadata_handles_unexpected_content_or_http_status( self, session_get, url_responses, expected, logs, caplog ): """read_metadata handles valid and invalid content and status codes.""" def fake_get(url): """Mock Response json, ok, status_code, text from url_responses.""" m_resp = mock.MagicMock() content = url_responses.get(url, '') m_resp.json.side_effect = lambda: json.loads(content) if content: mock_ok = mock.PropertyMock(return_value=True) mock_status_code = mock.PropertyMock(return_value=200) else: mock_ok = mock.PropertyMock(return_value=False) mock_status_code = mock.PropertyMock(return_value=404) type(m_resp).ok = mock_ok type(m_resp).status_code = mock_status_code mock_text = mock.PropertyMock(return_value=content) type(m_resp).text = mock_text return m_resp session_get.side_effect = fake_get if isinstance(expected, Exception): with pytest.raises(type(expected), match=re.escape(str(expected))): lxd.read_metadata() else: assert expected == lxd.read_metadata() caplogs = caplog.text for log in logs: assert log in caplogs
def test_net_v2_based_on_network_mode_virt_type_and_uname_machine( self, m_which, m_subp, m_system_info, uname_machine, systemd_detect_virt, expected, ): """Return network config v2 based on uname -m, systemd-detect-virt.""" if systemd_detect_virt is None: m_which.return_value = None m_system_info.return_value = {"uname": ["", "", "", "", uname_machine]} m_subp.return_value = (systemd_detect_virt, "") assert expected == lxd.generate_fallback_network_config() if systemd_detect_virt is None: assert 0 == m_subp.call_count assert 0 == m_system_info.call_count else: assert [ mock.call(["systemd-detect-virt"]) ] == m_subp.call_args_list if systemd_detect_virt != "kvm\n": assert 0 == m_system_info.call_count else: assert 1 == m_system_info.call_count
def test_expected_viable(self, m_exists, m_lstat, exists, lstat_mode, expected): """Return True only when LXD_SOCKET_PATH exists and is a socket.""" m_exists.return_value = exists m_lstat.return_value = LStatResponse(lstat_mode) assert expected is lxd.is_platform_viable() m_exists.assert_has_calls([mock.call(lxd.LXD_SOCKET_PATH)]) if exists: m_lstat.assert_has_calls([mock.call(lxd.LXD_SOCKET_PATH)]) else: assert 0 == m_lstat.call_count
def lxd_ds(request, paths, lxd_metadata): """ Return an instantiated DataSourceLXD. This also performs the mocking required for the default test case: * ``is_platform_viable`` returns True, * ``read_metadata`` returns ``LXD_V1_METADATA`` (This uses the paths fixture for the required helpers.Paths object) """ with mock.patch(DS_PATH + "is_platform_viable", return_value=True): with mock.patch(DS_PATH + "read_metadata", return_value=lxd_metadata): yield lxd.DataSourceLXD( sys_cfg={}, distro=mock.Mock(), paths=paths )