def test_sysdig_embedded_token(self):
        """Test Sysdig with an embedded token"""
        with requests_mock.mock(real_http=True) as req_mock:
            sde = MetricResource(**sysdig_embedded)
            url = sde.spec.urlTemplate
            response_json = {
                "data": [{
                    "t": 1582756200,
                    "d": [6.481]
                }],
                "start": 1582755600,
                "end": 1582756200
            }
            req_mock.register_uri('POST', url, json = response_json, status_code = 200, \
                request_headers={'Authorization': 'Bearer 87654321-1234-1234-1234-123456789012'})

            expr = ExperimentResource(**er_example)
            version = expr.spec.versionInfo.baseline
            version.variables = [
                NamedValue(name="userfilter", value='usergroup!~"wakanda"'),
                NamedValue(name="revision", value='sample-app-v1')
            ]
            start_time = expr.status.startTime

            # verify body
            body, err = get_body(sde, version, start_time)
            logger.info(body)
            assert err is None
            groups = re.search("'sample-app-v1'", body["filter"])
            assert groups is not None

            # verify jq expression
            value, err = get_metric_value(sde, version, start_time)
            assert err is None
            assert value == 6.481
    def test_new_relic_secret(self, mock_secret):
        """Test New Relic with a secret API Key"""
        with requests_mock.mock(real_http=True) as req_mock:
            nre = MetricResource(**new_relic_secret)
            url = nre.spec.urlTemplate
            file_path = os.path.join(os.path.dirname(__file__),
                                     'data/newrelic_responses',
                                     'newrelic_sample_response.json')
            response_json = json.load(open(file_path))
            req_mock.register_uri('GET', url, json = response_json, \
                status_code = 200, request_headers={'X-Query-Key': 't0p-secret-api-key'})
            mock_secret.return_value = ({"mykey": "t0p-secret-api-key"}, None)

            expr = ExperimentResource(**er_example)
            version = expr.spec.versionInfo.baseline
            version.variables = [
                NamedValue(name="userfilter", value='usergroup!~"wakanda"'),
                NamedValue(name="revision", value='sample-app-v1')
            ]
            start_time = expr.status.startTime

            # verify params
            params = get_params(nre, version, start_time)
            logger.info(params)
            groups = re.search("'sample-app-v1'", params[0]["nrql"])
            assert groups is not None

            # verify jq expression
            value, err = get_metric_value(nre, version, start_time)
            assert err is None
            assert value == 80275388
    def test_basic_auth(self, mock_secret):
        """When authType is Basic, and secret is valid, get basic auth information"""
        expr = ExperimentResource(**er_example)
        metric_resource: MetricResource = expr.status.metrics[0].metricObj
        metric_resource.spec.authType = AuthType.BASIC
        metric_resource.spec.secret = "valid"
        mock_secret.return_value = ({
            "username": "******",
            "password": "******"
        }, None)
        auth, err = get_basic_auth(metric_resource)
        mock_secret.assert_called_with(metric_resource)
        assert auth == HTTPBasicAuth("me", "t0p-secret")
        assert err is None

        with requests_mock.mock(real_http=True) as req_mock:
            file_path = os.path.join(os.path.dirname(__file__),
                                     'data/prom_responses',
                                     'prometheus_sample_response.json')
            response_json = json.load(open(file_path))
            req_mock.get(metric_resource.spec.urlTemplate, json=response_json)

            version = expr.spec.versionInfo.baseline
            start_time = expr.status.startTime
            value, err = get_metric_value(metric_resource, version, start_time)
            assert err is None
            assert value == float(
                response_json["data"]["result"][0]["value"][1])
    def test_prometheus_basic_auth(self, mock_secret):
        """Test prometheus with no authentication"""
        with requests_mock.mock(real_http=True) as req_mock:
            prometheus_basic_auth = request_count
            metric_info = MetricInfo(**prometheus_basic_auth)
            metric_info.metricObj.spec.params[0].value = \
                "sum(increase(revision_app_request_latencies_count{service_name='${name}',${userfilter}}[${elapsedTime}s])) or on() vector(0)"
            metric_info.metricObj.spec.authType = AuthType.BASIC
            metric_info.metricObj.spec.secret = "myns/promcredentials"
            url = metric_info.metricObj.spec.urlTemplate
            json_response = {
                "status": "success",
                "data": {
                    "resultType": "vector",
                    "result": [{
                        "value": [1556823494.744, "21.7639"]
                    }]
                }
            }
            req_mock.register_uri('GET',
                                  url,
                                  json=json_response,
                                  status_code=200)
            mock_secret.return_value = ({
                "username": "******",
                "password": "******"
            }, None)
            auth, err = get_basic_auth(metric_info.metricObj)
            mock_secret.assert_called_with(metric_info.metricObj)
            assert auth == HTTPBasicAuth("produser", "t0p-secret")
            assert err is None

            expr = ExperimentResource(**er_example)
            version = expr.spec.versionInfo.baseline
            version.variables = [
                NamedValue(name="userfilter", value='usergroup!~"wakanda"')
            ]
            start_time = expr.status.startTime

            # verify params
            params = get_params(metric_info.metricObj, version, start_time)
            logger.info(params)
            groups = re.search('(usergroup!~"wakanda")', params[0]["query"])
            assert groups is not None

            # verify jq expression
            value, err = get_metric_value(metric_info.metricObj, version,
                                          start_time)
            assert err is None
            assert value == 21.7639
Beispiel #5
0
    def test_elastic_secret(self, mock_secret):
        """Test Sysdig with a secret token"""
        with requests_mock.mock(real_http=True) as req_mock:
            ela = MetricResource(**elastic_secret)
            url = ela.spec.urlTemplate
            response_json = {
                "aggregations": {
                    "items_to_sell": {
                        "doc_count": 3,
                        "avg_sales": {
                            "value": 128.33333333333334
                        }
                    }
                }
            }
            req_mock.register_uri('POST', url, json = response_json, status_code = 200, \
                request_headers={'Authorization': 'Basic cHJvZHVzZXI6dDBwLXNlY3JldA=='})
            mock_secret.return_value = ({
                "username": "******",
                "password": "******"
            }, None)

            expr = ExperimentResource(**er_example)
            version = expr.spec.versionInfo.baseline
            version.variables = [
                NamedValue(name="userfilter", value='usergroup!~"wakanda"'),
                NamedValue(name="revision", value='sample-app-v1')
            ]
            start_time = expr.status.startTime

            # verify body
            body, err = get_body(ela, version, start_time)
            logger.info(body)
            assert err is None
            groups = re.search(
                "sample-app-v1",
                body["aggs"]["items_to_sell"]["filter"]["term"]["version"])
            assert groups is not None

            # verify jq expression
            value, err = get_metric_value(ela, version, start_time)
            assert err is None
            assert value == 128.33333333333334
    def test_post_metric(self):
        """POST metric query must result in a value"""
        with requests_mock.mock(real_http=True) as req_mock:
            req_mock.register_uri(
                'POST',
                cpu_utilization["metricObj"]["spec"]["urlTemplate"],
                json={
                    "data": [{
                        "t": 1582756200,
                        "d": [6.481]
                    }],
                    "start": 1582755600,
                    "end": 1582756200
                },
                status_code=200)

            expr = ExperimentResource(**er_example)
            metric_info = MetricInfo(**cpu_utilization)
            version = expr.spec.versionInfo.baseline
            start_time = expr.status.startTime
            value, err = get_metric_value(metric_info.metricObj, version,
                                          start_time)
            assert err is None
            assert value == 6.481