~julian+/testscenarios/testscenarios

« back to all changes in this revision

Viewing changes to lib/testscenarios/scenarios.py

  • Committer: Julian Berman
  • Date: 2013-08-27 03:23:51 UTC
  • Revision ID: julian@grayvines.com-20130827032351-2y6f1xd3m55swuz7
Add with_scenarios, generating test methods for each scenario.

Show diffs side-by-side

added added

removed removed

Lines of Context:
23
23
    'multiply_scenarios',
24
24
    ]
25
25
 
 
26
from functools import wraps
26
27
from itertools import (
27
28
    chain,
28
29
    product,
29
30
    )
 
31
from operator import methodcaller
 
32
import inspect
30
33
import sys
31
34
import unittest
32
35
 
164
167
            short_name, 
165
168
            {attribute_name: mod}))
166
169
    return scenarios
 
170
 
 
171
 
 
172
def with_scenarios(prefix="test"):
 
173
    """Mutate the decorated TestCase, producing methods for each scenario.
 
174
 
 
175
    :param str prefix: the prefix to match for test methods
 
176
 
 
177
    """
 
178
    def _populate_scenarios(cls):
 
179
        scenarios = getattr(cls, "scenarios", None)
 
180
        if scenarios is None:
 
181
            return cls
 
182
 
 
183
        tests = [
 
184
            (name, test) for name, test in inspect.getmembers(cls)
 
185
            if name.startswith(prefix)
 
186
        ]
 
187
 
 
188
        for name, test in tests:
 
189
            delattr(cls, name)
 
190
            for scenario_name, scenario_params in scenarios:
 
191
                _test = _make_test(name, test, scenario_name, scenario_params)
 
192
                setattr(cls, _test.__name__, _test)
 
193
        return cls
 
194
    return _populate_scenarios
 
195
 
 
196
 
 
197
def _make_test(name, test, scenario_name, scenario_params):
 
198
    """Create a test that wraps the given test under the given scenario.
 
199
 
 
200
    :param str name: the name of the test
 
201
    :param callable test: the test method
 
202
    :param str scenario_name: the scenario
 
203
    :param dict scenario_params: the scenario's parameters
 
204
 
 
205
    """
 
206
 
 
207
    @wraps(test)
 
208
    def _test(self, *args, **kwargs):
 
209
        for k, v in scenario_params.iteritems():
 
210
            setattr(self, k, v)
 
211
        return test(self, *args, **kwargs)
 
212
 
 
213
    _test.__name__ = "%s_%s" % (name, scenario_name)
 
214
    return _test