Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / test.py @ 38a79780

History | View | Annotate | Download (18.6 kB)

1 2fde8651 Stavros Sachtouris
# Copyright 2013 GRNET S.A. All rights reserved.
2 2fde8651 Stavros Sachtouris
#
3 2fde8651 Stavros Sachtouris
# Redistribution and use in source and binary forms, with or
4 2fde8651 Stavros Sachtouris
# without modification, are permitted provided that the following
5 2fde8651 Stavros Sachtouris
# conditions are met:
6 2fde8651 Stavros Sachtouris
#
7 2fde8651 Stavros Sachtouris
#   1. Redistributions of source code must retain the above
8 2fde8651 Stavros Sachtouris
#      copyright notice, this list of conditions and the following
9 2fde8651 Stavros Sachtouris
#      disclaimer.
10 2fde8651 Stavros Sachtouris
#
11 2fde8651 Stavros Sachtouris
#   2. Redistributions in binary form must reproduce the above
12 2fde8651 Stavros Sachtouris
#      copyright notice, this list of conditions and the following
13 2fde8651 Stavros Sachtouris
#      disclaimer in the documentation and/or other materials
14 2fde8651 Stavros Sachtouris
#      provided with the distribution.
15 2fde8651 Stavros Sachtouris
#
16 2fde8651 Stavros Sachtouris
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17 2fde8651 Stavros Sachtouris
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 2fde8651 Stavros Sachtouris
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 2fde8651 Stavros Sachtouris
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20 2fde8651 Stavros Sachtouris
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 2fde8651 Stavros Sachtouris
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 2fde8651 Stavros Sachtouris
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23 2fde8651 Stavros Sachtouris
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 2fde8651 Stavros Sachtouris
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 2fde8651 Stavros Sachtouris
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26 2fde8651 Stavros Sachtouris
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 2fde8651 Stavros Sachtouris
# POSSIBILITY OF SUCH DAMAGE.
28 2fde8651 Stavros Sachtouris
#
29 2fde8651 Stavros Sachtouris
# The views and conclusions contained in the software and
30 2fde8651 Stavros Sachtouris
# documentation are those of the authors and should not be
31 2fde8651 Stavros Sachtouris
# interpreted as representing official policies, either expressed
32 2fde8651 Stavros Sachtouris
# or implied, of GRNET S.A.
33 2fde8651 Stavros Sachtouris
34 2fde8651 Stavros Sachtouris
from unittest import makeSuite, TestSuite, TextTestRunner, TestCase
35 2fde8651 Stavros Sachtouris
from inspect import getmembers, isclass
36 98093aac Stavros Sachtouris
from tempfile import NamedTemporaryFile
37 4769da6b Stavros Sachtouris
from mock import patch, call
38 4769da6b Stavros Sachtouris
from itertools import product
39 2fde8651 Stavros Sachtouris
40 0962adb7 Stavros Sachtouris
from kamaki.cli.command_tree.test import Command, CommandTree
41 f767b407 Stavros Sachtouris
from kamaki.cli.config.test import Config
42 3a5b1ceb Stavros Sachtouris
from kamaki.cli.argument.test import (
43 3a5b1ceb Stavros Sachtouris
    Argument, ConfigArgument, RuntimeConfigArgument, FlagArgument,
44 8d427cb9 Stavros Sachtouris
    ValueArgument, IntArgument, DateArgument, VersionArgument,
45 ca5528f1 Stavros Sachtouris
    RepeatableArgument, KeyValueArgument, ProgressBarArgument,
46 ca5528f1 Stavros Sachtouris
    ArgumentParseManager)
47 b3cb58c2 Stavros Sachtouris
from kamaki.cli.utils.test import UtilsMethods
48 2fde8651 Stavros Sachtouris
49 2fde8651 Stavros Sachtouris
50 98093aac Stavros Sachtouris
class History(TestCase):
51 98093aac Stavros Sachtouris
52 98093aac Stavros Sachtouris
    def setUp(self):
53 98093aac Stavros Sachtouris
        from kamaki.cli.history import History as HClass
54 98093aac Stavros Sachtouris
        self.HCLASS = HClass
55 98093aac Stavros Sachtouris
        self.file = NamedTemporaryFile()
56 98093aac Stavros Sachtouris
57 98093aac Stavros Sachtouris
    def tearDown(self):
58 98093aac Stavros Sachtouris
        self.file.close()
59 98093aac Stavros Sachtouris
60 98093aac Stavros Sachtouris
    def test__match(self):
61 98093aac Stavros Sachtouris
        self.assertRaises(AttributeError, self.HCLASS._match, 'ok', 42)
62 98093aac Stavros Sachtouris
        self.assertRaises(TypeError, self.HCLASS._match, 2.71, 'ok')
63 98093aac Stavros Sachtouris
        for args, expected in (
64 98093aac Stavros Sachtouris
                (('XXX', None), True),
65 98093aac Stavros Sachtouris
                ((None, None), True),
66 98093aac Stavros Sachtouris
                (('this line has some terms', 'some terms'), True),
67 98093aac Stavros Sachtouris
                (('this line has some terms', 'some bad terms'), False),
68 98093aac Stavros Sachtouris
                (('small line', 'not so small line terms'), False),
69 98093aac Stavros Sachtouris
                ((['line', 'with', 'some', 'terms'], 'some terms'), True),
70 98093aac Stavros Sachtouris
                ((['line', 'with', 'some terms'], 'some terms'), False)):
71 98093aac Stavros Sachtouris
            self.assertEqual(self.HCLASS._match(*args), expected)
72 98093aac Stavros Sachtouris
73 98093aac Stavros Sachtouris
    def test_get(self):
74 98093aac Stavros Sachtouris
        history = self.HCLASS(self.file.name)
75 98093aac Stavros Sachtouris
        self.assertEqual(history.get(), [])
76 98093aac Stavros Sachtouris
77 98093aac Stavros Sachtouris
        sample_history = (
78 98093aac Stavros Sachtouris
            'kamaki history show\n',
79 98093aac Stavros Sachtouris
            'kamaki file list\n',
80 98093aac Stavros Sachtouris
            'kamaki touch pithos:f1\n',
81 98093aac Stavros Sachtouris
            'kamaki file info pithos:f1\n')
82 98093aac Stavros Sachtouris
        self.file.write(''.join(sample_history))
83 98093aac Stavros Sachtouris
        self.file.flush()
84 98093aac Stavros Sachtouris
85 98093aac Stavros Sachtouris
        expected = ['%s.  \t%s' % (
86 98093aac Stavros Sachtouris
            i + 1, event) for i, event in enumerate(sample_history)]
87 98093aac Stavros Sachtouris
        self.assertEqual(history.get(), expected)
88 98093aac Stavros Sachtouris
        self.assertEqual(history.get('kamaki'), expected)
89 98093aac Stavros Sachtouris
        self.assertEqual(history.get('file kamaki'), expected[1::2])
90 98093aac Stavros Sachtouris
        self.assertEqual(history.get('pithos:f1'), expected[2:])
91 98093aac Stavros Sachtouris
        self.assertEqual(history.get('touch pithos:f1'), expected[2:3])
92 98093aac Stavros Sachtouris
93 98093aac Stavros Sachtouris
        for limit in range(len(sample_history)):
94 98093aac Stavros Sachtouris
            self.assertEqual(history.get(limit=limit), expected[-limit:])
95 98093aac Stavros Sachtouris
            self.assertEqual(
96 98093aac Stavros Sachtouris
                history.get('kamaki', limit=limit), expected[-limit:])
97 98093aac Stavros Sachtouris
98 98093aac Stavros Sachtouris
    def test_add(self):
99 98093aac Stavros Sachtouris
        history = self.HCLASS(self.file.name)
100 98093aac Stavros Sachtouris
        some_strings = ('a brick', 'two bricks', 'another brick', 'A wall!')
101 98093aac Stavros Sachtouris
        for i, line in enumerate(some_strings):
102 98093aac Stavros Sachtouris
            history.add(line)
103 98093aac Stavros Sachtouris
            self.file.seek(0)
104 98093aac Stavros Sachtouris
            self.assertEqual(
105 98093aac Stavros Sachtouris
                self.file.read(), '\n'.join(some_strings[:(i + 1)]) + '\n')
106 98093aac Stavros Sachtouris
107 98093aac Stavros Sachtouris
    def test_clean(self):
108 98093aac Stavros Sachtouris
        content = 'a brick\ntwo bricks\nanother brick\nA wall!\n'
109 98093aac Stavros Sachtouris
        self.file.write(content)
110 98093aac Stavros Sachtouris
        self.file.flush()
111 98093aac Stavros Sachtouris
        self.file.seek(0)
112 98093aac Stavros Sachtouris
        self.assertEqual(self.file.read(), content)
113 98093aac Stavros Sachtouris
        history = self.HCLASS(self.file.name)
114 98093aac Stavros Sachtouris
        history.clean()
115 98093aac Stavros Sachtouris
        self.file.seek(0)
116 98093aac Stavros Sachtouris
        self.assertEqual(self.file.read(), '')
117 98093aac Stavros Sachtouris
118 98093aac Stavros Sachtouris
    def test_retrieve(self):
119 98093aac Stavros Sachtouris
        sample_history = (
120 98093aac Stavros Sachtouris
            'kamaki history show\n',
121 98093aac Stavros Sachtouris
            'kamaki file list\n',
122 98093aac Stavros Sachtouris
            'kamaki touch pithos:f1\n',
123 98093aac Stavros Sachtouris
            'kamaki file info pithos:f1\n',
124 98093aac Stavros Sachtouris
            'current / last command is always excluded')
125 98093aac Stavros Sachtouris
        self.file.write(''.join(sample_history))
126 98093aac Stavros Sachtouris
        self.file.flush()
127 98093aac Stavros Sachtouris
128 98093aac Stavros Sachtouris
        history = self.HCLASS(self.file.name)
129 98093aac Stavros Sachtouris
        self.assertRaises(ValueError, history.retrieve, 'must be number')
130 98093aac Stavros Sachtouris
        self.assertRaises(TypeError, history.retrieve, [1, 2, 3])
131 98093aac Stavros Sachtouris
132 98093aac Stavros Sachtouris
        for i in (0, len(sample_history), -len(sample_history)):
133 98093aac Stavros Sachtouris
            self.assertEqual(history.retrieve(i), None)
134 98093aac Stavros Sachtouris
        for i in range(1, len(sample_history)):
135 98093aac Stavros Sachtouris
            self.assertEqual(history.retrieve(i), sample_history[i - 1])
136 98093aac Stavros Sachtouris
            self.assertEqual(history.retrieve(- i), sample_history[- i - 1])
137 98093aac Stavros Sachtouris
138 98093aac Stavros Sachtouris
139 4769da6b Stavros Sachtouris
class LoggerMethods(TestCase):
140 4769da6b Stavros Sachtouris
141 4769da6b Stavros Sachtouris
    class PseudoLogger(object):
142 4769da6b Stavros Sachtouris
        level = 'some level'
143 4769da6b Stavros Sachtouris
        _setLevel_calls = []
144 4769da6b Stavros Sachtouris
        _addHandler_calls = []
145 4769da6b Stavros Sachtouris
146 4769da6b Stavros Sachtouris
        def setLevel(self, *args):
147 4769da6b Stavros Sachtouris
            self._setLevel_calls.append(args)
148 4769da6b Stavros Sachtouris
149 4769da6b Stavros Sachtouris
        def addHandler(self, *args):
150 4769da6b Stavros Sachtouris
            self._addHandler_calls.append(args)
151 4769da6b Stavros Sachtouris
152 4769da6b Stavros Sachtouris
    class PseudoHandler(object):
153 4769da6b Stavros Sachtouris
        _setFormatter_calls = []
154 4769da6b Stavros Sachtouris
155 4769da6b Stavros Sachtouris
        def setFormatter(self, *args):
156 4769da6b Stavros Sachtouris
            self._setFormatter_calls.append(args)
157 4769da6b Stavros Sachtouris
158 4769da6b Stavros Sachtouris
    def setUp(self):
159 4769da6b Stavros Sachtouris
        from kamaki.cli.logger import LOG_FILE, _blacklist
160 4769da6b Stavros Sachtouris
        self.LF, self.BL = list(LOG_FILE), dict(_blacklist)
161 4769da6b Stavros Sachtouris
162 4769da6b Stavros Sachtouris
    def tearDown(self):
163 4769da6b Stavros Sachtouris
        self.PseudoLogger._setLevel_calls = []
164 4769da6b Stavros Sachtouris
        self.PseudoLogger._addHandler_calls = []
165 4769da6b Stavros Sachtouris
        self.PseudoLogger._setFormatter_calls = []
166 4769da6b Stavros Sachtouris
        from kamaki.cli.logger import LOG_FILE, _blacklist
167 4769da6b Stavros Sachtouris
        for e in LOG_FILE:
168 4769da6b Stavros Sachtouris
            LOG_FILE.pop()
169 4769da6b Stavros Sachtouris
        for e in self.LF:
170 4769da6b Stavros Sachtouris
            LOG_FILE.append(e)
171 4769da6b Stavros Sachtouris
        _blacklist.clear()
172 4769da6b Stavros Sachtouris
        _blacklist.update(self.BL)
173 4769da6b Stavros Sachtouris
174 4769da6b Stavros Sachtouris
    @patch('kamaki.cli.logger.logging.getLogger', return_value=PseudoLogger())
175 4769da6b Stavros Sachtouris
    def test_deactivate(self, GL):
176 4769da6b Stavros Sachtouris
        from kamaki.cli.logger import deactivate, _blacklist
177 4769da6b Stavros Sachtouris
        self.assertEqual(_blacklist, {})
178 4769da6b Stavros Sachtouris
        deactivate('some logger')
179 4769da6b Stavros Sachtouris
        GL.assert_called_once_with('some logger')
180 4769da6b Stavros Sachtouris
        self.assertEqual(
181 4769da6b Stavros Sachtouris
            _blacklist.get('some logger', None), self.PseudoLogger.level)
182 4769da6b Stavros Sachtouris
        from logging import CRITICAL
183 4769da6b Stavros Sachtouris
        self.assertEqual(self.PseudoLogger._setLevel_calls[-1], (CRITICAL, ))
184 4769da6b Stavros Sachtouris
185 4769da6b Stavros Sachtouris
    @patch('kamaki.cli.logger.logging.getLogger', return_value=PseudoLogger())
186 4769da6b Stavros Sachtouris
    def test_activate(self, GL):
187 4769da6b Stavros Sachtouris
        from kamaki.cli.logger import activate
188 4769da6b Stavros Sachtouris
        activate('another logger')
189 4769da6b Stavros Sachtouris
        GL.assert_called_once_with('another logger')
190 4769da6b Stavros Sachtouris
        self.assertEqual(
191 4769da6b Stavros Sachtouris
            self.PseudoLogger._setLevel_calls[-1], (self.PseudoLogger.level, ))
192 4769da6b Stavros Sachtouris
193 4769da6b Stavros Sachtouris
    def test_get_log_filename(self):
194 4769da6b Stavros Sachtouris
        from kamaki.cli.logger import get_log_filename, LOG_FILE
195 4769da6b Stavros Sachtouris
        f = NamedTemporaryFile()
196 4769da6b Stavros Sachtouris
        for e in LOG_FILE:
197 4769da6b Stavros Sachtouris
            LOG_FILE.pop()
198 4769da6b Stavros Sachtouris
        LOG_FILE.append(f.name)
199 4769da6b Stavros Sachtouris
        self.assertEqual(get_log_filename(), f.name)
200 4769da6b Stavros Sachtouris
        LOG_FILE.pop()
201 4769da6b Stavros Sachtouris
        LOG_FILE.append(2 * f.name)
202 4769da6b Stavros Sachtouris
        print('\n  Should print error msg here: ')
203 4769da6b Stavros Sachtouris
        self.assertEqual(get_log_filename(), None)
204 4769da6b Stavros Sachtouris
205 4769da6b Stavros Sachtouris
    def test_set_log_filename(self):
206 4769da6b Stavros Sachtouris
        from kamaki.cli.logger import set_log_filename, LOG_FILE
207 4769da6b Stavros Sachtouris
        for n in ('some name', 'some other name'):
208 4769da6b Stavros Sachtouris
            set_log_filename(n)
209 4769da6b Stavros Sachtouris
            self.assertEqual(LOG_FILE[0], n)
210 4769da6b Stavros Sachtouris
211 4769da6b Stavros Sachtouris
    @patch('kamaki.cli.logger.get_logger', return_value=PseudoLogger())
212 4769da6b Stavros Sachtouris
    @patch('kamaki.cli.logger.logging.Formatter', return_value='f0rm4t')
213 4769da6b Stavros Sachtouris
    @patch(
214 4769da6b Stavros Sachtouris
        'kamaki.cli.logger.logging.StreamHandler',
215 4769da6b Stavros Sachtouris
        return_value=PseudoHandler())
216 4769da6b Stavros Sachtouris
    @patch(
217 4769da6b Stavros Sachtouris
        'kamaki.cli.logger.logging.FileHandler',
218 4769da6b Stavros Sachtouris
        return_value=PseudoHandler())
219 4769da6b Stavros Sachtouris
    def test__add_logger(self, FH, SH, F, GL):
220 4769da6b Stavros Sachtouris
        from kamaki.cli.logger import _add_logger
221 4769da6b Stavros Sachtouris
        from logging import DEBUG
222 4769da6b Stavros Sachtouris
        stdf, cnt = '%(name)s\n %(message)s', 0
223 4769da6b Stavros Sachtouris
        for name, level, filename, fmt in product(
224 4769da6b Stavros Sachtouris
                ('my logger', ),
225 4769da6b Stavros Sachtouris
                ('my level', None),
226 4769da6b Stavros Sachtouris
                ('my filename', None),
227 4769da6b Stavros Sachtouris
                ('my fmt', None)):
228 4769da6b Stavros Sachtouris
            log = _add_logger(name, level, filename, fmt)
229 4769da6b Stavros Sachtouris
            self.assertTrue(isinstance(log, self.PseudoLogger))
230 4769da6b Stavros Sachtouris
            self.assertEqual(GL.mock_calls[-1], call(name))
231 4769da6b Stavros Sachtouris
            if filename:
232 4769da6b Stavros Sachtouris
                self.assertEqual(FH.mock_calls[-1], call(filename))
233 4769da6b Stavros Sachtouris
            else:
234 4769da6b Stavros Sachtouris
                self.assertEqual(SH.mock_calls[-1], call())
235 4769da6b Stavros Sachtouris
            self.assertEqual(F.mock_calls[-1], call(fmt or stdf))
236 4769da6b Stavros Sachtouris
            self.assertEqual(
237 4769da6b Stavros Sachtouris
                self.PseudoHandler._setFormatter_calls[-1], ('f0rm4t', ))
238 4769da6b Stavros Sachtouris
            cnt += 1
239 4769da6b Stavros Sachtouris
            self.assertEqual(len(self.PseudoLogger._addHandler_calls), cnt)
240 4769da6b Stavros Sachtouris
            h = self.PseudoLogger._addHandler_calls[-1]
241 4769da6b Stavros Sachtouris
            self.assertTrue(isinstance(h[0], self.PseudoHandler))
242 4769da6b Stavros Sachtouris
            l = self.PseudoLogger._setLevel_calls[-1]
243 4769da6b Stavros Sachtouris
            self.assertEqual(l, (level or DEBUG, ))
244 4769da6b Stavros Sachtouris
245 4769da6b Stavros Sachtouris
    @patch('kamaki.cli.logger.get_log_filename', return_value='my log fname')
246 4769da6b Stavros Sachtouris
    @patch('kamaki.cli.logger.get_logger', return_value='my get logger ret')
247 4769da6b Stavros Sachtouris
    def test_add_file_logger(self, GL, GLF):
248 4769da6b Stavros Sachtouris
        from kamaki.cli.logger import add_file_logger
249 4769da6b Stavros Sachtouris
        with patch('kamaki.cli.logger._add_logger', return_value='AL') as AL:
250 4769da6b Stavros Sachtouris
            GLFcount = GLF.call_count
251 4769da6b Stavros Sachtouris
            for name, level, filename in product(
252 4769da6b Stavros Sachtouris
                    ('my name'), ('my level', None), ('my filename', None)):
253 4769da6b Stavros Sachtouris
                self.assertEqual(add_file_logger(name, level, filename), 'AL')
254 4769da6b Stavros Sachtouris
                self.assertEqual(AL.mock_calls[-1], call(
255 4769da6b Stavros Sachtouris
                    name, level, filename or 'my log fname',
256 4769da6b Stavros Sachtouris
                    fmt='%(name)s(%(levelname)s) %(asctime)s\n\t%(message)s'))
257 4769da6b Stavros Sachtouris
                if filename:
258 4769da6b Stavros Sachtouris
                    self.assertEqual(GLFcount, GLF.call_count)
259 4769da6b Stavros Sachtouris
                else:
260 4769da6b Stavros Sachtouris
                    GLFcount = GLF.call_count
261 4769da6b Stavros Sachtouris
                    self.assertEqual(GLF.mock_calls[-1], call())
262 4769da6b Stavros Sachtouris
        with patch('kamaki.cli.logger._add_logger', side_effect=Exception):
263 4769da6b Stavros Sachtouris
            self.assertEqual(add_file_logger('X'), 'my get logger ret')
264 4769da6b Stavros Sachtouris
            GL.assert_called_once_with('X')
265 4769da6b Stavros Sachtouris
266 4769da6b Stavros Sachtouris
    @patch('kamaki.cli.logger.get_logger', return_value='my get logger ret')
267 4769da6b Stavros Sachtouris
    def test_add_stream_logger(self, GL):
268 4769da6b Stavros Sachtouris
        from kamaki.cli.logger import add_stream_logger
269 4769da6b Stavros Sachtouris
        with patch('kamaki.cli.logger._add_logger', return_value='AL') as AL:
270 4769da6b Stavros Sachtouris
            for name, level, fmt in product(
271 4769da6b Stavros Sachtouris
                    ('my name'), ('my level', None), ('my fmt', None)):
272 4769da6b Stavros Sachtouris
                self.assertEqual(add_stream_logger(name, level, fmt), 'AL')
273 4769da6b Stavros Sachtouris
                self.assertEqual(AL.mock_calls[-1], call(name, level, fmt=fmt))
274 4769da6b Stavros Sachtouris
        with patch('kamaki.cli.logger._add_logger', side_effect=Exception):
275 4769da6b Stavros Sachtouris
            self.assertEqual(add_stream_logger('X'), 'my get logger ret')
276 4769da6b Stavros Sachtouris
            GL.assert_called_once_with('X')
277 4769da6b Stavros Sachtouris
278 4769da6b Stavros Sachtouris
    @patch('kamaki.cli.logger.logging.getLogger', return_value=PseudoLogger())
279 4769da6b Stavros Sachtouris
    def test_get_logger(self, GL):
280 4769da6b Stavros Sachtouris
        from kamaki.cli.logger import get_logger
281 4769da6b Stavros Sachtouris
        get_logger('my logger name')
282 4769da6b Stavros Sachtouris
        GL.assert_called_once_with('my logger name')
283 4769da6b Stavros Sachtouris
284 4769da6b Stavros Sachtouris
285 f10cef01 Stavros Sachtouris
_RET = None
286 f10cef01 Stavros Sachtouris
287 f10cef01 Stavros Sachtouris
288 f10cef01 Stavros Sachtouris
class PseudoException(object):
289 f10cef01 Stavros Sachtouris
290 f10cef01 Stavros Sachtouris
    def __init__(self, *args):
291 f10cef01 Stavros Sachtouris
        global _RET
292 f10cef01 Stavros Sachtouris
        _RET = args
293 f10cef01 Stavros Sachtouris
294 f10cef01 Stavros Sachtouris
295 f10cef01 Stavros Sachtouris
class CLIError(TestCase):
296 f10cef01 Stavros Sachtouris
297 f10cef01 Stavros Sachtouris
    @patch('__builtin__.super', return_value=PseudoException())
298 f10cef01 Stavros Sachtouris
    def test___init__(self, S):
299 f10cef01 Stavros Sachtouris
        from kamaki.cli.errors import CLIError
300 f10cef01 Stavros Sachtouris
        global _RET
301 f10cef01 Stavros Sachtouris
        for message, details, importance in (
302 f10cef01 Stavros Sachtouris
                ('some msg', [], 0),
303 f10cef01 Stavros Sachtouris
                ('some msg\n', 'details', 0),
304 f10cef01 Stavros Sachtouris
                ('some msg', ['details1', 'details2'], 10)):
305 f10cef01 Stavros Sachtouris
            clie = CLIError(message, details, importance)
306 f10cef01 Stavros Sachtouris
            self.assertEqual(S.mock_calls[-1], call(CLIError, clie))
307 f10cef01 Stavros Sachtouris
            self.assertEqual(_RET[0], (message + '\n') if (
308 f10cef01 Stavros Sachtouris
                message and not message.endswith('\n')) else message)
309 f10cef01 Stavros Sachtouris
            self.assertEqual(clie.details, (list(details) if (
310 f10cef01 Stavros Sachtouris
                isinstance(details, list)) else ['%s' % details]) if (
311 f10cef01 Stavros Sachtouris
                    details) else [])
312 f10cef01 Stavros Sachtouris
            self.assertEqual(clie.importance, int(importance))
313 f10cef01 Stavros Sachtouris
        clie = CLIError(message, details, 'non int')
314 f10cef01 Stavros Sachtouris
        self.assertEqual(clie.importance, 0)
315 f10cef01 Stavros Sachtouris
316 cfebddb5 Stavros Sachtouris
    def test_raiseCLIError(self):
317 cfebddb5 Stavros Sachtouris
        from kamaki.cli.errors import raiseCLIError, CLIError
318 cfebddb5 Stavros Sachtouris
        for err, message, importance, details in (
319 cfebddb5 Stavros Sachtouris
                (Exception('msg'), '', 0, []),
320 cfebddb5 Stavros Sachtouris
                (Exception('msg'), 'orther msg', 0, []),
321 cfebddb5 Stavros Sachtouris
                (Exception('msg'), 'orther msg', 0, ['d1', 'd2']),
322 cfebddb5 Stavros Sachtouris
                (Exception('msg'), '', 10, []),
323 cfebddb5 Stavros Sachtouris
                (Exception('msg'), '', None, []),
324 cfebddb5 Stavros Sachtouris
                (CLIError('some msg'), '', None, ['d1', 'd2'])
325 cfebddb5 Stavros Sachtouris
            ):
326 cfebddb5 Stavros Sachtouris
            try:
327 cfebddb5 Stavros Sachtouris
                raiseCLIError(err, message, importance, details)
328 cfebddb5 Stavros Sachtouris
            except CLIError as clie:
329 cfebddb5 Stavros Sachtouris
                exp_msg = '%s' % (message or err)
330 cfebddb5 Stavros Sachtouris
                exp_msg += '' if exp_msg.endswith('\n') else '\n'
331 cfebddb5 Stavros Sachtouris
                self.assertEqual('%s' % clie, exp_msg)
332 cfebddb5 Stavros Sachtouris
                self.assertEqual(clie.importance, importance or 0)
333 cfebddb5 Stavros Sachtouris
                exp_d = list(details) if isinstance(details, list) else [
334 cfebddb5 Stavros Sachtouris
                    '%s' % (details or '')]
335 cfebddb5 Stavros Sachtouris
                base_msg = '%s' % err
336 cfebddb5 Stavros Sachtouris
                if message and base_msg != message:
337 cfebddb5 Stavros Sachtouris
                    exp_d.append(base_msg)
338 cfebddb5 Stavros Sachtouris
                self.assertEqual(clie.details, exp_d)
339 cfebddb5 Stavros Sachtouris
340 f10cef01 Stavros Sachtouris
341 f10cef01 Stavros Sachtouris
class CLIUnimplemented(TestCase):
342 f10cef01 Stavros Sachtouris
343 f10cef01 Stavros Sachtouris
    def test___init__(self):
344 f10cef01 Stavros Sachtouris
        from kamaki.cli.errors import CLIUnimplemented
345 f10cef01 Stavros Sachtouris
        cliu = CLIUnimplemented()
346 f10cef01 Stavros Sachtouris
        self.assertEqual(
347 f10cef01 Stavros Sachtouris
            '%s' % cliu,
348 f10cef01 Stavros Sachtouris
            'I \'M SORRY, DAVE.\nI \'M AFRAID I CAN\'T DO THAT.\n')
349 f10cef01 Stavros Sachtouris
        self.assertEqual(cliu.details, [
350 f10cef01 Stavros Sachtouris
            '      _        |',
351 f10cef01 Stavros Sachtouris
            '   _-- --_     |',
352 f10cef01 Stavros Sachtouris
            '  --     --    |',
353 f10cef01 Stavros Sachtouris
            ' --   .   --   |',
354 f10cef01 Stavros Sachtouris
            ' -_       _-   |',
355 f10cef01 Stavros Sachtouris
            '   -_   _-     |',
356 f10cef01 Stavros Sachtouris
            '      -        |'])
357 f10cef01 Stavros Sachtouris
        self.assertEqual(cliu.importance, 3)
358 f10cef01 Stavros Sachtouris
359 f10cef01 Stavros Sachtouris
360 f10cef01 Stavros Sachtouris
class CLIBaseUrlError(TestCase):
361 f10cef01 Stavros Sachtouris
362 f10cef01 Stavros Sachtouris
    def test___init__(self):
363 f10cef01 Stavros Sachtouris
        from kamaki.cli.errors import CLIBaseUrlError
364 f10cef01 Stavros Sachtouris
        for service in ('', 'some service'):
365 f10cef01 Stavros Sachtouris
            clibue = CLIBaseUrlError(service=service)
366 f10cef01 Stavros Sachtouris
            self.assertEqual('%s' % clibue, 'No URL for %s\n' % service)
367 f10cef01 Stavros Sachtouris
            self.assertEqual(clibue.details, [
368 f10cef01 Stavros Sachtouris
                'Two ways to resolve this:',
369 f10cef01 Stavros Sachtouris
                '(Use the correct cloud name, instead of "default")',
370 f10cef01 Stavros Sachtouris
                'A. (recommended) Let kamaki discover endpoint URLs for all',
371 f10cef01 Stavros Sachtouris
                'services by setting a single Authentication URL and token:',
372 f10cef01 Stavros Sachtouris
                '  /config set cloud.default.url <AUTH_URL>',
373 f10cef01 Stavros Sachtouris
                '  /config set cloud.default.token <t0k3n>',
374 f10cef01 Stavros Sachtouris
                'B. (advanced users) Explicitly set an %s endpoint URL' % (
375 f10cef01 Stavros Sachtouris
                    service.upper()),
376 f10cef01 Stavros Sachtouris
                'Note: URL option has a higher priority, so delete it to',
377 f10cef01 Stavros Sachtouris
                'make that work',
378 f10cef01 Stavros Sachtouris
                '  /config delete cloud.default.url',
379 f10cef01 Stavros Sachtouris
                '  /config set cloud.%s.url <%s_URL>' % (
380 f10cef01 Stavros Sachtouris
                    service, service.upper())])
381 f10cef01 Stavros Sachtouris
            self.assertEqual(clibue.importance, 2)
382 f10cef01 Stavros Sachtouris
383 f10cef01 Stavros Sachtouris
384 f10cef01 Stavros Sachtouris
class CLISyntaxError(TestCase):
385 f10cef01 Stavros Sachtouris
386 f10cef01 Stavros Sachtouris
    def test___init__(self):
387 f10cef01 Stavros Sachtouris
        from kamaki.cli.errors import CLISyntaxError
388 f10cef01 Stavros Sachtouris
        clise = CLISyntaxError()
389 f10cef01 Stavros Sachtouris
        self.assertEqual('%s' % clise, 'Syntax Error\n')
390 f10cef01 Stavros Sachtouris
        self.assertEqual(clise.details, [])
391 f10cef01 Stavros Sachtouris
        self.assertEqual(clise.importance, 1)
392 f10cef01 Stavros Sachtouris
393 f10cef01 Stavros Sachtouris
394 8694bdad Stavros Sachtouris
class CLIInvalidArgument(TestCase):
395 8694bdad Stavros Sachtouris
396 8694bdad Stavros Sachtouris
    def test___init__(self):
397 8694bdad Stavros Sachtouris
        from kamaki.cli.errors import CLIInvalidArgument
398 8694bdad Stavros Sachtouris
        cliia = CLIInvalidArgument()
399 8694bdad Stavros Sachtouris
        self.assertEqual('%s' % cliia, 'Invalid Argument\n')
400 8694bdad Stavros Sachtouris
        self.assertEqual(cliia.details, [])
401 8694bdad Stavros Sachtouris
        self.assertEqual(cliia.importance, 1)
402 8694bdad Stavros Sachtouris
403 8694bdad Stavros Sachtouris
404 f10cef01 Stavros Sachtouris
class CLIUnknownCommand(TestCase):
405 f10cef01 Stavros Sachtouris
406 f10cef01 Stavros Sachtouris
    def test___init__(self):
407 f10cef01 Stavros Sachtouris
        from kamaki.cli.errors import CLIUnknownCommand
408 f10cef01 Stavros Sachtouris
        cliec = CLIUnknownCommand()
409 f10cef01 Stavros Sachtouris
        self.assertEqual('%s' % cliec, 'Unknown Command\n')
410 f10cef01 Stavros Sachtouris
        self.assertEqual(cliec.details, [])
411 f10cef01 Stavros Sachtouris
        self.assertEqual(cliec.importance, 1)
412 f10cef01 Stavros Sachtouris
413 f10cef01 Stavros Sachtouris
414 f10cef01 Stavros Sachtouris
class CLICmdSpecError(TestCase):
415 f10cef01 Stavros Sachtouris
416 f10cef01 Stavros Sachtouris
    def test___init__(self):
417 f10cef01 Stavros Sachtouris
        from kamaki.cli.errors import CLICmdSpecError
418 f10cef01 Stavros Sachtouris
        clicse = CLICmdSpecError()
419 f10cef01 Stavros Sachtouris
        self.assertEqual('%s' % clicse, 'Command Specification Error\n')
420 f10cef01 Stavros Sachtouris
        self.assertEqual(clicse.details, [])
421 f10cef01 Stavros Sachtouris
        self.assertEqual(clicse.importance, 0)
422 f10cef01 Stavros Sachtouris
423 f10cef01 Stavros Sachtouris
424 2fde8651 Stavros Sachtouris
#  TestCase auxiliary methods
425 2fde8651 Stavros Sachtouris
426 2fde8651 Stavros Sachtouris
def runTestCase(cls, test_name, args=[], failure_collector=[]):
427 2fde8651 Stavros Sachtouris
    """
428 2fde8651 Stavros Sachtouris
    :param cls: (TestCase) a set of Tests
429 2fde8651 Stavros Sachtouris

430 2fde8651 Stavros Sachtouris
    :param test_name: (str)
431 2fde8651 Stavros Sachtouris

432 2fde8651 Stavros Sachtouris
    :param args: (list) these are prefixed with test_ and used as params when
433 2fde8651 Stavros Sachtouris
        instantiating cls
434 2fde8651 Stavros Sachtouris

435 2fde8651 Stavros Sachtouris
    :param failure_collector: (list) collects info of test failures
436 2fde8651 Stavros Sachtouris

437 2fde8651 Stavros Sachtouris
    :returns: (int) total # of run tests
438 2fde8651 Stavros Sachtouris
    """
439 2fde8651 Stavros Sachtouris
    suite = TestSuite()
440 2fde8651 Stavros Sachtouris
    if args:
441 2fde8651 Stavros Sachtouris
        suite.addTest(cls('_'.join(['test'] + args)))
442 2fde8651 Stavros Sachtouris
    else:
443 2fde8651 Stavros Sachtouris
        suite.addTest(makeSuite(cls))
444 2fde8651 Stavros Sachtouris
    print('* Test * %s *' % test_name)
445 2fde8651 Stavros Sachtouris
    r = TextTestRunner(verbosity=2).run(suite)
446 2fde8651 Stavros Sachtouris
    failure_collector += r.failures
447 2fde8651 Stavros Sachtouris
    return r.testsRun
448 2fde8651 Stavros Sachtouris
449 2fde8651 Stavros Sachtouris
450 2fde8651 Stavros Sachtouris
def get_test_classes(module=__import__(__name__), name=''):
451 2fde8651 Stavros Sachtouris
    module_stack = [module]
452 2fde8651 Stavros Sachtouris
    while module_stack:
453 2fde8651 Stavros Sachtouris
        module = module_stack[-1]
454 2fde8651 Stavros Sachtouris
        module_stack = module_stack[:-1]
455 2fde8651 Stavros Sachtouris
        for objname, obj in getmembers(module):
456 2fde8651 Stavros Sachtouris
            if (objname == name or not name):
457 2fde8651 Stavros Sachtouris
                if isclass(obj) and objname != 'TestCase' and (
458 2fde8651 Stavros Sachtouris
                        issubclass(obj, TestCase)):
459 2fde8651 Stavros Sachtouris
                    yield (obj, objname)
460 2fde8651 Stavros Sachtouris
461 2fde8651 Stavros Sachtouris
462 2fde8651 Stavros Sachtouris
def main(argv):
463 2fde8651 Stavros Sachtouris
    found = False
464 2fde8651 Stavros Sachtouris
    failure_collector = list()
465 2fde8651 Stavros Sachtouris
    num_of_tests = 0
466 2fde8651 Stavros Sachtouris
    for cls, name in get_test_classes(name=argv[1] if len(argv) > 1 else ''):
467 2fde8651 Stavros Sachtouris
        found = True
468 2fde8651 Stavros Sachtouris
        num_of_tests += runTestCase(cls, name, argv[2:], failure_collector)
469 2fde8651 Stavros Sachtouris
    if not found:
470 2fde8651 Stavros Sachtouris
        print('Test "%s" not found' % ' '.join(argv[1:]))
471 2fde8651 Stavros Sachtouris
    else:
472 2fde8651 Stavros Sachtouris
        for i, failure in enumerate(failure_collector):
473 2fde8651 Stavros Sachtouris
            print('Failure %s: ' % (i + 1))
474 2fde8651 Stavros Sachtouris
            for field in failure:
475 2fde8651 Stavros Sachtouris
                print('\t%s' % field)
476 2fde8651 Stavros Sachtouris
        print('\nTotal tests run: %s' % num_of_tests)
477 2fde8651 Stavros Sachtouris
        print('Total failures: %s' % len(failure_collector))
478 2fde8651 Stavros Sachtouris
479 2fde8651 Stavros Sachtouris
480 2fde8651 Stavros Sachtouris
if __name__ == '__main__':
481 2fde8651 Stavros Sachtouris
    from sys import argv
482 2fde8651 Stavros Sachtouris
    main(argv)