#  testscenarios: extensions to python unittest to allow declarative
#  dependency injection ('scenarios') by tests.
#
# Copyright (c) 2009, Robert Collins <robertc@robertcollins.net>
# 
# Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
# license at the users choice. A copy of both licenses are available in the
# project source as Apache-2.0 and BSD. You may not use this file except in
# compliance with one of these two licences.
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
# license you chose for the specific language governing permissions and
# limitations under that license.

__all__ = [
    'apply_scenario',
    'apply_scenarios',
    'generate_scenarios',
    ]

import unittest

from testtools.testcase import clone_test_with_new_id
from testtools import iterate_tests


def apply_scenario((name, parameters), test):
    """Apply scenario to test.

    :param scenario: A tuple (name, parameters) to apply to the test. The test
        is cloned, its id adjusted to have (name) after it, and the parameters
        dict is used to update the new test.
    :param test: The test to apply the scenario to. This test is unaltered.
    :return: A new test cloned from test, with the scenario applied.
    """
    newtest = clone_test_with_new_id(test,
        test.id() + '(' + name + ')')
    for key, value in parameters.iteritems():
        setattr(newtest, key, value)
    return newtest


def apply_scenarios(scenarios, test):
    """Apply many scenarios to a test.

    :param scenarios: An iterable of scenarios.
    :param test: A test to apply the scenarios to.
    :return: A generator of tests.
    """
    for scenario in scenarios:
        yield apply_scenario(scenario, test)


def generate_scenarios(test_or_suite):
    """Yield the tests in test_or_suite with scenario multiplication done.

    TestCase objects with no scenarios specified are yielded unaltered. Tests
    with scenarios are not yielded at all, instead the results of multiplying
    them by the scenarios they specified gets yielded.

    :param test_or_suite: A TestCase or TestSuite.
    :return: A generator of tests - objects satisfying the TestCase protocol.
    """
    for test in iterate_tests(test_or_suite):
        scenarios = getattr(test, 'scenarios', None)
        if scenarios:
            for newtest in apply_scenarios(scenarios, test):
                newtest.scenarios = None
                yield newtest
        else:
            yield test
