Beispiel #1
0
    def test_web_policies_latest(self):
        """test POST /policies_latest with policyName"""
        match_to_policy_name = MockPolicyEngine2018.scope_prefix + "amet.*"
        expected_policies = MockPolicyEngine2018.gen_policies_latest(
            match_to_policy_name)

        body = json.dumps({POLICY_NAME: match_to_policy_name})
        request_id = str(uuid.uuid4())
        result = self.getPage("/policies_latest",
                              method='POST',
                              body=body,
                              headers=[(REQUEST_X_ECOMP_REQUESTID, request_id),
                                       (REQUEST_X_ONAP_REQUESTID, request_id),
                                       ("Content-Type", "application/json"),
                                       ('Content-Length', str(len(body)))])
        _LOGGER.info("result: %s", result)
        _LOGGER.info("body: %s", self.body)

        self.assertStatus('200 OK')

        policies_latest = json.loads(self.body)[LATEST_POLICIES]

        _LOGGER.info("policies_latest: %s", json.dumps(policies_latest))
        _LOGGER.info("expected_policies: %s", json.dumps(expected_policies))
        assert Utils.are_the_same(policies_latest, expected_policies)

        result = self.getPage("/healthcheck")
        _LOGGER.info("healthcheck result: %s", result)

        Tracker.validate()
Beispiel #2
0
def run_policy_handler():
    """main run function for policy-handler"""
    Config.init_config()

    from policyhandler import LogWriter
    from policyhandler.policy_receiver import PolicyReceiver
    from policyhandler.service_activator import ServiceActivator
    from policyhandler.web_server import PolicyWeb

    logger = Utils.get_logger(__file__)
    sys.stdout = LogWriter(logger.info)
    sys.stderr = LogWriter(logger.error)

    logger.info("========== run_policy_handler ========== %s", __package__)
    Audit.init(Config.system_name, Config.LOGGER_CONFIG_FILE_PATH)

    audit = Audit(req_message="start policy handler")

    Config.discover(audit)
    ServiceActivator.determine_mode_of_operation(audit)
    logger.info(
        audit.info("starting policy_handler with config: {}".format(
            Config.discovered_config)))

    PolicyReceiver.run(audit)
    PolicyWeb.run_forever(audit)
Beispiel #3
0
def test_get_policy_latest():
    """test /policy_latest/<policy-id>"""
    policy_id, expected_policy = MockPolicyEngine2018.gen_policy_latest(3)

    audit = Audit(job_name="test_get_policy_latest",
                  req_message="get /policy_latest/{}".format(policy_id or ""))

    policy_latest = pdp_client.PolicyRest.get_latest_policy((audit, policy_id, None, None)) or {}
    audit.audit_done(result=json.dumps(policy_latest))

    _LOGGER.info("expected_policy: %s", json.dumps(expected_policy))
    _LOGGER.info("policy_latest: %s", json.dumps(policy_latest))
    assert Utils.are_the_same(policy_latest, expected_policy)

    Tracker.validate()
Beispiel #4
0
    def test_web_policy_latest(self):
        """test /policy_latest/<policy-id>"""
        policy_id, expected_policy = MockPolicyEngine2018.gen_policy_latest(3)

        self.getPage("/policy_latest/{0}".format(policy_id or ""))
        self.assertStatus('200 OK')

        policy_latest = json.loads(self.body)

        _LOGGER.info("policy_latest: %s", self.body)
        _LOGGER.info("expected_policy: %s", json.dumps(expected_policy))
        assert Utils.are_the_same(policy_latest, expected_policy)

        result = self.getPage("/healthcheck")
        _LOGGER.info("healthcheck result: %s", result)

        Tracker.validate()
    def validate():
        """validate that the message history is as expected"""
        _LOGGER.info("Tracker.validate(%s)", Tracker.test_name)
        Tracker.validated_tests[Tracker.test_name] = True
        requests = [
            Tracker._hide_volatiles(copy.deepcopy(request))
            for request in Tracker.requests
        ]
        expected_reqs = [
            Tracker._hide_volatiles(copy.deepcopy(expected.get(REQUEST)))
            for expected in Tracker.expected
        ]

        _LOGGER.info("requests: %s", json.dumps(requests, sort_keys=True))
        _LOGGER.info("expected: %s", json.dumps(expected_reqs, sort_keys=True))
        assert Utils.are_the_same(requests, expected_reqs)

        _LOGGER.info("history valid for Tracker.validate(%s)",
                     Tracker.test_name)
        Tracker.valid_tests[Tracker.test_name] = True
    def get_response(request):
        """
        track the request to the history of requests
        and return the response with the status_code from the expected history queue
        """
        request_idx = len(Tracker.requests)
        request = copy.deepcopy(request)
        Tracker.requests.append(request)

        if request_idx < len(Tracker.expected):
            expected = Tracker.expected[request_idx] or {}
            masked_request = Tracker._hide_volatiles(copy.deepcopy(request))
            expected_request = Tracker._hide_volatiles(
                copy.deepcopy(expected.get(REQUEST)))
            if Utils.are_the_same(masked_request, expected_request):
                _LOGGER.info("as expected[%s]: %s", request_idx,
                             json.dumps(expected, sort_keys=True))
                return expected.get(STATUS_CODE), expected.get(RESPONSE)

            unexpected_request = {
                "unit-test-tracker": {
                    "request_idx": request_idx,
                    "received_request": copy.deepcopy(request),
                    "expected": copy.deepcopy(expected.get(REQUEST))
                }
            }
            _LOGGER.error("unexpected_request[%s]: %s", request_idx,
                          json.dumps(unexpected_request, sort_keys=True))
            return None, unexpected_request

        unexpected_request = {
            "unit-test-tracker": {
                "request_idx": request_idx,
                "out-of-range": len(Tracker.expected),
                "received_request": copy.deepcopy(request)
            }
        }
        _LOGGER.error("unexpected_request[%s]: %s", request_idx,
                      json.dumps(unexpected_request, sort_keys=True))
        return None, unexpected_request
Beispiel #7
0
    def test_web_all_policies_latest(self):
        """test GET /policies_latest"""
        expected_policies = MockPolicyEngine2018.gen_all_policies_latest()

        result = self.getPage("/policies_latest")
        _LOGGER.info("result: %s", result)
        _LOGGER.info("body: %s", self.body)

        self.assertStatus('200 OK')

        policies_latest = json.loads(self.body)
        self.assertIn(LATEST_POLICIES, policies_latest)
        policies_latest = policies_latest[LATEST_POLICIES]

        _LOGGER.info("policies_latest: %s", json.dumps(policies_latest))
        _LOGGER.info("expected_policies: %s", json.dumps(expected_policies))
        assert Utils.are_the_same(policies_latest, expected_policies)

        result = self.getPage("/healthcheck")
        _LOGGER.info("healthcheck result: %s", result)

        Tracker.validate()
    def test_web_policy_latest(self):
        """test /policy_latest/<policy-id>"""
        policy_id = "test_scope_prefix.pdp_decision_sit"
        expected_policy = {
            "policy_id": "test_scope_prefix.pdp_decision_sit",
            "policy_body": {
                "type": "unit.test.type.policies",
                "version": "1.0.0",
                "metadata": {
                    "policy-id": "test_scope_prefix.pdp_decision_sit",
                    "policy-version": "4.4.4",
                    "description": "description for test_scope_prefix.pdp_decision_sit"
                },
                "policyName": "test_scope_prefix.pdp_decision_sit.4-4-4.xml",
                "policyVersion": "4.4.4",
                "config": {
                    "policy_updated_from_ver": 3,
                    "policy_updated_to_ver": 4,
                    "policy_hello": "world!",
                    "updated_policy_id": "test_scope_prefix.pdp_decision_sit"
                }
            }
        }

        self.getPage("/policy_latest/{0}".format(policy_id or ""))
        self.assertStatus('200 OK')

        policy_latest = json.loads(self.body)

        _LOGGER.info("policy_latest: %s", self.body)
        _LOGGER.info("expected_policy: %s", json.dumps(expected_policy))
        assert Utils.are_the_same(policy_latest, expected_policy)

        result = self.getPage("/healthcheck")
        _LOGGER.info("healthcheck result: %s", result)

        Tracker.validate()
Beispiel #9
0
standard pytest file that contains the shared fixtures
https://docs.pytest.org/en/latest/fixture.html
"""

import time

import pytest
from policyhandler import pdp_client
from policyhandler.deploy_handler import DeployHandler
from policyhandler.onap.audit import Audit
from policyhandler.pdp_api.dmaap_mr import DmaapMr
from policyhandler.utils import Utils

from ..mock_tracker import MockHttpResponse

_LOGGER = Utils.get_logger(__file__)


@pytest.fixture()
def fix_pdp_post(monkeypatch):
    """monkeyed request /decision/v1 to PDP"""
    def monkeyed_policy_rest_post(uri, json=None, **kwargs):
        """monkeypatch for the POST to policy-engine"""
        return MockHttpResponse("post", uri, json=json, **kwargs)

    _LOGGER.info("setup fix_pdp_post")
    pdp_client.PolicyRest._lazy_inited = False
    pdp_client.PolicyRest._lazy_init()
    monkeypatch.setattr(
        'policyhandler.pdp_client.PolicyRest._requests_session.post',
        monkeyed_policy_rest_post)