FreeCAD

Форк
0
650 строк · 30.1 Кб
1
# SPDX-License-Identifier: LGPL-2.1-or-later
2
# ***************************************************************************
3
# *                                                                         *
4
# *   Copyright (c) 2022 FreeCAD Project Association                        *
5
# *                                                                         *
6
# *   This file is part of FreeCAD.                                         *
7
# *                                                                         *
8
# *   FreeCAD is free software: you can redistribute it and/or modify it    *
9
# *   under the terms of the GNU Lesser General Public License as           *
10
# *   published by the Free Software Foundation, either version 2.1 of the  *
11
# *   License, or (at your option) any later version.                       *
12
# *                                                                         *
13
# *   FreeCAD is distributed in the hope that it will be useful, but        *
14
# *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
15
# *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      *
16
# *   Lesser General Public License for more details.                       *
17
# *                                                                         *
18
# *   You should have received a copy of the GNU Lesser General Public      *
19
# *   License along with FreeCAD. If not, see                               *
20
# *   <https://www.gnu.org/licenses/>.                                      *
21
# *                                                                         *
22
# ***************************************************************************
23

24
import os
25
import tempfile
26
import unittest
27
import FreeCAD
28

29
from PySide import QtCore, QtWidgets
30

31
from addonmanager_installer_gui import AddonInstallerGUI, MacroInstallerGUI
32

33
from AddonManagerTest.gui.gui_mocks import DialogWatcher, DialogInteractor
34
from AddonManagerTest.app.mocks import MockAddon
35

36
translate = FreeCAD.Qt.translate
37

38

39
class TestInstallerGui(unittest.TestCase):
40

41
    MODULE = "test_installer_gui"  # file name without extension
42

43
    def setUp(self):
44
        self.addon_to_install = MockAddon()
45
        self.installer_gui = AddonInstallerGUI(self.addon_to_install)
46
        self.finalized_thread = False
47

48
    def tearDown(self):
49
        pass
50

51
    def test_success_dialog(self):
52
        # Pop the modal dialog and verify that it opens, and responds to an OK click
53
        dialog_watcher = DialogWatcher(
54
            translate("AddonsInstaller", "Success"),
55
            QtWidgets.QDialogButtonBox.Ok,
56
        )
57
        self.installer_gui._installation_succeeded()
58
        self.assertTrue(dialog_watcher.dialog_found, "Failed to find the expected dialog box")
59
        self.assertTrue(dialog_watcher.button_found, "Failed to find the expected button")
60

61
    def test_failure_dialog(self):
62
        # Pop the modal dialog and verify that it opens, and responds to a Cancel click
63
        dialog_watcher = DialogWatcher(
64
            translate("AddonsInstaller", "Installation Failed"),
65
            QtWidgets.QDialogButtonBox.Cancel,
66
        )
67
        self.installer_gui._installation_failed(
68
            self.addon_to_install, "Test of installation failure"
69
        )
70
        self.assertTrue(dialog_watcher.dialog_found, "Failed to find the expected dialog box")
71
        self.assertTrue(dialog_watcher.button_found, "Failed to find the expected button")
72

73
    def test_no_python_dialog(self):
74
        # Pop the modal dialog and verify that it opens, and responds to a No click
75
        dialog_watcher = DialogWatcher(
76
            translate("AddonsInstaller", "Cannot execute Python"),
77
            QtWidgets.QDialogButtonBox.No,
78
        )
79
        self.installer_gui._report_no_python_exe()
80
        self.assertTrue(dialog_watcher.dialog_found, "Failed to find the expected dialog box")
81
        self.assertTrue(dialog_watcher.button_found, "Failed to find the expected button")
82

83
    def test_no_pip_dialog(self):
84
        # Pop the modal dialog and verify that it opens, and responds to a No click
85
        dialog_watcher = DialogWatcher(
86
            translate("AddonsInstaller", "Cannot execute pip"),
87
            QtWidgets.QDialogButtonBox.No,
88
        )
89
        self.installer_gui._report_no_pip("pip not actually run, this was a test")
90
        self.assertTrue(dialog_watcher.dialog_found, "Failed to find the expected dialog box")
91
        self.assertTrue(dialog_watcher.button_found, "Failed to find the expected button")
92

93
    def test_dependency_failure_dialog(self):
94
        # Pop the modal dialog and verify that it opens, and responds to a No click
95
        dialog_watcher = DialogWatcher(
96
            translate("AddonsInstaller", "Package installation failed"),
97
            QtWidgets.QDialogButtonBox.No,
98
        )
99
        self.installer_gui._report_dependency_failure(
100
            "Unit test", "Nothing really failed, this is a test of the dialog box"
101
        )
102
        self.assertTrue(dialog_watcher.dialog_found, "Failed to find the expected dialog box")
103
        self.assertTrue(dialog_watcher.button_found, "Failed to find the expected button")
104

105
    def test_install(self):
106
        # Run the installation code and make sure it puts the directory in place
107
        with tempfile.TemporaryDirectory() as temp_dir:
108
            self.installer_gui.installer.installation_path = temp_dir
109
            self.installer_gui.install()  # This does not block
110
            self.installer_gui.installer.success.disconnect(
111
                self.installer_gui._installation_succeeded
112
            )
113
            self.installer_gui.installer.failure.disconnect(self.installer_gui._installation_failed)
114
            while not self.installer_gui.worker_thread.isFinished():
115
                QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents, 100)
116
            self.assertTrue(
117
                os.path.exists(os.path.join(temp_dir, "MockAddon")),
118
                "Installed directory not found",
119
            )
120

121
    def test_handle_disallowed_python(self):
122
        disallowed_packages = ["disallowed_package_name"]
123
        dialog_watcher = DialogWatcher(
124
            translate("AddonsInstaller", "Missing Requirement"),
125
            QtWidgets.QDialogButtonBox.Cancel,
126
        )
127
        self.installer_gui._handle_disallowed_python(disallowed_packages)
128
        self.assertTrue(dialog_watcher.dialog_found, "Failed to find the expected dialog box")
129
        self.assertTrue(dialog_watcher.button_found, "Failed to find the expected button")
130

131
    def test_handle_disallowed_python_long_list(self):
132
        """A separate test for when there are MANY packages, which takes a separate code path."""
133
        disallowed_packages = []
134
        for i in range(50):
135
            disallowed_packages.append(f"disallowed_package_name_{i}")
136
        dialog_watcher = DialogWatcher(
137
            translate("AddonsInstaller", "Missing Requirement"),
138
            QtWidgets.QDialogButtonBox.Cancel,
139
        )
140
        self.installer_gui._handle_disallowed_python(disallowed_packages)
141
        self.assertTrue(dialog_watcher.dialog_found, "Failed to find the expected dialog box")
142
        self.assertTrue(dialog_watcher.button_found, "Failed to find the expected button")
143

144
    def test_report_missing_workbenches_single(self):
145
        """Test only missing one workbench"""
146
        wbs = ["OneMissingWorkbench"]
147
        dialog_watcher = DialogWatcher(
148
            translate("AddonsInstaller", "Missing Requirement"),
149
            QtWidgets.QDialogButtonBox.Cancel,
150
        )
151
        self.installer_gui._report_missing_workbenches(wbs)
152
        self.assertTrue(dialog_watcher.dialog_found, "Failed to find the expected dialog box")
153
        self.assertTrue(dialog_watcher.button_found, "Failed to find the expected button")
154

155
    def test_report_missing_workbenches_multiple(self):
156
        """Test only missing one workbench"""
157
        wbs = ["FirstMissingWorkbench", "SecondMissingWorkbench"]
158
        dialog_watcher = DialogWatcher(
159
            translate("AddonsInstaller", "Missing Requirement"),
160
            QtWidgets.QDialogButtonBox.Cancel,
161
        )
162
        self.installer_gui._report_missing_workbenches(wbs)
163
        self.assertTrue(dialog_watcher.dialog_found, "Failed to find the expected dialog box")
164
        self.assertTrue(dialog_watcher.button_found, "Failed to find the expected button")
165

166
    def test_resolve_dependencies_then_install(self):
167
        class MissingDependenciesMock:
168
            def __init__(self):
169
                self.external_addons = ["addon_1", "addon_2"]
170
                self.python_requires = ["py_req_1", "py_req_2"]
171
                self.python_optional = ["py_opt_1", "py_opt_2"]
172

173
        missing = MissingDependenciesMock()
174
        dialog_watcher = DialogWatcher(
175
            translate("DependencyResolutionDialog", "Resolve Dependencies"),
176
            QtWidgets.QDialogButtonBox.Cancel,
177
        )
178
        self.installer_gui._resolve_dependencies_then_install(missing)
179
        self.assertTrue(dialog_watcher.dialog_found, "Failed to find the expected dialog box")
180
        self.assertTrue(dialog_watcher.button_found, "Failed to find the expected button")
181

182
    def test_check_python_version_bad(self):
183
        class MissingDependenciesMock:
184
            def __init__(self):
185
                self.python_min_version = {"major": 3, "minor": 9999}
186

187
        missing = MissingDependenciesMock()
188
        dialog_watcher = DialogWatcher(
189
            translate("AddonsInstaller", "Incompatible Python version"),
190
            QtWidgets.QDialogButtonBox.Cancel,
191
        )
192
        stop_installing = self.installer_gui._check_python_version(missing)
193
        self.assertTrue(dialog_watcher.dialog_found, "Failed to find the expected dialog box")
194
        self.assertTrue(dialog_watcher.button_found, "Failed to find the expected button")
195
        self.assertTrue(stop_installing, "Failed to halt installation on bad Python version")
196

197
    def test_check_python_version_good(self):
198
        class MissingDependenciesMock:
199
            def __init__(self):
200
                self.python_min_version = {"major": 3, "minor": 0}
201

202
        missing = MissingDependenciesMock()
203
        stop_installing = self.installer_gui._check_python_version(missing)
204
        self.assertFalse(stop_installing, "Failed to continue installation on good Python version")
205

206
    def test_clean_up_optional(self):
207
        class MissingDependenciesMock:
208
            def __init__(self):
209
                self.python_optional = [
210
                    "allowed_packages_1",
211
                    "allowed_packages_2",
212
                    "disallowed_package",
213
                ]
214

215
        allowed_packages = ["allowed_packages_1", "allowed_packages_2"]
216
        missing = MissingDependenciesMock()
217
        self.installer_gui.installer.allowed_packages = set(allowed_packages)
218
        self.installer_gui._clean_up_optional(missing)
219
        self.assertTrue("allowed_packages_1" in missing.python_optional)
220
        self.assertTrue("allowed_packages_2" in missing.python_optional)
221
        self.assertFalse("disallowed_package" in missing.python_optional)
222

223
    def intercept_run_dependency_installer(self, addons, python_requires, python_optional):
224
        self.assertEqual(python_requires, ["py_req_1", "py_req_2"])
225
        self.assertEqual(python_optional, ["py_opt_1", "py_opt_2"])
226
        self.assertEqual(addons[0].name, "addon_1")
227
        self.assertEqual(addons[1].name, "addon_2")
228

229
    def test_dependency_dialog_yes_clicked(self):
230
        class DialogMock:
231
            class ListWidgetMock:
232
                class ListWidgetItemMock:
233
                    def __init__(self, name):
234
                        self.name = name
235

236
                    def text(self):
237
                        return self.name
238

239
                    def checkState(self):
240
                        return QtCore.Qt.Checked
241

242
                def __init__(self, items):
243
                    self.list = []
244
                    for item in items:
245
                        self.list.append(DialogMock.ListWidgetMock.ListWidgetItemMock(item))
246

247
                def count(self):
248
                    return len(self.list)
249

250
                def item(self, i):
251
                    return self.list[i]
252

253
            def __init__(self):
254
                self.listWidgetAddons = DialogMock.ListWidgetMock(["addon_1", "addon_2"])
255
                self.listWidgetPythonRequired = DialogMock.ListWidgetMock(["py_req_1", "py_req_2"])
256
                self.listWidgetPythonOptional = DialogMock.ListWidgetMock(["py_opt_1", "py_opt_2"])
257

258
        class AddonMock:
259
            def __init__(self, name):
260
                self.name = name
261

262
        self.installer_gui.dependency_dialog = DialogMock()
263
        self.installer_gui.addons = [AddonMock("addon_1"), AddonMock("addon_2")]
264
        self.installer_gui._run_dependency_installer = self.intercept_run_dependency_installer
265
        self.installer_gui._dependency_dialog_yes_clicked()
266

267

268
class TestMacroInstallerGui(unittest.TestCase):
269
    class MockMacroAddon:
270
        class MockMacro:
271
            def __init__(self):
272
                self.install_called = False
273
                self.install_result = (
274
                    True  # External code can change to False to test failed install
275
                )
276
                self.name = "MockMacro"
277
                self.filename = "mock_macro_no_real_file.FCMacro"
278
                self.comment = "This is a mock macro for unit testing"
279
                self.icon = None
280
                self.xpm = None
281

282
            def install(self):
283
                self.install_called = True
284
                return self.install_result
285

286
        def __init__(self):
287
            self.macro = TestMacroInstallerGui.MockMacroAddon.MockMacro()
288
            self.name = self.macro.name
289
            self.display_name = self.macro.name
290

291
    class MockParameter:
292
        """Mock the parameter group to allow simplified behavior and introspection."""
293

294
        def __init__(self):
295
            self.params = {}
296
            self.groups = {}
297
            self.accessed_parameters = {}  # Dict is param name: default value
298

299
            types = ["Bool", "String", "Int", "UInt", "Float"]
300
            for t in types:
301
                setattr(self, f"Get{t}", self.get)
302
                setattr(self, f"Set{t}", self.set)
303
                setattr(self, f"Rem{t}", self.rem)
304

305
        def get(self, p, default=None):
306
            self.accessed_parameters[p] = default
307
            if p in self.params:
308
                return self.params[p]
309
            else:
310
                return default
311

312
        def set(self, p, value):
313
            self.params[p] = value
314

315
        def rem(self, p):
316
            if p in self.params:
317
                self.params.erase(p)
318

319
        def GetGroup(self, name):
320
            if name not in self.groups:
321
                self.groups[name] = TestMacroInstallerGui.MockParameter()
322
            return self.groups[name]
323

324
        def GetGroups(self):
325
            return self.groups.keys()
326

327
    class ToolbarIntercepter:
328
        def __init__(self):
329
            self.ask_for_toolbar_called = False
330
            self.install_macro_to_toolbar_called = False
331
            self.tb = None
332
            self.custom_group = TestMacroInstallerGui.MockParameter()
333
            self.custom_group.set("Name", "MockCustomToolbar")
334

335
        def _ask_for_toolbar(self, _):
336
            self.ask_for_toolbar_called = True
337
            return self.custom_group
338

339
        def _install_macro_to_toolbar(self, tb):
340
            self.install_macro_to_toolbar_called = True
341
            self.tb = tb
342

343
    class InstallerInterceptor:
344
        def __init__(self):
345
            self.ccc_called = False
346

347
        def _create_custom_command(
348
            self,
349
            toolbar,
350
            filename,
351
            menuText,
352
            tooltipText,
353
            whatsThisText,
354
            statustipText,
355
            pixmapText,
356
        ):
357
            self.ccc_called = True
358
            self.toolbar = toolbar
359
            self.filename = filename
360
            self.menuText = menuText
361
            self.tooltipText = tooltipText
362
            self.whatsThisText = whatsThisText
363
            self.statustipText = statustipText
364
            self.pixmapText = pixmapText
365

366
    def setUp(self):
367
        self.mock_macro = TestMacroInstallerGui.MockMacroAddon()
368
        self.installer = MacroInstallerGUI(self.mock_macro)
369
        self.installer.addon_params = TestMacroInstallerGui.MockParameter()
370
        self.installer.toolbar_params = TestMacroInstallerGui.MockParameter()
371

372
    def tearDown(self):
373
        pass
374

375
    def test_class_is_initialized(self):
376
        """Connecting to a signal does not throw"""
377
        self.installer.finished.connect(lambda: None)
378

379
    def test_ask_for_toolbar_no_dialog_default_exists(self):
380
        self.installer.addon_params.set("alwaysAskForToolbar", False)
381
        self.installer.addon_params.set("CustomToolbarName", "UnitTestCustomToolbar")
382
        utct = self.installer.toolbar_params.GetGroup("UnitTestCustomToolbar")
383
        utct.set("Name", "UnitTestCustomToolbar")
384
        utct.set("Active", True)
385
        result = self.installer._ask_for_toolbar([])
386
        self.assertIsNotNone(result)
387
        self.assertTrue(hasattr(result, "get"))
388
        name = result.get("Name")
389
        self.assertEqual(name, "UnitTestCustomToolbar")
390

391
    def test_ask_for_toolbar_with_dialog_cancelled(self):
392

393
        # First test: the user cancels the dialog
394
        self.installer.addon_params.set("alwaysAskForToolbar", True)
395
        dialog_watcher = DialogWatcher(
396
            translate("select_toolbar_dialog", "Select Toolbar"),
397
            QtWidgets.QDialogButtonBox.Cancel,
398
        )
399
        result = self.installer._ask_for_toolbar([])
400
        self.assertIsNone(result)
401

402
    def test_ask_for_toolbar_with_dialog_defaults(self):
403

404
        # Second test: the user leaves the dialog at all default values, so:
405
        #   - The checkbox "Ask every time" is unchecked
406
        #   - The selected toolbar option is "Create new toolbar", which triggers a search for
407
        # a new custom toolbar name by calling _create_new_custom_toolbar, which we mock.
408
        fake_custom_toolbar_group = TestMacroInstallerGui.MockParameter()
409
        fake_custom_toolbar_group.set("Name", "UnitTestCustomToolbar")
410
        self.installer._create_new_custom_toolbar = lambda: fake_custom_toolbar_group
411
        dialog_watcher = DialogWatcher(
412
            translate("select_toolbar_dialog", "Select Toolbar"),
413
            QtWidgets.QDialogButtonBox.Ok,
414
        )
415
        result = self.installer._ask_for_toolbar([])
416
        self.assertIsNotNone(result)
417
        self.assertTrue(hasattr(result, "get"))
418
        name = result.get("Name")
419
        self.assertEqual(name, "UnitTestCustomToolbar")
420
        self.assertIn("alwaysAskForToolbar", self.installer.addon_params.params)
421
        self.assertFalse(self.installer.addon_params.get("alwaysAskForToolbar", True))
422
        self.assertTrue(dialog_watcher.button_found, "Failed to find the expected button")
423

424
    def test_ask_for_toolbar_with_dialog_selection(self):
425

426
        # Third test: the user selects a custom toolbar in the dialog, and checks the box to always
427
        # ask.
428
        dialog_interactor = DialogInteractor(
429
            translate("select_toolbar_dialog", "Select Toolbar"),
430
            self.interactor_selection_option_and_checkbox,
431
        )
432
        ut_tb_1 = self.installer.toolbar_params.GetGroup("UT_TB_1")
433
        ut_tb_2 = self.installer.toolbar_params.GetGroup("UT_TB_2")
434
        ut_tb_3 = self.installer.toolbar_params.GetGroup("UT_TB_3")
435
        ut_tb_1.set("Name", "UT_TB_1")
436
        ut_tb_2.set("Name", "UT_TB_2")
437
        ut_tb_3.set("Name", "UT_TB_3")
438
        result = self.installer._ask_for_toolbar(["UT_TB_1", "UT_TB_2", "UT_TB_3"])
439
        self.assertIsNotNone(result)
440
        self.assertTrue(hasattr(result, "get"))
441
        name = result.get("Name")
442
        self.assertEqual(name, "UT_TB_3")
443
        self.assertIn("alwaysAskForToolbar", self.installer.addon_params.params)
444
        self.assertTrue(self.installer.addon_params.get("alwaysAskForToolbar", False))
445

446
    def interactor_selection_option_and_checkbox(self, parent):
447

448
        boxes = parent.findChildren(QtWidgets.QComboBox)
449
        self.assertEqual(len(boxes), 1)  # Just to make sure...
450
        box = boxes[0]
451
        box.setCurrentIndex(box.count() - 2)  # Select the last thing but one
452

453
        checkboxes = parent.findChildren(QtWidgets.QCheckBox)
454
        self.assertEqual(len(checkboxes), 1)  # Just to make sure...
455
        checkbox = checkboxes[0]
456
        checkbox.setChecked(True)
457

458
        parent.accept()
459

460
    def test_macro_button_exists_no_command(self):
461
        # Test 1: No command for this macro
462
        self.installer._find_custom_command = lambda _: None
463
        button_exists = self.installer._macro_button_exists()
464
        self.assertFalse(button_exists)
465

466
    def test_macro_button_exists_true(self):
467
        # Test 2: Macro is in the list of buttons
468
        ut_tb_1 = self.installer.toolbar_params.GetGroup("UnitTestCommand")
469
        ut_tb_1.set("UnitTestCommand", "FreeCAD")  # This is what the real thing looks like...
470
        self.installer._find_custom_command = lambda _: "UnitTestCommand"
471
        self.assertTrue(self.installer._macro_button_exists())
472

473
    def test_macro_button_exists_false(self):
474
        # Test 3: Macro is not in the list of buttons
475
        self.installer._find_custom_command = lambda _: "UnitTestCommand"
476
        self.assertFalse(self.installer._macro_button_exists())
477

478
    def test_ask_to_install_toolbar_button_disabled(self):
479
        self.installer.addon_params.SetBool("dontShowAddMacroButtonDialog", True)
480
        self.installer._ask_to_install_toolbar_button()
481
        # This should NOT block when dontShowAddMacroButtonDialog is True
482

483
    def test_ask_to_install_toolbar_button_enabled_no(self):
484
        self.installer.addon_params.SetBool("dontShowAddMacroButtonDialog", False)
485
        dialog_watcher = DialogWatcher(
486
            translate("toolbar_button", "Add button?"),
487
            QtWidgets.QDialogButtonBox.No,
488
        )
489
        # Note: that dialog does not use a QButtonBox, so we can really only test its
490
        # reject() signal, which is triggered by the DialogWatcher when it cannot find
491
        # the button. In this case, failure to find that button is NOT an error.
492
        self.installer._ask_to_install_toolbar_button()  # Blocks until killed by watcher
493
        self.assertTrue(dialog_watcher.dialog_found)
494

495
    def test_get_toolbar_with_name_found(self):
496
        ut_tb_1 = self.installer.toolbar_params.GetGroup("UnitTestToolbar")
497
        ut_tb_1.set("Name", "Unit Test Toolbar")
498
        ut_tb_1.set("UnitTestParam", True)
499
        tb = self.installer._get_toolbar_with_name("Unit Test Toolbar")
500
        self.assertIsNotNone(tb)
501
        self.assertTrue(tb.get("UnitTestParam", False))
502

503
    def test_get_toolbar_with_name_not_found(self):
504
        ut_tb_1 = self.installer.toolbar_params.GetGroup("UnitTestToolbar")
505
        ut_tb_1.set("Name", "Not the Unit Test Toolbar")
506
        tb = self.installer._get_toolbar_with_name("Unit Test Toolbar")
507
        self.assertIsNone(tb)
508

509
    def test_create_new_custom_toolbar_no_existing(self):
510
        tb = self.installer._create_new_custom_toolbar()
511
        self.assertEqual(tb.get("Name", ""), "Auto-Created Macro Toolbar")
512
        self.assertTrue(tb.get("Active", False), True)
513

514
    def test_create_new_custom_toolbar_one_existing(self):
515
        _ = self.installer._create_new_custom_toolbar()
516
        tb = self.installer._create_new_custom_toolbar()
517
        self.assertEqual(tb.get("Name", ""), "Auto-Created Macro Toolbar (2)")
518
        self.assertTrue(tb.get("Active", False), True)
519

520
    def test_check_for_toolbar_true(self):
521
        ut_tb_1 = self.installer.toolbar_params.GetGroup("UT_TB_1")
522
        ut_tb_1.set("Name", "UT_TB_1")
523
        self.assertTrue(self.installer._check_for_toolbar("UT_TB_1"))
524

525
    def test_check_for_toolbar_false(self):
526
        ut_tb_1 = self.installer.toolbar_params.GetGroup("UT_TB_1")
527
        ut_tb_1.set("Name", "UT_TB_1")
528
        self.assertFalse(self.installer._check_for_toolbar("Not UT_TB_1"))
529

530
    def test_install_toolbar_button_first_custom_toolbar(self):
531
        tbi = TestMacroInstallerGui.ToolbarIntercepter()
532
        self.installer._ask_for_toolbar = tbi._ask_for_toolbar
533
        self.installer._install_macro_to_toolbar = tbi._install_macro_to_toolbar
534
        self.installer._install_toolbar_button()
535
        self.assertTrue(tbi.install_macro_to_toolbar_called)
536
        self.assertFalse(tbi.ask_for_toolbar_called)
537
        self.assertTrue("Custom_1" in self.installer.toolbar_params.GetGroups())
538

539
    def test_install_toolbar_button_existing_custom_toolbar_1(self):
540
        # There is an existing custom toolbar, and we should use it
541
        tbi = TestMacroInstallerGui.ToolbarIntercepter()
542
        self.installer._ask_for_toolbar = tbi._ask_for_toolbar
543
        self.installer._install_macro_to_toolbar = tbi._install_macro_to_toolbar
544
        ut_tb_1 = self.installer.toolbar_params.GetGroup("UT_TB_1")
545
        ut_tb_1.set("Name", "UT_TB_1")
546
        self.installer.addon_params.set("CustomToolbarName", "UT_TB_1")
547
        self.installer._install_toolbar_button()
548
        self.assertTrue(tbi.install_macro_to_toolbar_called)
549
        self.assertFalse(tbi.ask_for_toolbar_called)
550
        self.assertEqual(tbi.tb.get("Name", ""), "UT_TB_1")
551

552
    def test_install_toolbar_button_existing_custom_toolbar_2(self):
553
        # There are multiple existing custom toolbars, and we should use one of them
554
        tbi = TestMacroInstallerGui.ToolbarIntercepter()
555
        self.installer._ask_for_toolbar = tbi._ask_for_toolbar
556
        self.installer._install_macro_to_toolbar = tbi._install_macro_to_toolbar
557
        ut_tb_1 = self.installer.toolbar_params.GetGroup("UT_TB_1")
558
        ut_tb_2 = self.installer.toolbar_params.GetGroup("UT_TB_2")
559
        ut_tb_3 = self.installer.toolbar_params.GetGroup("UT_TB_3")
560
        ut_tb_1.set("Name", "UT_TB_1")
561
        ut_tb_2.set("Name", "UT_TB_2")
562
        ut_tb_3.set("Name", "UT_TB_3")
563
        self.installer.addon_params.set("CustomToolbarName", "UT_TB_3")
564
        self.installer._install_toolbar_button()
565
        self.assertTrue(tbi.install_macro_to_toolbar_called)
566
        self.assertFalse(tbi.ask_for_toolbar_called)
567
        self.assertEqual(tbi.tb.get("Name", ""), "UT_TB_3")
568

569
    def test_install_toolbar_button_existing_custom_toolbar_3(self):
570
        # There are multiple existing custom toolbars, but none of them match
571
        tbi = TestMacroInstallerGui.ToolbarIntercepter()
572
        self.installer._ask_for_toolbar = tbi._ask_for_toolbar
573
        self.installer._install_macro_to_toolbar = tbi._install_macro_to_toolbar
574
        ut_tb_1 = self.installer.toolbar_params.GetGroup("UT_TB_1")
575
        ut_tb_2 = self.installer.toolbar_params.GetGroup("UT_TB_2")
576
        ut_tb_3 = self.installer.toolbar_params.GetGroup("UT_TB_3")
577
        ut_tb_1.set("Name", "UT_TB_1")
578
        ut_tb_2.set("Name", "UT_TB_2")
579
        ut_tb_3.set("Name", "UT_TB_3")
580
        self.installer.addon_params.set("CustomToolbarName", "UT_TB_4")
581
        self.installer._install_toolbar_button()
582
        self.assertTrue(tbi.install_macro_to_toolbar_called)
583
        self.assertTrue(tbi.ask_for_toolbar_called)
584
        self.assertEqual(tbi.tb.get("Name", ""), "MockCustomToolbar")
585

586
    def test_install_toolbar_button_existing_custom_toolbar_4(self):
587
        # There are multiple existing custom toolbars, one of them matches, but we have set
588
        # "alwaysAskForToolbar" to True
589
        tbi = TestMacroInstallerGui.ToolbarIntercepter()
590
        self.installer._ask_for_toolbar = tbi._ask_for_toolbar
591
        self.installer._install_macro_to_toolbar = tbi._install_macro_to_toolbar
592
        ut_tb_1 = self.installer.toolbar_params.GetGroup("UT_TB_1")
593
        ut_tb_2 = self.installer.toolbar_params.GetGroup("UT_TB_2")
594
        ut_tb_3 = self.installer.toolbar_params.GetGroup("UT_TB_3")
595
        ut_tb_1.set("Name", "UT_TB_1")
596
        ut_tb_2.set("Name", "UT_TB_2")
597
        ut_tb_3.set("Name", "UT_TB_3")
598
        self.installer.addon_params.set("CustomToolbarName", "UT_TB_3")
599
        self.installer.addon_params.set("alwaysAskForToolbar", True)
600
        self.installer._install_toolbar_button()
601
        self.assertTrue(tbi.install_macro_to_toolbar_called)
602
        self.assertTrue(tbi.ask_for_toolbar_called)
603
        self.assertEqual(tbi.tb.get("Name", ""), "MockCustomToolbar")
604

605
    def test_install_macro_to_toolbar_icon_abspath(self):
606
        ut_tb_1 = self.installer.toolbar_params.GetGroup("UT_TB_1")
607
        ut_tb_1.set("Name", "UT_TB_1")
608
        ii = TestMacroInstallerGui.InstallerInterceptor()
609
        self.installer._create_custom_command = ii._create_custom_command
610
        with tempfile.NamedTemporaryFile() as ntf:
611
            self.mock_macro.macro.icon = ntf.name
612
            self.installer._install_macro_to_toolbar(ut_tb_1)
613
            self.assertTrue(ii.ccc_called)
614
            self.assertEqual(ii.pixmapText, ntf.name)
615

616
    def test_install_macro_to_toolbar_icon_relpath(self):
617
        ut_tb_1 = self.installer.toolbar_params.GetGroup("UT_TB_1")
618
        ut_tb_1.set("Name", "UT_TB_1")
619
        ii = TestMacroInstallerGui.InstallerInterceptor()
620
        self.installer._create_custom_command = ii._create_custom_command
621
        with tempfile.TemporaryDirectory() as td:
622
            self.installer.macro_dir = td
623
            self.mock_macro.macro.icon = "RelativeIconPath.png"
624
            self.installer._install_macro_to_toolbar(ut_tb_1)
625
            self.assertTrue(ii.ccc_called)
626
            self.assertEqual(ii.pixmapText, os.path.join(td, "RelativeIconPath.png"))
627

628
    def test_install_macro_to_toolbar_xpm(self):
629
        ut_tb_1 = self.installer.toolbar_params.GetGroup("UT_TB_1")
630
        ut_tb_1.set("Name", "UT_TB_1")
631
        ii = TestMacroInstallerGui.InstallerInterceptor()
632
        self.installer._create_custom_command = ii._create_custom_command
633
        with tempfile.TemporaryDirectory() as td:
634
            self.installer.macro_dir = td
635
            self.mock_macro.macro.xpm = "Not really xpm data, don't try to use it!"
636
            self.installer._install_macro_to_toolbar(ut_tb_1)
637
            self.assertTrue(ii.ccc_called)
638
            self.assertEqual(ii.pixmapText, os.path.join(td, "MockMacro_icon.xpm"))
639
            self.assertTrue(os.path.exists(os.path.join(td, "MockMacro_icon.xpm")))
640

641
    def test_install_macro_to_toolbar_no_icon(self):
642
        ut_tb_1 = self.installer.toolbar_params.GetGroup("UT_TB_1")
643
        ut_tb_1.set("Name", "UT_TB_1")
644
        ii = TestMacroInstallerGui.InstallerInterceptor()
645
        self.installer._create_custom_command = ii._create_custom_command
646
        with tempfile.TemporaryDirectory() as td:
647
            self.installer.macro_dir = td
648
            self.installer._install_macro_to_toolbar(ut_tb_1)
649
            self.assertTrue(ii.ccc_called)
650
            self.assertIsNone(ii.pixmapText)
651

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.