# Copyright (C) 2018, 2020, 2021 The Meme Factory, Inc.
# http://www.karlpinc.com/

# This file is part of PGWUI_Common.
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with this program.  If not, see
# <http://www.gnu.org/licenses/>.
#

# Karl O. Pinc <kop@karlpinc.com>

import pytest

import logging
import pyramid.exceptions
import pgwui_common.assets as assets
import pgwui_common.exceptions as common_ex

from pgwui_develop import testing

# Activiate the PGWUI pytest plugin
pytest_plugins = ("pgwui",)

# Mark all tests with "unittest"
pytestmark = pytest.mark.unittest

mock_override_asset = testing.instance_method_mock_fixture('override_asset')


# override_assets()

@pytest.mark.parametrize(
    ('overrides', 'call_count'), [
        ({}, 0),
        ({'some_asset': 'new_asset'}, 1),
        ({'some_asset': 'new_asset',
          'other_asset': 'other new asset'}, 2)])
def test_override_assets_success(
        caplog, pyramid_config, mock_override_asset, overrides, call_count):
    '''override_asset() is called and a debug message logged
    for each good override
    '''
    caplog.set_level(logging.DEBUG)
    mocked_override_asset = mock_override_asset(pyramid_config)

    if overrides:
        settings = {'override_assets': overrides}
    else:
        settings = {}
    result = assets.override_assets(pyramid_config, {'pgwui': settings})

    assert result == []
    assert mocked_override_asset.call_count == call_count
    assert len(caplog.record_tuples) == call_count


@pytest.mark.parametrize(
    ('exception'), [
        (pyramid.exceptions.ConfigurationError,),
        (ModuleNotFoundError,)])
def test_override_assets_failure(
        caplog, pyramid_config, mock_override_asset, exception):
    '''There is no logging when the override_asset call fails,
    but an error is returned
    '''
    caplog.set_level(logging.DEBUG)
    mocked_override_asset = mock_override_asset(pyramid_config)
    mocked_override_asset.side_effect = exception

    result = assets.override_assets(pyramid_config,
                                    {'pgwui':
                                     {'override_assets':
                                      {'asset': 'new'}}})
    assert len(result) == 1
    assert isinstance(result[0], common_ex.BadAssetOverrideError)

    logs = caplog.record_tuples
    assert len(logs) == 0
