File: __init__.py

package info (click to toggle)
python-nose-random 1.0.0-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 92 kB
  • sloc: python: 93; makefile: 3
file content (73 lines) | stat: -rw-r--r-- 2,257 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
__version__ = '0.0.1'

from nose.plugins import Plugin
import os
import sys

PY3 = (sys.version_info[0] == 3)

from random import Random


_missing = object()


class NoseRandomConfig(object):
    def __init__(self):
        self.is_nose_plugin = False
        self._scenario = _missing

    @property
    def scenario(self):
        if self._scenario is _missing:
            import sys
            for arg in sys.argv:
                if arg.startswith('--scenario='):
                    self._scenario = arg[len('--scenario='):]
        return self._scenario

    @scenario.setter
    def scenario(self, value):
        self._scenario = value


config = NoseRandomConfig()


class NoseRandomPlugin(Plugin):
    def options(self, parser, env=os.environ):
        parser.add_option('--scenario', type='str',
                          dest='scenario',
                          help="Specify the scenario seed for debugging random tests.")

    def configure(self, options, conf):
        config.scenario = getattr(options, 'scenario', None)


def _generate_tag(n, rng):
    return ''.join(rng.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') for _ in range(n))


def randomize(n, scenario_generator, seed=12038728732):
    def decorator(test):
        def randomized_test(self):
            if config.scenario is not None:
                nseeds = 1
                seeds = [config.scenario]
            else:
                rng_seed = Random(seed)
                nseeds = n
                seeds = (_generate_tag(12, rng_seed) for i in range(n)) # (rng_seed.getrandbits(32) for i in range(n))
            for i, rseed in enumerate(seeds):
                rng = Random(rseed)
                scenario = scenario_generator(self, rng)
                try:
                    test(self, scenario)
                except Exception as e:
                    import sys
                    if PY3:
                        raise type(e).with_traceback(type(e)('%s with scenario %s (%i of %i)' % (e.message, rseed, i+1, nseeds)), sys.exc_info()[2])
                    else:
                        raise (type(e), type(e)('%s with scenario %s (%i of %i)' % (e.message, rseed, i+1, nseeds)), sys.exc_info()[2])
        return randomized_test
    return decorator