import requests import pytest from utils.check_mk_client import CheckMKClient class DummyResponse: def __init__(self, json_data=None, text='', status_code=200): self._json = json_data self.text = text self.status_code = status_code def json(self): if self._json is None: raise ValueError('Invalid JSON') return self._json def raise_for_status(self): if self.status_code >= 400: raise requests.HTTPError(f'Status {self.status_code}') class DummySession: def __init__(self, mapping=None): self.headers = {} self.auth = None self._mapping = mapping or {} self.last_get = None self.last_post = None def get(self, url, params=None, verify=True, timeout=None): self.last_get = dict(url=url, params=params, verify=verify, timeout=timeout) # choose response based on path substring for k, v in self._mapping.items(): if k in url: # v expected to be (json_data, text) json_data, text, status = v return DummyResponse(json_data, text or '', status or 200) return DummyResponse({'result': []}, '', 200) def post(self, url, headers=None, json=None, verify=True, timeout=None): self.last_post = dict(url=url, headers=headers, json=json, verify=verify, timeout=timeout) for k, v in self._mapping.items(): if k in url: json_data, text, status = v return DummyResponse(json_data, text or '', status or 200) return DummyResponse({'result': []}, '', 200) def test_basic_auth_and_verify_and_ca_bundle(monkeypatch): mapping = { '/api/1.0/objects/host/host2': ({'result': {'host_name': 'host2', 'name': 'host2'}}, '', 200), } def fake_session_ctor(): return DummySession(mapping) monkeypatch.setattr('requests.Session', fake_session_ctor) client = CheckMKClient('https://checkmk.local', user='u', password='p', verify=True) # basic auth should be set on session assert client.session.auth == ('u', 'p') # default verify True should be passed through _ = client.get_host_status('host2') assert client.session.last_get['verify'] is True # now supply ca_bundle path and ensure it is used as verify value client2 = CheckMKClient('https://checkmk.local', user='u', password='p', verify=True, api_token=None, ca_bundle='path/to/ca.pem') # monkeypatch the session instance used by client2 client2.session = DummySession(mapping) _ = client2.get_host_status('host2') assert client2.session.last_get['verify'] == 'path/to/ca.pem' def test_get_returns_raw_when_invalid_json(monkeypatch): mapping = { '/api/1.0/objects/host/any': (None, 'non-json response', 200), } def fake_session_ctor(): return DummySession(mapping) monkeypatch.setattr('requests.Session', fake_session_ctor) client = CheckMKClient('https://checkmk.local', api_token='t') result = client.get_host_status('any') # since JSON is invalid the method should return {} (no matching hosts) assert result == {}