Exemplo n.º 1
0
def test_filter_by_labels_notin(api):
    Query(api, Pod).filter(selector={
        'application__notin': ['foo', 'bar']
    }).execute()
    api.get.assert_called_once_with(
        url='pods?labelSelector=application+notin+%28bar%2Cfoo%29',
        version='v1')
Exemplo n.º 2
0
def test_filter_by_labels_notin(api):
    Query(api, Pod).filter(selector={
        "application__notin": ["foo", "bar"]
    }).execute()
    api.get.assert_called_once_with(
        url="pods?labelSelector=application+notin+%28bar%2Cfoo%29",
        version="v1")
Exemplo n.º 3
0
def test_filter_by_labels_eq(api):
    Query(api, Pod).filter(selector={
        'application': 'myapp',
        'component': 'backend'
    }).execute()
    api.get.assert_called_once_with(
        url='pods?labelSelector=application%3Dmyapp%2Ccomponent%3Dbackend',
        version='v1')
Exemplo n.º 4
0
def test_filter_by_labels_eq(api):
    Query(api, Pod).filter(selector={
        "application": "myapp",
        "component": "backend"
    }).execute()
    api.get.assert_called_once_with(
        url="pods?labelSelector=application%3Dmyapp%2Ccomponent%3Dbackend",
        version="v1")
Exemplo n.º 5
0
def test_add_event_update_existing(monkeypatch, resource, event):
    query = Query(resource.api, event, resource.namespace)
    monkeypatch.setattr("pykube.query.Query.get_or_none",
                        MagicMock(return_value=event))
    monkeypatch.setattr("pykube.objects.Event.objects",
                        MagicMock(return_value=query))
    e = helper.add_event(resource, "test message", "reason", "Normal", False)
    assert e.obj["count"] == 2
    event.update.assert_called_once()
Exemplo n.º 6
0
def test_as_table(api):
    response = MagicMock()
    response.json.return_value = {'kind': 'Table', 'columnDefinitions': [], 'rows': []}
    api.get.return_value = response

    table = Query(api, Pod).filter(selector={'app': 'foo'}).as_table()
    assert table.columns == []
    assert table.rows == []
    assert repr(table).startswith('<Table of Pod at')

    api.get.assert_called_once_with(url='pods?labelSelector=app%3Dfoo', version='v1', headers={'Accept': 'application/json;as=Table;v=v1beta1;g=meta.k8s.io'})
Exemplo n.º 7
0
    def _get_api_pod(self):
        """Get the pod resource from the API.

        :return: Dictionary representation of Pod from k8s API.
        """
        # If kubeconfig was specified, use the pykube library.
        if self.kubeconfig_path:
            _log.info("Using kubeconfig at %s", self.kubeconfig_path)
            try:
                api = HTTPClient(KubeConfig.from_file(self.kubeconfig_path))
                pod = Query(api, Pod,
                            self.namespace).get_by_name(self.pod_name)
                _log.debug("Found pod: %s: ", pod.obj)
            except Exception as e:
                raise PolicyException("Error querying Kubernetes API",
                                      details=str(e.message))
            else:
                return pod.obj

        # Otherwise, use direct HTTP query to get pod.
        with requests.Session() as session:
            if self.auth_token:
                _log.debug('Updating header with Token %s', self.auth_token)
                session.headers.update(
                    {'Authorization': 'Bearer ' + self.auth_token})

            # Generate the API endpoint to query.
            path = "namespaces/%s/pods/%s" % (self.namespace, self.pod_name)
            path = os.path.join(self.api_root, path)

            # Perform the API query and handle the result.
            try:
                _log.debug('Querying Kubernetes API for Pod: %s', path)

                if self.client_certificate and self.client_key:
                    _log.debug(
                        "Using client certificate for Query API. "
                        "cert: %s, key: %s", self.client_certificate,
                        self.client_key)
                    cert = (self.client_certificate, self.client_key)
                    response = session.get(path,
                                           cert=cert,
                                           verify=self.certificate_authority)
                else:
                    _log.debug('Using direct connection for query API')
                    response = session.get(path,
                                           verify=self.certificate_authority)
            except BaseException, e:
                _log.exception("Exception hitting Kubernetes API")
                raise ApplyProfileError("Error querying Kubernetes API",
                                        details=str(e.message))
            else:
Exemplo n.º 8
0
def test_watch_params_are_passed_through(api):
    line1 = json.dumps({"type": "ADDED", "object": {}}).encode("utf-8")
    expected_response = MagicMock()
    expected_response.iter_lines.return_value = [line1]
    api.get.return_value = expected_response

    params = dict(timeoutSeconds=123, arbitraryParam=456)
    stream = Query(api, Pod).watch(params=params)
    next(iter(stream))

    assert api.get.call_count == 1
    assert "timeoutSeconds=123" in api.get.call_args_list[0][1]["url"]
    assert "arbitraryParam=456" in api.get.call_args_list[0][1]["url"]
Exemplo n.º 9
0
def test_watch_params_are_passed_through(api):
    line1 = json.dumps({'type': 'ADDED', 'object': {}}).encode('utf-8')
    expected_response = MagicMock()
    expected_response.iter_lines.return_value = [line1]
    api.get.return_value = expected_response

    params = dict(timeoutSeconds=123, arbitraryParam=456)
    stream = Query(api, Pod).watch(params=params)
    next(iter(stream))

    assert api.get.call_count == 1
    assert 'timeoutSeconds=123' in api.get.call_args_list[0][1]['url']
    assert 'arbitraryParam=456' in api.get.call_args_list[0][1]['url']
Exemplo n.º 10
0
def test_watch_response_is_set_on_iter(api):
    line1 = json.dumps({"type": "ADDED", "object": {}}).encode("utf-8")
    expected_response = MagicMock()
    expected_response.iter_lines.return_value = [line1]
    api.get.return_value = expected_response

    stream = Query(api, Pod).watch()
    next(iter(stream))

    assert stream.response is expected_response

    assert api.get.call_count == 1
    assert api.get.call_args_list[0][1]["stream"] is True
    assert "watch=true" in api.get.call_args_list[0][1]["url"]
Exemplo n.º 11
0
def test_watch_response_is_set_on_iter(api):
    line1 = json.dumps({'type': 'ADDED', 'object': {}}).encode('utf-8')
    expected_response = MagicMock()
    expected_response.iter_lines.return_value = [line1]
    api.get.return_value = expected_response

    stream = Query(api, Pod).watch()
    next(iter(stream))

    assert stream.response is expected_response

    assert api.get.call_count == 1
    assert api.get.call_args_list[0][1]['stream'] is True
    assert 'watch=true' in api.get.call_args_list[0][1]['url']
Exemplo n.º 12
0
def test_get_more_than_one_object(api):
    response = MagicMock()
    response.json.return_value = {
        'items': [{
            'metadata': {
                'name': 'pod1'
            }
        }, {
            'metadata': {
                'name': 'pod2'
            }
        }]
    }
    api.get.return_value = response
    with pytest.raises(ValueError):
        Query(api, Pod).get(namespace='myns')
Exemplo n.º 13
0
def test_get_more_than_one_object(api):
    response = MagicMock()
    response.json.return_value = {
        "items": [{
            "metadata": {
                "name": "pod1"
            }
        }, {
            "metadata": {
                "name": "pod2"
            }
        }]
    }
    api.get.return_value = response
    with pytest.raises(ValueError):
        Query(api, Pod).get(namespace="myns")
Exemplo n.º 14
0
def test_as_table(api):
    response = MagicMock()
    response.json.return_value = {
        "kind": "Table",
        "columnDefinitions": [],
        "rows": []
    }
    api.get.return_value = response

    table = Query(api, Pod).filter(selector={"app": "foo"}).as_table()
    assert table.columns == []
    assert table.rows == []
    assert repr(table).startswith("<Table of Pod at")

    api.get.assert_called_once_with(
        url="pods?labelSelector=app%3Dfoo",
        version="v1",
        headers={
            "Accept": "application/json;as=Table;v=v1beta1;g=meta.k8s.io"
        },
    )
Exemplo n.º 15
0
def _get_list(query: Query):
    return list(query.iterator())
Exemplo n.º 16
0
def test_get_one_object(api):
    response = MagicMock()
    response.json.return_value = {"items": [{"metadata": {"name": "pod1"}}]}
    api.get.return_value = response
    pod = Query(api, Pod).get(namespace="myns")
    assert pod.name == "pod1"
Exemplo n.º 17
0
def test_filter_selector_string(api):
    Query(api, Pod).filter(selector='application=foo').execute()
    api.get.assert_called_once_with(url='pods?labelSelector=application%3Dfoo', version='v1')
Exemplo n.º 18
0
def test_filter_invalid_selector(api):
    with pytest.raises(ValueError):
        Query(api, Pod).filter(selector={'application__x': 'foo'}).execute()
Exemplo n.º 19
0
def test_filter_by_labels_neq(api):
    Query(api, Pod).filter(selector={'application__neq': 'myapp'}).execute()
    api.get.assert_called_once_with(url='pods?labelSelector=application+%21%3D+myapp', version='v1')
Exemplo n.º 20
0
def test_filter_by_labels_neq(api):
    Query(api, Pod).filter(selector={"application__neq": "myapp"}).execute()
    api.get.assert_called_once_with(
        url="pods?labelSelector=application+%21%3D+myapp", version="v1")
Exemplo n.º 21
0
def test_repr(api):
    query = Query(api, Pod)
    assert repr(query).startswith('<Query of Pod at ')
Exemplo n.º 22
0
def test_get(api):
    with pytest.raises(ObjectDoesNotExist):
        Query(api, Pod).get(namespace='myns')
Exemplo n.º 23
0
def wrap_query(query: Query, request, session):
    """Wrap a pykube Query object to inject the OAuth2 session token (if configured)"""
    if request.app[CONFIG].cluster_auth_use_session_token:
        query.api = HTTPClientWithAccessToken(query.api,
                                              session["access_token"])
    return query
Exemplo n.º 24
0
def test_watch_response_exists(api):
    stream = Query(api, Pod).watch()
    assert hasattr(stream, "response")
    assert stream.response is None  # not yet executed
Exemplo n.º 25
0
def test_watch_response_is_readonly(api):
    stream = Query(api, Pod).watch()
    with pytest.raises(AttributeError):
        stream.response = object()
Exemplo n.º 26
0
def test_get_one_object(api):
    response = MagicMock()
    response.json.return_value = {'items': [{'metadata': {'name': 'pod1'}}]}
    api.get.return_value = response
    pod = Query(api, Pod).get(namespace='myns')
    assert pod.name == 'pod1'
Exemplo n.º 27
0
def test_filter_by_namespace(api):
    Query(api, Pod).filter(namespace='myns').execute()
    api.get.assert_called_once_with(namespace='myns', url='pods', version='v1')
Exemplo n.º 28
0
def test_filter_by_namespace(api):
    Query(api, Pod).filter(namespace="myns").execute()
    api.get.assert_called_once_with(namespace="myns", url="pods", version="v1")