FreeCAD

Форк
0
/
Metadata.py 
207 строк · 8.6 Кб
1
# -*- coding: utf-8 -*-
2

3
# ***************************************************************************
4
# *   Copyright (c) 2022 FreeCAD Project Association                        *
5
# *                                                                         *
6
# *   This file is part of the FreeCAD CAx development system.              *
7
# *                                                                         *
8
# *   This library is free software; you can redistribute it and/or         *
9
# *   modify it under the terms of the GNU Lesser General Public            *
10
# *   License as published by the Free Software Foundation; either          *
11
# *   version 2.1 of the License, or (at your option) any later version.    *
12
# *                                                                         *
13
# *   This library is distributed in the hope that it will be useful,       *
14
# *   but 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 this library; if not, write to the Free Software   *
20
# *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA         *
21
# *   02110-1301  USA                                                       *
22
# *                                                                         *
23
# ***************************************************************************
24

25
import FreeCAD
26
import unittest
27
import os
28
import codecs
29
import tempfile
30

31

32
class TestMetadata(unittest.TestCase):
33
    def setUp(self):
34
        self.test_dir = os.path.join(FreeCAD.getHomePath(), "Mod", "Test", "TestData")
35

36
    def test_xml_constructor(self):
37
        try:
38
            filename = os.path.join(self.test_dir, "basic_metadata.xml")
39
            md = FreeCAD.Metadata(filename)
40
        except Exception:
41
            self.fail("Metadata construction from XML file failed")
42

43
        with self.assertRaises(
44
            FreeCAD.Base.XMLBaseException,
45
            msg="Metadata construction from XML file with bad root node did not raise an exception",
46
        ):
47
            filename = os.path.join(self.test_dir, "bad_root_node.xml")
48
            md = FreeCAD.Metadata(filename)
49

50
        with self.assertRaises(
51
            FreeCAD.Base.XMLBaseException,
52
            msg="Metadata construction from invalid XML file did not raise an exception",
53
        ):
54
            filename = os.path.join(self.test_dir, "bad_xml.xml")
55
            md = FreeCAD.Metadata(filename)
56

57
        with self.assertRaises(
58
            FreeCAD.Base.XMLBaseException,
59
            msg="Metadata construction from XML file with invalid version did not raise an exception",
60
        ):
61
            filename = os.path.join(self.test_dir, "bad_version.xml")
62
            md = FreeCAD.Metadata(filename)
63

64
    def test_toplevel_tags(self):
65
        filename = os.path.join(self.test_dir, "basic_metadata.xml")
66
        md = FreeCAD.Metadata(filename)
67

68
        # Tags with only one element:
69
        self.assertEqual(md.Name, "Test Workbench")
70
        self.assertEqual(md.Description, "A package.xml file for unit testing.")
71
        self.assertEqual(md.Version, "1.0.1")
72
        self.assertEqual(md.Date, "2022-01-07")
73
        self.assertEqual(md.Icon, "Resources/icons/PackageIcon.svg")
74

75
        # Tags that are lists of elements:
76
        maintainers = md.Maintainer
77
        self.assertEqual(len(maintainers), 2)
78

79
        authors = md.Author
80
        self.assertEqual(len(authors), 3)
81

82
        urls = md.Urls
83
        self.assertEqual(len(urls), 5)
84

85
        tags = md.Tag
86
        self.assertEqual(len(tags), 2)
87

88
    def test_copy_constructor(self):
89
        filename = os.path.join(self.test_dir, "basic_metadata.xml")
90
        md = FreeCAD.Metadata(filename)
91
        copy_of_md = FreeCAD.Metadata(md)
92
        self.assertEqual(md.Name, copy_of_md.Name)
93
        self.assertEqual(md.Description, copy_of_md.Description)
94
        self.assertEqual(md.Version, copy_of_md.Version)
95

96
    def test_default_constructor(self):
97
        try:
98
            _ = FreeCAD.Metadata()
99
        except Exception:
100
            self.fail("Metadata default constructor failed")
101

102
    def test_content_types(self):
103
        filename = os.path.join(self.test_dir, "content_items.xml")
104
        md = FreeCAD.Metadata(filename)
105

106
        content = md.Content
107
        self.assertTrue("workbench" in content)
108
        self.assertTrue("preferencepack" in content)
109
        self.assertTrue("macro" in content)
110
        self.assertTrue("other_content_item" in content)
111

112
        workbenches = content["workbench"]
113
        preferencepacks = content["preferencepack"]
114
        macros = content["macro"]
115
        other = content["other_content_item"]
116

117
        self.assertEqual(len(workbenches), 4)
118
        self.assertEqual(len(macros), 2)
119
        self.assertEqual(len(preferencepacks), 1)
120

121
    def test_file_path(self):
122
        # Issue 7112
123
        try:
124
            filename = os.path.join(tempfile.gettempdir(), b"H\xc3\xa5vard.xml".decode("utf-8"))
125
            xmlfile = codecs.open(filename, mode="w", encoding="utf-8")
126
            xmlfile.write(
127
                r"""<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
128
<package format="1" xmlns="https://wiki.freecad.org/Package_Metadata">
129
  <name>test</name>
130
  <description>Text</description>
131
  <version>1.0.0</version>
132
  <date>2022-01-01</date>
133
  <content>
134
    <workbench>
135
      <classname>Workbench</classname>
136
    </workbench>
137
  </content>
138
</package>"""
139
            )
140
            xmlfile.close()
141
            md = FreeCAD.Metadata(filename)
142
            self.assertEqual(md.Name, "test")
143
            self.assertEqual(md.Description, "Text")
144
            self.assertEqual(md.Version, "1.0.0")
145
        except UnicodeEncodeError as e:
146
            print("Ignore UnicodeEncodeError in test_file_path:\n{}".format(str(e)))
147

148
    def test_content_item_tags(self):
149
        filename = os.path.join(self.test_dir, "content_items.xml")
150
        md = FreeCAD.Metadata(filename)
151

152
        content = md.Content
153
        workbenches = content["workbench"]
154
        found = [False, False, False, False]
155
        for workbench in workbenches:
156
            print(workbench.Classname)
157
            if workbench.Classname == "TestWorkbenchA":
158
                found[0] = True
159
                self.assertEqual(workbench.FreeCADMin, "0.20.0")
160
                tags = workbench.Tag
161
                self.assertTrue("Tag A" in tags)
162
            elif workbench.Classname == "TestWorkbenchB":
163
                found[1] = True
164
                self.assertEqual(workbench.FreeCADMin, "0.1.0")
165
                self.assertEqual(workbench.FreeCADMax, "0.19.0")
166
                tags = workbench.Tag
167
                self.assertTrue("Tag B" in tags)
168
            elif workbench.Classname == "TestWorkbenchC":
169
                found[2] = True
170
                tags = workbench.Tag
171
                self.assertTrue("Tag C" in tags)
172
                self.assertTrue("Tag D" in tags)
173
            elif workbench.Classname == "TestWorkbenchD":
174
                found[3] = True
175
                dependencies = workbench.Depend
176
                expected_dependencies = {
177
                    "DependencyA": {"type": "automatic", "found": False},
178
                    "InternalWorkbench": {"type": "internal", "found": False},
179
                    "AddonWorkbench": {"type": "addon", "found": False},
180
                    "PythonPackage": {"type": "python", "found": False},
181
                    "DependencyB": {"type": "automatic", "found": False},
182
                }
183
                for dep in dependencies:
184
                    self.assertTrue(dep["package"] in expected_dependencies)
185
                    self.assertEqual(dep["type"], expected_dependencies[dep["package"]]["type"])
186
                    expected_dependencies[dep["package"]]["found"] = True
187
                for name, expected_dep in expected_dependencies.items():
188
                    self.assertTrue(expected_dep["found"], f"Failed to load dependency '{name}'")
189
        for f in found:
190
            self.assertTrue(
191
                f, f"One of the expected workbenches was not found in the metadata file"
192
            )
193

194
    def test_last_supported_version(self):
195
        pass
196

197
    def test_first_supported_version(self):
198
        pass
199

200
    def test_supports_current(self):
201
        pass
202

203
    def test_generic_metadata(self):
204
        pass
205

206
    def test_min_python_version(self):
207
        pass
208

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

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

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

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