Exemplo n.º 1
0
def test_parses_config_correctly(monkeypatch):
    sleep_mock = MagicMock()
    monkeypatch.setattr("time.sleep", sleep_mock)
    filename = pkg_resources.resource_filename("tests.policy",
                                               "example_config2.yml")
    policy = PolicyRunner.load_file(filename)
    inventory = MagicMock()
    k8s_inventory = MagicMock()
    driver = MagicMock()
    executor = MagicMock()
    LOOPS = policy.get("config").get("runStrategy").get("runs")
    PolicyRunner.run(policy, inventory, k8s_inventory, driver, executor)
    assert sleep_mock.call_count == LOOPS
    for call in sleep_mock.call_args_list:
        args, _ = call
        assert 77 <= args[0] <= 78
Exemplo n.º 2
0
def test_parses_a_whole_config_correctly(monkeypatch):
    sleep_mock = MagicMock()
    monkeypatch.setattr("time.sleep", sleep_mock)
    filename = pkg_resources.resource_filename("tests.policy", "example_config2.yml")
    policy = PolicyRunner.validate_file(filename)
    inventory = MagicMock()
    k8s_inventory = MagicMock()
    driver = MagicMock()
    executor = MagicMock()
    LOOPS = 1000
    nodes, pods = PolicyRunner.run(policy, inventory, k8s_inventory, driver, executor, loops=LOOPS)
    assert sleep_mock.call_count == LOOPS
    for call in sleep_mock.call_args_list:
        args, kwargs = call
        assert 77 <= args[0] <= 100
    assert inventory.sync.call_count == LOOPS
    assert len(nodes) == 2
    assert len(pods) == 1
Exemplo n.º 3
0
 def is_policy_valid(self):
     """
     Checks whether the specified policy is valid depending on the schema
     file used in the PolicyRunner class
     """
     schema = PolicyRunner.get_schema()
     try:
         jsonschema.validate(self.policy, schema)
     except jsonschema.ValidationError:
         return False
     return True
Exemplo n.º 4
0
def test_parses_config_correctly(monkeypatch):
    with mock.patch('powerfulseal.k8s.k8s_client') as k8s_client:
        k8s_client.get_scenarios = get_scenarios_mock
        sleep_mock = MagicMock()
        monkeypatch.setattr("time.sleep", sleep_mock)
        filename = pkg_resources.resource_filename("tests.policy",
                                                   "example_config2.yml")
        runner = PolicyRunner(filename, k8s_client)
        policy = runner.read_policy()
        inventory = MagicMock()
        k8s_inventory = MagicMock()
        driver = MagicMock()
        executor = MagicMock()
        LOOPS = policy.get("config").get("runStrategy").get("runs") + 1
        assert policy.get("scenarios")[1].get("name") == crd_scenario_name
        runner.run(inventory, k8s_inventory, driver, executor)
        assert sleep_mock.call_count == LOOPS
        for call in sleep_mock.call_args_list:
            args, _ = call
            assert 77 <= args[0] <= 78
Exemplo n.º 5
0
def policy_actions():
    if request.method == 'GET':
        # GET request: returns a JSON representation of the policy file
        policy = server_state.get_policy()
        return jsonify(PolicyFormatter.output_policy(policy))
    elif request.method == 'POST':
        # POST request: returns a YAML representation of the given policy
        input_policy = request.get_json().get('policy', None)
        if input_policy is None:
            return jsonify({'error': 'Policy field missing'}), 400

        try:
            modified_policy = PolicyFormatter.parse_policy(input_policy)
        except KeyError:
            return jsonify({'error': 'Policy not valid'}), 400
        if not PolicyRunner.is_policy_valid(modified_policy):
            return jsonify({'error': 'Policy not valid'}), 400

        return jsonify(
            {'policy': yaml.dump(modified_policy, default_flow_style=False)})
    elif request.method == 'PUT':
        # PUT request: modify a policy
        input_policy = request.get_json().get('policy', None)
        if input_policy is None:
            return jsonify({'error': 'Policy field missing'}), 400

        try:
            modified_policy = PolicyFormatter.parse_policy(input_policy)
        except KeyError:
            return jsonify({'error': 'Policy not valid'}), 400
        if not PolicyRunner.is_policy_valid(modified_policy):
            return jsonify({'error': 'Policy not valid'}), 400

        try:
            server_state.update_policy(modified_policy)
        except IOError:
            return jsonify({'error': 'Unable to overwrite policy file'}), 500

        return jsonify({}), 200

    return jsonify({}), 501
def test_is_policy_valid_validates():
    valid_policy_path = pkg_resources.resource_filename(
        "tests.policy", "example_config.yml")
    valid_policy = PolicyRunner.load_file(valid_policy_path)
    invalid_policy = {'config': {'minSecondsBetweenRuns': 'invalid'}}

    server_state = ServerState(valid_policy, None, None, None, None, None,
                               None, None)
    assert server_state.is_policy_valid()

    server_state = ServerState(invalid_policy, None, None, None, None, None,
                               None, None)
    assert not server_state.is_policy_valid()
def test_threaded_policy_runner():
    # Mock all the methods which will be called by the policy runner
    test_node_scenario = MagicMock()
    test_node_scenario.execute = MagicMock()
    test_pod_scenario = MagicMock()
    test_pod_scenario.execute = MagicMock()
    test_inventory = MagicMock()
    test_inventory.sync = MagicMock(return_value=None)

    policy = {
        'config': {
            'minSecondsBetweenRuns': 0,
            'maxSecondsBetweenRuns': 2
        }
    }
    assert PolicyRunner.is_policy_valid(policy)

    test_node_scenario.execute.assert_not_called()
    test_pod_scenario.execute.assert_not_called()
    test_inventory.sync.assert_not_called()

    # As the threaded policy runner runs on a separate thread, this can be tested
    # by waiting a reasonably short amount of time for the runner loop to run
    # and checking whether the expected functions have been called by the runner
    policy_runner = ThreadedPolicyRunner(policy, test_inventory, None, None,
                                         None, threading.Event())
    policy_runner.node_scenarios = [test_node_scenario]
    policy_runner.pod_scenarios = [test_pod_scenario]

    policy_runner.start()
    time.sleep(3)
    policy_runner.stop()
    policy_runner.join()

    assert policy_runner.stop_event
    test_node_scenario.execute.assert_called()
    test_pod_scenario.execute.assert_called()
    test_inventory.sync.assert_called()
    assert test_node_scenario.execute.call_count == test_pod_scenario.execute.call_count == test_inventory.sync.call_count
Exemplo n.º 8
0
def test_put_policy_actions(client):
    server_state_mock = MagicMock()
    server_state_mock.update_policy = MagicMock()

    valid_policy_path = pkg_resources.resource_filename(
        "tests.policy", "example_config.yml")
    valid_policy = PolicyRunner.load_file(valid_policy_path)

    invalid_policy = {'config': {'minSecondsBetweenRuns': 'invalid'}}

    with mock.patch("powerfulseal.web.server.server_state", server_state_mock):
        result = client.put("/api/policy",
                            data=json.dumps({
                                'policy':
                                PolicyFormatter.output_policy(valid_policy)
                            }),
                            content_type='application/json')
        assert result.status_code == 200

        result = client.put("/api/policy",
                            data=json.dumps({'policy': invalid_policy}),
                            content_type='application/json')
        assert result.status_code == 400
Exemplo n.º 9
0
def test_example_config_validates():
    filename = pkg_resources.resource_filename("tests.policy", "example_config.yml")
    PolicyRunner.validate_file(filename)
Exemplo n.º 10
0
def test_example_config_validates():
    filename = pkg_resources.resource_filename("tests.policy",
                                               "example_config.yml")
    policy = PolicyRunner.load_file(filename)
    assert PolicyRunner.is_policy_valid(policy)
Exemplo n.º 11
0
def test_default_policy_validates():
    assert PolicyRunner.is_policy_valid(PolicyRunner.DEFAULT_POLICY)