-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathTestUtility.cs
More file actions
485 lines (399 loc) · 19.1 KB
/
TestUtility.cs
File metadata and controls
485 lines (399 loc) · 19.1 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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using NUnit.Framework;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.ProBuilder.MeshOperations;
using UnityEngine.SceneManagement;
using UnityEngine.ProBuilder.Shapes;
using UObject = UnityEngine.Object;
using PackageInfo = UnityEditor.PackageManager.PackageInfo;
namespace UnityEngine.ProBuilder.Tests.Framework
{
abstract class TemporaryAssetTest
{
public string tempDirectory => TestUtility.temporarySavedAssetsDirectory;
[OneTimeSetUp]
public virtual void OneTimeSetUp()
{
if (!Directory.Exists(tempDirectory))
Directory.CreateDirectory(tempDirectory);
}
[OneTimeTearDown]
public virtual void OneTimeTearDown()
{
if (Directory.Exists(tempDirectory))
Directory.Delete(tempDirectory, true);
var meta = tempDirectory;
if (meta.EndsWith("/") || meta.EndsWith("\\"))
meta = meta.Substring(0, meta.Length - 1);
File.Delete(meta + ".meta");
AssetDatabase.Refresh();
}
public Scene OpenScene(string path, OpenSceneMode openMode = OpenSceneMode.Single)
{
var tempPath = $"{tempDirectory}/{Path.GetFileName(path)}";
AssetDatabase.CopyAsset(path, tempPath);
return EditorSceneManager.OpenScene(tempPath, openMode);
}
public bool CloseScene(Scene scene)
{
return EditorSceneManager.CloseScene(scene, true);
}
}
public static class TestUtility
{
const MeshArrays k_DefaultMeshArraysCompare = ~MeshArrays.Lightmap;
static readonly string k_TempDirectory = "Assets/ProBuilderUnitTestsTemp/";
static readonly string k_TemplatesDirectory = testsRootDirectory + "/Templates/";
static readonly string k_RedMaterialPath = testsRootDirectory + "/Materials/Red.mat";
static readonly string k_BlueMaterialPath = testsRootDirectory + "/Materials/Blue.mat";
static readonly string k_GreenMaterialPath = testsRootDirectory + "/Materials/Green.mat";
public static string templatesDirectory
{
get { return k_TemplatesDirectory; }
}
public static string testsRootDirectory
{
get
{
var packageName = PackageInfo.FindForAssembly(Assembly.GetExecutingAssembly()).name;
return "Packages/" + packageName + "/Tests";
}
}
public static string temporarySavedAssetsDirectory
{
get { return k_TempDirectory; }
}
public class IgnoreAssertScope : IDisposable
{
bool m_SavedState;
public IgnoreAssertScope()
{
m_SavedState = UnityEngine.TestTools.LogAssert.ignoreFailingMessages;
UnityEngine.TestTools.LogAssert.ignoreFailingMessages = true; // Ignore logs due to not executing OnGUI loop
}
public void Dispose()
{
UnityEngine.TestTools.LogAssert.ignoreFailingMessages = m_SavedState;
}
}
/// <summary>
/// Convert a full path to one relative to the project directory.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
static string ToAssetPath(string path)
{
return path.Replace("\\", "/").Replace(Application.dataPath, "Assets/");
}
public static void AssertMeshAttributesValid(Mesh mesh)
{
int vertexCount = mesh.vertexCount;
Vector3[] positions = mesh.vertices;
Color[] colors = mesh.colors;
Vector3[] normals = mesh.normals;
Vector4[] tangents = mesh.tangents;
Vector2[] uv0s = mesh.uv;
Vector2[] uv2s = mesh.uv2;
List<Vector4> uv3s = new List<Vector4>();
List<Vector4> uv4s = new List<Vector4>();
mesh.GetUVs(2, uv3s);
mesh.GetUVs(3, uv4s);
bool _hasPositions = positions != null && positions.Length == vertexCount;
bool _hasColors = colors != null && colors.Length == vertexCount;
bool _hasNormals = normals != null && normals.Length == vertexCount;
bool _hasTangents = tangents != null && tangents.Length == vertexCount;
bool _hasUv0 = uv0s != null && uv0s.Length == vertexCount;
bool _hasUv2 = uv2s != null && uv2s.Length == vertexCount;
bool _hasUv3 = uv3s.Count == vertexCount;
bool _hasUv4 = uv4s.Count == vertexCount;
for (int i = 0; i < vertexCount; i++)
{
if (_hasPositions)
{
Assert.IsFalse(float.IsNaN(positions[i].x), "mesh attribute \"position\" is NaN");
Assert.IsFalse(float.IsNaN(positions[i].y), "mesh attribute \"position\" is NaN");
Assert.IsFalse(float.IsNaN(positions[i].z), "mesh attribute \"position\" is NaN");
}
if (_hasColors)
{
Assert.IsFalse(float.IsNaN(colors[i].r), "mesh attribute \"color\" is NaN");
Assert.IsFalse(float.IsNaN(colors[i].g), "mesh attribute \"color\" is NaN");
Assert.IsFalse(float.IsNaN(colors[i].b), "mesh attribute \"color\" is NaN");
Assert.IsFalse(float.IsNaN(colors[i].a), "mesh attribute \"color\" is NaN");
}
if (_hasNormals)
{
Assert.IsFalse(float.IsNaN(normals[i].x), "mesh attribute \"normal\" is NaN");
Assert.IsFalse(float.IsNaN(normals[i].y), "mesh attribute \"normal\" is NaN");
Assert.IsFalse(float.IsNaN(normals[i].z), "mesh attribute \"normal\" is NaN");
}
if (_hasTangents)
{
Assert.IsFalse(float.IsNaN(tangents[i].x), "mesh attribute \"tangent\" is NaN");
Assert.IsFalse(float.IsNaN(tangents[i].y), "mesh attribute \"tangent\" is NaN");
Assert.IsFalse(float.IsNaN(tangents[i].z), "mesh attribute \"tangent\" is NaN");
Assert.IsFalse(float.IsNaN(tangents[i].w), "mesh attribute \"tangent\" is NaN");
}
if (_hasUv0)
{
Assert.IsFalse(float.IsNaN(uv0s[i].x), "mesh attribute \"uv0\" is NaN");
Assert.IsFalse(float.IsNaN(uv0s[i].y), "mesh attribute \"uv0\" is NaN");
}
if (_hasUv2)
{
Assert.IsFalse(float.IsNaN(uv2s[i].x), "mesh attribute \"uv2\" is NaN");
Assert.IsFalse(float.IsNaN(uv2s[i].y), "mesh attribute \"uv2\" is NaN");
}
if (_hasUv3)
{
Assert.IsFalse(float.IsNaN(uv3s[i].x), "mesh attribute \"uv3\" is NaN");
Assert.IsFalse(float.IsNaN(uv3s[i].y), "mesh attribute \"uv3\" is NaN");
Assert.IsFalse(float.IsNaN(uv3s[i].z), "mesh attribute \"uv3\" is NaN");
Assert.IsFalse(float.IsNaN(uv3s[i].w), "mesh attribute \"uv3\" is NaN");
}
if (_hasUv4)
{
Assert.IsFalse(float.IsNaN(uv4s[i].x), "mesh attribute \"uv4\" is NaN");
Assert.IsFalse(float.IsNaN(uv4s[i].y), "mesh attribute \"uv4\" is NaN");
Assert.IsFalse(float.IsNaN(uv4s[i].z), "mesh attribute \"uv4\" is NaN");
Assert.IsFalse(float.IsNaN(uv4s[i].w), "mesh attribute \"uv4\" is NaN");
}
}
}
/// <summary>
/// Compare two meshes for value-wise equality.
/// </summary>
/// <param name="expected"></param>
/// <param name="result"></param>
/// <returns></returns>
public static bool AssertAreEqual(Mesh expected, Mesh result, MeshArrays compare = k_DefaultMeshArraysCompare, string message = null)
{
int vertexCount = expected.vertexCount;
int subMeshCount = expected.subMeshCount;
Assert.AreEqual(vertexCount, result.vertexCount, expected.name + " != " + result.name + " (submesh count)");
Assert.AreEqual(subMeshCount, result.subMeshCount, expected.name + " != " + result.name + " (submesh count)");
Vertex[] leftVertices = expected.GetVertices();
Vertex[] rightVertices = result.GetVertices();
for (int i = 0; i < vertexCount; i++)
Assert.True(leftVertices[i].Equals(rightVertices[i], compare),
expected.name + " != " + result.name + "\nExpected\n" + leftVertices[i].ToString("F5") + "\n---\nReceived:\n" + rightVertices[i].ToString("F5"));
List<int> leftIndices = new List<int>();
List<int> rightIndices = new List<int>();
for (int i = 0; i < subMeshCount; i++)
{
uint indexCount = expected.GetIndexCount(i);
Assert.AreEqual(expected.GetTopology(i), result.GetTopology(i));
Assert.AreEqual(indexCount, result.GetIndexCount(i));
expected.GetIndices(leftIndices, i);
result.GetIndices(rightIndices, i);
for (int n = 0; n < indexCount; n++)
Assert.AreEqual(leftIndices[n], rightIndices[n], message);
}
return true;
}
/// <summary>
/// Compare two meshes for value-wise inequality.
/// </summary>
/// <param name="expected"></param>
/// <param name="result"></param>
/// <returns></returns>
public static bool AssertMeshesAreEqual(Mesh expected, Mesh result)
{
int vertexCount = expected.vertexCount;
int subMeshCount = expected.subMeshCount;
string prefix = string.Format("Expected {0}, Was {1}\n",
expected == null ? "null" : expected.name,
result == null ? "null" : result.name);
Assert.AreEqual(vertexCount, result.vertexCount, prefix + "Vertex count");
Assert.AreEqual(subMeshCount, result.subMeshCount, prefix + "Submesh count");
Vertex[] leftVertices = expected.GetVertices();
Vertex[] rightVertices = result.GetVertices();
for (int i = 0; i < vertexCount; i++)
Assert.IsTrue(leftVertices[i].Equals(rightVertices[i]), string.Format("{0} Vertices are not equal.\nExpected:\n{1}\nReceived:\n{2}",
prefix,
leftVertices[i].ToString("F2"),
rightVertices[i].ToString("F2")));
List<int> leftIndices = new List<int>();
List<int> rightIndices = new List<int>();
for (int i = 0; i < subMeshCount; i++)
{
uint indexCount = expected.GetIndexCount(i);
Assert.AreEqual(expected.GetTopology(i), result.GetTopology(i), prefix + "Mesh topology");
Assert.AreEqual(indexCount, result.GetIndexCount(i), prefix + "Submesh index count");
expected.GetIndices(leftIndices, i);
result.GetIndices(rightIndices, i);
for (int n = 0; n < indexCount; n++)
Assert.AreEqual(leftIndices[n], rightIndices[n], prefix + "Index mismatch");
}
return true;
}
/// <summary>
/// Compare two meshes for value-wise inequality.
/// </summary>
/// <param name="expected"></param>
/// <param name="result"></param>
/// <returns></returns>
public static bool MeshesAreEqual(Mesh expected, Mesh result)
{
int vertexCount = expected.vertexCount;
int subMeshCount = expected.subMeshCount;
if (vertexCount != result.vertexCount)
return false;
if (subMeshCount != result.subMeshCount)
return false;
Vertex[] leftVertices = expected.GetVertices();
Vertex[] rightVertices = result.GetVertices();
for (int i = 0; i < vertexCount; i++)
if (!leftVertices[i].Equals(rightVertices[i]))
return false;
List<int> leftIndices = new List<int>();
List<int> rightIndices = new List<int>();
for (int i = 0; i < subMeshCount; i++)
{
uint indexCount = expected.GetIndexCount(i);
if (expected.GetTopology(i) != result.GetTopology(i))
return false;
if (indexCount != result.GetIndexCount(i))
return false;
expected.GetIndices(leftIndices, i);
result.GetIndices(rightIndices, i);
for (int n = 0; n < indexCount; n++)
if (leftIndices[n] != rightIndices[n])
return false;
}
return true;
}
public static string GetTemplatePath<T>(string assetName, int methodOffset = 0)
{
StackTrace trace = new StackTrace(1 + methodOffset, true);
StackFrame calling = trace.GetFrame(0);
string filePath = calling.GetFileName();
if (string.IsNullOrEmpty(filePath))
{
UnityEngine.Debug.LogError(
"Cannot generate mesh templates directory path from calling method. Please use the explicit SaveMeshTemplate overload.");
return null;
}
// Get the calling file path relative to the `Tests/` directory
string fullFilePath = Path.GetFullPath(filePath).Replace("\\", "/");
string fullTestRootPath = Path.GetFullPath(testsRootDirectory).Replace("\\", "/");
string relativeTemplatePath = fullFilePath.Replace(fullTestRootPath, "");
string relativeTemplateDir = Path.GetDirectoryName(relativeTemplatePath).Replace("\\", "/").TrimStart('/');
string methodName = calling.GetMethod().Name;
return string.Format("{0}/{1}/{2}/{3}/{4}.asset",
typeof(T).ToString(),
relativeTemplateDir,
Path.GetFileNameWithoutExtension(filePath),
methodName,
assetName);
}
/// <summary>
/// Get a mesh saved from the same path with name. Use SaveAssetTemplate to automatically generate this path.
/// </summary>
/// <param name="name"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T GetAssetTemplate<T>(string name) where T : UObject
{
string assetPath = templatesDirectory + GetTemplatePath<T>(name, 1);
T asset = AssetDatabase.LoadAssetAtPath<T>(assetPath);
Assert.IsFalse(asset == null, "Failed loading asset template " + name + " at path " + assetPath);
return asset;
}
public static T GetAssetTemplateWithPath<T>(string pathRelativeToTemplatesDirectory) where T : UObject
{
T asset = AssetDatabase.LoadAssetAtPath<T>(pathRelativeToTemplatesDirectory);
Assert.IsFalse(asset == null, "Failed loading asset template: " + pathRelativeToTemplatesDirectory);
return asset;
}
/// <summary>
/// Utility for saving test asset templates with an automatically generated path from the calling file name and
/// method. See also GetAssetTemplate.
/// </summary>
/// <remarks>
/// See CreateBasicShapes for a simple example of use.
/// </remarks>
/// <param name="asset"></param>
/// <param name="name"></param>
/// <param name="methodOffset"></param>
/// <typeparam name="T"></typeparam>
public static void SaveAssetTemplate<T>(T asset, string name = null, int methodOffset = 0) where T : UObject
{
string templatePath = GetTemplatePath<T>(string.IsNullOrEmpty(name) ? asset.name : name, methodOffset + 1);
SaveAssetTemplateAtPath(asset, templatePath);
}
/// <summary>
/// Path is relative to the "Tests/Templates/" directory. Optional flag disables overwriting.
/// </summary>
/// <param name="asset"></param>
/// <param name="path"></param>
static void SaveAssetTemplateAtPath<T>(T asset, string path, bool overwrite = true) where T : UObject
{
if (!path.EndsWith(".asset"))
path += ".asset";
string assetPath = string.Format("{0}{1}", templatesDirectory, path);
string fullDirectoryPath = Path.GetDirectoryName(assetPath);
if (string.IsNullOrEmpty(fullDirectoryPath))
{
UnityEngine.Debug.LogError("Could not save asset at path: " + assetPath);
return;
}
if (!Directory.Exists(fullDirectoryPath))
Directory.CreateDirectory(fullDirectoryPath);
if (AssetDatabase.LoadAssetAtPath<UObject>(assetPath) != null)
{
if (!overwrite)
{
UnityEngine.Debug.LogError("Will not overwrite existing asset at path: " + assetPath);
return;
}
if (!AssetDatabase.DeleteAsset(assetPath))
{
UnityEngine.Debug.LogError("Failed to delete existing asset at path: " + assetPath);
return;
}
}
AssetDatabase.CreateAsset(asset, assetPath);
}
public static string SaveAssetTemporary<T>(UObject asset) where T : UObject
{
if (!Directory.Exists(temporarySavedAssetsDirectory))
Directory.CreateDirectory(temporarySavedAssetsDirectory);
string path = AssetDatabase.GenerateUniqueAssetPath(string.Format("{0}/{1}.asset", temporarySavedAssetsDirectory, asset.name));
AssetDatabase.CreateAsset(asset, path);
return path;
}
public static void ClearTempAssets()
{
if (!Directory.Exists(temporarySavedAssetsDirectory))
return;
Directory.Delete(temporarySavedAssetsDirectory);
}
public static Material redMaterial
{
get { return AssetDatabase.LoadAssetAtPath<Material>(k_RedMaterialPath); }
}
public static Material blueMaterial
{
get { return AssetDatabase.LoadAssetAtPath<Material>(k_BlueMaterialPath); }
}
public static Material greenMaterial
{
get { return AssetDatabase.LoadAssetAtPath<Material>(k_GreenMaterialPath); }
}
public static void AssertMeshIsValid(ProBuilderMesh mesh)
{
Assert.That(mesh, Is.Not.Null);
Assert.That(mesh.vertexCount > 0);
Assert.That(mesh.positionsInternal.Length, Is.EqualTo(mesh.vertexCount));
Assert.That(mesh.faceCount, Is.GreaterThan(0));
}
}
}