~ubuntuone-control-tower/ubuntuone-control-panel/trunk

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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
# -*- coding: utf-8 -*-

# Authors: Natalia B Bidart <natalia.bidart@canonical.com>
#
# Copyright 2010 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/>.

"""The test suite for the control panel user interface."""

from __future__ import division

import logging

from collections import defaultdict

from ubuntuone.devtools.handlers import MementoHandler

from ubuntuone.controlpanel.gtk import gui
from ubuntuone.controlpanel.tests import TOKEN, TestCase

# Attribute 'yyy' defined outside __init__
# pylint: disable=W0201

# Access to a protected member 'yyy' of a client class
# pylint: disable=W0212


FAKE_ACCOUNT_INFO = {'type': 'Payed', 'name': 'Test me',
    'email': 'test.com', 'quota_total': '12345', 'quota_used': '9999'}

FAKE_VOLUMES_INFO = [
    {'volume_id': '0', 'suggested_path': '~/foo', 'subscribed': ''},
    {'volume_id': '1', 'suggested_path': '~/bar', 'subscribed': 'True'},
    {'volume_id': '2', 'suggested_path': '~/baz', 'subscribed': 'True'},
]

FAKE_DEVICE_INFO = {
    'device_id': '1258-6854', 'device_name': 'Baz', 'device_type': 'Computer',
    'configurable': 'True', 'limit_bandwidth': 'True',
    'max_upload_speed': '1000', 'max_download_speed': '72548',
}

FAKE_DEVICES_INFO = [
    {'device_id': '0', 'name': 'Foo', 'type': 'Computer', 'configurable': ''},
    {'device_id': '1', 'name': 'Bar', 'type': 'Phone', 'configurable': ''},
    {'device_id': '2', 'name': 'Z', 'type': 'Computer',
     'configurable': 'True', 'limit_bandwidth': '',
     'max_upload_speed': '0', 'max_download_speed': '0'},
    {'device_id': '1258-6854', 'name': 'Baz', 'type': 'Computer',
     'configurable': 'True', 'limit_bandwidth': 'True',
     'max_upload_speed': '1000', 'max_download_speed': '72548'},
]


class FakedObject(object):
    """Fake an object, record every call."""

    exposed_methods = []

    def __init__(self, *args, **kwargs):
        self._args = args
        self._kwargs = kwargs
        self._called = {}
        for i in self.exposed_methods:
            setattr(self, i, self._record_call(i))

    def _record_call(self, func_name):
        """Store values when calling 'func_name'."""

        def inner(*args, **kwargs):
            """Fake 'func_name'."""
            self._called[func_name] = (args, kwargs)

        return inner


class FakedNMState(FakedObject):
    """Fake a NetworkManagerState."""

    exposed_methods = ['find_online_state']


class FakedDBusBackend(FakedObject):
    """Fake a DBus Backend."""

    bus_name = None
    object_path = None
    iface = None

    def __init__(self, obj, dbus_interface, *args, **kwargs):
        if dbus_interface != self.iface:
            raise TypeError()
        self._signals = defaultdict(list)
        super(FakedDBusBackend, self).__init__(*args, **kwargs)

    def connect_to_signal(self, signal, handler):
        """Bind 'handler' to be callback'd when 'signal' is fired."""
        self._signals[signal].append(handler)


class FakedSSOBackend(FakedDBusBackend):
    """Fake a SSO Backend, act as a dbus.Interface."""

    bus_name = gui.ubuntu_sso.DBUS_BUS_NAME
    object_path = gui.ubuntu_sso.DBUS_CREDENTIALS_PATH
    iface = gui.ubuntu_sso.DBUS_CREDENTIALS_IFACE
    exposed_methods = ['find_credentials', 'clear_credentials',
                       'login', 'register']


class FakedControlPanelBackend(FakedDBusBackend):
    """Fake a Control Panel Backend, act as a dbus.Interface."""

    bus_name = gui.DBUS_BUS_NAME
    object_path = gui.DBUS_PREFERENCES_PATH
    iface = gui.DBUS_PREFERENCES_IFACE
    exposed_methods = [
        'account_info', 'devices_info', 'change_device_settings',
        'volumes_info', 'change_volume_settings', 'file_sync_status',
    ]


class FakedSessionBus(object):
    """Fake a session bus."""

    def get_object(self, bus_name, object_path, introspect=True,
                   follow_name_owner_changes=False, **kwargs):
        """Return a faked proxy for the given remote object."""
        return None


class FakedInterface(object):
    """Fake a dbus interface."""

    def __new__(cls, obj, dbus_interface, *args, **kwargs):
        if dbus_interface == gui.DBUS_PREFERENCES_IFACE:
            return FakedControlPanelBackend(obj, dbus_interface,
                                            *args, **kwargs)
        if dbus_interface == gui.ubuntu_sso.DBUS_CREDENTIALS_IFACE:
            return FakedSSOBackend(obj, dbus_interface, *args, **kwargs)


class BaseTestCase(TestCase):
    """Basics for testing."""

    # self.klass is not callable
    # pylint: disable=E1102
    klass = None
    kwargs = {}

    def setUp(self):
        super(BaseTestCase, self).setUp()
        self.patch(gui.gtk, 'main', lambda: None)
        self.patch(gui.dbus, 'SessionBus', FakedSessionBus)
        self.patch(gui.dbus, 'Interface', FakedInterface)
        self.patch(gui.networkstate, 'NetworkManagerState', FakedNMState)

        if self.klass is not None:
            self.ui = self.klass(**self.kwargs)

        self.memento = MementoHandler()
        self.memento.setLevel(logging.DEBUG)
        gui.logger.addHandler(self.memento)

    def tearDown(self):
        try:
            self.ui.hide()
            del self.ui
            self.ui = None
        except AttributeError:
            pass
        super(BaseTestCase, self).tearDown()

    def assert_image_equal(self, image, filename):
        """Check that expected and actual represent the same image."""
        pb = gui.gtk.gdk.pixbuf_new_from_file(gui.get_data_file(filename))
        self.assertEqual(image.get_pixbuf().get_pixels(), pb.get_pixels())

    def assert_messages_equal(self, widget, msgs):
        """Check that 'widget' has all the entries in 'msgs'."""
        children = list(reversed(widget.get_children()))
        self.assertEqual(len(children), len(msgs))
        for label, msg in zip(reversed(children), msgs):
            full_msg = self.ui.BULLET + ' ' + msg
            self.assertTrue(label.get_visible())
            self.assertEqual(label.get_property('xalign'), 0)
            self.assertEqual(label.get_property('wrap'), True)
            self.assertEqual(label.get_label(), full_msg)

            expected = gui.gtk.Label()
            expected.set_markup(full_msg)
            self.assertEqual(label.get_text(), expected.get_text())

    def assert_backend_called(self, method_name, args, backend=None):
        """Check that the control panel backend 'method_name' was called."""
        if backend is None:
            backend = self.ui.backend
        self.assertIn(method_name, backend._called)
        self.assertEqual(backend._called[method_name], (args, {}))

    def assert_warning_correct(self, warning, text):
        """Check that 'warning' is visible, showing 'text'."""
        self.assertTrue(warning.get_visible(), 'Must be visible.')
        self.assertEqual(warning.get_text(), text)
        self.assertEqual(warning.get_label(), gui.WARNING_MARKUP % text)

    def assert_function_decorated(self, decorator, func):
        """Check that 'func' is decorated with 'decorator'."""
        expected = decorator(lambda: None)
        self.assertEqual(expected.func_code, func.im_func.func_code)


class ControlPanelMixinTestCase(BaseTestCase):
    """The test suite for the control panel widget."""

    klass = gui.ControlPanelMixin
    ui_filename = None

    def test_is_a_control_panel_mixin(self):
        """Inherits from ControlPanelMixin."""
        self.assertIsInstance(self.ui, gui.ControlPanelMixin)

    def test_ui_can_be_created(self):
        """UI main class exists and can be created."""
        self.assertTrue(self.ui is not None)


class ControlPanelWindowTestCase(BaseTestCase):
    """The test suite for the control panel window."""

    klass = gui.ControlPanelWindow

    def test_is_a_window(self):
        """Inherits from gtk.Window."""
        self.assertIsInstance(self.ui, gui.gtk.Window)

    def test_startup_visibility(self):
        """The widget is visible at startup."""
        self.assertTrue(self.ui.get_visible(), 'must be visible at startup.')

    def test_main_start_gtk_main_loop(self):
        """The GTK main loop is started when calling main()."""
        self.patch(gui.gtk, 'main', self._set_called)
        self.ui.main()
        self.assertEqual(self._called, ((), {}), 'gtk.main was called.')

    def test_closing_stops_the_main_lopp(self):
        """The GTK main loop is stopped when closing the window."""
        self.patch(gui.gtk, 'main_quit', self._set_called)
        self.ui.emit('delete-event', None)
        self.assertEqual(self._called, ((), {}), 'gtk.main_quit was called.')

    def test_title_is_correct(self):
        """The window title is correct."""
        expected = self.ui.TITLE % {'app_name': gui.U1_APP_NAME}
        self.assertEqual(self.ui.get_title(), expected)

    def test_control_panel_is_the_only_child(self):
        """The control panel is the window's content."""
        children = self.ui.get_children()
        self.assertEqual(1, len(children))

        control_panel = self.ui.get_children()[0]
        self.assertTrue(control_panel is self.ui.control_panel)
        self.assertIsInstance(self.ui.control_panel, gui.ControlPanel)
        self.assertTrue(self.ui.control_panel.get_visible())

    def test_window_id_is_passed_to_child(self):
        """The child gets the window_id."""
        assert self.ui.window is not None
        self.assertEqual(self.ui.control_panel._window_id,
                         self.ui.window.xid)

    def test_icon_name_is_correct(self):
        """The icon name is correct."""
        self.assertEqual(self.ui.get_icon_name(), 'ubuntuone')

    def test_max_size(self):
        """Max size is not bigger than 736x525 (LP: #645526, LP: #683164)."""
        self.assertTrue(self.ui.get_size_request() <= (736, 525))


class ControlPanelTestCase(ControlPanelMixinTestCase):
    """The test suite for the control panel itself."""

    klass = gui.ControlPanel
    kwargs = {'window_id': 7}
    ui_filename = 'controlpanel.ui'

    def test_is_a_vbox(self):
        """Inherits from gtk.VBox."""
        self.assertIsInstance(self.ui, gui.gtk.VBox)

    def test_startup_visibility(self):
        """The widget is visible at startup."""
        self.assertTrue(self.ui.itself.get_visible(),
                        'must be visible at startup.')

    def test_overview_is_shown_at_startup(self):
        """The overview is shown at startup."""
        self.assertIsInstance(self.ui.overview, gui.OverviewPanel)

    def test_window_id_is_passed_to_child(self):
        """The child gets the window_id."""
        self.assertEqual(self.ui.overview._window_id, self.kwargs['window_id'])

    def test_on_show_management_panel(self):
        """A ManagementPanel is shown when the callback is executed."""
        self.ui.on_show_management_panel()
        children = self.ui.get_children()
        self.assertIsInstance(children[-1], gui.ManagementPanel)

    def test_on_show_management_panel_is_idempotent(self):
        """Only one ManagementPanel is shown."""
        self.ui.on_show_management_panel()
        self.ui.on_show_management_panel()

        self.assertEqual(1, len(self.ui.get_children()))

    def test_credentials_found_shows_account_management_panel(self):
        """On 'credentials-found' signal, the management panel is shown.

        If first signal parameter is False, visible tab should be account.

        """
        a_token = object()
        self.ui.overview.emit('credentials-found', False, a_token)

        children = self.ui.get_children()
        self.assertIsInstance(children[-1], gui.ManagementPanel)
        self.assertEqual(self.ui.management.notebook.get_current_page(),
                         self.ui.management.ACCOUNT_PAGE)

    def test_credentials_found_shows_folders_management_panel(self):
        """On 'credentials-found' signal, the management panel is shown.

        If first signal parameter is True, visible tab should be folders.

        """
        a_token = object()
        self.ui.overview.emit('credentials-found', True, a_token)

        children = self.ui.get_children()
        self.assertIsInstance(children[-1], gui.ManagementPanel)
        self.assertEqual(self.ui.management.notebook.get_current_page(),
                         self.ui.management.FOLDERS_PAGE)


class UbuntuOneBinTestCase(BaseTestCase):
    """The test suite for a Ubuntu One panel."""

    klass = gui.UbuntuOneBin
    kwargs = {'title': 'Something old, something new and something blue.'}

    def test_is_a_vbox(self):
        """Inherits from proper gtk widget."""
        self.assertIsInstance(self.ui, gui.gtk.VBox)

    def test_startup_visibility(self):
        """The widget is visible at startup."""
        self.assertTrue(self.ui.get_visible(),
                        'must be visible at startup.')
        for child in self.ui.get_children():
            self.assertTrue(child.get_visible())

    def test_title_is_a_panel_title(self):
        """Title is the correct widget."""
        self.assertIsInstance(self.ui.title, gui.PanelTitle)
        self.assertIn(self.ui.title, self.ui.get_children())

    def test_title_markup_is_correct(self):
        """The title markup is correctly set when passed as argument."""
        self.assertEqual(self.ui.title.label.get_text(), self.kwargs['title'])

    def test_title_is_correct(self):
        """The title markup is correctly set when defined at class level."""
        ui = self.klass()  # no title given
        self.assertEqual(ui.title.label.get_text(), '')


class OverwiewPanelTestCase(ControlPanelMixinTestCase):
    """The test suite for the overview panel."""

    klass = gui.OverviewPanel
    kwargs = {'messages': None, 'window_id': 8}
    ui_filename = 'overview.ui'

    def test_is_a_greyable_bin(self):
        """Inherits from GreyableBin."""
        self.assertIsInstance(self.ui, gui.GreyableBin)

    def test_inner_widget_is_packed(self):
        """The 'itself' vbox is packed into the widget."""
        self.assertIn(self.ui.itself, self.ui.get_children())

    def test_join_now_is_default(self):
        """The 'join_now' button is the default widget."""
        self.assertTrue(self.ui.join_now_button.get_property('can-default'))

    def test_sso_backend(self):
        """Has a correct SSO backend."""
        self.assertIsInstance(self.ui.sso_backend, FakedSSOBackend)

    def test_sso_backend_signals(self):
        """The proper signals are connected to the backend."""
        self.assertEqual(self.ui.sso_backend._signals['CredentialsFound'],
                         [self.ui.on_credentials_found])
        self.assertEqual(self.ui.sso_backend._signals['CredentialsNotFound'],
                         [self.ui.on_credentials_not_found])
        self.assertEqual(self.ui.sso_backend._signals['CredentialsError'],
                         [self.ui.on_credentials_error])
        self.assertEqual(self.ui.sso_backend._signals['AuthorizationDenied'],
                         [self.ui.on_authorization_denied])


class OverwiewNetworkStatePanelTestCase(OverwiewPanelTestCase):
    """The test suite for the overview panel regarding network state."""

    def test_network_state_is_created(self):
        """The network state is created."""
        self.assertIsInstance(self.ui.network_manager_state,
                              gui.networkstate.NetworkManagerState)
        self.assertEqual(self.ui.network_manager_state._kwargs['result_cb'],
                         self.ui.on_network_state_changed)

    def test_network_state_is_queried_at_startup(self):
        """The network state is asked to the NetworkManagerState."""
        self.assertTrue('find_online_state' in
                        self.ui.network_manager_state._called)

    def test_state_online(self):
        """Network connection is online."""
        self.ui.on_network_state_changed(gui.networkstate.ONLINE)
        # all green, no warning
        self.assertEqual(self.ui.warning_label.get_text(), '')
        self.assertTrue(self.ui.get_sensitive())

    def test_state_offline(self):
        """Network connection is offline."""
        self.ui.on_network_state_changed(gui.networkstate.OFFLINE)
        msg = self.ui.NETWORK_OFFLINE % {'app_name': gui.U1_APP_NAME}

        self.assert_warning_correct(self.ui.warning_label, msg)
        self.assertFalse(self.ui.get_sensitive())

    def test_state_unknown(self):
        """Network connection is unknown."""
        self.ui.on_network_state_changed(gui.networkstate.UNKNOWN)

        self.assert_warning_correct(self.ui.warning_label,
                                    self.ui.NETWORK_UNKNOWN)
        self.assertFalse(self.ui.get_sensitive())


class OverwiewPanelOnlineTestCase(OverwiewPanelTestCase):
    """The test suite for the overview panel."""

    def setUp(self):
        super(OverwiewPanelOnlineTestCase, self).setUp()
        self.ui.on_network_state_changed(gui.networkstate.ONLINE)

    def test_find_credentials_is_called(self):
        """Credentials are asked to SSO backend."""
        self.assertFalse(self.ui._credentials_are_new)
        self.assert_backend_called('find_credentials', (gui.U1_APP_NAME, {}),
                                   backend=self.ui.sso_backend)

    def test_on_credentials_found(self):
        """Callback 'on_credentials_found' is correct."""
        self.ui.connect('credentials-found', self._set_called)

        self.ui.on_credentials_found(gui.U1_APP_NAME, TOKEN)

        self.assertFalse(self.ui.get_visible())
        # assume credentials were in local keyring
        self.assertEqual(self._called, ((self.ui, False, TOKEN), {}))

    def test_on_credentials_found_when_creds_are_not_new(self):
        """Callback 'on_credentials_found' distinguish if creds are new."""
        self.ui.connect('credentials-found', self._set_called)

        # credentials weren't in the system
        self.ui.on_credentials_not_found(gui.U1_APP_NAME)
        # now they are!
        self.ui.on_credentials_found(gui.U1_APP_NAME, TOKEN)

        self.assertFalse(self.ui.get_visible())
        # assume credentials were not in local keyring
        self.assertEqual(self._called, ((self.ui, True, TOKEN), {}))

    def test_on_credentials_not_found(self):
        """Callback 'on_credentials_not_found' is correct."""
        self.ui.on_credentials_not_found(gui.U1_APP_NAME)
        self.assertTrue(self.ui.get_visible())
        self.assertTrue(self.ui._credentials_are_new)

    def test_on_credentials_error(self):
        """Callback 'on_credentials_error' is correct."""
        self.ui.on_credentials_error(gui.U1_APP_NAME, {})
        self.assertTrue(self.ui.get_visible())
        self.assert_warning_correct(self.ui.warning_label,
                                    self.ui.CREDENTIALS_ERROR)

    def test_on_authorization_denied(self):
        """Callback 'on_authorization_denied' is correct."""
        self.ui.on_authorization_denied(gui.U1_APP_NAME)
        self.assertTrue(self.ui.get_visible())
        self.assert_warning_correct(self.ui.warning_label,
                                    self.ui.AUTHORIZATION_DENIED)


class OverwiewPanelAppNameMismatchTestCase(OverwiewPanelTestCase):
    """The test suite for the overview panel when the app_name won't match."""

    NOT_U1_APP = 'Not ' + gui.U1_APP_NAME

    def test_filter_by_app_name(self):
        """The filter_by_app_name decorator is correct."""
        f = gui.filter_by_app_name(self._set_called)
        f(self.ui, self.NOT_U1_APP)
        self.assertFalse(self._called)
        self.assertTrue(self.memento.check_info('ignoring', self.NOT_U1_APP))

        args = ('test', object())
        kwargs = {'really': 'AWESOME'}
        f(self.ui, gui.U1_APP_NAME, *args, **kwargs)
        self.assertEqual(self._called,
                         ((self.ui, gui.U1_APP_NAME,) + args, kwargs))

    def test_on_credentials_found(self):
        """Callback 'on_credentials_found' is not executed."""
        self.assert_function_decorated(gui.filter_by_app_name,
                                       self.ui.on_credentials_found)

    def test_on_credentials_not_found(self):
        """Callback 'on_credentials_not_found' is not executed."""
        self.assert_function_decorated(gui.filter_by_app_name,
                                       self.ui.on_credentials_not_found)

    def test_on_credentials_error(self):
        """Callback 'on_credentials_error' is not executed."""
        self.assert_function_decorated(gui.filter_by_app_name,
                                       self.ui.on_credentials_error)

    def test_on_authorization_denied(self):
        """Callback 'on_authorization_denied' is not executed."""
        self.assert_function_decorated(gui.filter_by_app_name,
                                       self.ui.on_authorization_denied)


class OverwiewPanelNoCredsTestCase(OverwiewPanelTestCase):
    """The test suite for the overview panel when no credentials are found."""

    messages = None

    def setUp(self):
        self.kwargs['messages'] = self.messages
        super(OverwiewPanelNoCredsTestCase, self).setUp()
        self.ui.on_credentials_not_found(gui.U1_APP_NAME)

    def test_startup_visibility(self):
        """The widget is visible at startup."""
        self.assertTrue(self.ui.get_visible(),
                        'must be visible at startup if credentials not found.')

    def test_warning_label_is_hidden(self):
        """The warning label is not shown by default."""
        self.assertEqual(self.ui.warning_label.get_text(), '')

    def test_image_is_correct(self):
        """There is an image attribute and is correct."""
        self.assert_image_equal(self.ui.image, 'overview.png')

    def test_messages(self):
        """If no messages are passed, the default list is used."""
        self.assert_messages_equal(self.ui.messages, gui.OVERVIEW_MSGS)

    def test_join_now_is_default_widget(self):
        """The join now button is the default widget."""
        self.assertTrue(self.ui.join_now_button.get_property('can_default'))

    def test_join_now_button_clicked(self):
        """Test the 'join now' button callback."""
        self.ui.join_now_button.clicked()

        args = (gui.U1_APP_NAME,
                {gui.TC_URL_KEY: gui.U1_TC_URL,
                 gui.HELP_TEXT_KEY: gui.U1_DESCRIPTION,
                 gui.WINDOW_ID_KEY: str(self.kwargs['window_id']),
                 gui.PING_URL_KEY: gui.U1_PING_URL})
        self.assert_backend_called('register', args,
                                   backend=self.ui.sso_backend)

    def test_connect_button_clicked(self):
        """Test the 'join now' button callback."""
        self.ui.connect_button.clicked()

        args = (gui.U1_APP_NAME,
                {gui.TC_URL_KEY: gui.U1_TC_URL,
                 gui.HELP_TEXT_KEY: gui.U1_DESCRIPTION,
                 gui.WINDOW_ID_KEY: str(self.kwargs['window_id']),
                 gui.PING_URL_KEY: gui.U1_PING_URL})
        self.assert_backend_called('login', args,
                                   backend=self.ui.sso_backend)

    def test_join_now_button_clicked_set_greyed(self):
        """Clicking on 'join_now' self is greyed."""
        self.ui.join_now_button.clicked()
        self.assertTrue(self.ui.get_property('greyed'), 'Must be greyed.')

    def test_join_now_button_clicked_removes_warning(self):
        """Clicking on 'join_now' the warnings are removed."""
        self.ui.on_authorization_denied(gui.U1_APP_NAME)  # show warning
        self.ui.join_now_button.clicked()

        self.assertEqual(self.ui.warning_label.get_text(), '')

    def test_connect_button_clicked_set_greyed(self):
        """Clicking on 'connect' self is greyed."""
        self.ui.connect_button.clicked()
        self.assertTrue(self.ui.get_property('greyed'), 'Must be greyed.')

    def test_connect_button_clicked_removes_warning(self):
        """Clicking on 'connect' the warnings are removed."""
        self.ui.on_authorization_denied(gui.U1_APP_NAME)  # show warning
        self.ui.connect_button.clicked()

        self.assertEqual(self.ui.warning_label.get_text(), '')

    def test_on_credentials_not_found_unset_greyed(self):
        """Callback 'on_credentials_not_found' unsets the 'greyed' prop."""
        self.ui.connect_button.clicked()
        self.ui.on_credentials_not_found(gui.U1_APP_NAME)

        self.assertFalse(self.ui.get_property('greyed'), 'Must not be greyed.')

    def test_on_credentials_error_unset_greyed(self):
        """Callback 'on_credentials_error' unsets the 'greyed' prop."""
        self.ui.connect_button.clicked()
        self.ui.on_credentials_error(gui.U1_APP_NAME, {})

        self.assertFalse(self.ui.get_property('greyed'), 'Must not be greyed.')

    def test_on_authorization_denied_unset_greyed(self):
        """Callback 'on_authorization_denied' unsets the 'greyed' prop."""
        self.ui.connect_button.clicked()
        self.ui.on_authorization_denied(gui.U1_APP_NAME)

        self.assertFalse(self.ui.get_property('greyed'), 'Must not be greyed.')

    def test_buttons_disabled_when_greyed(self):
        """Buttons should be disabled when widget is greyed."""
        self.ui.set_sensitive(True)
        self.ui.set_property('greyed', True)

        self.assertFalse(self.ui.join_now_button.is_sensitive())
        self.assertFalse(self.ui.connect_button.is_sensitive())

    def test_buttons_enabled_when_not_greyed(self):
        """Buttons should be enabled when widget is not greyed."""
        self.ui.set_sensitive(False)
        self.ui.set_property('greyed', False)

        self.assertTrue(self.ui.join_now_button.is_sensitive())
        self.assertTrue(self.ui.connect_button.is_sensitive())


class OverwiewPanelMessagesTestCase(OverwiewPanelTestCase):
    """The test suite for the overview panel when messages are set."""

    messages = ['Test me', 'A little bit more']


class OverwiewPanelMarkupMessagesTestCase(OverwiewPanelTestCase):
    """The test suite for the overview panel when markup messages are set."""

    messages = ['<small>Test me</small>', 'A <b>little</b> bit more']


class AccountTestCase(ControlPanelMixinTestCase):
    """The test suite for the account panel."""

    klass = gui.AccountPanel
    ui_filename = 'account.ui'

    def assert_account_info_correct(self, info):
        """Check that the displayed account info matches 'info'."""
        self.assertEqual(self.ui.name_label.get_text(),
                         FAKE_ACCOUNT_INFO['name'])
        self.assertEqual(self.ui.type_label.get_text(),
                         FAKE_ACCOUNT_INFO['type'])
        self.assertEqual(self.ui.email_label.get_text(),
                         FAKE_ACCOUNT_INFO['email'])

    def test_is_an_ubuntuone_bin(self):
        """Inherits from UbuntuOneBin."""
        self.assertIsInstance(self.ui, gui.UbuntuOneBin)

    def test_inner_widget_is_packed(self):
        """The 'itself' vbox is packed into the widget."""
        self.assertIn(self.ui.itself, self.ui.get_children())

    def test_is_visible(self):
        """Is visible."""
        self.assertTrue(self.ui.get_visible())

    def test_type_label_is_loading(self):
        """Placeholder for type label is a Loading widget."""
        self.assertIsInstance(self.ui.type_label, gui.LabelLoading)
        self.assertIn(self.ui.type_label, self.ui.type_box.get_children())

    def test_email_label_is_loading(self):
        """Placeholder for email label is a Loading widget."""
        self.assertIsInstance(self.ui.email_label, gui.LabelLoading)
        self.assertIn(self.ui.email_label, self.ui.email_box.get_children())

    def test_backend_signals(self):
        """The proper signals are connected to the backend."""
        self.assertEqual(self.ui.backend._signals['AccountInfoReady'],
                         [self.ui.on_account_info_ready])
        self.assertEqual(self.ui.backend._signals['AccountInfoError'],
                         [self.ui.on_account_info_error])

    def test_on_account_info_ready(self):
        """The account info is processed when ready."""
        self.ui.on_account_info_ready(FAKE_ACCOUNT_INFO)
        self.assert_account_info_correct(FAKE_ACCOUNT_INFO)

        for widget in (self.ui.name_label, self.ui.type_label,
                       self.ui.email_label):
            self.assertFalse(widget.active)

    def test_on_account_info_error(self):
        """The account info couldn't be retrieved."""
        self.ui.on_account_info_error()
        for widget in (self.ui.name_label, self.ui.type_label,
                       self.ui.email_label):
            self.assert_warning_correct(widget, self.ui.VALUE_ERROR)
            self.assertFalse(widget.active)


class FoldersTestCase(ControlPanelMixinTestCase):
    """The test suite for the folders panel."""

    klass = gui.FoldersPanel
    ui_filename = 'folders.ui'

    def setUp(self):
        super(FoldersTestCase, self).setUp()
        self.ui.load()

    def test_is_an_ubuntuone_bin(self):
        """Inherits from UbuntuOneBin."""
        self.assertIsInstance(self.ui, gui.UbuntuOneBin)

    def test_inner_widget_is_packed(self):
        """The 'itself' vbox is packed into the widget."""
        self.assertIn(self.ui.itself, self.ui.get_children())

    def test_is_visible(self):
        """Is visible."""
        self.assertTrue(self.ui.get_visible())

    def test_backend_signals(self):
        """The proper signals are connected to the backend."""
        self.assertEqual(self.ui.backend._signals['VolumesInfoReady'],
                         [self.ui.on_volumes_info_ready])
        self.assertEqual(self.ui.backend._signals['VolumesInfoError'],
                         [self.ui.on_volumes_info_error])

    def test_volumes_info_is_requested_on_load(self):
        """The volumes info is requested to the backend."""
        # clean backend calls
        self.ui.backend._called.pop('volumes_info', None)
        self.ui.load()

        self.assert_backend_called('volumes_info', ())

    def test_volumes_label(self):
        """The volumes label is a LabelLoading."""
        self.assertIsInstance(self.ui.volumes_label, gui.LabelLoading)
        self.assertTrue(self.ui.volumes_label.active)
        self.assertIn(self.ui.volumes_label, self.ui.label_alignment)

    def test_volumes_label_after_load(self):
        """The volumes label is active when contents are load."""
        self.ui.on_volumes_info_ready(FAKE_VOLUMES_INFO)
        self.ui.load()

        self.assertTrue(self.ui.volumes_label.active)

    def test_volumes_label_after_non_empty_volumes_info_ready(self):
        """The volumes label is a LabelLoading."""
        self.ui.on_volumes_info_ready(FAKE_VOLUMES_INFO)

        self.assertFalse(self.ui.volumes_label.active)
        self.assertFalse(self.ui.label_alignment.get_visible())

    def test_volumes_label_after_empty_volumes_info_ready(self):
        """When there are no volumes, a notification is shown."""
        self.ui.on_volumes_info_ready([])

        self.assertTrue(self.ui.label_alignment.get_visible())
        self.assertFalse(self.ui.volumes_label.active)
        self.assertEqual(self.ui.volumes_label.get_text(), self.ui.NO_VOLUMES)

    def test_on_volumes_info_ready(self):
        """The volumes info is processed when ready."""
        self.ui.on_volumes_info_ready(FAKE_VOLUMES_INFO)

        self.assertFalse(self.ui.label_alignment.get_visible())
        self.assertEqual(self.ui.folders.get_children(), [self.ui.volumes])

        volumes = self.ui.volumes.get_children()
        volumes.reverse()

        header = volumes[:2]  # grab header
        self.assertEqual(header[0].get_text(), 'Local path')
        self.assertEqual(header[1].get_text(), 'Subscribed')

        volumes = volumes[2:]  # drop header
        labels = filter(lambda w: isinstance(w, gui.gtk.Label), volumes)
        checks = filter(lambda w: isinstance(w, gui.gtk.CheckButton), volumes)

        self.assertEqual(len(checks), len(FAKE_VOLUMES_INFO))

        for label, check, volume in zip(labels, checks, FAKE_VOLUMES_INFO):
            self.assertEqual(volume['suggested_path'], label.get_text())
            self.assertEqual(bool(volume['subscribed']), check.get_active())
            self.assertEqual(volume['volume_id'], check.get_label())
            self.assertFalse(check.get_child().get_visible())

    def test_on_volumes_info_ready_clears_the_list(self):
        """The old volumes info is cleared before updated."""
        self.ui.on_volumes_info_ready(FAKE_VOLUMES_INFO)
        self.ui.on_volumes_info_ready(FAKE_VOLUMES_INFO)

        self.assertEqual(len(self.ui.folders.get_children()), 1)
        child = self.ui.folders.get_children()[0]
        self.assertEqual(child, self.ui.volumes)

        volumes = filter(lambda w: isinstance(w, gui.gtk.CheckButton),
                         self.ui.volumes.get_children())
        self.assertEqual(len(volumes), len(FAKE_VOLUMES_INFO))

    def test_on_volumes_info_ready_with_no_volumes(self):
        """When there are no volumes, a notification is shown."""
        self.ui.on_volumes_info_ready([])
        # no volumes table
        self.assertEqual(len(self.ui.folders.get_children()), 0)
        self.assertTrue(self.ui.volumes is None)

    def test_on_subscribed_clicked(self):
        """Clicking on 'subscribed' updates the folder subscription."""
        self.ui.on_volumes_info_ready(FAKE_VOLUMES_INFO)

        method = 'change_volume_settings'
        for checkbutton in self.ui._subscribed:
            checkbutton.clicked()
            fid = checkbutton.get_label()

            subscribed = gui.bool_str(checkbutton.get_active())
            self.assert_backend_called(method,
                                       (fid, {'subscribed': subscribed}))
            # clean backend calls
            self.ui.backend._called.pop(method)

            checkbutton.clicked()
            subscribed = gui.bool_str(checkbutton.get_active())
            self.assert_backend_called('change_volume_settings',
                                       (fid, {'subscribed': subscribed}))

    def test_on_volumes_info_error(self):
        """The volumes info couldn't be retrieved."""
        self.ui.on_volumes_info_error()
        self.assert_warning_correct(warning=self.ui.volumes_label,
                                    text=self.ui.VALUE_ERROR)
        self.assertFalse(self.ui.volumes_label.active)
        self.assertTrue(self.ui.label_alignment.get_visible())

    def test_on_volumes_info_error_after_success(self):
        """The volumes info couldn't be retrieved after a prior success."""
        self.ui.on_volumes_info_ready(FAKE_VOLUMES_INFO)

        self.ui.on_volumes_info_error()

        self.test_on_volumes_info_error()
        self.test_on_volumes_info_ready_with_no_volumes()


class DeviceTestCase(ControlPanelMixinTestCase):
    """The test suite for the device widget."""

    klass = gui.Device
    ui_filename = 'device.ui'

    def assert_device_equal(self, device, expected):
        """Assert that the device has the values from expected."""
        self.assertEqual(device.device_id.get_text(),
                         expected['device_id'])
        self.assertEqual(device.device_name.get_text(),
                         expected['device_name'])
        self.assertEqual(device.device_type.get_icon_name()[0],
                         expected['device_type'].lower())
        self.assertEqual(device.configurable,
                         bool(expected['configurable']))
        self.assertEqual(device.limit_bandwidth.get_active(),
                         bool(expected['limit_bandwidth']))

        value = int(expected['max_upload_speed']) // gui.KILOBYTES
        self.assertEqual(device.max_upload_speed.get_value_as_int(), value)
        value = int(expected['max_download_speed']) // gui.KILOBYTES
        self.assertEqual(device.max_download_speed.get_value_as_int(), value)

    def assert_device_settings_changed(self):
        """Changing throttling settings updates the backend properly."""
        expected = self.ui.__dict__
        self.assert_backend_called('change_device_settings',
                                   (self.ui.device_id.get_text(), expected))
        self.assertEqual(self.ui.warning_label.get_text(), '')

    def modify_settings(self):
        """Modify settings so values actually change."""
        new_val = not self.ui.limit_bandwidth.get_active()
        self.ui.limit_bandwidth.set_active(new_val)

        new_val = self.ui.max_upload_speed.get_value_as_int() + 1
        self.ui.max_upload_speed.set_value(new_val)

        new_val = self.ui.max_download_speed.get_value_as_int() + 1
        self.ui.max_download_speed.set_value(new_val)

    def test_is_a_vbox(self):
        """Inherits from VBox."""
        self.assertIsInstance(self.ui, gui.gtk.VBox)

    def test_inner_widget_is_packed(self):
        """The 'itself' vbox is packed into the widget."""
        self.assertIn(self.ui.itself, self.ui.get_children())

    def test_is_visible(self):
        """Is visible."""
        self.assertTrue(self.ui.get_visible())

    def test_is_sensitive(self):
        """Is sensitive."""
        self.assertTrue(self.ui.get_sensitive())

    def test_warning_label_is_cleared(self):
        """The warning label is cleared."""
        self.assertEqual(self.ui.warning_label.get_text(), '')

    def test_device_id_is_hidden(self):
        """The device id label is hidden."""
        self.assertFalse(self.ui.device_id.get_visible())

    def test_default_values(self):
        """Default values are correct."""
        self.assertEqual(self.ui.device_id.get_text(), '')
        self.assertEqual(self.ui.device_name.get_text(), '')
        self.assertEqual(self.ui.device_type.get_icon_name()[0],
                         gui.DEVICE_TYPE_COMPUTER.lower())
        self.assertEqual(self.ui.configurable, False)
        self.assertEqual(self.ui.limit_bandwidth.get_active(), False)
        self.assertEqual(self.ui.max_upload_speed.get_value_as_int(), 0)
        self.assertEqual(self.ui.max_download_speed.get_value_as_int(), 0)

    def test_init_does_not_call_backend(self):
        """When updating, the backend is not called."""
        self.assertEqual(self.ui.backend._called, {})

    def test_update_device_id(self):
        """A device can be updated from a dict."""
        value = '741-822-963'
        self.ui.update(device_id=value)
        self.assertEqual(value, self.ui.device_id.get_text())

    def test_update_device_name(self):
        """A device can be updated from a dict."""
        value = 'The death star'
        self.ui.update(device_name=value)
        self.assertEqual(value, self.ui.device_name.get_text())

    def test_update_unicode_device_name(self):
        """A device can be updated from a dict."""
        value = u'Ñoño Ñandú'
        self.ui.update(device_name=value)
        self.assertEqual(value, self.ui.device_name.get_text())

    def test_update_device_type_computer(self):
        """A device can be updated from a dict."""
        dtype = gui.DEVICE_TYPE_COMPUTER
        self.ui.update(device_type=dtype)
        self.assertEqual((dtype.lower(), gui.gtk.ICON_SIZE_BUTTON),
                         self.ui.device_type.get_icon_name())

    def test_update_device_type_phone(self):
        """A device can be updated from a dict."""
        dtype = gui.DEVICE_TYPE_PHONE
        self.ui.update(device_type=dtype)
        self.assertEqual((dtype.lower(), gui.gtk.ICON_SIZE_BUTTON),
                         self.ui.device_type.get_icon_name())

    def test_update_configurable(self):
        """A device can be updated from a dict."""
        self.ui.update(configurable='')
        self.assertFalse(self.ui.configurable)
        self.assertFalse(self.ui.throttling.get_visible())

    def test_update_non_configurable(self):
        """A device can be updated from a dict."""
        self.ui.update(configurable='True')
        self.assertTrue(self.ui.configurable)
        self.assertTrue(self.ui.throttling.get_visible())

    def test_update_limit_bandwidth(self):
        """A device can be updated from a dict."""
        self.ui.update(limit_bandwidth='')
        self.assertFalse(self.ui.limit_bandwidth.get_active())

        self.ui.update(limit_bandwidth='True')
        self.assertTrue(self.ui.limit_bandwidth.get_active())

    def test_update_upload_speed(self):
        """A device can be updated from a dict."""
        value = '12345'
        self.ui.update(max_upload_speed=value)
        self.assertEqual(int(value) // gui.KILOBYTES,
                         self.ui.max_upload_speed.get_value_as_int())

    def test_update_download_speed(self):
        """A device can be updated from a dict."""
        value = '987654'
        self.ui.update(max_download_speed=value)
        self.assertEqual(int(value) // gui.KILOBYTES,
                         self.ui.max_download_speed.get_value_as_int())

    def test_update_does_not_call_backend(self):
        """When updating, the backend is not called."""
        self.ui.update(**FAKE_DEVICE_INFO)
        self.assertEqual(self.ui.backend._called, {})
        self.assert_device_equal(self.ui, FAKE_DEVICE_INFO)

    def test_on_limit_bandwidth_toggled(self):
        """When toggling limit_bandwidth, backend is updated."""
        self.ui.limit_bandwidth.toggled()
        self.assert_device_settings_changed()

    def test_on_max_upload_speed_value_changed(self):
        """When setting max_upload_speed, backend is updated."""
        self.ui.max_upload_speed.set_value(25)
        self.assert_device_settings_changed()

    def test_on_max_download_speed_value_changed(self):
        """When setting max_download_speed, backend is updated."""
        self.ui.max_download_speed.set_value(52)
        self.assert_device_settings_changed()

    def test_backend_signals(self):
        """The proper signals are connected to the backend."""
        self.assertEqual(self.ui.backend._signals['DeviceSettingsChanged'],
                         [self.ui.on_device_settings_changed])
        self.assertEqual(self.ui.backend._signals['DeviceSettingsChangeError'],
                         [self.ui.on_device_settings_change_error])

    def test_on_device_settings_changed(self):
        """When settings were changed for this device, enable it."""
        self.modify_settings()
        did = self.ui.device_id.get_text()
        self.ui.on_device_settings_changed(device_id=did)

        self.assertTrue(self.ui.get_sensitive())
        self.assertEqual(self.ui.warning_label.get_text(), '')
        self.assertEqual(self.ui.__dict__, self.ui._last_settings)

    def test_on_device_settings_change_after_error(self):
        """Change success after error."""
        self.modify_settings()
        did = self.ui.device_id.get_text()
        self.ui.on_device_settings_change_error(device_id=did)  # change failed

        self.test_on_device_settings_changed()

    def test_on_device_settings_changed_different_id(self):
        """When settings were changed for other device, nothing changes."""
        self.modify_settings()
        self.ui.on_device_settings_changed(device_id='yadda')

        self.assertEqual(self.ui.warning_label.get_text(), '')

    def test_on_device_settings_change_error(self):
        """When settings were not changed for this device, notify the user.

        Also, confirm that old values were restored.

        """
        self.ui.update(**FAKE_DEVICE_INFO)  # use known values

        self.modify_settings()

        did = self.ui.device_id.get_text()
        self.ui.on_device_settings_change_error(device_id=did)  # change failed

        self.assertTrue(self.ui.get_sensitive())
        self.assert_warning_correct(self.ui.warning_label,
                                    self.ui.DEVICE_CHANGE_ERROR)
        self.assert_device_equal(self.ui, FAKE_DEVICE_INFO)  # restored info

    def test_on_device_settings_change_error_after_success(self):
        """Change error after success."""
        self.modify_settings()
        did = self.ui.device_id.get_text()
        self.ui.on_device_settings_changed(device_id=did)

        self.test_on_device_settings_change_error()

    def test_on_device_settings_change_error_different_id(self):
        """When settings were not changed for other device, do nothing."""
        self.modify_settings()
        self.ui.on_device_settings_change_error(device_id='yudo')
        self.assertEqual(self.ui.warning_label.get_text(), '')


class DevicesTestCase(ControlPanelMixinTestCase):
    """The test suite for the devices panel."""

    klass = gui.DevicesPanel
    ui_filename = 'devices.ui'

    def test_is_an_ubuntuone_bin(self):
        """Inherits from UbuntuOneBin."""
        self.assertIsInstance(self.ui, gui.UbuntuOneBin)

    def test_inner_widget_is_packed(self):
        """The 'itself' vbox is packed into the widget."""
        self.assertIn(self.ui.itself, self.ui.get_children())

    def test_is_visible(self):
        """Is visible."""
        self.assertTrue(self.ui.get_visible())

    def test_backend_signals(self):
        """The proper signals are connected to the backend."""
        self.assertEqual(self.ui.backend._signals['DevicesInfoReady'],
                         [self.ui.on_devices_info_ready])
        self.assertEqual(self.ui.backend._signals['DevicesInfoError'],
                         [self.ui.on_devices_info_error])

    def test_devices_info_is_requested(self):
        """The devices info is requested to the backend."""
        self.assert_backend_called('devices_info', ())

    def test_on_devices_info_ready(self):
        """The devices info is processed when ready."""
        self.ui.on_devices_info_ready(FAKE_DEVICES_INFO)

        children = self.ui.devices.get_children()
        self.assertEqual(len(children), len(FAKE_DEVICES_INFO))

        for child, device in zip(children, FAKE_DEVICES_INFO):
            self.assertIsInstance(child, gui.Device)

            self.assertEqual(device['device_id'],
                             child.device_id.get_text())
            self.assertEqual(device['device_name'],
                             child.device_name.get_text())
            self.assertEqual(device['device_type'].lower(),
                             child.device_type.get_icon_name()[0])
            self.assertEqual(bool(device['configurable']),
                             child.configurable)

            if bool(device['configurable']):
                self.assertEqual(bool(device['limit_bandwidth']),
                                 child.limit_bandwidth.get_active())
                value = int(device['max_upload_speed']) // gui.KILOBYTES
                self.assertEqual(value,
                                 child.max_upload_speed.get_value_as_int())
                value = int(device['max_download_speed']) // gui.KILOBYTES
                self.assertEqual(value,
                                 child.max_download_speed.get_value_as_int())

    def test_on_devices_info_error(self):
        """The devices info couldn't be retrieved."""
        self.ui.on_devices_info_error()


class ApplicationsTestCase(ControlPanelMixinTestCase):
    """The test suite for the applications panel."""

    klass = gui.ApplicationsPanel
    ui_filename = 'applications.ui'

    def test_is_an_ubuntuone_bin(self):
        """Inherits from UbuntuOneBin."""
        self.assertIsInstance(self.ui, gui.UbuntuOneBin)

    def test_inner_widget_is_packed(self):
        """The 'itself' vbox is packed into the widget."""
        self.assertIn(self.ui.itself, self.ui.get_children())

    def test_is_visible(self):
        """Is visible."""
        self.assertTrue(self.ui.get_visible())


class ManagementPanelTestCase(ControlPanelMixinTestCase):
    """The test suite for the management panel."""

    klass = gui.ManagementPanel
    ui_filename = 'management.ui'

    def assert_account_info_correct(self, info):
        """Check that the displayed account info matches 'info'."""
        used = int(info['quota_used'])
        total = int(info['quota_total'])
        percentage = (used / total) * 100
        expected = {'used': self.ui.humanize(used),
                    'total': self.ui.humanize(total),
                    'percentage': percentage}
        self.assertEqual(self.ui.quota_label.get_text(),
                         self.ui.QUOTA_LABEL % expected)
        self.assertEqual(self.ui.quota_progressbar.get_fraction(),
                         percentage / 100)

    def test_is_a_vbox(self):
        """Inherits from gtk.VBox."""
        self.assertIsInstance(self.ui, gui.gtk.VBox)

    def test_startup_visibility(self):
        """The widget is visible at startup."""
        self.assertTrue(self.ui.get_visible(),
                        'must be visible at startup.')

    def test_inner_widget_is_packed(self):
        """The 'itself' vbox is packed into the widget."""
        self.assertIn(self.ui.itself, self.ui.get_children())

    def test_tabs_are_not_shown(self):
        """Tabs are not shown."""
        self.assertFalse(self.ui.notebook.get_show_tabs())

    def test_default_page_is_account(self):
        """The default page is Account."""
        self.assertEqual(self.ui.notebook.get_current_page(),
                         self.ui.ACCOUNT_PAGE)
        self.assertTrue(self.ui.account_button.get_active())

    def test_buttons_set_notebook_pages(self):
        """The notebook pages are set when clicking buttons."""
        msg = 'Page num should be %i when %s was clicked (got %i instead).'
        for tab in self.ui.tabs:
            button = '%s_button' % tab
            getattr(self.ui, button).clicked()
            expected = getattr(self.ui, ('%s_page' % tab).upper())
            actual = self.ui.notebook.get_current_page()
            self.assertEqual(actual, expected,
                             msg % (expected, button, actual))

    def test_buttons_indicates_current_page(self):
        """Only one button is activated at a time."""
        msg = 'Only button %s should be active (%s was active as well).'
        for tab in self.ui.tabs:
            button = '%s_button' % tab
            getattr(self.ui, button).clicked()
            for other in self.ui.tabs:
                if other is tab:
                    continue
                active = getattr(self.ui, '%s_button' % other).get_active()
                self.assertFalse(active, msg % (button, other))


class ManagementPanelAccountTestCase(ManagementPanelTestCase):
    """The test suite for the management panel (account tab)."""

    def test_backend_account_signals(self):
        """The proper signals are connected to the backend."""
        self.assertEqual(self.ui.backend._signals['AccountInfoReady'],
                         [self.ui.on_account_info_ready])
        self.assertEqual(self.ui.backend._signals['AccountInfoError'],
                         [self.ui.on_account_info_error])

    def test_account_info_is_requested(self):
        """The account info is requested to the backend."""
        self.assert_backend_called('account_info', ())

    def test_account_panel_is_packed(self):
        """The account panel is packed."""
        self.assertIsInstance(self.ui.account, gui.AccountPanel)
        actual = self.ui.notebook.get_nth_page(self.ui.ACCOUNT_PAGE)
        self.assertTrue(self.ui.account is actual)

    def test_folders_panel_is_packed(self):
        """The folders panel is packed."""
        self.assertIsInstance(self.ui.folders, gui.FoldersPanel)
        actual = self.ui.notebook.get_nth_page(self.ui.FOLDERS_PAGE)
        self.assertTrue(self.ui.folders is actual)

    def test_devices_panel_is_packed(self):
        """The devices panel is packed."""
        self.assertIsInstance(self.ui.devices, gui.DevicesPanel)
        actual = self.ui.notebook.get_nth_page(self.ui.DEVICES_PAGE)
        self.assertTrue(self.ui.devices is actual)

    def test_applications_panel_is_packed(self):
        """The applications panel is packed."""
        self.assertIsInstance(self.ui.applications, gui.ApplicationsPanel)
        actual = self.ui.notebook.get_nth_page(self.ui.APPLICATIONS_PAGE)
        self.assertTrue(self.ui.applications is actual)

    def test_entering_folders_tab_loads_content(self):
        """The volumes info is loaded when entering the Folders tab."""
        self.patch(self.ui.folders, 'load', self._set_called)
        # clean backend calls
        self.ui.folders_button.clicked()

        self.assertEqual(self._called, ((), {}))

    def test_placeholders_are_loading(self):
        """Placeholders for labels are a Loading widget."""
        widgets = (self.ui.quota_label, self.ui.status_label)
        for widget in widgets:
            self.assertIsInstance(widget, gui.LabelLoading)
            self.assertIn(widget, self.ui.status_box.get_children())

    def test_on_account_info_ready(self):
        """The account info is processed when ready."""
        self.ui.on_account_info_ready(FAKE_ACCOUNT_INFO)
        self.assert_account_info_correct(FAKE_ACCOUNT_INFO)

        for widget in (self.ui.quota_label,):
            self.assertFalse(widget.active)

    def test_on_account_info_error(self):
        """The account info couldn't be retrieved."""
        self.ui.on_account_info_error()
        for widget in (self.ui.quota_label,):
            self.assert_warning_correct(widget, self.ui.VALUE_ERROR)
            self.assertFalse(widget.active)

    def test_backend_file_sync_signals(self):
        """The proper signals are connected to the backend."""
        matches = (
            ('FileSyncStatusDisabled', [self.ui.on_file_sync_status_disabled]),
            ('FileSyncStatusStarting', [self.ui.on_file_sync_status_starting]),
            ('FileSyncStatusDisconnected',
             [self.ui.on_file_sync_status_disconnected]),
            ('FileSyncStatusSyncing', [self.ui.on_file_sync_status_syncing]),
            ('FileSyncStatusIdle', [self.ui.on_file_sync_status_idle]),
            ('FileSyncStatusError', [self.ui.on_file_sync_status_error]),
        )
        for sig, handlers in matches:
            self.assertEqual(self.ui.backend._signals[sig], handlers)

    def test_file_sync_status_is_requested(self):
        """The file sync status is requested to the backend."""
        self.assert_backend_called('file_sync_status', ())

    def test_on_file_sync_status_disabled(self):
        """The file sync is disabled."""
        self.ui.on_file_sync_status_disabled('msg')

        self.assertFalse(self.ui.status_label.active)
        self.assertEqual(self.ui.status_label.get_text(),
                         self.ui.FILE_SYNC_DISABLED)

    def test_on_file_sync_status_starting(self):
        """The file sync status is starting."""
        self.ui.on_file_sync_status_starting('msg')

        self.assertFalse(self.ui.status_label.active)
        self.assertEqual(self.ui.status_label.get_text(),
                         self.ui.FILE_SYNC_STARTING)

    def test_on_file_sync_status_disconnected(self):
        """The file sync status is disconnected."""
        self.ui.on_file_sync_status_disconnected('msg')

        self.assertFalse(self.ui.status_label.active)
        self.assertEqual(self.ui.status_label.get_text(),
                         self.ui.FILE_SYNC_DISCONNECTED)

    def test_on_file_sync_status_syncing(self):
        """The file sync status is syncing."""
        self.ui.on_file_sync_status_syncing('msg')

        self.assertFalse(self.ui.status_label.active)
        self.assertEqual(self.ui.status_label.get_text(),
                         self.ui.FILE_SYNC_SYNCING)

    def test_on_file_sync_status_idle(self):
        """The file sync status is idle."""
        self.ui.on_file_sync_status_idle('msg')

        self.assertFalse(self.ui.status_label.active)
        self.assertEqual(self.ui.status_label.get_text(),
                         self.ui.FILE_SYNC_IDLE)

    def test_on_file_sync_status_error(self):
        """The file sync status couldn't be retrieved."""
        self.ui.on_file_sync_status_error({'error_msg': 'error msg'})

        self.assert_warning_correct(self.ui.status_label,
                                    self.ui.FILE_SYNC_ERROR)
        self.assertFalse(self.ui.status_label.active)