Exemplo n.º 1
0
        public void TestLoad()
        {
            var replaceList = new Dictionary <string, string>();

            replaceList.Add("BOOTHID", "id");
            replaceList.Add("NAME", "name");
            Assert.That(TemplateLoader.Load("Sample_template", replaceList, "Assets"), Is.True);
            AssetDatabase.CreateFolder("Assets", "TestTemplateLoad");
            Assert.That(TemplateLoader.Load("Sample_template", replaceList, "Assets/TestTemplateLoad"), Is.True);
            LogAssert.Expect(LogType.Error, new Regex("^Template load failed.*"));
            TemplateLoader.Load("Sample_template", replaceList, "Assets/TestTemplateLoad/invalid");
            LogAssert.Expect(LogType.Error, new Regex("^Template load failed.*"));
            TemplateLoader.Load("Sample_template", replaceList, "invalid");
            var invalidReplaceList = new Dictionary <string, string>();

            invalidReplaceList.Add("BOOTHID", "/");
            invalidReplaceList.Add("NAME", "test2");
            AssetDatabase.CreateFolder("Assets", "TestTemplateLoad2");
            LogAssert.Expect(LogType.Error, new Regex("^入力した文字列に使えない文字が含まれています。.*"));
            TemplateLoader.Load("Sample_template", invalidReplaceList, "Assets/TestTemplateLoad2");
        }
        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();
            });
        }
Exemplo n.º 3
0
        public IEnumerator ImportAsync_ObjFetchSuccessMtlFetchFail_CreateObjectWithDefaultMat()
        {
            ObjImporter objImporter = SetUpObjImporter(cubeObj, "");

            objImporter.MtlLibrary.ContentLoader = FakeContentLoaderFactory.CreateFakeFailLoader <string>();

            LogAssert.Expect(LogType.Error, new Regex(@"\w*This is a simulated fail\w*"));
            LogAssert.Expect(LogType.Error, new Regex(@"\w*Could not load .mtl file\w*"));

            Task <GameObject> task = objImporter.ImportAsync("http://test.org/test.obj");

            yield return(AsyncTest.WaitForTask(task));

            GameObject res = task.Result;

            Assert.NotNull(res);
            Assert.AreEqual(1, res.transform.childCount);
            MeshRenderer mr = res.transform.GetChild(0).GetComponent <MeshRenderer>();

            Assert.AreEqual("New Material", mr.sharedMaterial.name);
        }
Exemplo n.º 4
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 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);
        }
Exemplo n.º 7
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"));
    }
Exemplo n.º 8
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;
            }
        }
Exemplo n.º 9
0
        public IEnumerator EndTurnTest2()
        {
            Player previousPlayer = GameManager.CurrentPlayer;

            GameManager.Players[1].IsHuman = true;
            Assert.NotNull(previousPlayer);

            foreach (Character character in previousPlayer.Characters)
            {
                character.HasMoved = true;
            }

            yield return(null);

            LogAssert.Expect(LogType.Log, "All characters have moved");

            Player currentPlayer = GameManager.CurrentPlayer;

            Assert.NotNull(currentPlayer);
            Assert.AreNotSame(previousPlayer, currentPlayer);
        }
        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());
        }
Exemplo n.º 11
0
        public void CreateBranchWithDuplicateChildren()
        {
            const int    brushUserID  = 10;
            const int    branchUserID = 12;
            CSGTreeBrush brush        = CSGTreeBrush.Create(userID: brushUserID);

            CSGManager.ClearDirty(brush);

            LogAssert.Expect(LogType.Error, new Regex("Have duplicate child"));
            CSGTreeBranch branch = CSGTreeBranch.Create(branchUserID, new CSGTreeNode[] { brush, brush });


            TestUtility.ExpectInvalidBranch(ref branch);
            Assert.AreEqual(false, brush.Dirty);
            Assert.AreEqual(0, brush.Parent.NodeID);
            Assert.AreEqual(0, brush.Tree.NodeID);
            Assert.AreEqual(1, CSGManager.TreeBrushCount, "Expected 1 TreeBrush to Exist");
            Assert.AreEqual(0, CSGManager.TreeBranchCount, "Expected 0 TreeBranches to Exist");
            Assert.AreEqual(0, CSGManager.TreeCount, "Expected 0 Trees to Exist");
            Assert.AreEqual(1, CSGManager.TreeNodeCount, "Expected 1 TreeNode to Exist");
        }
Exemplo n.º 12
0
        public void ShouldLogExceptionAndShouldNotResetQueueEventsAndNotStopCurrentEventWhenHandlerThrowExceptionTest()
        {
            string keyMessage = nameof(keyMessage);
            bool   flagFromIsolateHandlers = false;
            bool   flagFromIsolateEvent    = false;

            EventAggregator.AddHandler <IsolateHandlersEvent>(_ => throw new Exception(keyMessage));
            EventAggregator.AddHandler <IsolateHandlersEvent>(_ => flagFromIsolateHandlers = true);
            EventAggregator.AddHandler <IsolateHandlersEvent>(_ => EventAggregator.Event(new IsolateEvent()));
            EventAggregator.AddHandler <IsolateEvent>(_ => flagFromIsolateEvent = true);

            LogAssert.Expect(LogType.Exception, new Regex(".keyMessage"));
            EventAggregator.Event(new IsolateHandlersEvent());

            Assert.True(flagFromIsolateHandlers);
            Assert.True(flagFromIsolateEvent);

            EventManagerDispatcher <IsolateHandlersEvent> .RemoveEventManagerInternal();

            EventManagerDispatcher <IsolateEvent> .RemoveEventManagerInternal();
        }
        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" }));
        }
Exemplo n.º 14
0
    public void State_StateChangeMonitor_CanBeRemovedFromMonitorCallback()
    {
        var gamepad = InputSystem.AddDevice <Gamepad>();

        var buttonWestMonitor = InputSystem.AddStateChangeMonitor(gamepad.buttonWest,
                                                                  (c, d, e, m) => { Debug.Log("ButtonWest"); });

        InputSystem.AddStateChangeMonitor(gamepad.buttonEast,
                                          (control, time, eventPtr, monitorIndex) =>
        {
            Debug.Log("ButtonEast");
            InputSystem.RemoveStateChangeMonitor(gamepad.buttonWest, buttonWestMonitor);
        });

        LogAssert.Expect(LogType.Log, "ButtonEast");
        Press(gamepad.buttonEast);
        LogAssert.NoUnexpectedReceived();

        Press(gamepad.buttonWest);
        LogAssert.NoUnexpectedReceived();
    }
Exemplo n.º 15
0
        public static void Unreloadable()
        {
            var target = new Mux.Markup.Transform();

            try
            {
                var reference = new WeakReference <Mux.Markup.IInternalTransform>(target);

                Mux.Markup.Transforms.Add("path", reference);
                Mux.Markup.Transforms.Reload(new[] { "path" });
                LogAssert.Expect(LogType.Log, "Reloadable Mux ancestor not found for Mux.Markup.Transform.");
                LogAssert.NoUnexpectedReceived();

                Mux.Markup.Transforms.Remove("path", reference);
                Mux.Markup.Transforms.Reload(new[] { "path" });
            }
            finally
            {
                target.Destroy();
            }
        }
Exemplo n.º 16
0
        public void RoutineShouldThrowExceptionIfNestedRoutineHaveErrorTest()
        {
            var routineWithError = Routine.ByAction(() => throw new Exception("Its test exception"));

            LogAssert.Expect(LogType.Error, new Regex("."));
            routineWithError.Complete();


            IEnumerator TestRoutine(RoutineControl <int> control)
            {
                yield return(routineWithError);

                control.SetResult(50);
            }

            var routine = Routine.ByEnumerator <int>(TestRoutine);

            LogAssert.Expect(LogType.Error, new Regex("."));
            routine.Complete();
            Assert.True(routine.IsError);
        }
Exemplo n.º 17
0
        [Test] // runtime string formatting
        public void ComponentSystemSorter_OrderFirstUpdateAfterOrderLast_WarnAndIgnoreConstraint()
        {
            var parent  = World.CreateSystem <TestGroup>();
            var systems = new List <EmptySystem>
            {
                World.CreateSystem <FirstAfterLastSystem>(),
                World.CreateSystem <DummyLastSystem>(),
            };

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

            LogAssert.Expect(LogType.Warning, "Ignoring invalid [UpdateAfter(Unity.Entities.Tests.ComponentSystemGroupTests+DummyLastSystem)] attribute on Unity.Entities.Tests.ComponentSystemGroupTests+FirstAfterLastSystem because OrderFirst/OrderLast has higher precedence.");
            parent.SortSystems();
            LogAssert.NoUnexpectedReceived();

            CollectionAssert.AreEqual(systems, parent.Systems);
        }
Exemplo n.º 18
0
        public IEnumerator ServerAndClient_SendMessageWithoutReadingIt_GivesErrorOnDriverUpdate()
        {
            SetupServerAndClientAndConnectThem(0);

            //send data from client
            DataStreamWriter m_OutStream = new DataStreamWriter(16, Allocator.Persistent);

            m_OutStream.Clear();
            m_OutStream.Write(SharedConstants.ping);
            clientToServerConnection.Send(client_driver, m_OutStream);
            m_OutStream.Dispose();

            server_driver.ScheduleUpdate().Complete();
            client_driver.ScheduleUpdate().Complete();

            LogAssert.Expect(LogType.Error, "Resetting event queue with pending events (Count=1, ConnectionID=0) Listening: 1");
            server_driver.ScheduleUpdate().Complete();

            DisconnectAndCleanup();
            yield return(null);
        }
Exemplo n.º 19
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);
        }
Exemplo n.º 20
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);
        }
Exemplo n.º 21
0
        public void TestAddDuplicateUrl()
        {
            var temp = Path.GetTempFileName();

            try
            {
                File.WriteAllText(temp, "UnityFS");

                var request = new MapRequest()
                {
                    name = "name",
                    url  = "file://" + temp,
                };

                Mock.Reset();
                Mock.Setup(srv => srv.Add(It.IsAny <MapModel>())).Throws <Exception>(); // TODO: we need to use more specialized exception here!
                MockUser.Reset();
                MockDownload.Reset();
                MockNotification.Reset();

                LogAssert.Expect(LogType.Exception, new Regex("^Exception"));
                var result = Browser.Post($"/maps", ctx =>
                {
                    ctx.JsonBody(request);
                }).Result;

                Assert.AreEqual(HttpStatusCode.InternalServerError, result.StatusCode);
                Assert.That(result.ContentType.StartsWith("application/json"));

                Mock.Verify(srv => srv.Add(It.Is <MapModel>(m => m.Name == request.name)), Times.Once);
                Mock.VerifyNoOtherCalls();
                MockUser.VerifyNoOtherCalls();
                MockDownload.VerifyNoOtherCalls();
                MockNotification.VerifyNoOtherCalls();
            }
            finally
            {
                File.Delete(temp);
            }
        }
Exemplo n.º 22
0
        public void BranchWithThreeChildren_RemoveWithNegativeIndex_ReturnsFalse()
        {
            const int branchUserID = 10;
            const int brushUserID1 = 11;
            const int brushUserID2 = 12;
            const int brushUserID3 = 12;
            var       brush1       = CSGTreeBrush.Create(userID: brushUserID1);
            var       brush2       = CSGTreeBrush.Create(userID: brushUserID2);
            var       brush3       = CSGTreeBrush.Create(userID: brushUserID3);
            var       branch       = CSGTreeBranch.Create(branchUserID, new CSGTreeNode[] { brush1, brush2, brush3 });

            CompactHierarchyManager.ClearDirty(brush1);
            CompactHierarchyManager.ClearDirty(brush2);
            CompactHierarchyManager.ClearDirty(brush3);
            CompactHierarchyManager.ClearDirty(branch);

            var result = branch.RemoveAt(-1);

            LogAssert.Expect(LogType.Error, new Regex("must be between"));

            Assert.IsFalse(result);
            TestUtility.ExpectValidBranchWithUserID(ref branch, branchUserID);
            TestUtility.ExpectValidBrushWithUserID(ref brush1, brushUserID1);
            TestUtility.ExpectValidBrushWithUserID(ref brush2, brushUserID2);
            TestUtility.ExpectValidBrushWithUserID(ref brush3, brushUserID3);
            Assert.IsFalse(brush1.Dirty);
            Assert.IsFalse(brush2.Dirty);
            Assert.IsFalse(brush3.Dirty);
            Assert.IsFalse(branch.Dirty);
            Assert.IsFalse(brush1.Tree.Valid);
            Assert.IsFalse(brush2.Tree.Valid);
            Assert.IsFalse(brush3.Tree.Valid);
            Assert.AreEqual(3, branch.Count);
            Assert.AreEqual((CSGTreeNode)brush1, (CSGTreeNode)branch[0]);
            Assert.AreEqual((CSGTreeNode)brush2, (CSGTreeNode)branch[1]);
            Assert.AreEqual((CSGTreeNode)brush3, (CSGTreeNode)branch[2]);
            Assert.AreEqual((CSGTreeNode)branch, (CSGTreeNode)brush1.Parent);
            Assert.AreEqual((CSGTreeNode)branch, (CSGTreeNode)brush2.Parent);
            Assert.AreEqual((CSGTreeNode)branch, (CSGTreeNode)brush3.Parent);
        }
Exemplo n.º 23
0
        public void Test_05_04_UnregisterMixedRealityExtensionServicesByType()
        {
            TestUtilities.InitializeMixedRealityToolkitScene();

            // 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.IsEmpty(MixedRealityToolkit.ActiveSystems);
            Assert.AreEqual(2, MixedRealityToolkit.RegisteredMixedRealityServices.Count);
            Assert.AreEqual(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.IsEmpty(MixedRealityToolkit.ActiveSystems);
            Assert.IsEmpty(MixedRealityToolkit.RegisteredMixedRealityServices);
            LogAssert.Expect(LogType.Error, $"Unable to find {typeof(ITestExtensionService1).Name} service.");
            LogAssert.Expect(LogType.Error, $"Unable to find {typeof(ITestExtensionService2).Name} service.");
        }
Exemplo n.º 24
0
    public IEnumerator DragCallbacksDoGetCalled()
    {
        // While left mouse button is pressed and the mouse is moving, OnBeginDrag and OnDrag callbacks should be called
        // Then when the left mouse button is released, OnEndDrag callback should be called

        // Add script to EventSystem to update the mouse position
        m_EventSystem.gameObject.AddComponent <MouseUpdate>();

        // Add script to Image which implements OnBeginDrag, OnDrag & OnEndDrag callbacks
        m_Image.gameObject.AddComponent <DragCallbackCheck>();

        // Setting required input.mousePresent to fake mouse presence
        m_FakeBaseInput.MousePresent = true;

        yield return(null);

        // Left mouse button down simulation
        m_FakeBaseInput.MouseButtonDown[0] = true;

        yield return(null);

        // Left mouse button down flag needs to reset in the next frame
        m_FakeBaseInput.MouseButtonDown[0] = false;

        yield return(null);

        // Left mouse button up simulation
        m_FakeBaseInput.MouseButtonUp[0] = true;

        yield return(null);

        // Left mouse button up flag needs to reset in the next frame
        m_FakeBaseInput.MouseButtonUp[0] = false;

        yield return(null);

        LogAssert.Expect(LogType.Log, "OnBeginDrag");
        LogAssert.Expect(LogType.Log, "OnDrag");
        LogAssert.Expect(LogType.Log, "OnEndDrag");
    }
Exemplo n.º 25
0
        public void TestLogStringsWithNonConnectedPorts()
        {
            m_Node.Messages.DataCount = 5;
            CustomSetup();
            var stringRef4 = new StringReference {
                Index = 4
            };
            var stringRef2 = new StringReference {
                Index = 2
            };

            m_GraphInstanceMock.Setup(x => x.GetString(stringRef4)).Returns(new NativeString128("4"));
            m_GraphInstanceMock.Setup(x => x.GetString(stringRef2)).Returns(new NativeString128("2"));
            m_GraphInstanceMock.Setup(x => x.ReadValue(m_Node.Messages.SelectPort(0))).Returns(new Value());
            m_GraphInstanceMock.Setup(x => x.ReadValue(m_Node.Messages.SelectPort(1))).Returns(stringRef4);
            m_GraphInstanceMock.Setup(x => x.ReadValue(m_Node.Messages.SelectPort(2))).Returns(new Value());
            m_GraphInstanceMock.Setup(x => x.ReadValue(m_Node.Messages.SelectPort(3))).Returns(stringRef2);
            m_GraphInstanceMock.Setup(x => x.ReadValue(m_Node.Messages.SelectPort(4))).Returns(new Value());
            TriggerPort(m_Node.Input);
            LogAssert.Expect(LogType.Log, "Unknown4Unknown2Unknown");
            AssertPortTriggered(m_Node.Output, Times.Once());
        }
Exemplo n.º 26
0
        [Test] // TODO: fix jobs
        public void OnEnterAndExitWorks([Values(CodeGenMode.NoJobs)] CodeGenMode mode)
        {
            SetupTestGraphMultipleFrames(mode, graphModel =>
            {
                var group        = graphModel.CreateComponentQuery("g");
                var positionType = typeof(Translation).GenerateTypeHandle(Stencil);
                group.AddComponent(graphModel.Stencil, positionType, ComponentDefinitionFlags.None);
                group.AddComponent(graphModel.Stencil, typeof(Rotation).GenerateTypeHandle(Stencil), ComponentDefinitionFlags.None);
                var groupInstance = graphModel.CreateVariableNode(group, Vector2.zero);
                var update        = graphModel.CreateNode <OnStartEntitiesNodeModel>("update", Vector2.zero);
                graphModel.CreateEdge(update.InstancePort, groupInstance.OutputPort);

                var set = update.CreateStackedNode <SetPositionNodeModel>("set", 0, SpawnFlags.Default, n => n.Mode = SetPositionNodeModel.TranslationMode.Float3);
                set.Add = true;     // increment so we can detect multiple runs if they happen
                ((Float3ConstantModel)set.InputConstantsById["Value"]).value = new Vector3(1f, 0.0f, 0.0f);

                IVariableModel posComponent = GraphModel.CreateVariableNode(update.FunctionParameterModels.Single(p => p.DataType == positionType), Vector2.zero);
                GraphModel.CreateEdge(set.InstancePort, posComponent.OutputPort);

                var log = update.CreateFunctionCallNode(typeof(Debug).GetMethod("Log", new[] { typeof(object) }), 0);
                IVariableModel entityVariable = GraphModel.CreateVariableNode(update.FunctionParameterModels.Single(p => p.DataType == typeof(Entity).GenerateTypeHandle(Stencil)), Vector2.zero);
                GraphModel.CreateEdge(log.GetParameterPorts().First(), entityVariable.OutputPort);
            },
                                         EachEntity((manager, i, e) => manager.AddComponent(e, typeof(Rotation))),
                                         EachEntity((manager, i, e) =>
            {
                manager.AddComponent(e, typeof(Translation));     // will make the entity enter the query
                Assert.That(manager.GetComponentData <Translation>(e).Value.x, Is.EqualTo(0));
            }),
                                         EachEntity((manager, i, e) => Assert.That(manager.GetComponentData <Translation>(e).Value.x, Is.EqualTo(1))), // translate ran once
                                         EachEntity((manager, i, e) => Assert.That(manager.GetComponentData <Translation>(e).Value.x, Is.EqualTo(1))), // not twice
                                         EachEntity((manager, i, e) =>
            {
                LogAssert.Expect(LogType.Log, $"Entity({i}:1)");
                manager.RemoveComponent <Rotation>(e);
            }),
                                         EachEntity((manager, i, e) => {})
                                         );
        }
Exemplo n.º 27
0
        public void TestSerialPortsList()
        {
            var serialPorts = new SerialPorts();
            var portsCount  = serialPorts.GetPortsCount();

            if (portsCount <= 0)
            {
                LogAssert.Expect(LogType.Error, "no ports");
            }

            for (uint i = 0; i < portsCount; i++)
            {
                var portInfo = serialPorts.GetPortAt(i);
                Assert.True(portInfo.IsValid);
            }

            // invalid port index
            {
                var portInfo = serialPorts.GetPortAt(portsCount + 1);
                Assert.True(!portInfo.IsValid);
            }
        }
Exemplo n.º 28
0
    public void Test_PlayerGainsNoPointsAfterTryingToKillADeadEnemy()
    {
        PlayerStatsClass player = new PlayerStatsClass();

        player.AttackDamage = 500;
        IGameController mockController = Substitute.For <IGameController>();

        mockController.GetPlayerStats().Returns(player);
        EnemyStatsClass enemy = new EnemyStatsClass();

        enemy.SetUpEnemyStats(mockController);


        player.AttackOpponent(enemy, false, true);
        int pointsAfterFirstKill = player.GetCurrentPoints();

        player.AttackOpponent(enemy, false, true);
        int pointsAfterSecondKill = player.GetCurrentPoints();

        Assert.AreEqual(pointsAfterFirstKill, pointsAfterSecondKill, "Player received points after trying to kill an enemy that's already dead!");
        LogAssert.Expect(LogType.Warning, "Fighter tried to attack an opponent that already died. Can't attack dead opponents!");
    }
        public IEnumerator BundledCatalog_LoadCatalogFromBundle_WhenCalledMultipleTimes_OpNotCompleted_FirstShouldSucceedAndOthersShouldFail()
        {
            var bundleFilePath = Path.Combine(Addressables.RuntimePath, m_RuntimeCatalogFilename);

            var timesCalled    = 0;
            var bundledCatalog = new ContentCatalogProvider.InternalOp.BundledCatalog(bundleFilePath);

            bundledCatalog.OnLoaded += catalogData =>
            {
                Assert.NotNull(catalogData);
                Assert.AreEqual(ResourceManagerRuntimeData.kCatalogAddress, catalogData.ProviderId);
                timesCalled++;
            };

            bundledCatalog.LoadCatalogFromBundleAsync();
            bundledCatalog.LoadCatalogFromBundleAsync();
            LogAssert.Expect(LogType.Error, new Regex("progress", RegexOptions.IgnoreCase));

            yield return(new WaitWhile(() => bundledCatalog.OpInProgress));

            Assert.AreEqual(1, timesCalled);
        }
Exemplo n.º 30
0
        public void EntityManagerDestructionDetectsUnregisteredJob()
        {
#if !UNITY_DOTSPLAYER
            LogAssert.Expect(LogType.Error, new System.Text.RegularExpressions.Regex("job is still running"));
#endif

            /*var entity =*/ m_Manager.CreateEntity(typeof(EcsTestData));
            var group = m_Manager.CreateEntityQuery(typeof(EcsTestData));

            var job = new TestIncrementJob();
            job.entities = group.ToEntityArray(Allocator.TempJob);
            job.data     = m_Manager.GetComponentDataFromEntity <EcsTestData>();
            var jobHandle = job.Schedule();

            // This call should detect the unregistered running job & emit the expected error message
            TearDown();

            // Manually complete the job before cleaning up for real
            jobHandle.Complete();
            TearDown();
            job.entities.Dispose();
        }