FreeCAD

Форк
0
213 строк · 8.0 Кб
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

24
import os
25
import sys
26
import tempfile
27
from typing import Dict
28
import unittest
29
from unittest.mock import MagicMock
30

31
sys.path.append("../../")  # So the IDE can find the
32

33
import FreeCAD
34

35
from addonmanager_macro import Macro
36

37

38
class TestMacro(unittest.TestCase):
39
    MODULE = "test_macro"  # file name without extension
40

41
    def setUp(self):
42
        self.test_dir = os.path.join(
43
            FreeCAD.getHomePath(), "Mod", "AddonManager", "AddonManagerTest", "data"
44
        )
45

46
    def test_basic_metadata(self):
47
        replacements = {
48
            "COMMENT": "test comment",
49
            "WEB": "https://test.url",
50
            "VERSION": "1.2.3",
51
            "AUTHOR": "Test Author",
52
            "DATE": "2022-03-09",
53
            "ICON": "testicon.svg",
54
        }
55
        m = self.generate_macro(replacements)
56
        self.assertEqual(m.comment, replacements["COMMENT"])
57
        self.assertEqual(m.url, replacements["WEB"])
58
        self.assertEqual(m.version, replacements["VERSION"])
59
        self.assertEqual(m.author, replacements["AUTHOR"])
60
        self.assertEqual(m.date, replacements["DATE"])
61
        self.assertEqual(m.icon, replacements["ICON"])
62

63
    def test_other_files(self):
64
        replacements = {
65
            "FILES": "file_a,file_b,file_c",
66
        }
67
        m = self.generate_macro(replacements)
68
        self.assertEqual(len(m.other_files), 3)
69
        self.assertEqual(m.other_files[0], "file_a")
70
        self.assertEqual(m.other_files[1], "file_b")
71
        self.assertEqual(m.other_files[2], "file_c")
72

73
        replacements = {
74
            "FILES": "file_a, file_b, file_c",
75
        }
76
        m = self.generate_macro(replacements)
77
        self.assertEqual(len(m.other_files), 3)
78
        self.assertEqual(m.other_files[0], "file_a")
79
        self.assertEqual(m.other_files[1], "file_b")
80
        self.assertEqual(m.other_files[2], "file_c")
81

82
        replacements = {
83
            "FILES": "file_a file_b file_c",
84
        }
85
        m = self.generate_macro(replacements)
86
        self.assertEqual(len(m.other_files), 1)
87
        self.assertEqual(m.other_files[0], "file_a file_b file_c")
88

89
    def test_version_from_string(self):
90
        replacements = {
91
            "VERSION": "1.2.3",
92
        }
93
        m = self.generate_macro(replacements)
94
        self.assertEqual(m.version, "1.2.3")
95

96
    def test_version_from_date(self):
97
        replacements = {
98
            "DATE": "2022-03-09",
99
        }
100
        outfile = self.generate_macro_file(replacements)
101
        with open(outfile) as f:
102
            lines = f.readlines()
103
            output_lines = []
104
            for line in lines:
105
                if "VERSION" in line:
106
                    line = "__Version__ = __Date__"
107
                output_lines.append(line)
108
        with open(outfile, "w") as f:
109
            f.write("\n".join(output_lines))
110
        m = Macro("Unit Test Macro")
111
        m.fill_details_from_file(outfile)
112
        self.assertEqual(m.version, "2022-03-09")
113

114
    def test_version_from_float(self):
115
        outfile = self.generate_macro_file()
116
        with open(outfile) as f:
117
            lines = f.readlines()
118
            output_lines = []
119
            for line in lines:
120
                if "VERSION" in line:
121
                    line = "__Version__ = 1.23"
122
                output_lines.append(line)
123
        with open(outfile, "w") as f:
124
            f.write("\n".join(output_lines))
125
        m = Macro("Unit Test Macro")
126
        m.fill_details_from_file(outfile)
127
        self.assertEqual(m.version, "1.23")
128

129
    def test_version_from_int(self):
130
        outfile = self.generate_macro_file()
131
        with open(outfile) as f:
132
            lines = f.readlines()
133
            output_lines = []
134
            for line in lines:
135
                if "VERSION" in line:
136
                    line = "__Version__ = 1"
137
                output_lines.append(line)
138
        with open(outfile, "w") as f:
139
            f.write("\n".join(output_lines))
140
        m = Macro("Unit Test Macro")
141
        m.fill_details_from_file(outfile)
142
        self.assertEqual(m.version, "1")
143

144
    def test_xpm(self):
145
        outfile = self.generate_macro_file()
146
        xpm_data = """/* XPM */
147
static char * blarg_xpm[] = {
148
"16 7 2 1",
149
"* c #000000",
150
". c #ffffff",
151
"**..*...........",
152
"*.*.*...........",
153
"**..*..**.**..**",
154
"*.*.*.*.*.*..*.*",
155
"**..*..**.*...**",
156
"...............*",
157
".............**."
158
};"""
159
        with open(outfile) as f:
160
            contents = f.read()
161
            contents += f'\n__xpm__ = """{xpm_data}"""\n'
162

163
        with open(outfile, "w") as f:
164
            f.write(contents)
165
        m = Macro("Unit Test Macro")
166
        m.fill_details_from_file(outfile)
167
        self.assertEqual(m.xpm, xpm_data)
168

169
    def generate_macro_file(self, replacements: Dict[str, str] = {}) -> os.PathLike:
170
        with open(os.path.join(self.test_dir, "macro_template.FCStd")) as f:
171
            lines = f.readlines()
172
            outfile = tempfile.NamedTemporaryFile(mode="wt", delete=False)
173
            for line in lines:
174
                for key, value in replacements.items():
175
                    line = line.replace(key, value)
176

177
                outfile.write(line)
178
            outfile.close()
179
            return outfile.name
180

181
    def generate_macro(self, replacements: Dict[str, str] = {}) -> Macro:
182
        outfile = self.generate_macro_file(replacements)
183
        m = Macro("Unit Test Macro")
184
        m.fill_details_from_file(outfile)
185
        os.unlink(outfile)
186
        return m
187

188
    def test_fetch_raw_code_no_data(self):
189
        m = Macro("Unit Test Macro")
190
        Macro.blocking_get = MagicMock(return_value=None)
191
        returned_data = m._fetch_raw_code(
192
            'rawcodeurl <a href="https://fake_url.com">Totally fake</a>'
193
        )
194
        self.assertIsNone(returned_data)
195
        m.blocking_get.assert_called_with("https://fake_url.com")
196
        Macro.blocking_get = None
197

198
    def test_fetch_raw_code_no_url(self):
199
        m = Macro("Unit Test Macro")
200
        Macro.blocking_get = MagicMock(return_value=None)
201
        returned_data = m._fetch_raw_code("Fake pagedata with no URL at all.")
202
        self.assertIsNone(returned_data)
203
        m.blocking_get.assert_not_called()
204
        Macro.blocking_get = None
205

206
    def test_fetch_raw_code_with_data(self):
207
        m = Macro("Unit Test Macro")
208
        Macro.blocking_get = MagicMock(return_value=b"Data returned to _fetch_raw_code")
209
        returned_data = m._fetch_raw_code(
210
            'rawcodeurl <a href="https://fake_url.com">Totally fake</a>'
211
        )
212
        self.assertEqual(returned_data, "Data returned to _fetch_raw_code")
213
        Macro.blocking_get = None
214

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

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

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

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