public void CreateCachedQuery_OverflowWithCacheSize4_ResizesByAtLeastHalf()
        {
            var cache = new EntityQueryCache(4);

            SimpleWrapCreateCachedQuery(cache, 0, k_DummyGroup);
            SimpleWrapCreateCachedQuery(cache, 1, k_DummyGroup);
            SimpleWrapCreateCachedQuery(cache, 2, k_DummyGroup);
            SimpleWrapCreateCachedQuery(cache, 3, k_DummyGroup);

#if UNITY_DOTSRUNTIME
            LogAssert.ExpectReset();
#endif
            LogAssert.Expect(LogType.Error, k_ResizeError);
            SimpleWrapCreateCachedQuery(cache, 4, k_DummyGroup);
            LogAssert.NoUnexpectedReceived();

            // this should not error
            SimpleWrapCreateCachedQuery(cache, 5, k_DummyGroup);
            LogAssert.NoUnexpectedReceived();
        }
Example #2
0
    public IEnumerator Test_EnemyCanOnlyAttackIfPartOfCurrentBattle()
    {
        Player player     = CreatePlayer();
        Enemy  enemyRight = CreateEnemy();
        Enemy  enemyWrong = CreateEnemy();

        GameController gameCtr = CreateGameController(player);

        enemyRight.GameCtr = gameCtr;
        enemyWrong.GameCtr = gameCtr;
        player.GameCtr     = gameCtr;

        yield return(new WaitForEndOfFrame());

        gameCtr.StartBattle(enemyRight);

        enemyWrong.stats.AttackOpponent(player.stats, false, true);

        LogAssert.Expect(LogType.Error, "Enemy that is not part of the current battle tried to attack the player!");
    }
Example #3
0
        public override IEnumerator LoadScenes([ValueSource(nameof(UnityPhysicsSamplesTest.GetScenes))] string scenePath)
        {
            // Don't create log messages about the number of trial days remaining
            PlayerPrefs.SetInt("Havok.Auth.SuppressDialogs", 1);

            // Log scene name in case Unity crashes and test results aren't written out.
            Debug.Log("Loading " + scenePath);
            LogAssert.Expect(LogType.Log, "Loading " + scenePath);

            SceneManager.sceneLoaded += (Scene scene, LoadSceneMode mode) => SetSimulationType(SimulationType.HavokPhysics, scene, mode);
            SceneManager.LoadScene(scenePath);
            yield return(new WaitForSeconds(1));

            UnityPhysicsSamplesTest.EntitiesCleanup();
            yield return(new WaitForFixedUpdate());

            LogAssert.NoUnexpectedReceived();

            PlayerPrefs.DeleteKey("Havok.Auth.SuppressDialogs");
        }
    public void CreateForwardRendererAssetWithoutErrors()
    {
        // Test without any render pipeline assigned to GraphicsSettings.
        var renderPipelineAsset = GraphicsSettings.renderPipelineAsset;

        GraphicsSettings.renderPipelineAsset = null;

        try
        {
            var asset = ScriptableObject.CreateInstance <ForwardRendererData>();
            ResourceReloader.ReloadAllNullIn(asset, LightweightRenderPipelineAsset.packagePath);
            LogAssert.NoUnexpectedReceived();
            ScriptableObject.DestroyImmediate(asset);
        }
        // Makes sure the render pipeline is restored in case of a NullReference exception.
        finally
        {
            GraphicsSettings.renderPipelineAsset = renderPipelineAsset;
        }
    }
Example #5
0
        public IEnumerator RunCodeErrorsAsExpected()
        {
            // Arrange
            const int timeoutMilliseconds = 10_000;

            PMWrapper.mainCode        = "IckeDefinieradFunktion()";
            PMWrapper.speedMultiplier = 1;

            // Act
            var coroutine = PlaygroundTestHelper.RunCompilerWithTimeout(timeoutMilliseconds);

            while (coroutine.MoveNext())
            {
                yield return(coroutine.Current);
            }

            // Assert
            LogAssert.Expect(LogType.Exception, new Regex(".*RuntimeVariableNotDefinedException.*"));
            LogAssert.Expect(LogType.Exception, new Regex(".*PMRuntimeException.*"));
        }
Example #6
0
        public void FindOrSpawnObject_ErrorWhenPrefabInNullInDictionary()
        {
            const uint netId = 1002;
            SpawnMessage msg = new SpawnMessage
            {
                netId = netId,
                assetId = validPrefabGuid
            };

            // could happen if the prefab is destroyed or unloaded
            prefabs.Add(validPrefabGuid, null);

            LogAssert.Expect(LogType.Error, $"Failed to spawn server object, did you forget to add it to the NetworkManager? assetId={msg.assetId} netId={msg.netId}");
            LogAssert.Expect(LogType.Error, $"Could not spawn assetId={msg.assetId} scene={msg.sceneId:X} netId={msg.netId}");
            bool success = ClientScene.FindOrSpawnObject(msg, out NetworkIdentity networkIdentity);


            Assert.IsFalse(success);
            Assert.IsNull(networkIdentity);
        }
        public IEnumerator RosIntegration_Publisher_Success()
        {
#if INTEGRATION_TEST
            m_Cube.AddComponent <RosPublisherExample>().cube = m_Cube;
            yield return(new EnterPlayMode());

            while (Time.time < k_SimulationTime)
            {
                yield return(null);
            }

            yield return(new ExitPlayMode());

            LogAssert.NoUnexpectedReceived();
            Object.DestroyImmediate(Object.FindObjectOfType <RosPublisherExample>().gameObject);
#else
            ThrowNotImplementedException();
            yield return(null);
#endif
        }
        [Test] // runtime string formatting
        public void ComponentSystemSorter_OrderLastUpdateBeforeOrderFirst_WarnAndIgnoreConstraint()
        {
            var parent  = World.CreateSystem <TestGroup>();
            var systems = new List <EmptySystem>
            {
                World.CreateSystem <DummyFirstSystem>(),
                World.CreateSystem <LastBeforeFirstSystem>(),
            };

            // Insert in reverse order
            for (int i = systems.Count - 1; i >= 0; --i)
            {
                parent.AddSystemToUpdateList(systems[i]);
            }

            LogAssert.Expect(LogType.Warning, "Ignoring invalid [UpdateBefore(Unity.Entities.Tests.ComponentSystemGroupTests+DummyFirstSystem)] attribute on Unity.Entities.Tests.ComponentSystemGroupTests+LastBeforeFirstSystem because OrderFirst/OrderLast has higher precedence.");
            parent.SortSystems();
            LogAssert.NoUnexpectedReceived();
            CollectionAssert.AreEqual(systems, parent.Systems);
        }
Example #9
0
        public static IEnumerator TestAutoCancellation()
        {
            CoroutineRegularUpdater cru = new GameObject().AddComponent <CoroutineRegularUpdater>();
            var cts = new Cancellable();

            cru.RunRIEnumerator(NestLoC(cts));
            cts.Cancel();
            cru.gameObject.SetActive(false);
            Assert.AreEqual(cru.NumRunningCoroutines, 0);
            cru.gameObject.SetActive(true);
            cru.RunDroppableRIEnumerator(NestLoC(Cancellable.Null));
            cru.gameObject.SetActive(false);
            Assert.AreEqual(cru.NumRunningCoroutines, 0);
            cru.gameObject.SetActive(true);
            cru.RunRIEnumerator(NestLoC(Cancellable.Null));
            LogAssert.Expect(LogType.Error, new Regex(".*1 leftover coroutine.*"));
            cru.gameObject.SetActive(false);
            Assert.AreEqual(cru.NumRunningCoroutines, 1);
            yield return(null);
        }
        public IEnumerator RosIntegration_ServiceClient_Success()
        {
#if INTEGRATION_TEST
            m_Cube.AddComponent <RosServiceCallExample>().cube = m_Cube;
            yield return(new EnterPlayMode());

            while (Time.time < k_SimulationTime)
            {
                yield return(null);
            }
            LogAssert.Expect(LogType.Log, "Destination reached.");
            LogAssert.Expect(LogType.Log, new Regex(@"^New Destination: .*$"));
            yield return(new ExitPlayMode());

            Object.DestroyImmediate(Object.FindObjectOfType <RosServiceCallExample>().gameObject);
#else
            ThrowNotImplementedException();
            yield return(null);
#endif
        }
        public void SetAssetId_GivesErrorForEmptyGuid()
        {
            CreateNetworked(out GameObject _, out NetworkIdentity identity);

            if (identity.assetId == Guid.Empty)
            {
                identity.assetId = Guid.NewGuid();
            }

            Guid guid1 = identity.assetId;

            // assign a guid
            Guid guid2 = new Guid();

            LogAssert.Expect(LogType.Error, $"Can not set AssetId to empty guid on NetworkIdentity '{identity.name}', old assetId '{guid1.ToString("N")}'");
            identity.assetId = guid2;

            // guid was NOT changed
            Assert.That(identity.assetId, Is.EqualTo(guid1));
        }
        public void SetAssetId_GivesErrorIfOneExists()
        {
            CreateNetworked(out GameObject _, out NetworkIdentity identity);

            if (identity.assetId == Guid.Empty)
            {
                identity.assetId = Guid.NewGuid();
            }

            Guid guid1 = identity.assetId;

            // assign a guid
            Guid guid2 = Guid.NewGuid();

            LogAssert.Expect(LogType.Error, $"Can not Set AssetId on NetworkIdentity '{identity.name}' because it already had an assetId, current assetId '{guid1.ToString("N")}', attempted new assetId '{guid2.ToString("N")}'");
            identity.assetId = guid2;

            // guid was changed
            Assert.That(identity.assetId, Is.EqualTo(guid1));
        }
        public void FirstProgressReportsTheMaximumProgress3()
        {
            var deferred1 = Promise.NewDeferred <int>();

            float progress = float.NaN;

            Promise.First(deferred1.Promise, Promise.Resolved(1))
            .Progress(p => progress = p);

            Promise.Manager.HandleCompletesAndProgress();
            Assert.AreEqual(1f, progress, 0f);

            deferred1.Resolve(1);
            Promise.Manager.HandleCompletesAndProgress();

            // Clean up.
            GC.Collect();
            Promise.Manager.HandleCompletesAndProgress();
            LogAssert.NoUnexpectedReceived();
        }
Example #14
0
        public void TestGetComponent()
        {
            SetupTestGraphDefinitionMultipleFrames((b, _) =>
            {
                var componentTypeRef = new TypeReference {
                    TypeHash = TypeHash.CalculateStableTypeHash(typeof(TestComponent))
                };
                var onUpdate = b.AddNode(new OnUpdate());
                var enabled  = b.AddNode(new ConstantBool {
                    Value = true
                });
                var getComponent = b.AddNode(new GetComponent {
                    Type = componentTypeRef, ComponentData = new OutputDataMultiPort {
                        DataCount = 2
                    }
                });
                var log = b.AddNode(new Log()
                {
                    Messages = new InputDataMultiPort {
                        DataCount = 1
                    }
                });

                b.CreateEdge(enabled.ValuePort, onUpdate.Enabled);
                b.CreateEdge(onUpdate.Output, log.Input);
                b.CreateEdge(getComponent.ComponentData.SelectPort(0), log.Messages.SelectPort(0));
                b.AddReferencedComponent(componentTypeRef);
            }, (manager, entity, index) =>
            {
                // don't add the component yet, next frame we can test that "get component" returns the default value
            }, (manager, entity, index) =>
            {
                LogAssert.Expect(LogType.Log, "0");     // no component on entity should give default value
                manager.AddComponentData(entity, new TestComponent {
                    Int = 42, Float = 12.7f
                });
            }, (manager, entity, index) =>
            {
                LogAssert.Expect(LogType.Log, "42");
            });
        }
        public void Test_05_04_UnregisterMixedRealityExtensionServicesByType()
        {
            TestUtilities.InitializeMixedRealityToolkitScene();
            var activeSystemCount  = MixedRealityToolkit.ActiveSystems.Count;
            var activeServiceCount = MixedRealityToolkit.RegisteredMixedRealityServices.Count;

            // Add test ExtensionService
            MixedRealityToolkit.RegisterService <ITestExtensionService1>(new TestExtensionService1("Test ExtensionService 1"));
            MixedRealityToolkit.RegisterService <ITestExtensionService2>(new TestExtensionService2("Test ExtensionService 2"));

            // Retrieve all registered IMixedRealityExtensionServices
            var extensionServices = MixedRealityToolkit.GetActiveServices <IMixedRealityExtensionService>();

            // Tests
            Assert.IsNotNull(MixedRealityToolkit.Instance.ActiveProfile);
            Assert.AreEqual(activeSystemCount, MixedRealityToolkit.ActiveSystems.Count);
            Assert.AreEqual(activeServiceCount + extensionServices.Count, MixedRealityToolkit.RegisteredMixedRealityServices.Count);

            // Retrieve services
            var extensionService1 = MixedRealityToolkit.GetService <ITestExtensionService1>();
            var extensionService2 = MixedRealityToolkit.GetService <ITestExtensionService2>();

            // Validate
            Assert.IsNotNull(extensionService1);
            Assert.IsNotNull(extensionService2);

            var success = MixedRealityToolkit.UnregisterServicesOfType <IMixedRealityExtensionService>();

            // Validate non-existent service
            var isService1Registered = MixedRealityToolkit.IsServiceRegistered <ITestExtensionService1>();
            var isService2Registered = MixedRealityToolkit.IsServiceRegistered <ITestExtensionService2>();

            // Tests
            Assert.IsTrue(success);
            Assert.IsFalse(isService1Registered);
            Assert.IsFalse(isService2Registered);
            Assert.AreEqual(activeSystemCount, MixedRealityToolkit.ActiveSystems.Count);
            Assert.AreEqual(activeServiceCount, MixedRealityToolkit.RegisteredMixedRealityServices.Count);
            LogAssert.Expect(LogType.Error, $"Unable to find {typeof(ITestExtensionService1).Name} service.");
            LogAssert.Expect(LogType.Error, $"Unable to find {typeof(ITestExtensionService2).Name} service.");
        }
Example #16
0
        private static void Main(string[] args)
        {
            var dir = Path.GetFullPath(args[0]);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            Console.WriteLine("Writing logs in {0}", dir);

            var config = string.Format(
                @"
<loggers>
  <etwlogging enabled='true' />
  <log name='demo' rotationInterval='60' type='etl' directory='{0}' timestampLocal='true'>
    <source name='Demo' minimumSeverity='informational' />
  </log>
</loggers>
", dir);

            LogManager.Start();
            LogAssert.Assert(LogManager.SetConfiguration(config));
            LogManager.ConsoleLogger.SubscribeToEvents(DemoEvents.Write, EventLevel.Verbose);
            LogManager.ConsoleLogger.SubscribeToEvents(InternalLogger.Write, EventLevel.Verbose);

            var t = new Timer(_ => DemoEvents.Write.Log(DateTime.Now.ToString()), null, TimeSpan.Zero,
                              new TimeSpan(0, 0, 1));

            Console.CancelKeyPress +=
                (sender, eventArgs) =>
            {
                Console.WriteLine("Shutting down...");
                LogManager.Shutdown();
                Environment.Exit(0);
            };

            while (true)
            {
                Thread.Sleep(100);
            }
        }
Example #17
0
        /// <summary>
        /// Tests the map.
        /// </summary>
        /// <param name="map">The map to execute.</param>
        /// <param name="xsltExtensionObjectOverrides">The overrides for the XSLT arguments - allowing you to mock external assembly methods.</param>
        /// <param name="validateInput">if set to <c>true</c> then the input flat file contents and converted XML is validated.</param>
        /// <param name="validateOutput">if set to <c>true</c> then the output is validated.</param>
        public void TestMap(TransformBase map, IEnumerable <XsltExtensionObjectDescriptor> xsltExtensionObjectOverrides, bool validateInput, bool validateOutput)
        {
            if (map == null)
            {
                throw new ArgumentNullException(nameof(map));
            }

            XNode inputXml = BizTalkXmlFlatFileAdapter.ConvertInputFlatFileContentsToInputXml(map, this.InputFlatFileContents);

            if (validateInput)
            {
                BizTalkXmlMapTestValidator.ValidateInputXml(map, inputXml, this.Logger);
            }

            Logger.Log("Executing the BizTalk map (flat file to flat file) " + map.GetType().Name);
            string outputXmlString = BizTalkXmlMapExecutor.PerformTransform(map, xsltExtensionObjectOverrides, inputXml);

            LogAssert.IsTrue("XML output from the BizTalk map exists", !string.IsNullOrWhiteSpace(outputXmlString));

            var actualOutputXml = XElement.Parse(outputXmlString);

            if (validateOutput)
            {
                BizTalkXmlMapTestValidator.ValidateOutputXml(map, actualOutputXml, this.Logger);
            }

            var schemaTree = BizTalkMapSchemaUtility.CreateSchemaTreeAndLoadSchema(map, map.TargetSchemas[0]);

            if (schemaTree.IsStandardXML)
            {
                throw new InvalidOperationException("The map does not have a schema for converting to a flat file.");
            }
            else
            {
                Logger.Log("Converting the XML output of the BizTalk map to a flat file");
                this.ActualOutputFlatFileContents = BizTalkXmlFlatFileAdapter.ConvertOutputXmlToOutputFlatFileContents(map, actualOutputXml, validateOutput);
            }

            Logger.Log();
            Logger.Log("BizTalk map (flat file to flat file) execution completed");
        }
        public void TestSetRotationEulerAngles()
        {
            GraphBuilder.VariableHandle handle = default;
            var setValue = new float3(-30f, 0f, 0f);

            SetupTestGraphDefinitionMultipleFrames((b, _) =>
            {
                handle = b.BindVariableToDataIndex("TestEntity");

                var onUpdate = b.AddNode(new OnUpdate());
                var enabled  = b.AddNode(new ConstantBool {
                    Value = true
                });
                var setRotation           = b.AddNode(new SetRotation {
                });
                var quatFromEuler         = b.AddNode(new RotationEuler());
                var constantRotationValue = b.AddNode(new ConstantFloat3()
                {
                    Value = setValue
                });

                b.BindVariableToInput(handle, setRotation.GameObject);
                b.CreateEdge(enabled.ValuePort, onUpdate.Enabled);
                b.CreateEdge(onUpdate.Output, setRotation.Input);
                b.CreateEdge(constantRotationValue.ValuePort, quatFromEuler.Euler);
                b.CreateEdge(quatFromEuler.Value, setRotation.Value);
            }
                                                   , (manager, entity, index) =>
            {
                GraphInstance instance = GetGraphInstance(entity);
                instance.WriteValueToDataSlot(handle.DataIndex, entity);

                Assert.That(!manager.HasComponent <Rotation>(entity));
            }, (manager, entity, index) =>
            {
                Rotation rotation = manager.GetComponentData <Rotation>(entity);
                var q             = rotation.Value;
                Assert.That(q, Is.EqualTo(quaternion.Euler(math.radians(setValue))));
                LogAssert.NoUnexpectedReceived();
            });
        }
Example #19
0
        public void FindOrSpawnObject_ErrorWhenSpawnHanlderReturnsNull()
        {
            const uint   netId = 1003;
            SpawnMessage msg   = new SpawnMessage
            {
                netId   = netId,
                assetId = validPrefabGuid
            };

            spawnHandlers.Add(validPrefabGuid, (x) =>
            {
                return(null);
            });

            LogAssert.Expect(LogType.Error, $"Spawn Handler returned null, Handler assetId '{msg.assetId}'");
            LogAssert.Expect(LogType.Error, $"Could not spawn assetId={msg.assetId} scene={msg.sceneId} netId={msg.netId}");
            bool success = ClientScene.FindOrSpawnObject(msg, out NetworkIdentity networkIdentity);

            Assert.IsFalse(success);
            Assert.IsNull(networkIdentity);
        }
        public void WhenAssetHasANullRepresentation_LogsWarning()
        {
            // Create an asset
            string assetPath = Path.Combine(kTestAssetFolder, "myPrefab.prefab");
            GUID   guid      = CreateGameObject(assetPath);

            CalculateAssetDependencyData.TaskInput input = CreateDefaultInput();
            input.Assets = new List <GUID>()
            {
                guid
            };
            input.EngineHooks = new NullLoadRepresentationFake();

            LogAssert.Expect(LogType.Warning, new Regex(".+It will not be included in the build"));

            CalculateAssetDependencyData.RunInternal(input, out CalculateAssetDependencyData.TaskOutput output);

            Assert.AreEqual(guid, output.AssetResults[0].asset);
            Assert.AreEqual(2, output.AssetResults[0].assetInfo.includedObjects.Count); // GameObject and Transform
            Assert.AreEqual(0, output.AssetResults[0].assetInfo.referencedObjects.Count);
        }
Example #21
0
    public void CreatePipelineAssetWithoutErrors()
    {
        // Test without any render pipeline assigned to GraphicsSettings.
        var renderPipelineAsset = GraphicsSettings.renderPipelineAsset;

        GraphicsSettings.renderPipelineAsset = null;

        try
        {
            UniversalRendererData        data  = ScriptableObject.CreateInstance <UniversalRendererData>();
            UniversalRenderPipelineAsset asset = UniversalRenderPipelineAsset.Create(data);
            LogAssert.NoUnexpectedReceived();
            ScriptableObject.DestroyImmediate(asset);
            ScriptableObject.DestroyImmediate(data);
        }
        // Makes sure the render pipeline is restored in case of a NullReference exception.
        finally
        {
            GraphicsSettings.renderPipelineAsset = renderPipelineAsset;
        }
    }
Example #22
0
        public void SendCalledWhileNotActive_ShouldGiveWarning(string functionName)
        {
            LogAssert.Expect(LogType.Warning, $"Can not send using NetworkServer.{functionName}<T>(T msg) because NetworkServer is not active");

            switch (functionName)
            {
            case nameof(NetworkServer.SendToAll):
                NetworkServer.SendToAll(new NetworkPingMessage {
                });
                break;

            case nameof(NetworkServer.SendToReady):
                NetworkServer.SendToReady(new NetworkPingMessage {
                });
                break;

            default:
                Debug.LogError("Could not find function name");
                break;
            }
        }
Example #23
0
        public IEnumerator FailGracefullyWhenIdsCannotBeResolved()
        {
            avatarModel.wearables = new List <string>()
            {
                "Scioli_right_arm", "Peron_hands"
            };
            avatarModel.bodyShape = "Invalid_id";

            avatarRenderer.SetVisibility(true);

            bool success = false;

            avatarRenderer.ApplyModel(avatarModel, () => success = true, null);
            yield return(new DCL.WaitUntil(() => success, 4));

            LogAssert.Expect(LogType.Error, "Bodyshape Invalid_id not found in catalog");
            LogAssert.Expect(LogType.Error, "Wearable Scioli_right_arm not found in catalog");
            LogAssert.Expect(LogType.Error, "Wearable Peron_hands not found in catalog");

            UnityEngine.Assertions.Assert.IsTrue(success);
        }
        public IEnumerator SetupThrows_ShouldDisable()
        {
            ResetScene();
            yield return(new EnterPlayMode());

            var mockLabeler = new Mock <CameraLabeler>();

            mockLabeler.Protected().Setup("Setup").Throws <InvalidOperationException>();
            var labeler = mockLabeler.Object;
            var camera  = SetupCamera(null);

            camera.GetComponent <PerceptionCamera>().AddLabeler(labeler);
            LogAssert.Expect(LogType.Exception, "InvalidOperationException: Operation is not valid due to the current state of the object.");
            yield return(null);

            mockLabeler.Protected().Verify("Setup", Times.Once());
            mockLabeler.Protected().Verify("OnUpdate", Times.Never());
            mockLabeler.Protected().Verify("OnBeginRendering", Times.Never());
            Assert.IsFalse(labeler.enabled);
            yield return(new ExitPlayMode());
        }
Example #25
0
    public void NativeBitArray_CreateAndUseAfterFreeInBurstJob_UsesCustomOwnerTypeName()
    {
        // Make sure this isn't the first container of this type ever created, so that valid static safety data exists
        var numBits = 256;

        var test = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory);

        test.Dispose();

        var job = new NativeBitArrayCreateAndUseAfterFreeBurst
        {
        };

        // Two things:
        // 1. This exception is logged, not thrown; thus, we use LogAssert to detect it.
        // 2. Calling write operation after container.Dispose() emits an unintuitive error message. For now, all this test cares about is whether it contains the
        //    expected type name.
        job.Run();
        LogAssert.Expect(LogType.Exception,
                         new Regex($"InvalidOperationException: The {Regex.Escape(test.GetType().ToString())} has been declared as \\[ReadOnly\\] in the job, but you are writing to it"));
    }
        public void LogResult_SupportFormattingCharacters()
        {
            var pipeline = BuildPipeline.CreateInstance();
            var config   = BuildConfiguration.CreateInstance();

            var resultSuccess = BuildPipelineResult.Success(pipeline, config);

            Assert.DoesNotThrow(() =>
            {
                LogAssert.Expect(LogType.Log, new Regex(@"Build succeeded after .+\."));
                resultSuccess.LogResult();
            });

            var resultFailure = BuildPipelineResult.Failure(pipeline, config, @"{}{{}}{0}{s}%s%%\s±@£¢¤¬¦²³¼½¾");

            Assert.DoesNotThrow(() =>
            {
                LogAssert.Expect(LogType.Error, new Regex(@"Build failed after .+\.\n.+"));
                resultFailure.LogResult();
            });
        }
Example #27
0
        public static void ExtrudeAllFaces_IndividualFaces()
        {
            using (var shapes = new TestUtility.BuiltInPrimitives())
            {
                foreach (var pb in (IEnumerable <ProBuilderMesh>)shapes)
                {
                    int vertexCountBeforeExtrude = pb.vertexCount;
                    pb.Extrude(pb.facesInternal, ExtrudeMethod.IndividualFaces, .5f);
                    pb.ToMesh();
                    pb.Refresh();
                    LogAssert.NoUnexpectedReceived();
                    Assert.AreNotEqual(vertexCountBeforeExtrude, pb.vertexCount);
                    TestUtility.AssertMeshAttributesValid(pb.mesh);
#if PB_CREATE_TEST_MESH_TEMPLATES
                    TestUtility.SaveAssetTemplate(pb.mesh, pb.name);
#endif
                    Mesh template = TestUtility.GetAssetTemplate <Mesh>(pb.name);
                    TestUtility.AssertAreEqual(template, pb.mesh, message: pb.name);
                }
            }
        }
Example #28
0
        public void Branch_InsertTree_ReturnsFalse()
        {
            const int branchUserID = 10;
            const int treeUserID   = 11;
            var       tree         = CSGTree.Create(treeUserID);
            var       branch       = CSGTreeBranch.Create(branchUserID);

            CompactHierarchyManager.ClearDirty(tree);
            CompactHierarchyManager.ClearDirty(branch);

            var result = branch.Insert(0, tree);

            LogAssert.Expect(LogType.Error, new Regex("Cannot add a tree as a child"));

            Assert.IsFalse(result);
            TestUtility.ExpectValidBranchWithUserID(ref branch, branchUserID);
            TestUtility.ExpectValidTreeWithUserID(ref tree, treeUserID);
            Assert.IsFalse(tree.Dirty);
            Assert.IsFalse(branch.Dirty);
            Assert.AreEqual(0, branch.Count);
        }
Example #29
0
        public IEnumerator UnloadingScene_Synchronously_LogsWarning()
        {
            var loadOp = m_Addressables.LoadSceneAsync(m_SceneKey, LoadSceneMode.Additive);

            loadOp.WaitForCompletion();
            yield return(loadOp);

            var unloadOp = m_Addressables.UnloadSceneAsync(loadOp, UnloadSceneOptions.None, false);

            LogAssert.Expect(LogType.Warning, "Cannot unload a Scene with WaitForCompletion. Scenes must be unloaded asynchronously.");
            unloadOp.WaitForCompletion();
            yield return(unloadOp);

            Assert.AreEqual(AsyncOperationStatus.Succeeded, unloadOp.Status);
            Assert.IsTrue(unloadOp.IsValid());
            Assert.IsTrue(unloadOp.IsDone);

            //Cleanup
            ReleaseOp(unloadOp);
            ReleaseOp(loadOp);
        }
        public void WhenPipelineFails_StepsAndCleanupRan([Values] bool shouldThrow)
        {
            var context  = CreateTestContext();
            var pipeline = ScriptableObject.CreateInstance <BuildPipeline>();

            pipeline.AddSteps(new TestStep1(), new FailStep {
                Throw = shouldThrow
            }, new TestStep2());

            LogAssert.Expect(LogType.Error, s_BuildFailureRegex);

            pipeline.RunSteps(context);

            var runResults = context.Get <StepRunResults>();

            Assert.That(runResults.stepsRan, Is.EqualTo(new[] { "step1", "fail" }));

            var cleanResults = context.Get <StepCleanupResults>();

            Assert.That(cleanResults.stepsCleaned, Is.EqualTo(new[] { "fail", "step1" }));
        }