Revision fa9c0c38 kamaki/cli/utils/test.py

b/kamaki/cli/utils/test.py
35 35
from tempfile import NamedTemporaryFile
36 36
from mock import patch, call
37 37
from itertools import product
38
from io import StringIO
38 39

  
39 40

  
40 41
class UtilsMethods(TestCase):
......
64 65
                self.assertRaises(AssertionError, guess_mime_type, *args)
65 66

  
66 67
    @patch('kamaki.cli.utils.dumps', return_value='(dumps output)')
67
    @patch('kamaki.cli.utils._print')
68
    def test_print_json(self, PR, JD):
68
    def test_print_json(self, JD):
69 69
        from kamaki.cli.utils import print_json, INDENT_TAB
70
        print_json('some data')
70
        out = StringIO()
71
        print_json('some data', out)
71 72
        JD.assert_called_once_with('some data', indent=INDENT_TAB)
72
        PR.assert_called_once_with('(dumps output)')
73
        self.assertEqual(out.getvalue(), u'(dumps output)\n')
73 74

  
74
    @patch('kamaki.cli.utils._print')
75
    def test_print_dict(self, PR):
75
    def test_print_dict(self):
76 76
        from kamaki.cli.utils import print_dict, INDENT_TAB
77
        call_counter = 0
77
        out = StringIO()
78 78
        self.assertRaises(AssertionError, print_dict, 'non-dict think')
79 79
        self.assertRaises(AssertionError, print_dict, {}, indent=-10)
80 80
        for args in product(
......
104 104
            with patch('kamaki.cli.utils.print_dict') as PD:
105 105
                with patch('kamaki.cli.utils.print_list') as PL:
106 106
                    pd_calls, pl_calls = 0, 0
107
                    print_dict(*args)
108
                    exp_calls = []
107
                    print_dict(*args, out=out)
108
                    exp_calls = u''
109 109
                    for i, (k, v) in enumerate(d.items()):
110 110
                        if k in exclude:
111 111
                            continue
112
                        str_k = ' ' * indent
113
                        str_k += '%s.' % (i + 1) if with_enumeration else ''
114
                        str_k += '%s:' % k
112
                        str_k = u' ' * indent
113
                        str_k += u'%s.' % (i + 1) if with_enumeration else u''
114
                        str_k += u'%s:' % k
115 115
                        if isinstance(v, dict):
116 116
                            self.assertEqual(
117 117
                                PD.mock_calls[pd_calls],
......
120 120
                                    exclude,
121 121
                                    indent + INDENT_TAB,
122 122
                                    recursive_enumeration,
123
                                    recursive_enumeration))
123
                                    recursive_enumeration,
124
                                    out))
124 125
                            pd_calls += 1
125
                            exp_calls.append(call(str_k))
126
                            exp_calls += str_k + '\n'
126 127
                        elif isinstance(v, list) or isinstance(v, tuple):
127 128
                            self.assertEqual(
128 129
                                PL.mock_calls[pl_calls],
......
131 132
                                    exclude,
132 133
                                    indent + INDENT_TAB,
133 134
                                    recursive_enumeration,
134
                                    recursive_enumeration))
135
                                    recursive_enumeration,
136
                                    out))
135 137
                            pl_calls += 1
136
                            exp_calls.append(call(str_k))
138
                            exp_calls += str_k + '\n'
137 139
                        else:
138
                            exp_calls.append(call('%s %s' % (str_k, v)))
139
                    real_calls = PR.mock_calls[call_counter:]
140
                    call_counter = len(PR.mock_calls)
141
                    self.assertEqual(sorted(real_calls), sorted(exp_calls))
140
                            exp_calls += u'%s %s\n' % (str_k, v)
141
                    self.assertEqual(exp_calls, out.getvalue())
142
                    out = StringIO()
142 143

  
143
    @patch('kamaki.cli.utils._print')
144
    def test_print_list(self, PR):
144
    def test_print_list(self):
145 145
        from kamaki.cli.utils import print_list, INDENT_TAB
146
        call_counter = 0
146
        out = StringIO()
147 147
        self.assertRaises(AssertionError, print_list, 'non-list non-tuple')
148 148
        self.assertRaises(AssertionError, print_list, {}, indent=-10)
149 149
        for args in product(
......
159 159
            with patch('kamaki.cli.utils.print_dict') as PD:
160 160
                with patch('kamaki.cli.utils.print_list') as PL:
161 161
                    pd_calls, pl_calls = 0, 0
162
                    print_list(*args)
163
                    exp_calls = []
162
                    print_list(*args, out=out)
163
                    exp_calls = ''
164 164
                    for i, v in enumerate(l):
165
                        str_v = ' ' * indent
166
                        str_v += '%s.' % (i + 1) if with_enumeration else ''
165
                        str_v = u' ' * indent
166
                        str_v += u'%s.' % (i + 1) if with_enumeration else u''
167 167
                        if isinstance(v, dict):
168 168
                            if with_enumeration:
169
                                exp_calls.append(call(str_v))
169
                                exp_calls += str_v + '\n'
170 170
                            elif i and i < len(l):
171
                                exp_calls.append(call())
171
                                exp_calls += u'\n'
172 172
                            self.assertEqual(
173 173
                                PD.mock_calls[pd_calls],
174 174
                                call(
......
177 177
                                    indent + (
178 178
                                        INDENT_TAB if with_enumeration else 0),
179 179
                                    recursive_enumeration,
180
                                    recursive_enumeration))
180
                                    recursive_enumeration,
181
                                    out))
181 182
                            pd_calls += 1
182 183
                        elif isinstance(v, list) or isinstance(v, tuple):
183 184
                            if with_enumeration:
184
                                exp_calls.append(call(str_v))
185
                                exp_calls += str_v + '\n'
185 186
                            elif i and i < len(l):
186
                                exp_calls.append(call())
187
                                exp_calls += u'\n'
187 188
                            self.assertEqual(
188 189
                                PL.mock_calls[pl_calls],
189 190
                                call(
......
191 192
                                    exclude,
192 193
                                    indent + INDENT_TAB,
193 194
                                    recursive_enumeration,
194
                                    recursive_enumeration))
195
                                    recursive_enumeration,
196
                                    out))
195 197
                            pl_calls += 1
196 198
                        elif ('%s' % v) in exclude:
197 199
                            continue
198 200
                        else:
199
                            exp_calls.append(call('%s%s' % (str_v, v)))
200
                    real_calls = PR.mock_calls[call_counter:]
201
                    call_counter = len(PR.mock_calls)
202
                    self.assertEqual(sorted(real_calls), sorted(exp_calls))
203

  
204
    @patch('__builtin__.raw_input')
205
    def test_page_hold(self, RI):
206
        from kamaki.cli.utils import page_hold
207
        ri_counter = 0
208
        for args, expected in (
209
                ((0, 0, 0), False),
210
                ((1, 3, 10), True),
211
                ((3, 3, 10), True),
212
                ((5, 3, 10), True),
213
                ((6, 3, 10), True),
214
                ((10, 3, 10), False),
215
                ((11, 3, 10), False)):
216
            self.assertEqual(page_hold(*args), expected)
217
            index, limit, maxlen = args
218
            if index and index < maxlen and index % limit == 0:
219
                self.assertEqual(ri_counter + 1, len(RI.mock_calls))
220
                self.assertEqual(RI.mock_calls[-1], call(
221
                    '(%s listed - %s more - "enter" to continue)' % (
222
                        index, maxlen - index)))
223
            else:
224
                self.assertEqual(ri_counter, len(RI.mock_calls))
225
            ri_counter = len(RI.mock_calls)
201
                            exp_calls += u'%s%s\n' % (str_v, v)
202
                    self.assertEqual(out.getvalue(), exp_calls)
203
                    out = StringIO()
226 204

  
227
    @patch('kamaki.cli.utils._print')
228
    @patch('kamaki.cli.utils._write')
229 205
    @patch('kamaki.cli.utils.print_dict')
230 206
    @patch('kamaki.cli.utils.print_list')
231
    @patch('kamaki.cli.utils.page_hold')
232 207
    @patch('kamaki.cli.utils.bold', return_value='bold')
233
    def test_print_items(self, bold, PH, PL, PD, WR, PR):
208
    def test_print_items(self, bold, PL, PD):
234 209
        from kamaki.cli.utils import print_items, INDENT_TAB
235 210
        for args in product(
236 211
                (
......
239 214
                    ({'k': 1, 'id': 2}, [5, 6, 7], (8, 9), '10')),
240 215
                (('id', 'name'), ('something', 2), ('lala', )),
241 216
                (False, True),
242
                (False, True),
243
                (0, 1, 2, 10)):
244
            items, title, with_enumeration, with_redundancy, page_size = args
245
            wr_counter, pr_counter = len(WR.mock_calls), len(PR.mock_calls)
217
                (False, True)):
218
            items, title, with_enumeration, with_redundancy = args
246 219
            pl_counter, pd_counter = len(PL.mock_calls), len(PD.mock_calls)
247
            bold_counter, ph_counter = len(bold.mock_calls), len(PH.mock_calls)
248
            print_items(*args)
220
            bold_counter, out_counter = len(bold.mock_calls), 0
221
            out = StringIO()
222
            print_items(*args, out=out)
223
            out.seek(0)
249 224
            if not (isinstance(items, dict) or isinstance(
250 225
                    items, list) or isinstance(items, tuple)):
251 226
                if items:
252
                    self.assertEqual(PR.mock_calls[-1], call('%s' % items))
227
                    self.assertEqual(out.getvalue(), '%s\n' % items)
253 228
            else:
254 229
                for i, item in enumerate(items):
255 230
                    if with_enumeration:
256
                        self.assertEqual(
257
                            WR.mock_calls[wr_counter],
258
                            call('%s. ' % (i + 1)))
259
                        wr_counter += 1
231
                        exp_str = '%s. ' % (i + 1)
232
                        self.assertEqual(out.read(len(exp_str)), exp_str)
260 233
                    if isinstance(item, dict):
261 234
                        title = sorted(set(title).intersection(item))
262 235
                        pick = item.get if with_redundancy else item.pop
263 236
                        header = ' '.join('%s' % pick(key) for key in title)
264 237
                        self.assertEqual(
265 238
                            bold.mock_calls[bold_counter], call(header))
266
                        self.assertEqual(
267
                            PR.mock_calls[pr_counter], call('bold'))
239
                        self.assertEqual(out.read(5), 'bold\n')
268 240
                        self.assertEqual(
269 241
                            PD.mock_calls[pd_counter],
270
                            call(item, indent=INDENT_TAB))
271
                        pr_counter += 1
242
                            call(item, indent=INDENT_TAB, out=out))
272 243
                        pd_counter += 1
273 244
                        bold_counter += 1
274 245
                    elif isinstance(item, list) or isinstance(item, tuple):
275 246
                        self.assertEqual(
276 247
                            PL.mock_calls[pl_counter],
277
                            call(item, indent=INDENT_TAB))
248
                            call(item, indent=INDENT_TAB, out=out))
278 249
                        pl_counter += 1
279 250
                    else:
280
                        self.assertEqual(
281
                            PR.mock_calls[pr_counter], call(' %s' % item))
282
                        pr_counter += 1
283
                    page_size = page_size if page_size > 0 else len(items)
284
                    self.assertEqual(
285
                        PH.mock_calls[ph_counter],
286
                        call(i + 1, page_size, len(items)))
287
                    ph_counter += 1
251
                        exp_str = u' %s\n' % item
252
                        self.assertEqual(out.read(len(exp_str)), exp_str)
288 253

  
289 254
    def test_format_size(self):
290 255
        from kamaki.cli.utils import format_size
......
426 391
                    'Is', 'this', 'a', 'parsed', 'string?'])):
427 392
            self.assertEqual(split_input(line), expected)
428 393

  
429
    @patch('kamaki.cli.utils._readline', return_value='read line')
430
    @patch('kamaki.cli.utils._flush')
431
    @patch('kamaki.cli.utils._write')
432
    def test_ask_user(self, WR, FL, RL):
394
    def test_ask_user(self):
433 395
        from kamaki.cli.utils import ask_user
434
        msg = 'some question'
435
        self.assertFalse(ask_user(msg))
436
        WR.assert_called_once_with('%s [y/N]: ' % msg)
437
        FL.assert_called_once_with()
438
        RL.assert_called_once_with()
439

  
440
        self.assertTrue(ask_user(msg, ('r', )))
441
        self.assertEqual(WR.mock_calls[-1], call('%s [r/N]: ' % msg))
442
        self.assertEqual(FL.mock_calls, 2 * [call()])
443
        self.assertEqual(RL.mock_calls, 2 * [call()])
396
        msg = u'some question'
397
        out = StringIO()
398
        user_in = StringIO(u'n')
399
        self.assertFalse(ask_user(msg, out=out, user_in=user_in))
400
        self.assertEqual(out.getvalue(), u'%s [y/N]: ' % msg)
444 401

  
445
        self.assertTrue(ask_user(msg, ('Z', 'r', 'k')))
446
        self.assertEqual(WR.mock_calls[-1], call('%s [Z, r, k/N]: ' % msg))
447
        self.assertEqual(FL.mock_calls, 3 * [call()])
448
        self.assertEqual(RL.mock_calls, 3 * [call()])
402
        user_in.seek(0)
403
        out.seek(0)
404
        self.assertTrue(ask_user(msg, ('n', ), out=out, user_in=user_in))
405
        self.assertEqual(out.getvalue(), u'%s [n/<not n>]: ' % msg)
449 406

  
450
    @patch('kamaki.cli.utils._flush')
451
    @patch('kamaki.cli.utils._write')
452
    def test_spiner(self, WR, FL):
453
        from kamaki.cli.utils import spiner
454
        spins = ('/', '-', '\\', '|')
455
        prev = 1
456
        for i, SP in enumerate(spiner(6)):
457
            if not i:
458
                self.assertEqual(WR.mock_calls[-2], call(' '))
459
            elif i > 5:
460
                break
461
            self.assertEqual(SP, None)
462
            self.assertEqual(WR.mock_calls[-1], call('\b%s' % spins[i % 4]))
463
            self.assertEqual(FL.mock_calls, prev * [call()])
464
            prev += 1
407
        user_in = StringIO(unicode('N'))
408
        out.seek(0)
409
        self.assertTrue(ask_user(msg, ('r', 'N'), out=out, user_in=user_in))
410
        self.assertEqual(out.getvalue(), u'%s [r, N/<not r, N>]: ' % msg)
465 411

  
466 412
    def test_remove_from_items(self):
467 413
        from kamaki.cli.utils import remove_from_items

Also available in: Unified diff