From ab9c27e8b2505d54aa0b47ddb5976560d317fbce Mon Sep 17 00:00:00 2001 From: lukemassa Date: Fri, 6 Sep 2019 14:45:38 -0400 Subject: [PATCH] Add flag to http client to allow for the client to be dryrun (#43) --- pykube/http.py | 8 +++++++- tests/test_http.py | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/pykube/http.py b/pykube/http.py index 92fd9e0..31a3590 100644 --- a/pykube/http.py +++ b/pykube/http.py @@ -160,7 +160,7 @@ class HTTPClient: Client for interfacing with the Kubernetes API. """ - def __init__(self, config: KubeConfig, timeout: float = DEFAULT_HTTP_TIMEOUT): + def __init__(self, config: KubeConfig, timeout: float = DEFAULT_HTTP_TIMEOUT, dry_run: bool = False): """ Creates a new instance of the HTTPClient. @@ -170,6 +170,7 @@ def __init__(self, config: KubeConfig, timeout: float = DEFAULT_HTTP_TIMEOUT): self.config = config self.timeout = timeout self.url = self.config.cluster["server"] + self.dry_run = dry_run session = requests.Session() session.headers['User-Agent'] = f'pykube-ng/{__version__}' @@ -242,6 +243,11 @@ def get_kwargs(self, **kwargs) -> dict: if 'timeout' not in kwargs: # apply default HTTP timeout kwargs['timeout'] = self.timeout + if self.dry_run: + # Add http query param for dryRun + params = kwargs.get('params', {}) + params['dryRun'] = 'All' + kwargs['params'] = params return kwargs def raise_for_status(self, resp): diff --git a/tests/test_http.py b/tests/test_http.py index 88279f3..f2672ca 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -34,6 +34,22 @@ def test_http(monkeypatch): assert mock_send.call_args[1]['timeout'] == DEFAULT_HTTP_TIMEOUT +def test_http_with_dry_run(monkeypatch): + cfg = KubeConfig.from_file(GOOD_CONFIG_FILE_PATH) + api = HTTPClient(cfg, dry_run=True) + + mock_send = MagicMock() + mock_send.side_effect = Exception('MOCK HTTP') + monkeypatch.setattr('pykube.http.KubernetesHTTPAdapter._do_send', mock_send) + + with pytest.raises(Exception): + api.get(url='test') + + mock_send.assert_called_once() + # check that dry run http parameters were set + assert mock_send.call_args[0][0].url == "http://localhost/api/v1/test?dryRun=All" + + def test_http_insecure_skip_tls_verify(monkeypatch): cfg = KubeConfig.from_file(CONFIG_WITH_INSECURE_SKIP_TLS_VERIFY) api = HTTPClient(cfg)