Inheritance: MonoBehaviour
        public void Delete_WithDifferentIp_IsForbidden()
        {
            var endPoint = new IPEndPoint(101, 1);

            using (var context = MockDataContext.GetContext()) {
                context.Servers.Add(new GameServer {
                    Name           = "C",
                    Address        = endPoint.Address.ToString(),
                    QueryPort      = endPoint.Port,
                    GamePort       = 300,
                    RoundStatus    = "starting",
                    RoundStartTime = DateTime.Now,
                    Game           = "SS3D",
                    LastUpdate     = DateTime.Now - TimeSpan.FromMinutes(6)
                });
                context.SaveChanges();
            }

            using (var context = MockDataContext.GetContext()) {
                var controller = new ServersController(context, ConstructChallengeRespondingMock(), logger);
                MockControllerConnection(controller, new IPAddress(202));

                IActionResult response = controller.DeleteServer(endPoint.ToString());

                Assert.Equal(StatusCodes.Status204NoContent, (response as IStatusCodeActionResult).StatusCode);
            }
        }
Esempio n. 2
0
        public void InvalidPostServerId()
        {
            var mockRepo         = new Mock <IServerManager>();
            var serverController = new ServersController(mockRepo.Object);

            Assert.Null(serverController.Post(GetServerTest(null, "http://localhost:58493")));
        }
        public async void PostNewServer_WithNew_IsSuccessful()
        {
            using (var context = MockDataContext.GetContext()) {
                // A mock which returns the input challenge.
                var controller = new ServersController(context, ConstructChallengeRespondingMock(), logger);

                var endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 100);
                MockControllerConnection(controller, endPoint.Address);

                var result = await controller.PostNewServer(new GameServer {
                    Name           = "Server A",
                    Address        = endPoint.Address.ToString(),
                    QueryPort      = endPoint.Port,
                    GamePort       = 100,
                    RoundStatus    = "starting",
                    RoundStartTime = DateTime.Now,
                    Game           = "SS3D"
                }).ConfigureAwait(false);

                Assert.Equal(StatusCodes.Status201Created, (result as IStatusCodeActionResult).StatusCode);
            }

            using (var context = MockDataContext.GetContext()) {
                Assert.Single(context.Servers);
            }
        }
        public void GetRamLoads_ShouldReturnNotFound()
        {
            ServersController controller = new ServersController(true);
            var actionResult             = controller.GetRamLoads("NotAvailableServer");

            Assert.IsInstanceOfType(actionResult, typeof(NotFoundResult));
        }
Esempio n. 5
0
        public void InvalidPostServerURL()
        {
            var mockRepo         = new Mock <IServerManager>();
            var serverController = new ServersController(mockRepo.Object);

            Assert.Null(serverController.Post(GetServerTest("12345", null)));
        }
Esempio n. 6
0
        public void InfoReturnListIfHaveOnlyAdvertise()
        {
            var options = new DbContextOptionsBuilder()
                          .UseInMemoryDatabase("InfoAdvertise")
                          .Options;

            using (var context = new DatabaseContext(options))
            {
                var server = new ServerModel
                {
                    endpoint  = "167.42.23.32-1337",
                    name      = "] My P3rfect Server [",
                    gameModes = new List <GameModeModel>
                    {
                        new GameModeModel {
                            value = "DM"
                        },
                        new GameModeModel {
                            value = "TDM"
                        }
                    }
                };

                context.Servers.Add(server);
                context.SaveChanges();
            }

            using (var context = new DatabaseContext(options))
            {
                var controller = new ServersController(context);
                var result     = controller.Info();
                Assert.NotEmpty(result);
            }
        }
Esempio n. 7
0
        public void TestExternalListTest()
        {
            List <Server> serverList = GetServers();
            IMemoryCache  cache      = CreateCache();
            List <string> serversIds = new List <string>();

            for (int i = 0; i < serverList.Count; i++)
            {
                serversIds.Add(serverList[i].ServerId);
            }
            cache.TryGetValue("servers", out List <string> ids);
            ids.AddRange(serversIds);
            for (int i = 0; i < serverList.Count; i++)
            {
                cache.Set(serverList[i].ServerId, serverList[i]);
            }
            ServersController controller = new ServersController(cache);
            var responseList             = (List <Server>)controller.GetAllServers();

            Assert.IsNotNull(responseList);
            for (int i = 0; i < serverList.Count; i++)
            {
                Assert.AreEqual(serverList[i].ServerId, responseList[i].ServerId);
            }
        }
        public void PostServerHeartBeat_WithDifferentIp_GivesForbidden()
        {
            var endPoint = new IPEndPoint(100, 1);

            using (var preContext = MockDataContext.GetContext()) {
                preContext.Servers.Add(new GameServer {
                    Name           = "A",
                    Address        = endPoint.Address.ToString(),
                    QueryPort      = endPoint.Port,
                    GamePort       = 200,
                    RoundStatus    = "starting",
                    RoundStartTime = DateTime.Now,
                    Game           = "SS3D",
                    LastUpdate     = DateTime.Now - TimeSpan.FromMinutes(2)
                });
                preContext.SaveChanges();
            }

            using var context = MockDataContext.GetContext();
            // Test
            var controller = new ServersController(context, ConstructChallengeRespondingMock(), logger);

            MockControllerConnection(controller, new IPAddress(200));

            // Actual Test
            var response = controller.PostHeartBeatUpdate(endPoint.ToString());

            Assert.IsType <ForbidResult>(response);
        }
        public void PostServerHeartBeat_WithBadForm_GivesBadRequest()
        {
            var endPoint = new IPEndPoint(100, 1);

            using (var preContext = MockDataContext.GetContext()) {
                preContext.Servers.Add(new GameServer {
                    Name           = "A",
                    Address        = endPoint.Address.ToString(),
                    QueryPort      = endPoint.Port,
                    GamePort       = 200,
                    RoundStatus    = "starting",
                    RoundStartTime = DateTime.Now,
                    Game           = "SS3D",
                    LastUpdate     = DateTime.Now - TimeSpan.FromMinutes(2)
                });
                preContext.SaveChanges();
            }

            using var context = MockDataContext.GetContext();
            var controller = new ServersController(context, ConstructChallengeRespondingMock(), logger);

            MockControllerConnection(controller, endPoint.Address);

            var response = controller.PostHeartBeatUpdate("fsafsfa");

            Assert.Equal(StatusCodes.Status400BadRequest, (response as IStatusCodeActionResult).StatusCode);
        }
Esempio n. 10
0
        public void invalidDeleteId()
        {
            var mockRepo         = new Mock <IServerManager>();
            var serverController = new ServersController(mockRepo.Object);

            mockRepo.Setup(p => p.DeleteServer("111111")).Throws <InvalidOperationException>();
            Assert.Throws <InvalidOperationException>(() => serverController.Delete("111111"));
        }
Esempio n. 11
0
        public void ServersController_GetServers_ReturnServers()
        {
            var expected = _mockRepo.GetServersOutput;
            ServersController serversController = new ServersController(_mockRepo);

            var answer = (OkObjectResult)serversController.GetAllServers().Result;
            var actual = answer.Value;

            Assert.AreEqual(actual, expected, "Invalid Answer in get servers method.");
        }
Esempio n. 12
0
        public void ServersController_postServer_ReturnValidResponse()
        {
            var expected = _mockRepo.DeleteServerOutput;
            ServersController serversController = new ServersController(_mockRepo);

            var answer = (OkObjectResult)serversController.DeleteServer("").Result;
            var actual = answer.Value;

            Assert.AreEqual(actual, expected, "Invalid Answer in get servers method.");
        }
        public void Delete_WithNonExistant_GivesNotFound()
        {
            var endPoint = new IPEndPoint(100, 1);

            using var context = MockDataContext.GetContext();
            var controller = new ServersController(context, ConstructChallengeRespondingMock(), logger);

            IActionResult response = controller.DeleteServer(endPoint.ToString());

            Assert.Equal(StatusCodes.Status404NotFound, (response as IStatusCodeActionResult).StatusCode);
        }
        public void GetRamLoads_ShouldReturnRamLoads()
        {
            ServersController controller = new ServersController(true);

            var actionResult          = controller.GetRamLoads(Global.Utility.PopulatedServer);
            var contentResult         = actionResult as OkNegotiatedContentResult <RamLoadAveragesDto>;
            var generatedLoadAverages = Utility.TestHelper.CreateRamLoadAverages(Global.Utility.LoadRate);

            Assert.IsNotNull(contentResult.Content);
            Assert.AreEqual(true, Utility.TestHelper.AreRamLoadAveragesEqual(contentResult.Content, generatedLoadAverages));
        }
        public void RecordLoads_ShouldReturnNotFound()
        {
            ServersController controller = new ServersController(true);
            var actionResult             = controller.RecordLoads(new CreateServerLoadDto()
            {
                ServerName = "NotAvailableServer",
                CpuLoad    = 1.1,
                RamLoad    = 1.1
            });

            Assert.IsInstanceOfType(actionResult, typeof(NotFoundResult));
        }
        public void RecordLoads_ShouldReturnOK()
        {
            ServersController controller = new ServersController(true);
            var actionResult             = controller.RecordLoads(new CreateServerLoadDto()
            {
                ServerName = Global.Utility.NewServer,
                CpuLoad    = 1.1,
                RamLoad    = 1.1
            });

            Assert.IsInstanceOfType(actionResult, typeof(OkNegotiatedContentResult <CreateServerLoadDto>));
        }
Esempio n. 17
0
        public void CheckServers()
        {
            // Arrange
            IMemoryCache        memoryCache = new MemoryCache(new MemoryCacheOptions());
            Mock <IMemoryCache> cache       = new Mock <IMemoryCache>();

            var myContext = new Mock <HttpContext>();

            DateTime now    = DateTime.Now;
            Servers  server = new Servers();

            server.ServerId  = "das423";
            server.ServerURL = "/http/8080";

            var          json      = JsonConvert.SerializeObject(server);
            var          byteArray = Encoding.ASCII.GetBytes(json);
            MemoryStream stream    = new MemoryStream(byteArray);

            stream.Flush();
            stream.Position = 0;

            myContext.SetupGet(x => x.Request.Body).Returns(stream);
            var controllerContext = new ControllerContext()
            {
                HttpContext = myContext.Object,
            };
            ServersController controller = new ServersController(memoryCache)
            {
                ControllerContext = controllerContext,
            };

            // Act
            var answer = controller.AddServer(server);

            // Assert
            Assert.AreEqual(answer.Value, server);

            // Arrange
            controller = new ServersController(memoryCache);

            // Act
            ActionResult <List <Servers> > list = controller.GetServers();

            // Assert
            Assert.IsTrue(list.Value.Count == 1);

            // Act
            answer = controller.DeleteServerById(server.ServerId);

            // Assert
            Assert.AreEqual(answer.Value, server);
        }
Esempio n. 18
0
        public void InfoReturnEmptyListIfDatabaseIsEmpty()
        {
            var options = new DbContextOptionsBuilder()
                          .UseInMemoryDatabase("InfoEmpty")
                          .Options;

            using (var context = new DatabaseContext(options))
            {
                var controller = new ServersController(context);
                var result     = controller.Info();
                Assert.Empty(result);
            }
        }
        public void GetRamLoads_ShouldReturnEmpty()
        {
            ServersController controller = new ServersController(true);
            var actionResult             = controller.GetRamLoads(Global.Utility.NewServer);
            var contentResult            = actionResult as OkNegotiatedContentResult <RamLoadAveragesDto>;
            var emptyLoad = new RamLoadAveragesDto()
            {
                AverageRamLoadsForLastHourByMinute = new double[0],
                AverageRamLoadsForLastDayByHour    = new double[0]
            };

            Assert.IsNotNull(contentResult.Content);
            Assert.AreEqual(true, Utility.TestHelper.AreRamLoadAveragesEqual(contentResult.Content, emptyLoad));
        }
        public void PostServerHeartBeat_WithNonExistant_GivesNotFound()
        {
            var endPoint = new IPEndPoint(100, 1);

            using var context = MockDataContext.GetContext();
            var controller = new ServersController(context, ConstructChallengeRespondingMock(), logger);

            MockControllerConnection(controller, endPoint.Address);

            // Note: This assumes the resource format
            var response = controller.PostHeartBeatUpdate(endPoint.ToString());

            Assert.Equal(StatusCodes.Status404NotFound, (response as IStatusCodeActionResult).StatusCode);
        }
        public async void GetServers_WithOutdated_OnlyReturnsCurrent()
        {
            using (var context = MockDataContext.GetContext()) {
                context.Servers.Add(new GameServer {
                    Name           = "A",
                    Address        = "127.0.0.1",
                    QueryPort      = 100,
                    GamePort       = 100,
                    RoundStatus    = "starting",
                    RoundStartTime = DateTime.Now,
                    Game           = "SS3D",
                    LastUpdate     = DateTime.Now
                });
                context.Servers.Add(new GameServer {
                    Name           = "B",
                    Address        = "127.0.0.2",
                    QueryPort      = 200,
                    GamePort       = 200,
                    RoundStatus    = "starting",
                    RoundStartTime = DateTime.Now,
                    Game           = "SS3D",
                    LastUpdate     = DateTime.Now - TimeSpan.FromMinutes(2)
                });
                // This one should definitely be out of date
                context.Servers.Add(new GameServer {
                    Name           = "C",
                    Address        = "127.0.0.3",
                    QueryPort      = 300,
                    GamePort       = 300,
                    RoundStatus    = "starting",
                    RoundStartTime = DateTime.Now,
                    Game           = "SS3D",
                    LastUpdate     = DateTime.Now - TimeSpan.FromMinutes(6)
                });
                context.SaveChanges();
            }

            // Use a separate, fresh context for testing.
            using (var context = MockDataContext.GetContext()) {
                var controller = new ServersController(context, HttpFactoryMock.CreateMock().Object, logger);

                IEnumerable <GameServer> servers = await controller.GetServers().ToListAsync();

                Assert.Equal(2, servers.Count());
                Assert.DoesNotContain(servers, server => server.Name == "C");
            }
        }
        public void PutServer_WithMissing_WillGiveError()
        {
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 100);

            using var context = MockDataContext.GetContext();

            var controller = new ServersController(context, ConstructChallengeRespondingMock(), logger);

            MockControllerConnection(controller, endPoint.Address);

            var result = controller.PutServer(endPoint.ToString(), new GameServer {
                Name = "Not A"
            });

            // Should have 200 status code, given that the item already exists.
            Assert.Equal(StatusCodes.Status404NotFound, (result as IStatusCodeActionResult).StatusCode);
        }
Esempio n. 23
0
        public void Test_AddServer()
        {
            // Setup
            string serverUrl = "http://test2.com";
            string serverId  = "test_server2";
            Server server    = new Server(serverId, serverUrl);

            var mockRemoteServersConnector = new RemoteServersConnector();
            var serversController          = new ServersController(mockRemoteServersConnector);

            // Act
            IActionResult addAction = serversController.AddServer(server);


            // Assert
            Assert.IsType <OkResult>(addAction);
            Assert.Single(mockRemoteServersConnector.GetAllServers());
        }
        public void GetTest()
        {
            // Arrange
            var httpContextAccessor = new Mock <IHttpContextAccessor>();

            httpContextAccessor.Setup(repo => repo.HttpContext.Request.Host)
            .Returns(new HostString("localhost:44351"));
            var serverManagerMock = new Mock <IServerManager>();

            serverManagerMock.Setup(repo => repo.GetServers())
            .Returns(GetServerTest());
            var serverController = new ServersController(serverManagerMock.Object, httpContextAccessor.Object);

            //act
            var result = serverController.Get();

            //assert
            Assert.Equal(2, result.Count);
        }
        public async void PostNewServer_WithExisting_GivesError()
        {
            // Setup
            using (var context = MockDataContext.GetContext()) {
                context.Servers.Add(new GameServer {
                    Name           = "Server Not A",
                    Address        = "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
                    QueryPort      = 100,
                    GamePort       = 100,
                    RoundStatus    = "starting",
                    RoundStartTime = DateTime.Now,
                    Game           = "SS3D",
                    LastUpdate     = DateTime.Now
                });
                context.SaveChanges();
            }

            using (var context = MockDataContext.GetContext()) {
                var controller = new ServersController(context, ConstructChallengeRespondingMock(), logger);

                var endPoint = new IPEndPoint(IPAddress.Parse("2001:0db8:85a3:0000:0000:8a2e:0370:7334"), 100);
                MockControllerConnection(controller, endPoint.Address);

                var result = await controller.PostNewServer(new GameServer {
                    Name           = "Server A",
                    Address        = endPoint.Address.ToString(),
                    QueryPort      = endPoint.Port,
                    GamePort       = 100,
                    RoundStatus    = "starting",
                    RoundStartTime = DateTime.Now,
                }).ConfigureAwait(false);

                Assert.Equal(StatusCodes.Status409Conflict, (result as IStatusCodeActionResult).StatusCode);
            }

            using (var context = MockDataContext.GetContext()) {
                var controller = new ServersController(context, ConstructChallengeRespondingMock(), logger);
                var servers    = await controller.GetServers().ToListAsync();

                Assert.Single(servers);
                Assert.Equal("Server Not A", servers[0].Name); // Nothing about the original entry should have changed.
            }
        }
        public void PutServer_WithExisting_WillChangeItem()
        {
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 100);

            using (var context = MockDataContext.GetContext()) {
                context.Servers.Add(new GameServer {
                    Name           = "Server Not A",
                    Address        = endPoint.Address.ToString(),
                    QueryPort      = endPoint.Port,
                    GamePort       = 100,
                    RoundStatus    = "starting",
                    RoundStartTime = DateTime.Now,
                    Game           = "SS3D",
                    LastUpdate     = DateTime.Now - TimeSpan.FromMinutes(2)
                });
                context.SaveChanges();
            }

            // Use a separate, fresh context for testing.
            using (var context = MockDataContext.GetContext()) {
                var controller = new ServersController(context, ConstructChallengeRespondingMock(), logger);
                MockControllerConnection(controller, endPoint.Address);

                var result = controller.PutServer(endPoint.ToString(), new GameServer {
                    Name           = "Not A",
                    GamePort       = 100,
                    RoundStatus    = "starting",
                    RoundStartTime = DateTime.Now,
                    Game           = "SS3D"
                });

                // Should have 200 status code, given that the item already exists.
                Assert.Equal(StatusCodes.Status200OK, (result as IStatusCodeActionResult).StatusCode);
            }

            using (var postContext = MockDataContext.GetContext()) {
                var onlyServer = Assert.Single(postContext.Servers);
                Assert.Equal("Not A", onlyServer.Name);

                // Check that the LastUpdate has changed to now too
                Assert.True(onlyServer.LastUpdate > DateTime.Now - TimeSpan.FromSeconds(10));
            }
        }
        public void PutServer_WithDifferentAddress_WillGiveError()
        {
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 100);

            using (var context = MockDataContext.GetContext()) {
                context.Servers.Add(new GameServer {
                    Name           = "Server Not A",
                    Address        = endPoint.Address.ToString(),
                    QueryPort      = endPoint.Port,
                    GamePort       = 100,
                    RoundStatus    = "starting",
                    RoundStartTime = DateTime.Now,
                    Game           = "SS3D",
                    LastUpdate     = DateTime.Now - TimeSpan.FromMinutes(2)
                });
                context.SaveChanges();
            }

            // Use a separate, fresh context for testing.
            using (var context = MockDataContext.GetContext()) {
                var controller = new ServersController(context, ConstructChallengeRespondingMock(), logger);
                MockControllerConnection(controller, endPoint.Address);

                var result = controller.PutServer(endPoint.ToString(), new GameServer {
                    Name           = "Not A",
                    Address        = "128.0.0.1",
                    GamePort       = 100,
                    RoundStatus    = "starting",
                    RoundStartTime = DateTime.Now,
                    Game           = "SS3D"
                });

                // Should have 200 status code, given that the item already exists.
                Assert.Equal(StatusCodes.Status400BadRequest, (result as IStatusCodeActionResult).StatusCode);
            }

            // Just double check for no updates to db
            using (var postContext = MockDataContext.GetContext()) {
                var onlyServer = Assert.Single(postContext.Servers);
                Assert.Equal("Server Not A", onlyServer.Name);
            }
        }
Esempio n. 28
0
        public void Test_DeleteServer()
        {
            // Setup
            string serverUrl = "http://test3.com";
            string serverId  = "test_server3";
            Server server    = new Server(serverId, serverUrl);

            var mockRemoteServersConnector = new RemoteServersConnector();

            mockRemoteServersConnector.AddServer(server);
            var serversController = new ServersController(mockRemoteServersConnector);

            // Act
            IActionResult delAction = serversController.DeleteServer(server.ServerId);


            // Assert
            Assert.IsType <OkResult>(delAction);
            Assert.Empty(mockRemoteServersConnector.GetAllServers());
        }
Esempio n. 29
0
        public void TestPostServer()
        {
            Server serv1 = new Server {
                ServerId = "sapir22", ServerUrl = "www.test1.com"
            };
            List <Server> servers = new List <Server>();

            servers.Add(serv1);
            IMemoryCache      cache      = CreateCache();
            ServersController controller = new ServersController(cache);
            string            serJson    = "{\"ServerId\":\"sapir22\",\"ServerURL\":\"www.test1.com\"}";
            JsonDocument      doc        = JsonDocument.Parse(serJson);
            JsonElement       root       = doc.RootElement;

            controller.Post(root);
            var responseList = (List <Server>)controller.GetAllServers();

            Assert.AreEqual(responseList[0].ServerId, servers[0].ServerId);
            Assert.AreEqual(responseList[0].ServerUrl, servers[0].ServerUrl);
        }
        public void PostServerHeartBeat_WithExisting_UpdatesTime()
        {
            // SETUP
            var endPoint = new IPEndPoint(100, 1);

            using (var preContext = MockDataContext.GetContext()) {
                preContext.Servers.Add(new GameServer {
                    Name           = "A",
                    Address        = endPoint.Address.ToString(),
                    QueryPort      = endPoint.Port,
                    GamePort       = 100,
                    RoundStatus    = "starting",
                    RoundStartTime = DateTime.Now,
                    Game           = "SS3D",
                    LastUpdate     = DateTime.Now - TimeSpan.FromMinutes(2)
                });
                preContext.SaveChanges();
            }

            using var context = MockDataContext.GetContext();

            var controller = new ServersController(context, ConstructChallengeRespondingMock(), logger);

            MockControllerConnection(controller, endPoint.Address);

            // ACTUAL TEST

            // Use same IP as was originally given
            var response = controller.PostHeartBeatUpdate(endPoint.ToString());

            // Should be successful
            Assert.Equal(StatusCodes.Status200OK, (response as IStatusCodeActionResult).StatusCode);

            // Get the server
            using (var postContext = MockDataContext.GetContext()) {
                var onlyServer = Assert.Single(postContext.Servers);

                // Check that the LastUpdate has changed
                Assert.True(onlyServer.LastUpdate > DateTime.Now - TimeSpan.FromSeconds(10));
            }
        }