public virtual void UpdateTestClientWithActiveTask(ITestClient testClient, ITestTask actualTask)
 {
     testClient.Status = TestClientStatuses.Running;
     testClient.TaskId = actualTask.Id;
     testClient.TaskName = actualTask.Name;
     testClient.TestRunId = actualTask.TestRunId;
 }
Esempio n. 2
0
        private static int RunMixedPackTest(ITestClient testClient, int loopSize, string key1, string key2, bool flushdb = true)
        {
            using (testClient)
            {
                var payload = Payloads.MediumPayload;
                testClient.Connect(_cs);
                if (flushdb)
                {
                    testClient.FlushDb();
                }
                var sw = new Stopwatch();
                sw.Start();

                for (var i = 0; i < loopSize; i++)
                {
                    testClient.SetAsync(key1, payload);
                    testClient.IncrAsync(key2);
                }

                var result     = testClient.GetString(key1);
                var incrResult = testClient.GetInt(key2);

                if (result != payload)
                {
                    Console.Write("[condition failed Result == Payload] ");
                }
                if (incrResult != loopSize)
                {
                    Console.Write("[condition failed IncrResult == LoopSize] ");
                }

                sw.Stop();
                return((int)sw.ElapsedMilliseconds);
            }
        }
Esempio n. 3
0
        private static int RunBasicTest(ITestClient testClient, string payload, int loopSize)
        {
            using (testClient)
            {
                testClient.Connect(_cs);

                testClient.FlushDb();
                var sw = new Stopwatch();
                sw.Start();

                for (var i = 0; i < loopSize; i++)
                {
                    testClient.SetAsync(KeyName, payload);
                }

                var result = testClient.GetString(KeyName);

                if (result != payload)
                {
                    Console.Write("[condition failed Result == Payload] ");
                }

                sw.Stop();
                return((int)sw.ElapsedMilliseconds);
            }
        }
 public virtual void UpdateTestClientWithActiveTask(ITestClient testClient, ITestTask actualTask)
 {
     testClient.Status    = TestClientStatuses.Running;
     testClient.TaskId    = actualTask.Id;
     testClient.TaskName  = actualTask.Name;
     testClient.TestRunId = actualTask.TestRunId;
 }
Esempio n. 5
0
        protected async Task TestPut(ITestClient client, string apiUrl, string[] expectedFields, Dictionary <string, object> updates, string identifierName = "id")
        {
            var existing = await GetExistingObject(client, apiUrl, expectedFields);

            Assert.IsNotNull(existing);

            //ensure new props
            foreach (var key in updates.Keys.ToList())
            {
                Assert.IsTrue(existing.ContainsKey(key), $"{key} not found in json");
                EnsureJsonTypeMatchesObjectType(existing[key].Type, updates[key]);

                //have to check for null because existing[key] can be null
                if (existing[key] == null && updates[key] == null || existing[key].ToString() == updates[key].ToString())
                {
                    Assert.Fail($"property {key} is already equal; hence this test does not fully test the intended behaviour. aborting");
                }
            }

            //put changes
            await client.PutAsync(apiUrl + "/" + existing[identifierName], updates);

            //check that it has been preserved
            await EnsureObjectExists(client, apiUrl, expectedFields, identifierName, (int)existing[identifierName], updates);
        }
Esempio n. 6
0
        protected override async Task PerformIntegrationTest(ITestClient testClient)
        {
            //arrange
            var payload = new byte[] { 50, 20, 30 };
            var apiUrl  = "/Backup";

            //info page should contain infos to urls
            var str = await testClient.GetAsync(apiUrl);

            Assert.IsNotNull(str);
            Assert.IsTrue(str.Contains(apiUrl));

            //download original db
            var originalDb = await testClient.GetFileAsync(apiUrl + "/db.sqlite");

            Assert.IsNotNull(originalDb);
            Assert.IsTrue(originalDb.Length > 0);

            //replace db with own file
            var replaceResponse = await testClient.PostFileAsync(apiUrl + "/post", payload);

            Assert.IsNotNull(replaceResponse);
            Assert.IsTrue(replaceResponse.ToLower().Contains("true"));

            //check that replace was successful
            var replaceDb = await testClient.GetFileAsync(apiUrl + "/db.sqlite");

            CheckArraysMatch(payload, replaceDb);

            //check that backup was successful
            var backupDb = await testClient.GetFileAsync(apiUrl + "/db.sqlite_backup");

            CheckArraysMatch(originalDb, backupDb);
        }
Esempio n. 7
0
 /// <summary>
 /// 开始测试客户端
 /// </summary>
 private static void StartTestClient()
 {
     ConsoleHelper.TestWriteLine("正在启动服务");
     _testClient = TestClientHelper.ServiceProvider.GetService <ITestClient>();
     _testClient.Init();
     _testClient.Start();
 }
Esempio n. 8
0
        protected async Task <object> TestGet(ITestClient client, string apiUrl, string[] expectedFields)
        {
            var response = await client.GetJsonAsync(apiUrl);

            AssertHelper.AssertArray(response, expectedFields);

            return(response);
        }
Esempio n. 9
0
 ITestClient WhenSendingRegistrationAsJson(ITestClient testClient)
 {
     _response = _browser.Post(UrlList.TestClientRegistrationPoint_absPath, with => {
         with.JsonBody(testClient);
         with.Accept("application/json");
     });
     return(_response.Body.DeserializeJson <TestClient>());
 }
Esempio n. 10
0
 public void ResetData()
 {
     ClientId        = Guid.Empty;
     ServerUrl       = string.Empty;
     StopImmediately = false;
     TaskResult      = new string[] {};
     CurrentTask     = null;
     CurrentClient   = null;
 }
Esempio n. 11
0
 public void ResetData()
 {
     ClientId = Guid.Empty;
     ServerUrl = string.Empty;
     StopImmediately = false;
     TaskResult = new string[] {};
     CurrentTask = null;
     CurrentClient = null;
 }
Esempio n. 12
0
        private async Task <JObject> GetExistingObject(ITestClient client, string apiUrl, string[] expectedFields)
        {
            var getResponse = await TestGet(client, apiUrl, expectedFields);

            var getArray = AssertHelper.AssertArray(getResponse);

            //if no identifier provided simply return first element
            return(getArray.Count > 0 ? AssertHelper.AssertObject(getArray[0], expectedFields) : null);
        }
Esempio n. 13
0
        Negotiator returnTaskToClient_StatusOk(ITestClient testClient, ITestTask actualTask)
        {
            ServerObjectFactory.Resolve <TestTaskCollectionMethods>().UpdateTestClientWithActiveTask(testClient, actualTask);

            // 20141020 squeezing a task to its proxy
            return(Negotiate.WithModel(actualTask).WithStatusCode(HttpStatusCode.OK));
            // return Negotiate.WithModel(actualTask.SqueezeTaskToTaskResultProxy()).WithStatusCode(HttpStatusCode.OK);
            // return Negotiate.WithModel(actualTask.SqueezeTaskToTaskCodeProxy()).WithStatusCode(HttpStatusCode.OK);
        }
Esempio n. 14
0
        Negotiator returnNoTask_StatusNotFound(ITestClient testClient)
        {
            Trace.TraceInformation("returnNoTask_StatusNotFound(ITestClient testClient).1");

            testClient.SetNoTasksStatus();

            Trace.TraceInformation("returnNoTask_StatusNotFound(ITestClient testClient).2");

            return(Negotiate.WithStatusCode(HttpStatusCode.NotFound));
        }
Esempio n. 15
0
 Negotiator returnNoTask_StatusNotFound(ITestClient testClient)
 {
     Trace.TraceInformation("returnNoTask_StatusNotFound(ITestClient testClient).1");
     
     testClient.SetNoTasksStatus();
     
     Trace.TraceInformation("returnNoTask_StatusNotFound(ITestClient testClient).2");
     
     return Negotiate.WithStatusCode(HttpStatusCode.NotFound);
 }
Esempio n. 16
0
        static async Task Main(string[] args)
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddDefaultScalarSerializers();
            serviceCollection.AddtestClient();
            serviceCollection.AddHttpClient("TestClient").ConfigureHttpClient(client =>
                                                                              client.BaseAddress = new Uri(GraphQLService));

            IServiceProvider services = serviceCollection.BuildServiceProvider();
            ITestClient      client   = services.GetRequiredService <ITestClient>();

            int t = 0;

            int numberOfCalls = 30;

            while (t < numberOfCalls)
            {
                // Default very high timeout (don't cancel)
                int cancelAfter = 30000;

                // Every second call should cancel faster then request takes to process
                if (t % 2 == 0)
                {
                    cancelAfter = 50;
                }

                var token = new CancellationTokenSource(cancelAfter).Token;

                try
                {
                    var result = await client.GetValuesAsync(token);

                    // Expect this result everytime
                    var data = $"{result.Data?.Data?.Value1}{result.Data?.Data?.Value2}{result.Data?.Data?.Value3}";

                    if (data != "Value1Value2Value3")
                    {
                        Console.WriteLine("DATA IS WRONG : " + data);
                    }
                    else
                    {
                        Console.WriteLine("Data is ok");
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("Operation canceled");
                }

                t++;
            }
            Console.WriteLine("Done");
        }
Esempio n. 17
0
 public StartTestParams GetNotCommitedSessions(int userId, bool getLastSession)
 {
     try
     {
         return(_testClient.GetNotCommitedSessions(userId, getLastSession));
     }
     catch (CommunicationException)
     {
         _testClient = _factory.CreateChannel();
         return(_testClient.GetNotCommitedSessions(userId, getLastSession));
     }
 }
Esempio n. 18
0
 public byte[] GetImage(string imageId)
 {
     try
     {
         return(_testClient.GetImage(imageId));
     }
     catch (CommunicationException)
     {
         _testClient = _factory.CreateChannel();
         return(_testClient.GetImage(imageId));
     }
 }
Esempio n. 19
0
 public void DeleteSession(int sessionId)
 {
     try
     {
         _testClient.DeleteSession(sessionId);
     }
     catch (CommunicationException)
     {
         _testClient = _factory.CreateChannel();
         _testClient.DeleteSession(sessionId);
     }
 }
Esempio n. 20
0
        private async Task <JObject> GetExistingObject(ITestClient client, string apiUrl, string[] expectedFields, string identifierName, int identifier)
        {
            var getResponse = await TestGet(client, apiUrl, expectedFields);

            var getArray = AssertHelper.AssertArray(getResponse);

            var existingCandidates = getArray.Children().Where(j => (int)j[identifierName] == identifier).ToList();

            Assert.IsTrue(existingCandidates.Count <= 1);

            return(existingCandidates.FirstOrDefault() as JObject);
        }
Esempio n. 21
0
 public byte[] GetQuestion(int questId, bool getBLOBs)
 {
     try
     {
         return(_testClient.GetQuestion(questId, getBLOBs));
     }
     catch (CommunicationException)
     {
         _testClient = _factory.CreateChannel();
         return(_testClient.GetQuestion(questId, getBLOBs));
     }
 }
Esempio n. 22
0
 public string GetDatabasePassword(string databaseName)
 {
     try
     {
         return(_testClient.GetDatabasePassword(databaseName));
     }
     catch (CommunicationException)
     {
         _testClient = _factory.CreateChannel();
         return(_testClient.GetDatabasePassword(databaseName));
     }
 }
Esempio n. 23
0
 public TestorSecurityAlertResult SetSecurityAlert(string uniqId)
 {
     try
     {
         return(_testClient.SetSecurityAlert(uniqId));
     }
     catch (CommunicationException)
     {
         _testClient = _factory.CreateChannel();
         return(_testClient.SetSecurityAlert(uniqId));
     }
 }
Esempio n. 24
0
 public TestorTreeItem[] GetAppointedTests()
 {
     try
     {
         return(_testClient.GetAppointedTests());
     }
     catch (CommunicationException)
     {
         _testClient = _factory.CreateChannel();
         return(_testClient.GetAppointedTests());
     }
 }
Esempio n. 25
0
 public string[] GetDatabaseNamesList()
 {
     try
     {
         return(_testClient.GetDatabaseNamesList());
     }
     catch (CommunicationException)
     {
         _testClient = _factory.CreateChannel();
         return(_testClient.GetDatabaseNamesList());
     }
 }
Esempio n. 26
0
 public TestorTreeItem[] GetCurrentUserFailRequirements(int testId)
 {
     try
     {
         return(_testClient.GetCurrentUserFailRequirements(testId));
     }
     catch (CommunicationException)
     {
         _testClient = _factory.CreateChannel();
         return(_testClient.GetCurrentUserFailRequirements(testId));
     }
 }
Esempio n. 27
0
 public bool IsPassagesNumberNotOverlimit(int testId)
 {
     try
     {
         return(_testClient.IsPassagesNumberNotOverlimit(testId));
     }
     catch (CommunicationException)
     {
         _testClient = _factory.CreateChannel();
         return(_testClient.IsPassagesNumberNotOverlimit(testId));
     }
 }
Esempio n. 28
0
 public int[] GetSessionQuestions(int sessionId)
 {
     try
     {
         return(_testClient.GetSessionQuestions(sessionId));
     }
     catch (CommunicationException)
     {
         _testClient = _factory.CreateChannel();
         return(_testClient.GetSessionQuestions(sessionId));
     }
 }
 public bool CreateNewClient(ITestClient testClient)
 {
     if (!TestRunQueue.TestRuns.HasActiveTestRuns())
         return false;
     testClient.TestRunId = TestRunQueue.TestRuns.ActiveTestRunIds().First();
     ClientsCollection.Clients.Add(testClient);
     var taskSelector = ServerObjectFactory.Resolve<TaskSelector>();
     var tasksForClient = taskSelector.SelectTasksForClient(testClient.Id, TaskPool.Tasks);
     tasksForClient.ForEach(task => task.TestRunId = testClient.TestRunId);
     TaskPool.TasksForClients.AddRange(tasksForClient);
     return true;
 }
Esempio n. 30
0
 public StartTestParams StartTest(int testId)
 {
     try
     {
         return(_testClient.StartTest(testId));
     }
     catch (CommunicationException)
     {
         _testClient = _factory.CreateChannel();
         return(_testClient.StartTest(testId));
     }
 }
Esempio n. 31
0
 public string GetAppealHtml(int sessionId)
 {
     try
     {
         return(_testClient.GetAppealHtml(sessionId));
     }
     catch (CommunicationException)
     {
         _testClient = _factory.CreateChannel();
         return(_testClient.GetAppealHtml(sessionId));
     }
 }
Esempio n. 32
0
 public AppealResult GetQuestionAppeal(int sessionId, int questId, bool getBLOBs)
 {
     try
     {
         return(_testClient.GetQuestionAppeal(sessionId, questId, getBLOBs));
     }
     catch (CommunicationException)
     {
         _testClient = _factory.CreateChannel();
         return(_testClient.GetQuestionAppeal(sessionId, questId, getBLOBs));
     }
 }
Esempio n. 33
0
 public EndSessionResult EndSession()
 {
     try
     {
         return(_testClient.EndSession());
     }
     catch (CommunicationException)
     {
         _testClient = _factory.CreateChannel();
         return(_testClient.EndSession());
     }
 }
Esempio n. 34
0
 public QuestAnswerResult ProcessAnswer(int questId, Dictionary <string, List <string> > requestParams)
 {
     try
     {
         return(_testClient.ProcessAnswer(questId, requestParams));
     }
     catch (CommunicationException)
     {
         _testClient = _factory.CreateChannel();
         return(_testClient.ProcessAnswer(questId, requestParams));
     }
 }
 public virtual bool CreateNewClient(ITestClient testClient)
 {
     if (!TestRunQueue.TestRuns.HasActiveTestRuns())
         return false;
     // TODO: improve the selection of a test run by matching test client to task rules
     var activeWorkflowIds = WorkflowCollection.Workflows.ActiveWorkflows().Select(wfl => wfl.Id);
     var legitimateWorkflowIds = TaskPool.Tasks
         .Where(task => activeWorkflowIds.Contains(task.WorkflowId) && 
                (
                    Regex.IsMatch(testClient.CustomString ?? string.Empty, task.Rule) ||
                    Regex.IsMatch(testClient.EnvironmentVersion ?? string.Empty, task.Rule) ||
                    Regex.IsMatch(testClient.Fqdn ?? string.Empty, task.Rule) ||
                    Regex.IsMatch(testClient.Hostname ?? string.Empty, task.Rule) ||
                    Regex.IsMatch(testClient.OsVersion ?? string.Empty, task.Rule) ||
                    Regex.IsMatch(testClient.UserDomainName ?? string.Empty, task.Rule) ||
                    Regex.IsMatch(testClient.Username ?? string.Empty, task.Rule)
                    /*
                    Regex.IsMatch(task.Rule, testClient.CustomString ?? string.Empty) ||
                    Regex.IsMatch(task.Rule, testClient.EnvironmentVersion ?? string.Empty) ||
                    Regex.IsMatch(task.Rule, testClient.Fqdn ?? string.Empty) ||
                    Regex.IsMatch(task.Rule, testClient.Hostname ?? string.Empty) ||
                    Regex.IsMatch(task.Rule, testClient.OsVersion ?? string.Empty) ||
                    Regex.IsMatch(task.Rule, testClient.UserDomainName ?? string.Empty) ||
                    Regex.IsMatch(task.Rule, testClient.Username ?? string.Empty)
                    */
                ))
         .Select(task => task.WorkflowId);
     
     var workflowIds = legitimateWorkflowIds as Guid[] ?? legitimateWorkflowIds.ToArray();
     if (!workflowIds.Any())
         return false;
     
     // 20150922
     // testClient.TestRunId = TestRunQueue.TestRuns.First(testRun => testRun.IsActive() && workflowIds.Contains(testRun.WorkflowId)).Id;
     testClient.TestRunId = TestRunQueue.TestRuns.First(testRun => testRun.IsAcceptingNewClients() && workflowIds.Contains(testRun.WorkflowId)).Id;
     
     ClientsCollection.Clients.Add(testClient);
     var taskSelector = ServerObjectFactory.Resolve<TaskSelector>();
     var tasksForClient = taskSelector.SelectTasksForClient(testClient.Id, TaskPool.Tasks);
     tasksForClient.ForEach(task => task.TestRunId = testClient.TestRunId);
     TaskPool.TasksForClients.AddRange(tasksForClient);
     return true;
 }
Esempio n. 36
0
 void WHEN_SendingDeregistration_as_json(ITestClient testClient)
 {
     _browser.Delete(UrlList.TestClients_Root + "/" + testClient.Id, with => with.Accept("application/json"));
 }
Esempio n. 37
0
        private static int RunManyClientsTest(ITestClient client, int iterations)
        {
            var rand = new Random();
            _clientsRunning = 0;
            //warm up
            var sw = new Stopwatch();
            sw.Start();
            RunMixedPackTest(client.CreateOne(), iterations, KeyName, KeyName2);
            sw.Stop();

            var time = (int)sw.ElapsedMilliseconds;
            int spawnTimes = 0;
            int result = 0;
            var tasks = new List<Task>();
            for (var i = 0; i < Iterations; i++)
            {
                SpinWait.SpinUntil(() => _clientsRunning < MaxClients);

                tasks.Add(Task.Run(() =>
                    {
                        spawnTimes++;
                        Console.WriteLine("Spawn new " + client.ClientName);
                        Interlocked.Increment(ref _clientsRunning);
                        var tmp = RunMixedPackTest(client.CreateOne(), iterations, KeyName + "_" + spawnTimes, KeyName2 + "_" + spawnTimes,false);
                        result += tmp;
                        Console.WriteLine("Client time ms = "+tmp);
                        Interlocked.Decrement(ref _clientsRunning);
                        Console.WriteLine("Destroy " + client.ClientName);
                    }));
                Thread.Sleep(rand.Next(time));
            }
            Task.WaitAll(tasks.ToArray());
            return result/spawnTimes;
        }
Esempio n. 38
0
        Negotiator returnTaskToClient_StatusOk(ITestClient testClient, ITestTask actualTask)
        {
            ServerObjectFactory.Resolve<TestTaskCollectionMethods>().UpdateTestClientWithActiveTask(testClient, actualTask);

            // 20141020 squeezing a task to its proxy
            return Negotiate.WithModel(actualTask).WithStatusCode(HttpStatusCode.OK);
            // return Negotiate.WithModel(actualTask.SqueezeTaskToTaskResultProxy()).WithStatusCode(HttpStatusCode.OK);
            // return Negotiate.WithModel(actualTask.SqueezeTaskToTaskCodeProxy()).WithStatusCode(HttpStatusCode.OK);
        }
Esempio n. 39
0
 // TODO: duplicated
 void THEN_test_client_is_busy(ITestClient testClient)
 {
     Xunit.Assert.Equal(TestClientStatuses.Running, testClient.Status);
 }
Esempio n. 40
0
 void THEN_test_client_is_free(ITestClient testClient)
 {
     Xunit.Assert.Equal(TestClientStatuses.NoTasks, testClient.Status);
 }
Esempio n. 41
0
        private static int RunSyncExecutionTest(string payload, ITestClient testClient, int loopSize)
        {
            using (testClient)
            {
                testClient.Connect(_cs);

                testClient.FlushDb();
                var sw = new Stopwatch();
                sw.Start();

                for (var i = 0; i < loopSize; i++)
                    testClient.Set(KeyName, payload);

                var result = testClient.GetString(KeyName);

                if (result != payload)
                    Console.Write("[condition failed Result == Payload] ");

                sw.Stop();
                return (int)sw.ElapsedMilliseconds;
            }
        }
Esempio n. 42
0
 ITestClient GivenSendingRegistrationAsJson(ITestClient testClient)
 {
     WhenSendingRegistrationAsJson(testClient);
     return _response.Body.DeserializeJson<TestClient>();
 }
Esempio n. 43
0
 ITestClient GIVEN_SendingRegistration_as_Json(ITestClient testClient)
 {
     WHEN_SendingRegistration_as_Json(testClient);
     return _response.Body.DeserializeJson<TestClient>();
 }
Esempio n. 44
0
        private static int RunMixedPackTest(ITestClient testClient, int loopSize, string key1, string key2, bool flushdb = true)
        {
            using (testClient)
            {
                var payload = Payloads.MediumPayload;
                testClient.Connect(_cs);
                if (flushdb)
                    testClient.FlushDb();
                var sw = new Stopwatch();
                sw.Start();

                for (var i = 0; i < loopSize; i++)
                {
                    testClient.SetAsync(key1, payload);
                    testClient.IncrAsync(key2);
                }

                var result = testClient.GetString(key1);
                var incrResult = testClient.GetInt(key2);

                if (result != payload)
                    Console.Write("[condition failed Result == Payload] ");
                if (incrResult != loopSize)
                    Console.Write("[condition failed IncrResult == LoopSize] ");

                sw.Stop();
                return (int) sw.ElapsedMilliseconds;
            }
        }
Esempio n. 45
0
 ITestClient WhenSendingRegistrationAsJson(ITestClient testClient)
 {
     _response = _browser.Post(UrlList.TestClientRegistrationPoint_absPath, with => {
         with.JsonBody(testClient);
         with.Accept("application/json");
     });
     return _response.Body.DeserializeJson<TestClient>();
 }
Esempio n. 46
0
 void WhenSendingDeregistrationAsXml(ITestClient testClient)
 {
     _browser.Delete(UrlList.TestClients_Root + "/" + testClient.Id, with => with.Accept("application/xml"));
 }
Esempio n. 47
0
 // TODO: duplicated
 void ThenTestClientIsBusy(ITestClient testClient)
 {
     Assert.Equal(TestClientStatuses.Running, testClient.Status);
 }
Esempio n. 48
0
 void ThenTestClientIsFree(ITestClient testClient)
 {
     Assert.Equal(TestClientStatuses.NoTasks, testClient.Status);
 }