Skip to content
Navigation Menu
{{ message }}
forked from SolidCode/SolidPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_solidpython.py
More file actions
executable file
·399 lines (337 loc) · 19.5 KB
/
Copy pathtest_solidpython.py
File metadata and controls
executable file
·399 lines (337 loc) · 19.5 KB
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
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import unittest
import tempfile
from solid.test.ExpandedTestCase import DiffOutput
from solid import *
scad_test_case_templates = [
{'name': 'polygon', 'kwargs': {'paths': [[0, 1, 2]]}, 'expected': '\n\npolygon(paths = [[0, 1, 2]], points = [[0, 0, 0], [1, 0, 0], [0, 1, 0]]);', 'args': {'points': [[0, 0, 0], [1, 0, 0], [0, 1, 0]]}, },
{'name': 'circle', 'kwargs': {'segments': 12, 'r': 1}, 'expected': '\n\ncircle($fn = 12, r = 1);', 'args': {}, },
{'name': 'circle', 'kwargs': {'segments': 12, 'd': 1}, 'expected': '\n\ncircle($fn = 12, d = 1);', 'args': {}, },
{'name': 'square', 'kwargs': {'center': False, 'size': 1}, 'expected': '\n\nsquare(center = false, size = 1);', 'args': {}, },
{'name': 'sphere', 'kwargs': {'segments': 12, 'r': 1}, 'expected': '\n\nsphere($fn = 12, r = 1);', 'args': {}, },
{'name': 'sphere', 'kwargs': {'segments': 12, 'd': 1}, 'expected': '\n\nsphere($fn = 12, d = 1);', 'args': {}, },
{'name': 'cube', 'kwargs': {'center': False, 'size': 1}, 'expected': '\n\ncube(center = false, size = 1);', 'args': {}, },
{'name': 'cylinder', 'kwargs': {'r1': None, 'r2': None, 'h': 1, 'segments': 12, 'r': 1, 'center': False}, 'expected': '\n\ncylinder($fn = 12, center = false, h = 1, r = 1);', 'args': {}, },
{'name': 'cylinder', 'kwargs': {'d1': 4, 'd2': 2, 'h': 1, 'segments': 12, 'center': False}, 'expected': '\n\ncylinder($fn = 12, center = false, d1 = 4, d2 = 2, h = 1);', 'args': {}, },
{'name': 'polyhedron', 'kwargs': {'convexity': None}, 'expected': '\n\npolyhedron(faces = [[0, 1, 2]], points = [[0, 0, 0], [1, 0, 0], [0, 1, 0]]);', 'args': {'points': [[0, 0, 0], [1, 0, 0], [0, 1, 0]], 'faces': [[0, 1, 2]]}, },
{'name': 'union', 'kwargs': {}, 'expected': '\n\nunion();', 'args': {}, },
{'name': 'intersection','kwargs': {}, 'expected': '\n\nintersection();', 'args': {}, },
{'name': 'difference', 'kwargs': {}, 'expected': '\n\ndifference();', 'args': {}, },
{'name': 'translate', 'kwargs': {'v': [1, 0, 0]}, 'expected': '\n\ntranslate(v = [1, 0, 0]);', 'args': {}, },
{'name': 'scale', 'kwargs': {'v': 0.5}, 'expected': '\n\nscale(v = 0.5000000000);', 'args': {}, },
{'name': 'rotate', 'kwargs': {'a': 45, 'v': [0, 0, 1]}, 'expected': '\n\nrotate(a = 45, v = [0, 0, 1]);', 'args': {}, },
{'name': 'mirror', 'kwargs': {}, 'expected': '\n\nmirror(v = [0, 0, 1]);', 'args': {'v': [0, 0, 1]}, },
{'name': 'resize', 'kwargs': {'newsize':[5,5,5], 'auto':[True, True, False]}, 'expected': '\n\nresize(auto = [true, true, false], newsize = [5, 5, 5]);', 'args': {}, },
{'name': 'multmatrix', 'kwargs': {}, 'expected': '\n\nmultmatrix(m = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]);', 'args': {'m': [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]}, },
{'name': 'color', 'kwargs': {}, 'expected': '\n\ncolor(c = [1, 0, 0]);', 'args': {'c': [1, 0, 0]}, },
{'name': 'minkowski', 'kwargs': {}, 'expected': '\n\nminkowski();', 'args': {}, },
{'name': 'offset', 'kwargs': {'r': 1}, 'expected': '\n\noffset(r = 1);', 'args': {}, },
{'name': 'offset', 'kwargs': {'delta': 1}, 'expected': '\n\noffset(chamfer = false, delta = 1);', 'args': {}, },
{'name': 'hull', 'kwargs': {}, 'expected': '\n\nhull();', 'args': {}, },
{'name': 'render', 'kwargs': {'convexity': None}, 'expected': '\n\nrender();', 'args': {}, },
{'name': 'projection', 'kwargs': {'cut': None}, 'expected': '\n\nprojection();', 'args': {}, },
{'name': 'surface', 'kwargs': {'center': False, 'convexity': None}, 'expected': '\n\nsurface(center = false, file = "/Path/to/dummy.dxf");', 'args': {'file': "'/Path/to/dummy.dxf'"}, },
{'name': 'import_stl', 'kwargs': {'layer': None, 'origin': (0,0)}, 'expected': '\n\nimport(file = "/Path/to/dummy.stl", origin = [0, 0]);', 'args': {'file': "'/Path/to/dummy.stl'"}, },
{'name': 'import_dxf', 'kwargs': {'layer': None, 'origin': (0,0)}, 'expected': '\n\nimport(file = "/Path/to/dummy.dxf", origin = [0, 0]);', 'args': {'file': "'/Path/to/dummy.dxf'"}, },
{'name': 'import_', 'kwargs': {'layer': None, 'origin': (0,0)}, 'expected': '\n\nimport(file = "/Path/to/dummy.dxf", origin = [0, 0]);', 'args': {'file': "'/Path/to/dummy.dxf'"}, },
{'name': 'import_', 'kwargs': {'layer': None, 'origin': (0,0), 'convexity': 2}, 'expected': '\n\nimport(convexity = 2, file = "/Path/to/dummy.dxf", origin = [0, 0]);', 'args': {'file': "'/Path/to/dummy.dxf'"}, },
{'name': 'linear_extrude', 'kwargs': {'twist': None, 'slices': None, 'center': False, 'convexity': None, 'height': 1, 'scale': 0.9}, 'expected': '\n\nlinear_extrude(center = false, height = 1, scale = 0.9000000000);', 'args': {}, },
{'name': 'rotate_extrude', 'kwargs': {'angle':90, 'segments': 4, 'convexity': None}, 'expected': '\n\nrotate_extrude($fn = 4, angle = 90);', 'args': {}, },
{'name': 'intersection_for', 'kwargs': {}, 'expected': '\n\nintersection_for(n = [0, 1, 2]);', 'args': {'n': [0, 1, 2]}, },
]
class TemporaryFileBuffer(object):
name = None
contents = None
def __enter__(self):
f = tempfile.NamedTemporaryFile(delete=False)
self.name = f.name
try:
f.close()
except:
self._cleanup()
raise
return self
def __exit__(self, exc_type, exc_val, exc_tb):
try:
with open(self.name, 'r') as f:
self.contents = f.read()
finally:
self._cleanup()
def _cleanup(self):
try:
os.unlink(self.name)
except:
pass
class TestSolidPython(DiffOutput):
# test cases will be dynamically added to this instance
def expand_scad_path(self, filename):
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../')
return os.path.join(path, filename)
def test_infix_union(self):
a = cube(2)
b = sphere(2)
expected = '\n\nunion() {\n\tcube(size = 2);\n\tsphere(r = 2);\n}'
actual = scad_render(a + b)
self.assertEqual(expected, actual)
def test_infix_difference(self):
a = cube(2)
b = sphere(2)
expected = '\n\ndifference() {\n\tcube(size = 2);\n\tsphere(r = 2);\n}'
actual = scad_render(a - b)
self.assertEqual(expected, actual)
def test_infix_intersection(self):
a = cube(2)
b = sphere(2)
expected = '\n\nintersection() {\n\tcube(size = 2);\n\tsphere(r = 2);\n}'
actual = scad_render(a * b)
self.assertEqual(expected, actual)
def test_parse_scad_callables(self):
test_str = """
module hex (width=10, height=10,
flats= true, center=false){}
function righty (angle=90) = 1;
function lefty(avar) = 2;
module more(a=[something, other]) {}
module pyramid(side=10, height=-1, square=false, centerHorizontal=true, centerVertical=false){}
module no_comments(arg=10, //test comment
other_arg=2, /* some extra comments
on empty lines */
last_arg=4){}
module float_arg(arg=1.0){}
module arg_var(var5){}
module kwarg_var(var2=78){}
module var_true(var_true = true){}
module var_false(var_false = false){}
module var_int(var_int = 5){}
module var_negative(var_negative = -5){}
module var_float(var_float = 5.5){}
module var_number(var_number = -5e89){}
module var_empty_vector(var_empty_vector = []){}
module var_simple_string(var_simple_string = "simple string"){}
module var_complex_string(var_complex_string = "a \"complex\"\tstring with a\\"){}
module var_vector(var_vector = [5454445, 565, [44545]]){}
module var_complex_vector(var_complex_vector = [545 + 4445, 565, [cos(75) + len("yes", 45)]]){}
module var_vector(var_vector = [5, 6, "string\twith\ttab"]){}
module var_range(var_range = [0:10e10]){}
module var_range_step(var_range_step = [-10:0.5:10]){}
module var_with_arithmetic(var_with_arithmetic = 8 * 9 - 1 + 89 / 15){}
module var_with_parentheses(var_with_parentheses = 8 * ((9 - 1) + 89) / 15){}
module var_with_functions(var_with_functions = abs(min(chamferHeight2, 0)) */-+ 1){}
module var_with_conditionnal_assignment(var_with_conditionnal_assignment = mytest ? 45 : yop){}
"""
expected = [
{'name': 'hex', 'args': [], 'kwargs': ['width', 'height', 'flats', 'center']},
{'name': 'righty', 'args': [], 'kwargs': ['angle']},
{'name': 'lefty', 'args': ['avar'], 'kwargs': []},
{'name': 'more', 'args': [], 'kwargs': ['a']},
{'name': 'pyramid', 'args': [], 'kwargs': ['side', 'height', 'square', 'centerHorizontal', 'centerVertical']},
{'name': 'no_comments', 'args': [], 'kwargs': ['arg', 'other_arg', 'last_arg']},
{'name': 'float_arg', 'args': [], 'kwargs': ['arg']},
{'name': 'arg_var', 'args': ['var5'], 'kwargs': []},
{'name': 'kwarg_var', 'args': [], 'kwargs': ['var2']},
{'name': 'var_true', 'args': [], 'kwargs': ['var_true']},
{'name': 'var_false', 'args': [],'kwargs': ['var_false']},
{'name': 'var_int', 'args': [], 'kwargs': ['var_int']},
{'name': 'var_negative', 'args': [], 'kwargs': ['var_negative']},
{'name': 'var_float', 'args': [], 'kwargs': ['var_float']},
{'name': 'var_number', 'args': [], 'kwargs': ['var_number']},
{'name': 'var_empty_vector', 'args': [], 'kwargs': ['var_empty_vector']},
{'name': 'var_simple_string', 'args': [], 'kwargs': ['var_simple_string']},
{'name': 'var_complex_string', 'args': [], 'kwargs': ['var_complex_string']},
{'name': 'var_vector', 'args': [], 'kwargs': ['var_vector']},
{'name': 'var_complex_vector', 'args': [], 'kwargs': ['var_complex_vector']},
{'name': 'var_vector', 'args': [], 'kwargs': ['var_vector']},
{'name': 'var_range', 'args': [], 'kwargs': ['var_range']},
{'name': 'var_range_step', 'args': [], 'kwargs': ['var_range_step']},
{'name': 'var_with_arithmetic', 'args': [], 'kwargs': ['var_with_arithmetic']},
{'name': 'var_with_parentheses', 'args': [], 'kwargs': ['var_with_parentheses']},
{'name': 'var_with_functions', 'args': [], 'kwargs': ['var_with_functions']},
{'name': 'var_with_conditionnal_assignment', 'args': [], 'kwargs': ['var_with_conditionnal_assignment']}
]
from solid.solidpython import parse_scad_callables
actual = parse_scad_callables(test_str)
self.assertEqual(expected, actual)
def test_use(self):
include_file = self.expand_scad_path("examples/scad_to_include.scad")
use(include_file)
a = steps(3)
actual = scad_render(a)
abs_path = a._get_include_path(include_file)
expected = "use <%s>\n\n\nsteps(howmany = 3);" % abs_path
self.assertEqual(expected, actual)
def test_use_reserved_words(self):
scad_str = '''module reserved_word_arg(or=3){\n\tcube(or);\n}\nmodule or(arg=3){\n\tcube(arg);\n}\n'''
fd, path = tempfile.mkstemp(text=True)
try:
os.close(fd)
with open(path, "w") as f:
f.write(scad_str)
use(path)
a = reserved_word_arg(or_=5)
actual = scad_render(a)
expected = "use <%s>\n\n\nreserved_word_arg(or = 5);"%path;
self.assertEqual(expected, actual)
b = or_(arg=5)
actual = scad_render(b)
expected = "use <%s>\n\n\nor(arg = 5);"%path;
self.assertEqual(expected, actual)
finally:
os.remove(path)
def test_include(self):
include_file = self.expand_scad_path("examples/scad_to_include.scad")
self.assertIsNotNone(include_file, 'examples/scad_to_include.scad not found')
include(include_file)
a = steps(3)
actual = scad_render(a)
abs_path = a._get_include_path(include_file)
expected = "include <%s>\n\n\nsteps(howmany = 3);" % abs_path
self.assertEqual(expected, actual)
def test_extra_args_to_included_scad(self):
include_file = self.expand_scad_path("examples/scad_to_include.scad")
use(include_file)
a = steps(3, external_var=True)
actual = scad_render(a)
abs_path = a._get_include_path(include_file)
expected = "use <%s>\n\n\nsteps(external_var = true, howmany = 3);" % abs_path
self.assertEqual(expected, actual)
def test_background(self):
a = cube(10)
expected = '\n\n%cube(size = 10);'
actual = scad_render(background(a))
self.assertEqual(expected, actual)
def test_debug(self):
a = cube(10)
expected = '\n\n#cube(size = 10);'
actual = scad_render(debug(a))
self.assertEqual(expected, actual)
def test_disable(self):
a = cube(10)
expected = '\n\n*cube(size = 10);'
actual = scad_render(disable(a))
self.assertEqual(expected, actual)
def test_root(self):
a = cube(10)
expected = '\n\n!cube(size = 10);'
actual = scad_render(root(a))
self.assertEqual(expected, actual)
def test_explicit_hole(self):
a = cube(10, center=True) + hole()(cylinder(2, 20, center=True))
expected = '\n\ndifference(){\n\tunion() {\n\t\tcube(center = true, size = 10);\n\t}\n\t/* Holes Below*/\n\tunion(){\n\t\tcylinder(center = true, h = 20, r = 2);\n\t} /* End Holes */ \n}'
actual = scad_render(a)
self.assertEqual(expected, actual)
def test_hole_transform_propagation(self):
# earlier versions of holes had problems where a hole
# that was used a couple places wouldn't propagate correctly.
# Confirm that's still happening as it's supposed to
h = hole()(
rotate(a=90, v=[0, 1, 0])(
cylinder(2, 20, center=True)
)
)
h_vert = rotate(a=-90, v=[0, 1, 0])(
h
)
a = cube(10, center=True) + h + h_vert
expected = '\n\ndifference(){\n\tunion() {\n\t\tcube(center = true, size = 10);\n\t\trotate(a = -90, v = [0, 1, 0]) {\n\t\t}\n\t}\n\t/* Holes Below*/\n\tunion(){\n\t\trotate(a = 90, v = [0, 1, 0]) {\n\t\t\tcylinder(center = true, h = 20, r = 2);\n\t\t}\n\t\trotate(a = -90, v = [0, 1, 0]){\n\t\t\trotate(a = 90, v = [0, 1, 0]) {\n\t\t\t\tcylinder(center = true, h = 20, r = 2);\n\t\t\t}\n\t\t}\n\t} /* End Holes */ \n}'
actual = scad_render(a)
self.assertEqual(expected, actual)
def test_separate_part_hole(self):
# Make two parts, a block with hole, and a cylinder that
# fits inside it. Make them separate parts, meaning
# holes will be defined at the level of the part_root node,
# not the overall node. This allows us to preserve holes as
# first class space, but then to actually fill them in with
# the parts intended to fit in them.
b = cube(10, center=True)
c = cylinder(r=2, h=12, center=True)
p1 = b - hole()(c)
# Mark this cube-with-hole as a separate part from the cylinder
p1 = part()(p1)
# This fits in the hole. If p1 is set as a part_root, it will all appear.
# If not, the portion of the cylinder inside the cube will not appear,
# since it would have been removed by the hole in p1
p2 = cylinder(r=1.5, h=14, center=True)
a = p1 + p2
expected = '\n\nunion() {\n\tdifference(){\n\t\tdifference() {\n\t\t\tcube(center = true, size = 10);\n\t\t}\n\t\t/* Holes Below*/\n\t\tunion(){\n\t\t\tcylinder(center = true, h = 12, r = 2);\n\t\t} /* End Holes */ \n\t}\n\tcylinder(center = true, h = 14, r = 1.5000000000);\n}'
actual = scad_render(a)
self.assertEqual(expected, actual)
def test_scad_render_animated_file(self):
def my_animate(_time=0):
import math
# _time will range from 0 to 1, not including 1
rads = _time * 2 * math.pi
rad = 15
c = translate([rad * math.cos(rads), rad * math.sin(rads)])(square(10))
return c
with TemporaryFileBuffer() as tmp:
scad_render_animated_file(my_animate, steps=2, back_and_forth=False,
filepath=tmp.name, include_orig_code=False)
actual = tmp.contents
expected = '\nif ($t >= 0.0 && $t < 0.5){ \n\ttranslate(v = [15.0000000000, 0.0000000000]) {\n\t\tsquare(size = 10);\n\t}\n}\nif ($t >= 0.5 && $t < 1.0){ \n\ttranslate(v = [-15.0000000000, 0.0000000000]) {\n\t\tsquare(size = 10);\n\t}\n}\n'
self.assertEqual(expected, actual)
def test_scad_render_to_file(self):
a = circle(10)
# No header, no included original code
with TemporaryFileBuffer() as tmp:
scad_render_to_file(a, filepath=tmp.name, include_orig_code=False)
actual = tmp.contents
expected = '\n\ncircle(r = 10);'
self.assertEqual(expected, actual)
# Header
with TemporaryFileBuffer() as tmp:
scad_render_to_file(a, filepath=tmp.name, include_orig_code=False,
file_header='$fn = 24;')
actual = tmp.contents
expected = '$fn = 24;\n\ncircle(r = 10);'
self.assertEqual(expected, actual)
# TODO: test include_orig_code=True, but that would have to
# be done from a separate file, or include everything in this one
def test_numpy_type(self):
try:
import numpy
numpy_cube = cube(size=numpy.array([1,2,3]))
expected ='\n\ncube(size = [1,2,3]);'
actual = scad_render(numpy_cube)
self.assertEqual(expected, actual, 'Numpy SolidPython not rendered correctly')
except ImportError:
pass
def test_custom_iterables(self):
from euclid3 import Vector3
class CustomIterable:
def __iter__(self):
return iter([1, 2, 3])
expected ='\n\ncube(size = [1, 2, 3]);'
iterables = [
[1, 2, 3],
(1, 2, 3),
Vector3(1, 2, 3),
CustomIterable(),
]
for iterable in iterables:
name = type(iterable).__name__
actual = scad_render(cube(size=iterable))
self.assertEqual(expected, actual, '%s SolidPython not rendered correctly' % name)
def single_test(test_dict):
name, args, kwargs, expected = test_dict['name'], test_dict['args'], test_dict['kwargs'], test_dict['expected']
def test(self):
call_str = name + "("
for k, v in args.items():
call_str += "%s=%s, " % (k, v)
for k, v in kwargs.items():
call_str += "%s=%s, " % (k, v)
call_str += ')'
scad_obj = eval(call_str)
actual = scad_render(scad_obj)
self.assertEqual(expected, actual)
return test
def generate_cases_from_templates():
for test_dict in scad_test_case_templates:
test = single_test(test_dict)
test_name = "test_%(name)s" % test_dict
setattr(TestSolidPython, test_name, test)
if __name__ == '__main__':
generate_cases_from_templates()
unittest.main()
You can’t perform that action at this time.
