Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / livetest / __init__.py @ 2bd23362

History | View | Annotate | Download (7 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
import inspect
35
from unittest import TestCase, TestSuite, TextTestRunner
36
from argparse import ArgumentParser
37
from sys import stdout
38

    
39
from kamaki.cli.config import Config
40

    
41

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

    
47

    
48
class Generic(TestCase):
49

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

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

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

    
74
    def _key(self, key):
75
        return ('', key) if isinstance(key, str)\
76
            else ('', key[0]) if len(key) == 1\
77
            else key
78

    
79
    def _get_from_cnf(self, key):
80
        val = 0
81
        if key[0]:
82
            keystr = '%s_%s' % key
83
            val = self._cnf.get('livetest', keystr) or self._cnf.get(*key)
84
        if not val:
85
            val = self._cnf.get('livetest', key[1]) or self._cnf.get(
86
                'global',
87
                key[1])
88
        self._fetched[key] = val
89
        return val
90

    
91
    def _safe_progress_bar(self, msg):
92
        """Try to get a progress bar, but do not raise errors"""
93
        try:
94
            from progress.bar import ShadyBar
95
            wait_bar = ShadyBar(msg)
96

    
97
            def wait_gen(n):
98
                for i in wait_bar.iter(range(int(n))):
99
                    yield
100
                yield
101
            wait_cb = wait_gen
102
        except Exception:
103
            stdout.write('%s:' % msg)
104
            (wait_bar, wait_cb) = None, None
105
        return (wait_bar, wait_cb)
106

    
107
    def _safe_progress_bar_finish(self, progress_bar):
108
        try:
109
            progress_bar.finish()
110
        except Exception:
111
            print('\b DONE')
112

    
113
    def do_with_progress_bar(self, action, msg, items):
114
        if not items:
115
            print('%s: DONE' % msg)
116
            return
117
        (action_bar, action_cb) = self._safe_progress_bar(msg)
118
        action_gen = action_cb(len(items))
119
        try:
120
            action_gen.next()
121
        except Exception:
122
            pass
123
        for item in items:
124
            action(item)
125
            action_gen.next()
126
        self._safe_progress_bar_finish(action_bar)
127

    
128
    def assert_dicts_are_equal(self, d1, d2):
129
        self.assertTrue(set(d1) == set(d2))
130
        for k, v in d1.items():
131
            if isinstance(v, dict):
132
                self.assert_dicts_are_equal(d1[k], d2[k])
133
            else:
134
                self.assertEqual(v, d2[k])
135

    
136
    def assert_dicts_are_deeply_equal(self, d1, d2):
137
        st1 = set([unicode(k) for k in d1])
138
        st2 = set([unicode(k) for k in d2])
139
        diff1 = st1.difference(st2)
140
        diff2 = st2.difference(st1)
141
        self.assertTrue(
142
            not (diff1 or diff2),
143
            'Key differences:\n\td1-d2=%s\n\td2-d1=%s' % (diff1, diff2))
144
        for k, v in d1.items():
145
            if isinstance(v, dict):
146
                self.assert_dicts_are_deeply_equal(v, d2[k])
147
            else:
148
                self.assertEqual(unicode(v), unicode(d2[k]))
149

    
150
    def test_000(self):
151
        print('')
152
        methods = [method for method in inspect.getmembers(
153
            self,
154
            predicate=inspect.ismethod) if method[0].startswith('_test_')]
155
        failures = 0
156
        for method in methods:
157
            stdout.write('Test %s ' % method[0][6:])
158
            stdout.flush()
159
            try:
160
                method[1]()
161
                print(' ...ok')
162
            except AssertionError:
163
                print('  FAIL: %s (%s)' % (method[0], method[1]))
164
                failures += 1
165
        if failures:
166
            raise AssertionError('%s failures' % failures)
167

    
168

    
169
def init_parser():
170
    parser = ArgumentParser(add_help=False)
171
    parser.add_argument(
172
        '-h', '--help',
173
        dest='help',
174
        action='store_true',
175
        default=False,
176
        help="Show this help message and exit")
177
    return parser
178

    
179

    
180
def main(argv, config=None):
181
    suiteFew = TestSuite()
182
    if len(argv) == 0 or argv[0] == 'pithos':
183
        from kamaki.clients.livetest.pithos import Pithos
184
        test_method = 'test_%s' % (argv[1] if len(argv) > 1 else '000')
185
        suiteFew.addTest(Pithos(test_method, config))
186
    if len(argv) == 0 or argv[0] == 'cyclades':
187
        from kamaki.clients.livetest.cyclades import Cyclades
188
        test_method = 'test_%s' % (argv[1] if len(argv) > 1 else '000')
189
        suiteFew.addTest(Cyclades(test_method, config))
190
    if len(argv) == 0 or argv[0] == 'image':
191
        from kamaki.clients.livetest.image import Image
192
        test_method = 'test_%s' % (argv[1] if len(argv) > 1 else '000')
193
        suiteFew.addTest(Image(test_method, config))
194
    if len(argv) == 0 or argv[0] == 'astakos':
195
        from kamaki.clients.livetest.astakos import Astakos
196
        test_method = 'test_%s' % (argv[1] if len(argv) > 1 else '000')
197
        suiteFew.addTest(Astakos(test_method, config))
198

    
199
    TextTestRunner(verbosity=2).run(suiteFew)
200

    
201
if __name__ == '__main__':
202
    parser = init_parser()
203
    args, argv = parser.parse_known_args()
204
    if len(argv) > 2 or getattr(args, 'help') or len(argv) < 1:
205
        raise Exception('\tusage: livetest <group> [command]')
206
    main(argv)