#   Foremast - Pipeline Tooling
#
#   Copyright 2016 Gogo, LLC
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
"""Test IAM Policies for correctness."""
import json
from unittest import mock

from foremast.iam.construct_policy import construct_policy


@mock.patch('foremast.utils.credentials.API_URL', 'http://test.com')
@mock.patch('foremast.utils.credentials.requests.get')
def test_iam_construct_policy(requests_get):
    """Check general assemblage."""
    settings = {}

    policy_json = construct_policy(pipeline_settings=settings)
    # checking empty policy
    assert policy_json is None

    settings = {'services': {'s3': True}}
    policy_json = construct_policy(app='unicornforrest', env='stage', group='forrest', pipeline_settings=settings)

    # checking s3 policy
    assert type(json.loads(policy_json)) == dict

    # TODO: Test other services besides S3
    settings.update({'services': {'dynamodb': ['coreforrest', 'edgeforrest', 'attendantdevops']}})
    policy_json = construct_policy(pipeline_settings=settings)
    policy = json.loads(policy_json)


@mock.patch('foremast.utils.credentials.API_URL', 'http://test.com')
@mock.patch('foremast.utils.credentials.requests.get')
def test_construct_lambda(requests_get):
    """Check Lambda Policy."""
    policy_json = construct_policy(
        app='unicornforrest', env='dev', group='forrest', pipeline_settings={'type': 'lambda'})
    policy = json.loads(policy_json)

    statements = list(statement for statement in policy['Statement'] if statement['Sid'] == 'LambdaCloudWatchLogs')
    assert len(statements) == 1

    statement = statements[0]
    assert statement['Effect'] == 'Allow'
    assert len(statement['Action']) == 3
    assert all(action.startswith('logs:') for action in statement['Action'])

@@ -1728,22 +1728,30 @@
 nstruct_
-lambda
+cloudwatchlogs
 (request
@@ -1785,24 +1785,106 @@
  Policy.%22%22%22%0A
+    pipeline_settings = %7B'services': %7B'cloudwatchlogs': True%7D, 'type': 'lambda'%7D%0A%0A
     policy_j
@@ -1987,26 +1987,25 @@
 ngs=
-%7B'type': 'lambda'%7D
+pipeline_settings
 )%0A  

Check cloudwatchlogs specifically