Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / tests / __init__.py @ 02846a75

History | View | Annotate | Download (6.2 kB)

1
# Copyright 2012-2013 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
from unittest import TestCase, TestSuite, makeSuite, TextTestRunner
35
from argparse import ArgumentParser
36
from sys import stdout
37
from progress.bar import ShadyBar
38

    
39
from kamaki.cli.config import Config
40
from kamaki.cli.utils import spiner
41

    
42

    
43
def _add_value(foo, value):
44
    def wrap(self):
45
        return foo(self, value)
46
    return wrap
47

    
48

    
49
class Generic(TestCase):
50

    
51
    _waits = []
52
    _cnf = None
53
    _grp = None
54
    _fetched = {}
55

    
56
    def __init__(self, specific=None, config_file=None, group=None):
57
        super(Generic, self).__init__(specific)
58
        self._cnf = Config(config_file)
59
        self._grp = group
60
        self._waits.append(0.71828)
61
        for i in range(10):
62
            self._waits.append(self._waits[-1] * 2.71828)
63

    
64
    def __getitem__(self, key):
65
        key = self._key(key)
66
        try:
67
            return self._fetched[key]
68
        except KeyError:
69
            return self._get_from_cnf(key)
70

    
71
    def _key(self, key):
72
        return ('', key) if isinstance(key, str)\
73
            else ('', key[0]) if len(key) == 1\
74
            else key
75

    
76
    def _get_from_cnf(self, key):
77
        val = 0
78
        if key[0]:
79
            val = self._cnf.get('test', '%s_%s' % key)\
80
                or self._cnf.get(*key)
81
        if not val:
82
            val = self._cnf.get('test', key[1])\
83
                or self._cnf.get('global', key[1])
84
        self._fetched[key] = val
85
        return val
86

    
87
    def _safe_progress_bar(self, msg):
88
        """Try to get a progress bar, but do not raise errors"""
89
        try:
90
            wait_bar = ShadyBar(msg)
91

    
92
            def wait_gen(n):
93
                for i in wait_bar.iter(range(int(n))):
94
                    yield
95
                yield
96
            wait_cb = wait_gen
97
        except Exception:
98
            stdout.write('%s:' % msg)
99
            (wait_bar, wait_cb) = (None, spiner)
100
        return (wait_bar, wait_cb)
101

    
102
    def _safe_progress_bar_finish(self, progress_bar):
103
        try:
104
            progress_bar.finish()
105
        except Exception:
106
            print(' DONE')
107

    
108
    def do_with_progress_bar(self, action, msg, items):
109
        if not items:
110
            print('%s: DONE' % msg)
111
            return
112
        (action_bar, action_cb) = self._safe_progress_bar(msg)
113
        action_gen = action_cb(len(items))
114
        for item in items:
115
            action(item)
116
            action_gen.next()
117
        self._safe_progress_bar_finish(action_bar)
118

    
119
    def assert_dicts_are_deeply_equal(self, d1, d2):
120
        for k, v in d1.items():
121
            self.assertTrue(k in d2)
122
            if isinstance(v, dict):
123
                self.assert_dicts_are_deeply_equal(v, d2[k])
124
            else:
125
                self.assertEqual(unicode(v), unicode(d2[k]))
126

    
127
    def test_000(self):
128
        import inspect
129
        methods = [method for method in inspect.getmembers(
130
            self,
131
            predicate=inspect.ismethod)\
132
            if method[0].startswith('_test_')]
133
        failures = 0
134
        for method in methods:
135
            stdout.write('Test %s' % method[0][6:])
136
            try:
137
                method[1]()
138
                print(' ...ok')
139
            except AssertionError:
140
                print('  FAIL: %s (%s)' % (method[0], method[1]))
141
                failures += 1
142
        if failures:
143
            raise AssertionError('%s failures' % failures)
144

    
145

    
146
def init_parser():
147
    parser = ArgumentParser(add_help=False)
148
    parser.add_argument('-h', '--help',
149
        dest='help',
150
        action='store_true',
151
        default=False,
152
        help="Show this help message and exit")
153
    return parser
154

    
155

    
156
def main(argv):
157

    
158
    suiteFew = TestSuite()
159
    """
160
    if len(argv) == 0 or argv[0] == 'pithos':
161
        if len(argv) == 1:
162
            suiteFew.addTest(unittest.makeSuite(testPithos))
163
        else:
164
            suiteFew.addTest(testPithos('test_' + argv[1]))
165
    """
166
    if len(argv) == 0 or argv[0] == 'cyclades':
167
        from kamaki.clients.tests.cyclades import Cyclades
168
        test_method = 'test_%s' % (argv[1] if len(argv) > 1 else '000')
169
        suiteFew.addTest(Cyclades(test_method))
170
    if len(argv) == 0 or argv[0] == 'image':
171
        from kamaki.clients.tests.image import Image
172
        test_method = 'test_%s' % (argv[1] if len(argv) > 1 else '000')
173
        suiteFew.addTest(Image(test_method))
174
    if len(argv) == 0 or argv[0] == 'astakos':
175
        from kamaki.clients.tests.astakos import Astakos
176
        if len(argv) == 1:
177
            suiteFew.addTest(makeSuite(Astakos))
178
        else:
179
            suiteFew.addTest(Astakos('test_' + argv[1]))
180

    
181
    TextTestRunner(verbosity=2).run(suiteFew)
182

    
183
if __name__ == '__main__':
184
    parser = init_parser()
185
    args, argv = parser.parse_known_args()
186
    if len(argv) > 2 or getattr(args, 'help') or len(argv) < 1:
187
        raise Exception('\tusage: tests.py <group> [command]')
188
    main(argv)