Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / tests / __init__.py @ d1f78278

History | View | Annotate | Download (6.4 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
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
            return self._fetched[key]
67
        except KeyError:
68
            return self._get_from_cnf(key)
69

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

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

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

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

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

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

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

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

    
148

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

    
158

    
159
def main(argv):
160
    _main(argv, config=None)
161

    
162

    
163
def _main(argv, config=None):
164
    suiteFew = TestSuite()
165
    """
166
    if len(argv) == 0 or argv[0] == 'pithos':
167
        if len(argv) == 1:
168
            suiteFew.addTest(unittest.makeSuite(testPithos))
169
        else:
170
            suiteFew.addTest(testPithos('test_' + argv[1]))
171
    """
172
    if len(argv) == 0 or argv[0] == 'cyclades':
173
        from kamaki.clients.tests.cyclades import Cyclades
174
        test_method = 'test_%s' % (argv[1] if len(argv) > 1 else '000')
175
        suiteFew.addTest(Cyclades(test_method, config))
176
    if len(argv) == 0 or argv[0] == 'image':
177
        from kamaki.clients.tests.image import Image
178
        test_method = 'test_%s' % (argv[1] if len(argv) > 1 else '000')
179
        suiteFew.addTest(Image(test_method, config))
180
    if len(argv) == 0 or argv[0] == 'astakos':
181
        from kamaki.clients.tests.astakos import Astakos
182
        if len(argv) == 1:
183
            suiteFew.addTest(makeSuite(Astakos, config))
184
        else:
185
            suiteFew.addTest(Astakos('test_' + argv[1], config))
186

    
187
    TextTestRunner(verbosity=2).run(suiteFew)
188

    
189
if __name__ == '__main__':
190
    parser = init_parser()
191
    args, argv = parser.parse_known_args()
192
    if len(argv) > 2 or getattr(args, 'help') or len(argv) < 1:
193
        raise Exception('\tusage: tests.py <group> [command]')
194
    main(argv)