FreeCAD

Форк
0
126 строк · 5.7 Кб
1
# SPDX-License-Identifier: LGPL-2.1-or-later
2
# ***************************************************************************
3
# *                                                                         *
4
# *   Copyright (c) 2022-2023 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
import datetime
24
import sys
25
import unittest
26
from datetime import date
27
from unittest import TestCase
28
from unittest.mock import MagicMock, patch
29

30
sys.path.append("../..")
31

32
import addonmanager_cache as cache
33
from AddonManagerTest.app.mocks import MockPref, MockExists
34

35

36
class TestCache(TestCase):
37
    @patch("addonmanager_freecad_interface.getUserCachePath")
38
    @patch("addonmanager_freecad_interface.ParamGet")
39
    @patch("os.remove", MagicMock())
40
    @patch("os.makedirs", MagicMock())
41
    def test_local_cache_needs_update(self, param_mock: MagicMock, cache_mock: MagicMock):
42
        cache_mock.return_value = ""
43
        param_mock.return_value = MockPref()
44
        default_prefs = {
45
            "UpdateFrequencyComboEntry": 0,
46
            "LastCacheUpdate": "2000-01-01",
47
            "CustomRepoHash": "",
48
            "CustomRepositories": "",
49
        }
50
        today = date.today().isoformat()
51
        yesterday = (date.today() - datetime.timedelta(1)).isoformat()
52

53
        # Organize these as subtests because of all the patching that has to be done: once we are in this function,
54
        # the patch is complete, and we can just modify the return values of the fakes one by one
55
        tests = (
56
            {
57
                "case": "No existing cache",
58
                "files_that_exist": [],
59
                "prefs_to_set": {},
60
                "expect": True,
61
            },
62
            {
63
                "case": "Last cache update was interrupted",
64
                "files_that_exist": ["CACHE_UPDATE_INTERRUPTED"],
65
                "prefs_to_set": {},
66
                "expect": True,
67
            },
68
            {
69
                "case": "Cache exists and updating is blocked",
70
                "files_that_exist": ["AddonManager"],
71
                "prefs_to_set": {},
72
                "expect": False,
73
            },
74
            {
75
                "case": "Daily updates set and last update was long ago",
76
                "files_that_exist": ["AddonManager"],
77
                "prefs_to_set": {"UpdateFrequencyComboEntry": 1},
78
                "expect": True,
79
            },
80
            {
81
                "case": "Daily updates set and last update was today",
82
                "files_that_exist": ["AddonManager"],
83
                "prefs_to_set": {"UpdateFrequencyComboEntry": 1, "LastCacheUpdate": today},
84
                "expect": False,
85
            },
86
            {
87
                "case": "Daily updates set and last update was yesterday",
88
                "files_that_exist": ["AddonManager"],
89
                "prefs_to_set": {"UpdateFrequencyComboEntry": 1, "LastCacheUpdate": yesterday},
90
                "expect": True,
91
            },
92
            {
93
                "case": "Weekly updates set and last update was long ago",
94
                "files_that_exist": ["AddonManager"],
95
                "prefs_to_set": {"UpdateFrequencyComboEntry": 1},
96
                "expect": True,
97
            },
98
            {
99
                "case": "Weekly updates set and last update was yesterday",
100
                "files_that_exist": ["AddonManager"],
101
                "prefs_to_set": {"UpdateFrequencyComboEntry": 2, "LastCacheUpdate": yesterday},
102
                "expect": False,
103
            },
104
            {
105
                "case": "Custom repo list changed",
106
                "files_that_exist": ["AddonManager"],
107
                "prefs_to_set": {"CustomRepositories": "NewRepo"},
108
                "expect": True,
109
            },
110
        )
111
        for test_case in tests:
112
            with self.subTest(test_case["case"]):
113
                case_prefs = default_prefs
114
                for pref, setting in test_case["prefs_to_set"].items():
115
                    case_prefs[pref] = setting
116
                param_mock.return_value.set_prefs(case_prefs)
117
                exists_mock = MockExists(test_case["files_that_exist"])
118
                with patch("os.path.exists", exists_mock.exists):
119
                    if test_case["expect"]:
120
                        self.assertTrue(cache.local_cache_needs_update())
121
                    else:
122
                        self.assertFalse(cache.local_cache_needs_update())
123

124

125
if __name__ == "__main__":
126
    unittest.main()
127

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

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

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

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