< Summary

Class:DCL.ABConverter.Tests.ABConverterShould
Assembly:ABConverterTests
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/ABConverter/Tests/ABConverterCoreShould.cs
Covered lines:0
Uncovered lines:2
Coverable lines:2
Total lines:430
Line coverage:0% (0 of 2)
Covered branches:0
Total branches:0

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
DumpAreaCorrectly()0%6200%
DumpSceneCorrectly()0%6200%

File(s)

/tmp/workspace/unity-renderer/unity-renderer/Assets/ABConverter/Tests/ABConverterCoreShould.cs

#LineLine coverage
 1using DCL;
 2using NUnit.Framework;
 3using System.Collections;
 4using System.Collections.Generic;
 5using System.IO;
 6using System.Text;
 7using System.Text.RegularExpressions;
 8using DCL.Helpers;
 9using UnityEditor;
 10using UnityEngine;
 11using UnityEngine.Events;
 12using UnityEngine.TestTools;
 13using UnityEngine.UI;
 14using UnityGLTF.Cache;
 15
 16namespace DCL.ABConverter.Tests
 17{
 18    public class ABConverterShould
 19    {
 20        [UnityTest]
 21        public IEnumerator DumpAreaCorrectly()
 22        {
 23            //TODO(Brian): Implement later
 024            yield break;
 25        }
 26
 27        [UnityTest]
 28        public IEnumerator DumpSceneCorrectly()
 29        {
 30            //TODO(Brian): Implement later
 031            yield break;
 32        }
 33    }
 34
 35    public class ABConverterCoreShould
 36    {
 37        private ABConverter.Core core;
 38        private ABConverter.Environment env;
 39
 40        string basePath = @"C:\test-path\";
 41        string hash1 = "QmHash1", hash2 = "QmHash2", hash3 = "QmHash3", hash4 = "QmHash4";
 42        string baseUrl = @"https://peer.decentraland.org/lambdas/contentv2/contents/";
 43        private string contentData1 = "TestContent1 - guid: 14e357df3f3b75940b5d59e1035255b1\n";
 44        private string contentData2 = "TestContent2 - guid: 14e357df3f3b75940b5d59e1035255b2\n";
 45        private string contentData3 = "TestContent3 - guid: 14e357df3f3b75940b5d59e1035255b3\n";
 46
 47        [SetUp]
 48        public void SetUp()
 49        {
 50            ResetCacheAndWorkingFolders();
 51
 52            var settings = new ABConverter.Client.Settings(ContentServerUtils.ApiTLD.ZONE);
 53            settings.deleteDownloadPathAfterFinished = false;
 54
 55            env = ABConverter.Environment.CreateWithMockImplementations();
 56            core = new ABConverter.Core(env, settings);
 57
 58            if (env.webRequest is Mocked.WebRequest mockedReq)
 59            {
 60                mockedReq.mockedContent.Add($"{baseUrl}{hash1}", contentData1);
 61                mockedReq.mockedContent.Add($"{baseUrl}{hash2}", contentData2);
 62                mockedReq.mockedContent.Add($"{baseUrl}{hash3}", contentData3);
 63            }
 64        }
 65
 66        [TearDown]
 67        public void TearDown() { ResetCacheAndWorkingFolders(); }
 68
 69        [Test]
 70        public void PopulateLowercaseMappingsCorrectly()
 71        {
 72            var pairs = new List<ContentServerUtils.MappingPair>();
 73
 74            pairs.Add(new ContentServerUtils.MappingPair() { file = "foo", hash = "tEsT1" });
 75            pairs.Add(new ContentServerUtils.MappingPair() { file = "foo", hash = "Test2" });
 76            pairs.Add(new ContentServerUtils.MappingPair() { file = "foo", hash = "tesT3" });
 77            pairs.Add(new ContentServerUtils.MappingPair() { file = "foo", hash = "teSt4" });
 78
 79            core.PopulateLowercaseMappings(pairs.ToArray());
 80
 81            Assert.IsTrue(core.hashLowercaseToHashProper.ContainsKey("test1"));
 82            Assert.IsTrue(core.hashLowercaseToHashProper.ContainsKey("test2"));
 83            Assert.IsTrue(core.hashLowercaseToHashProper.ContainsKey("test3"));
 84            Assert.IsTrue(core.hashLowercaseToHashProper.ContainsKey("test4"));
 85
 86            Assert.AreEqual("tEsT1", core.hashLowercaseToHashProper["test1"]);
 87            Assert.AreEqual("Test2", core.hashLowercaseToHashProper["test2"]);
 88            Assert.AreEqual("tesT3", core.hashLowercaseToHashProper["test3"]);
 89            Assert.AreEqual("teSt4", core.hashLowercaseToHashProper["test4"]);
 90        }
 91
 92        [Test]
 93        public void InitializeDirectoryPathsCorrectly()
 94        {
 95            var settings = new ABConverter.Client.Settings(ContentServerUtils.ApiTLD.ZONE);
 96            settings.deleteDownloadPathAfterFinished = false;
 97
 98            env = ABConverter.Environment.CreateWithDefaultImplementations();
 99            core = new ABConverter.Core(env, settings);
 100
 101            core.InitializeDirectoryPaths(false);
 102
 103            Assert.IsFalse(string.IsNullOrEmpty(core.settings.finalAssetBundlePath));
 104            Assert.IsFalse(string.IsNullOrEmpty(core.finalDownloadedPath));
 105
 106            Assert.IsTrue(env.directory.Exists(core.settings.finalAssetBundlePath));
 107            Assert.IsTrue(env.directory.Exists(core.finalDownloadedPath));
 108
 109            string file1 = core.settings.finalAssetBundlePath + "test.txt";
 110            string file2 = core.finalDownloadedPath + "test.txt";
 111
 112            env.file.WriteAllText(file1, "test");
 113            env.file.WriteAllText(file2, "test");
 114
 115            core.InitializeDirectoryPaths(true);
 116
 117            Assert.IsFalse(env.file.Exists(file1));
 118            Assert.IsFalse(env.file.Exists(file2));
 119        }
 120
 121        [Test]
 122        public void InjectTexturesCorrectly()
 123        {
 124            AssetPath gltfPath = new AssetPath(core.finalDownloadedPath, "MyHash", "model/myModel.gltf");
 125            AssetPath texturePath = new AssetPath(core.finalDownloadedPath, "MyHash2", "model/texture.png");
 126            AssetPath texturePath2 = new AssetPath(core.finalDownloadedPath, "MyHash3", "model/invalid-texture.png");
 127
 128            PersistentAssetCache.ImageCacheByUri.Clear();
 129            PersistentAssetCache.StreamCacheByUri.Clear();
 130
 131            core.RetrieveAndInjectTexture(gltfPath, texturePath);
 132
 133            string content1 = "Test";
 134            env.file.WriteAllText(texturePath.finalPath, content1);
 135
 136            core.RetrieveAndInjectTexture(gltfPath, texturePath);
 137            core.RetrieveAndInjectTexture(gltfPath, texturePath2);
 138
 139            string id1 = $"texture.png@{gltfPath.finalPath}";
 140            string id2 = $"invalid-texture.png@{gltfPath.finalPath}";
 141
 142            //NOTE(Brian): Check if streams exists and are added correctly
 143            Assert.IsTrue(PersistentAssetCache.HasImage(id1), $"id1:{id1} doesn't exist?");
 144            Assert.IsFalse(PersistentAssetCache.HasImage(id2), $"Second file with {id2} shouldn't be injected because it
 145
 146            Assert.IsNotNull(PersistentAssetCache.GetImage(id1), "First image don't exist!");
 147
 148            //NOTE(Brian): Read image and validate content
 149            var image1 = PersistentAssetCache.GetImage(id1);
 150        }
 151
 152        [Test]
 153        public void InjectBuffersCorrectly()
 154        {
 155            AssetPath gltfPath = new AssetPath(core.finalDownloadedPath, "MyHash", "models/myModel.gltf");
 156            AssetPath bufferPath = new AssetPath(core.finalDownloadedPath, "MyHash2", "models/anims/anim1.bin");
 157            AssetPath bufferPath2 = new AssetPath(core.finalDownloadedPath, "MyHash3", "models/misc.bin");
 158            AssetPath bufferPath3 = new AssetPath(core.finalDownloadedPath, "MyHash4", "missing-file.bin");
 159
 160            PersistentAssetCache.ImageCacheByUri.Clear();
 161            PersistentAssetCache.StreamCacheByUri.Clear();
 162
 163            string content1 = "Test";
 164            string content2 = "Test2";
 165
 166            env.file.WriteAllText(bufferPath.finalPath, content1);
 167            env.file.WriteAllText(bufferPath2.finalPath, content2);
 168
 169            core.RetrieveAndInjectBuffer(gltfPath, bufferPath);
 170            core.RetrieveAndInjectBuffer(gltfPath, bufferPath2);
 171            core.RetrieveAndInjectBuffer(gltfPath, bufferPath3);
 172
 173            char ds = Path.DirectorySeparatorChar;
 174
 175            string id1 = $"anims{ds}anim1.bin@{gltfPath.finalPath}";
 176            string id2 = $"misc.bin@{gltfPath.finalPath}";
 177            string id3 = $"..{ds}missing-file.bin@{gltfPath.finalPath}";
 178
 179            //NOTE(Brian): Check if streams exists and are added correctly
 180            Assert.IsTrue(PersistentAssetCache.HasBuffer(id1));
 181            Assert.IsTrue(PersistentAssetCache.HasBuffer(id2));
 182            Assert.IsFalse(PersistentAssetCache.HasBuffer(id3), "Third file shouldn't be injected because it doesn't exi
 183
 184            Assert.IsNotNull(PersistentAssetCache.GetBuffer(id1), "First stream don't exist!");
 185            Assert.IsNotNull(PersistentAssetCache.GetBuffer(id2), "Second stream don't exist!");
 186
 187            //NOTE(Brian): Read stream and validate content
 188            var buffer1 = PersistentAssetCache.GetBuffer(id1);
 189            var buffer2 = PersistentAssetCache.GetBuffer(id2);
 190
 191            byte[] chars = new byte[100];
 192            buffer1.stream.Read(chars, 0, 100);
 193            string bufferText = UTF8Encoding.UTF8.GetString(chars).TrimEnd('\0');
 194            Assert.AreEqual(content1, bufferText, "First stream has invalid content!");
 195
 196            buffer2.stream.Read(chars, 0, 100);
 197            bufferText = UTF8Encoding.UTF8.GetString(chars).TrimEnd('\0');
 198            Assert.AreEqual(content2, bufferText, "Second stream has invalid content!");
 199
 200            buffer1.stream.Dispose();
 201            buffer2.stream.Dispose();
 202        }
 203
 204        [Test]
 205        public void DumpGLTFSucceedsCorrectly()
 206        {
 207            List<AssetPath> texturePaths = new List<AssetPath>();
 208            List<AssetPath> bufferPaths = new List<AssetPath>();
 209
 210            AssetPath gltfPath = new AssetPath(basePath, hash1, "test.gltf");
 211
 212            var output = core.DumpGltf(gltfPath, texturePaths, bufferPaths);
 213
 214            Assert.IsNotNull(output);
 215        }
 216
 217        [Test]
 218        public void DumpGLTFFailsCorrectly()
 219        {
 220            List<AssetPath> texturePaths = new List<AssetPath>();
 221            List<AssetPath> bufferPaths = new List<AssetPath>();
 222
 223            AssetPath gltfPath = new AssetPath(basePath, "QmNonExistentHash", "test.gltf");
 224
 225            var output = core.DumpGltf(gltfPath, texturePaths, bufferPaths);
 226
 227            LogAssert.Expect(LogType.Error, new Regex("^.*?Download failed!"));
 228            Assert.IsNull(output);
 229        }
 230
 231        [Test]
 232        public void DumpImportableAssetsCorrectly()
 233        {
 234            List<AssetPath> paths = new List<AssetPath>();
 235
 236            string[] files = { "file1.png", "file2.png", "file3.png", "file4.png" };
 237
 238            paths.Add(new AssetPath(basePath, hash1, files[0]));
 239            paths.Add(new AssetPath(basePath, hash2, files[1]));
 240            paths.Add(new AssetPath(basePath, hash3, files[2]));
 241            paths.Add(new AssetPath(basePath, hash4, files[3]));
 242
 243            string targetGuid1 = ABConverter.Utils.CidToGuid(hash1);
 244            string targetGuid2 = ABConverter.Utils.CidToGuid(hash2);
 245            string targetGuid3 = ABConverter.Utils.CidToGuid(hash3);
 246
 247            var textures = core.DumpImportableAssets(paths);
 248
 249            LogAssert.Expect(LogType.Error, new Regex(@"^.*?Download failed"));
 250            LogAssert.Expect(LogType.Error, new Regex(@"^.*?QmHash4"));
 251
 252            Assert.AreEqual(3, textures.Count);
 253
 254            //NOTE(Brian): textures exist?
 255            Assert.IsTrue(env.file.Exists(paths[0].finalPath));
 256            Assert.IsTrue(env.file.Exists(paths[1].finalPath));
 257            Assert.IsTrue(env.file.Exists(paths[2].finalPath));
 258            Assert.IsFalse(env.file.Exists(paths[3].finalPath));
 259
 260            //NOTE(Brian): textures .meta exist?
 261            Assert.IsTrue(env.file.Exists(paths[0].finalMetaPath));
 262            Assert.IsTrue(env.file.Exists(paths[1].finalMetaPath));
 263            Assert.IsTrue(env.file.Exists(paths[2].finalMetaPath));
 264            Assert.IsFalse(env.file.Exists(paths[3].finalMetaPath));
 265
 266            //NOTE(Brian): textures .meta guid is changed?
 267            Assert.IsTrue(env.file.ReadAllText(paths[0].finalMetaPath).Contains(targetGuid1));
 268            Assert.IsTrue(env.file.ReadAllText(paths[1].finalMetaPath).Contains(targetGuid2));
 269            Assert.IsTrue(env.file.ReadAllText(paths[2].finalMetaPath).Contains(targetGuid3));
 270        }
 271
 272        [Test]
 273        public void DumpRawAssetsCorrectly()
 274        {
 275            List<AssetPath> paths = new List<AssetPath>();
 276
 277            string[] files = { "file1.bin", "file2.bin", "file3.bin", "file4.bin" };
 278
 279            paths.Add(new AssetPath(basePath, hash1, files[0]));
 280            paths.Add(new AssetPath(basePath, hash2, files[1]));
 281            paths.Add(new AssetPath(basePath, hash3, files[2]));
 282            paths.Add(new AssetPath(basePath, hash4, files[3]));
 283
 284            var buffers = core.DumpRawAssets(paths);
 285
 286            LogAssert.Expect(LogType.Error, new Regex(@"^.*?Download failed"));
 287            LogAssert.Expect(LogType.Error, new Regex(@"^.*?QmHash4"));
 288
 289            Assert.AreEqual(3, buffers.Count);
 290
 291            //NOTE(Brian): textures exist?
 292            Assert.IsTrue(env.file.Exists(paths[0].finalPath));
 293            Assert.IsTrue(env.file.Exists(paths[1].finalPath));
 294            Assert.IsTrue(env.file.Exists(paths[2].finalPath));
 295            Assert.IsFalse(env.file.Exists(paths[3].finalPath));
 296
 297            //NOTE(Brian): textures .meta exist?
 298            Assert.IsTrue(env.file.Exists(paths[0].finalMetaPath));
 299            Assert.IsTrue(env.file.Exists(paths[1].finalMetaPath));
 300            Assert.IsTrue(env.file.Exists(paths[2].finalMetaPath));
 301            Assert.IsFalse(env.file.Exists(paths[3].finalMetaPath));
 302        }
 303
 304        [Test]
 305        public void DownloadAssetCorrectly()
 306        {
 307            AssetPath path = new AssetPath(
 308                basePath: basePath,
 309                hash: hash1,
 310                file: "texture.png"
 311            );
 312
 313            string output = core.DownloadAsset(path);
 314
 315            UnityEngine.Assertions.Assert.IsTrue(env.file.Exists(path.finalPath));
 316            UnityEngine.Assertions.Assert.IsTrue(env.file.Exists(path.finalMetaPath));
 317            UnityEngine.Assertions.Assert.AreEqual(contentData1, env.file.ReadAllText(output));
 318        }
 319
 320        [UnityTest]
 321        public IEnumerator ConvertAssetsWithExternalTextures()
 322        {
 323            ContentServerUtils.MappingPair[] input =
 324            {
 325                new ContentServerUtils.MappingPair { file = "SimpleCubeWithSharedNormal.gltf", hash = "SimpleCubeWithSha
 326                new ContentServerUtils.MappingPair { file = "SimpleCubeWithSharedNormal.bin", hash = "SimpleCubeWithShar
 327                new ContentServerUtils.MappingPair { file = "Textures/Test.png", hash = "Test.png" }
 328            };
 329
 330            core.settings.baseUrl = TestAssetsUtils.GetPath() + "/GLTF/SimpleCube/";
 331
 332            env = ABConverter.Environment.CreateWithDefaultImplementations();
 333            core = new ABConverter.Core(env, core.settings);
 334
 335            core.Convert(input);
 336
 337            yield return new WaitUntil(() => core.state.step == ABConverter.Core.State.Step.FINISHED);
 338
 339            Assert.IsTrue(core.state.lastErrorCode == ABConverter.Core.ErrorCodes.SUCCESS);
 340
 341            AssetBundle abDependency = AssetBundle.LoadFromFile(ABConverter.Config.ASSET_BUNDLES_PATH_ROOT + "/Test.png"
 342            abDependency.LoadAllAssets();
 343
 344            AssetBundle abMain = AssetBundle.LoadFromFile(ABConverter.Config.ASSET_BUNDLES_PATH_ROOT + "/SimpleCubeWithS
 345            Material[] mats = abMain.LoadAllAssets<Material>();
 346
 347            bool hasMap = false;
 348
 349            foreach (var mat in mats)
 350            {
 351                hasMap = mat.GetTexture("_BaseMap") != null;
 352            }
 353
 354            abMain.Unload(true);
 355            abDependency.Unload(true);
 356
 357            Assert.IsTrue(hasMap, "Dependency has NOT been generated correctly!");
 358        }
 359
 360        [UnityTest]
 361        public IEnumerator NotGenerateColorMapsWithDXTnm()
 362        {
 363            ContentServerUtils.MappingPair[] input =
 364            {
 365                new ContentServerUtils.MappingPair { file = "SimpleCubeWithSharedNormal.gltf", hash = "SimpleCubeWithSha
 366                new ContentServerUtils.MappingPair { file = "SimpleCubeWithSharedNormal.bin", hash = "SimpleCubeWithShar
 367                new ContentServerUtils.MappingPair { file = "Textures/Test.png", hash = "Test.png" }
 368            };
 369
 370            core.settings.baseUrl = TestAssetsUtils.GetPath() + "/GLTF/SimpleCube/";
 371            core.settings.verbose = true;
 372            core.settings.dumpOnly = true;
 373            core.settings.deleteDownloadPathAfterFinished = false;
 374
 375            env = ABConverter.Environment.CreateWithDefaultImplementations();
 376            core = new ABConverter.Core(env, core.settings);
 377
 378            core.Convert(input);
 379
 380            yield return new WaitUntil(() => core.state.step == ABConverter.Core.State.Step.FINISHED);
 381
 382            Assert.IsTrue(core.state.lastErrorCode == ABConverter.Core.ErrorCodes.SUCCESS);
 383
 384            string importerPath = $"{core.finalDownloadedPath}Test.png{ABConverter.Config.DASH}Test.png.png";
 385            TextureImporter importer = env.assetDatabase.GetImporterAtPath(importerPath) as TextureImporter;
 386
 387            Assert.IsTrue(importer != null, "Texture importer is null!");
 388            Assert.IsTrue(TextureImporterType.NormalMap != importer.textureType, "Texture is used for color! It shouldn'
 389        }
 390
 391        [UnityTest]
 392        public IEnumerator NotFailIfExternalTexturesAreMissing()
 393        {
 394            ContentServerUtils.MappingPair[] input =
 395            {
 396                new ContentServerUtils.MappingPair { file = "SimpleCubeWithSharedNormal.gltf", hash = "SimpleCubeWithSha
 397                new ContentServerUtils.MappingPair { file = "SimpleCubeWithSharedNormal.bin", hash = "SimpleCubeWithShar
 398            };
 399
 400            core.settings.baseUrl = TestAssetsUtils.GetPath() + "/GLTF/SimpleCube/";
 401
 402            env = ABConverter.Environment.CreateWithDefaultImplementations();
 403            core = new ABConverter.Core(env, core.settings);
 404
 405            core.Convert(input);
 406
 407            yield return new WaitUntil(() => core.state.step == ABConverter.Core.State.Step.FINISHED);
 408
 409            Assert.IsTrue(core.state.lastErrorCode == ABConverter.Core.ErrorCodes.SUCCESS);
 410            LogAssert.Expect(LogType.Error, new Regex(@"^.*?Buffer file not found"));
 411            LogAssert.Expect(LogType.Error, new Regex(@"^.*?Buffer file not found"));
 412        }
 413
 414        void ResetCacheAndWorkingFolders()
 415        {
 416            Caching.ClearCache();
 417
 418            if (Directory.Exists(ABConverter.Config.ASSET_BUNDLES_PATH_ROOT))
 419                Directory.Delete(ABConverter.Config.ASSET_BUNDLES_PATH_ROOT, true);
 420
 421            if (Directory.Exists(ABConverter.Config.DOWNLOADED_PATH_ROOT))
 422                Directory.Delete(ABConverter.Config.DOWNLOADED_PATH_ROOT, true);
 423
 424            if (File.Exists(ABConverter.Config.DOWNLOADED_PATH_ROOT + ".meta"))
 425                File.Delete(ABConverter.Config.DOWNLOADED_PATH_ROOT + ".meta");
 426
 427            UnityEditor.AssetDatabase.Refresh();
 428        }
 429    }
 430}