~mvo/ubuntu-sso-client/strawman-lp711413

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
# -*- coding: utf-8 -*-
#
# Copyright 2012 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.
"""Test the proxy UI."""

import qt4reactor

from PyQt4.QtCore import QObject, pyqtSignal
from twisted.internet import defer, reactor
from twisted.trial.unittest import TestCase

from ubuntu_sso.qt import proxy_dialog

# pylint: disable=E1101,W0212,


class FakeSignal(object):
    """A fake qt signal."""

    def __init__(self):
        """Create a new instance."""
        self.called = []

    def connect(self, cb):
        """Connect signals."""
        self.called.append(('connect', cb))


class FakeWidget(object):
    """A fake widget that contains text."""

    def __init__(self, object_name, called, text=''):
        """Create a new instance."""
        self.object_name = object_name
        self.called = called
        self.internal_text = text
        self.clicked = FakeSignal()

    # pylint: disable=C0103
    def setText(self, text):
        """Set the text of the widget."""
        self.internal_text = text
        if not self.object_name in self.called:
            self.called[self.object_name] = [('setText', text)]
        else:
            self.called[self.object_name].append(('setText', text))

    def text(self):
        """Return the text."""
        if not self.object_name in self.called:
            self.called[self.object_name] = [('text',)]
        else:
            self.called[self.object_name].append(('text',))
        return self.internal_text

    def setPixmap(self, pixmap):
        """Set a pixmap."""
        if not self.object_name in self.called:
            self.called[self.object_name] = [('setPixmap', pixmap)]
        else:
            self.called[self.object_name].append(('setPixmap', pixmap))

    def setVisible(self, visible):
        """Set the ui element visible."""
        if not self.object_name in self.called:
            self.called[self.object_name] = [('setVisible', visible)]
        else:
            self.called[self.object_name].append(('setVisible', visible))

    # pylint: enable=C0103


class FakeUIProxyCredsDialog(object):
    """The fake .ui for the creds dialog."""

    ui_labels = ('title_label', 'explanation_label', 'connection_label',
                   'error_label', 'username_label', 'password_label',
                   'domain_label', 'logo_label')
    ui_buttons = ('help_button', 'cancel_button', 'save_button')
    ui_entries = ('username_entry', 'password_entry')

    def __init__(self):
        """Create a new instance."""
        self.called = {}
        for name in self.ui_labels + self.ui_buttons + self.ui_entries:
            setattr(self, name, FakeWidget(name, self.called))

    # pylint: disable=C0103
    def setupUi(self, dialog):
        """Set the ui."""
        self.called['FakeUIProxyCredsDialog'] = ('setupUi', dialog)
    # pylint: enable=C0103


class FakeQIcon(object):
    """QIcon class."""

    def __init__(self):
        """Create a new instance."""
        self.called = []

    # pylint: disable=C0103
    def fromTheme(self, icon_id):
        """Return the icon with the given id."""
        self.called.append(('fromTheme', icon_id))
        return self
    # pylint: enable=C0103

    # pylint: disable=C0103
    def pixmap(self, h, w):
        """Get the pixmap with the given size."""
        self.called.append(('pixmap', h, w))
        return self
    # pylint: disable=C0103


class ProxyCredsDialogTest(TestCase):
    """Test the proxy creds dialog."""

    @defer.inlineCallbacks
    def setUp(self):
        """Set tests."""
        yield super(ProxyCredsDialogTest, self).setUp()
        self.patch(proxy_dialog, 'Ui_ProxyCredsDialog',
                   FakeUIProxyCredsDialog)
        self.icon = FakeQIcon()
        self.patch(proxy_dialog, 'QIcon', self.icon)

    def test_set_labels(self):
        """Ensure the correct labels are used."""
        dialog = proxy_dialog.ProxyCredsDialog()
        for label in dialog.ui.ui_labels:
            self.assertIn(label, dialog.ui.called, label)

    def test_set_buttons(self):
        """Ensure that buttons are set."""
        dialog = proxy_dialog.ProxyCredsDialog()
        for label in dialog.ui.ui_buttons:
            self.assertIn(label, dialog.ui.called)
        # assert that the clicked was set
        self.assertIn(('connect', dialog._on_save_clicked),
                      dialog.ui.save_button.clicked.called)
        self.assertIn(('connect', dialog._on_cancel_clicked),
                      dialog.ui.cancel_button.clicked.called)

    def test_domain_empty(self):
        """Test that if the domain is not passed we set ''"""
        dialog = proxy_dialog.ProxyCredsDialog()
        self.assertIn('domain_label', dialog.ui.called)
        self.assertIn(('setText', ''), dialog.ui.called['domain_label'])

    def test_domain_not_empty(self):
        """Test that we do set the domain."""
        domain = '192.168.1.100'
        dialog = proxy_dialog.ProxyCredsDialog(domain=domain)
        self.assertIn('domain_label', dialog.ui.called)
        self.assertIn(('setText', domain), dialog.ui.called['domain_label'])

    @defer.inlineCallbacks
    def test_retry_present_creds(self):
        """Test that we do set the error label correctly."""
        creds = dict(username='username', password='password')
        called = []
        dialog = proxy_dialog.ProxyCredsDialog(retry=True)

        def fake_get_credentials(app_name):
            """Fake the get creds."""
            called.append(('get_credentials', app_name))
            return defer.succeed(creds)

        self.patch(dialog.keyring, 'get_credentials', fake_get_credentials)

        yield dialog._load_creds()
        self.assertIn('get_credentials', called[0])
        self.assertIn('error_label', dialog.ui.called)
        self.assertIn(('setVisible', True), dialog.ui.called['error_label'])
        self.assertIn(('setText', creds['username']),
                      dialog.ui.called['username_entry'])
        self.assertIn(('setText', creds['password']),
                      dialog.ui.called['password_entry'])

    @defer.inlineCallbacks
    def test_retry_none_creds(self):
        """Test that we do set the error label correctly."""
        called = []
        dialog = proxy_dialog.ProxyCredsDialog(retry=True)

        def fake_get_credentials(app_name):
            """Fake the get creds."""
            called.append(('get_credentials', app_name))
            return defer.succeed(None)

        self.patch(dialog.keyring, 'get_credentials', fake_get_credentials)

        yield dialog._load_creds()
        self.assertIn('get_credentials', called[0])
        self.assertIn('error_label', dialog.ui.called)
        self.assertIn(('setVisible', True), dialog.ui.called['error_label'])
        self.assertNotIn('username_entry', dialog.ui.called)
        self.assertNotIn('password_entry', dialog.ui.called)

    @defer.inlineCallbacks
    def test_retry_exception_creds(self):
        """Test that we do set the error label correctly."""
        called = []
        dialog = proxy_dialog.ProxyCredsDialog(retry=True)

        def fake_get_credentials(app_name):
            """Fake the get creds."""
            called.append(('get_credentials', app_name))
            return defer.fail(Exception('Fail test'))

        self.patch(dialog.keyring, 'get_credentials', fake_get_credentials)

        yield dialog._load_creds()
        self.assertIn('get_credentials', called[0])
        self.assertIn('error_label', dialog.ui.called)
        self.assertIn(('setVisible', True), dialog.ui.called['error_label'])
        self.assertNotIn('username_entry', dialog.ui.called)
        self.assertNotIn('password_entry', dialog.ui.called)

    def test_is_not_retry(self):
        """Test that we do set the error label correctly."""
        dialog = proxy_dialog.ProxyCredsDialog(retry=False)
        self.assertIn('error_label', dialog.ui.called)
        self.assertIn(('setVisible', False), dialog.ui.called['error_label'])

    def test_icon(self):
        """Test that we correctly set the icon."""
        dialog = proxy_dialog.ProxyCredsDialog()
        self.assertIn(('fromTheme', 'gtk-dialog-authentication'),
                      self.icon.called)
        self.assertIn(('pixmap', 48, 48),
                      self.icon.called)
        self.assertIn(('setPixmap', self.icon),
                      dialog.ui.called['logo_label'])

    def test_on_cancel_clicked(self):
        """Test the on cancel clicked event."""
        dialog = proxy_dialog.ProxyCredsDialog()
        called = []

        def fake_done(result):
            """Fake the done method."""
            called.append(('done', result))

        self.patch(dialog, 'done', fake_done)

        dialog._on_cancel_clicked()
        self.assertIn(('done', proxy_dialog.USER_CANCELLATION), called)

    def assert_save_button(self, set_creds_callback, result_number):
        """Test the save button execution."""
        dialog = proxy_dialog.ProxyCredsDialog()
        called = []

        def fake_done(result):
            """Fake the done method."""
            called.append(('done', result))

        self.patch(dialog, 'done', fake_done)

        def fake_set_credentials(app_name, creds):
            """Fake an error."""
            called.append(('set_credentials', app_name, creds))
            return set_creds_callback()

        self.patch(dialog.keyring, 'set_credentials', fake_set_credentials)

        dialog._on_save_clicked()
        self.assertIn(('done', result_number), called)

    def test_on_save_clicked_exception(self):
        """Test that the exception is handled correctly."""
        set_creds_cb = lambda: defer.fail(Exception())
        result_number = proxy_dialog.EXCEPTION_RAISED
        self.assert_save_button(set_creds_cb, result_number)

    def test_on_save_clicked_correct(self):
        """Test that we do save the creds."""
        set_creds_cb = lambda: defer.succeed(True)
        result_number = proxy_dialog.USER_SUCCESS
        self.assert_save_button(set_creds_cb, result_number)


class FakeArgs(object):
    """Some fake args."""

    def __init__(self, domain='', retry=False):
        """Create a new instance."""
        self.domain = domain
        self.retry = retry


class FakeCredsDialog(QObject):
    """A fake dialog."""

    finished = pyqtSignal(int)

    def __init__(self, called, code):
        """Create a new instance."""
        super(FakeCredsDialog, self).__init__()
        self.domain = None
        self.retry = None
        self.called = called
        self.return_code = code

    def __call__(self, domain, retry):
        """Fake init."""
        self.domain = domain
        self.retry = retry
        return self

    def show(self):
        """Show the dialog."""
        self.called.append(('show',))

    def exec_(self):
        """Show the dialog."""
        self.called.append(('exec_',))
        return self.return_code


class FakeQApplication(object):
    """A fake QApplication."""

    test_instance = None

    def __init__(self, called):
        """Create a new instance."""
        self.called = called
        self.args = None
        self.code = None
        FakeQApplication.test_instance = self

    def __call__(self, args):
        """Fake construntor."""
        self.args = args

    @classmethod
    def instance(cls):
        """Return the instance."""
        return FakeQApplication.test_instance

    def exit(self, code):
        """Exit the app."""
        self.called.append(('exit', code))
        self.code = code


class MainTest(TestCase):
    """Test the main method."""

    @defer.inlineCallbacks
    def setUp(self):
        """Set the different tests."""
        yield super(MainTest, self).setUp()
        self.called = []

        self.return_code = 0
        self.dialog = FakeCredsDialog(self.called, self.return_code)
        self.patch(proxy_dialog, 'ProxyCredsDialog', self.dialog)

        self.args = FakeArgs(domain='domain', retry=False)
        self.patch(proxy_dialog, 'parse_args', lambda: self.args)

        self.exit_code = None

        self.app = FakeQApplication(self.called)

        self.patch(proxy_dialog, 'QApplication', self.app)

    def _set_old_platform(self, platform):
        """Set back the platform."""
        proxy_dialog.sys.platform = platform

    def _assert_basic_start(self):
        """Assert the common code is actually ran."""
        self.assertEqual(self.args.domain, self.dialog.domain)
        self.assertEqual(self.args.retry, self.dialog.retry)

    def test_linux_main(self):
        """Test the main method on linux."""
        old_platform = proxy_dialog.sys.platform
        proxy_dialog.sys.platform = 'linux'
        self.addCleanup(self._set_old_platform, old_platform)

        def fake_exit(code):
            """Fake sys exit."""
            self.called.append(('exit', code))

        self.patch(proxy_dialog.sys, 'exit', fake_exit)

        proxy_dialog.main()

        self._assert_basic_start()
        self.assertIn(('exec_',), self.called)
        self.assertIn(('exit', self.return_code), self.called)

    def test_windows_main(self):
        """Test the main method on windows."""
        old_platform = proxy_dialog.sys.platform
        proxy_dialog.sys.platform = 'win32'
        self.addCleanup(self._set_old_platform, old_platform)

        def fake_install():
            """Fake the reactor installation."""
            self.called.append(('install',))

        self.patch(qt4reactor, 'install', fake_install)

        def fake_start():
            """Fake reactor.start."""
            self.called.append(('run',))

        self.patch(reactor, 'run', fake_start)

        def fake_exit(code):
            """Fake the exit method."""
            self.called.append(('exit_code', code))

        self.patch(proxy_dialog, 'exit_code', fake_exit)

        proxy_dialog.main()

        self._assert_basic_start()
        self.assertIn(('show',), self.called)
        self.assertIn(('run',), self.called)

        self.dialog.finished.emit(self.return_code)
        self.assertIn(('exit_code', self.return_code), self.called)

    def test_exit_code_windows(self):
        """"Test the exit code function."""
        old_platform = proxy_dialog.sys.platform
        proxy_dialog.sys.platform = 'win32'
        self.addCleanup(self._set_old_platform, old_platform)

        def fake_stop():
            """Fake reactor.start."""
            self.called.append(('stop',))

        self.patch(reactor, 'stop', fake_stop)

        proxy_dialog.exit_code(self.return_code)
        self.assertIn(('stop',), self.called)
        self.assertIn(('exit', self.return_code), self.called)