# Copyright (c) 2020 CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com

from unittest.mock import Mock

import pytest

from czc.constants import PROJECT_NAME
from czt.unittest import Context, MockEx

from tests.sample_data import NAMESPACE, SENTRY_DSN, SENTRY_SECRET_STRING


def _create_test_secret(secrets, namespace):
    secrets.create_secret(Name=f'cz-{namespace}-feature-setup-secrets', SecretString=SENTRY_SECRET_STRING)


@pytest.fixture(scope='function')
def context(mocker, environ, mock_secretsmanager):
    import czc.sentry as sentry

    _create_test_secret(mock_secretsmanager, NAMESPACE)
    with Context(mocker, sentry, modules_to_mock=['sentry_sdk'], extra={'sentry': sentry, 'mock_scope': Mock()}) as context:
        context.mock_sentry_sdk.push_scope.return_value.__enter__.return_value = context.mock_scope
        yield context
    mocker.stopall()


@pytest.mark.unit
@pytest.mark.parametrize(
    'dsn',
    [
        (SENTRY_DSN),
        ('other dsn'),
    ],
)
def test_send_inits_with_dsn(context, dsn):
    context.sentry.send(message={}, sentry_dsn=dsn)
    expected_dsn = dsn if dsn else SENTRY_DSN
    assert MockEx(context.mock_sentry_sdk.init).was_called_once_with(expected_dsn)
    assert MockEx(context.mock_sentry_sdk.capture_message).was_called_once_with(f'{PROJECT_NAME} alarm')


@pytest.mark.unit
@pytest.mark.parametrize(
    'message,tags',
    [
        ({'foo': 'bar'}, {}),
        ({'baz': 'boo'}, {}),
        ({}, {'namespace': NAMESPACE}),
        ({}, {'namespace': NAMESPACE, 'environment': NAMESPACE}),
    ],
)
def test_send_sets_scope(context, mocker, message, tags):
    context.sentry.send(message=message, sentry_dsn=SENTRY_DSN, tags=tags)
    assert context.mock_scope.set_tag.call_count == len(tags) + 2
    assert MockEx(context.mock_scope.set_context).was_called_once_with('message', message)
