public virtual void UpdateTestClientWithActiveTask(ITestClient testClient, ITestTask actualTask) { testClient.Status = TestClientStatuses.Running; testClient.TaskId = actualTask.Id; testClient.TaskName = actualTask.Name; testClient.TestRunId = actualTask.TestRunId; }
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); } }
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); } }
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); }
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); }
/// <summary> /// 开始测试客户端 /// </summary> private static void StartTestClient() { ConsoleHelper.TestWriteLine("正在启动服务"); _testClient = TestClientHelper.ServiceProvider.GetService <ITestClient>(); _testClient.Init(); _testClient.Start(); }
protected async Task <object> TestGet(ITestClient client, string apiUrl, string[] expectedFields) { var response = await client.GetJsonAsync(apiUrl); AssertHelper.AssertArray(response, expectedFields); return(response); }
ITestClient WhenSendingRegistrationAsJson(ITestClient testClient) { _response = _browser.Post(UrlList.TestClientRegistrationPoint_absPath, with => { with.JsonBody(testClient); with.Accept("application/json"); }); return(_response.Body.DeserializeJson <TestClient>()); }
public void ResetData() { ClientId = Guid.Empty; ServerUrl = string.Empty; StopImmediately = false; TaskResult = new string[] {}; CurrentTask = null; CurrentClient = null; }
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); }
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); }
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)); }
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); }
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"); }
public StartTestParams GetNotCommitedSessions(int userId, bool getLastSession) { try { return(_testClient.GetNotCommitedSessions(userId, getLastSession)); } catch (CommunicationException) { _testClient = _factory.CreateChannel(); return(_testClient.GetNotCommitedSessions(userId, getLastSession)); } }
public byte[] GetImage(string imageId) { try { return(_testClient.GetImage(imageId)); } catch (CommunicationException) { _testClient = _factory.CreateChannel(); return(_testClient.GetImage(imageId)); } }
public void DeleteSession(int sessionId) { try { _testClient.DeleteSession(sessionId); } catch (CommunicationException) { _testClient = _factory.CreateChannel(); _testClient.DeleteSession(sessionId); } }
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); }
public byte[] GetQuestion(int questId, bool getBLOBs) { try { return(_testClient.GetQuestion(questId, getBLOBs)); } catch (CommunicationException) { _testClient = _factory.CreateChannel(); return(_testClient.GetQuestion(questId, getBLOBs)); } }
public string GetDatabasePassword(string databaseName) { try { return(_testClient.GetDatabasePassword(databaseName)); } catch (CommunicationException) { _testClient = _factory.CreateChannel(); return(_testClient.GetDatabasePassword(databaseName)); } }
public TestorSecurityAlertResult SetSecurityAlert(string uniqId) { try { return(_testClient.SetSecurityAlert(uniqId)); } catch (CommunicationException) { _testClient = _factory.CreateChannel(); return(_testClient.SetSecurityAlert(uniqId)); } }
public TestorTreeItem[] GetAppointedTests() { try { return(_testClient.GetAppointedTests()); } catch (CommunicationException) { _testClient = _factory.CreateChannel(); return(_testClient.GetAppointedTests()); } }
public string[] GetDatabaseNamesList() { try { return(_testClient.GetDatabaseNamesList()); } catch (CommunicationException) { _testClient = _factory.CreateChannel(); return(_testClient.GetDatabaseNamesList()); } }
public TestorTreeItem[] GetCurrentUserFailRequirements(int testId) { try { return(_testClient.GetCurrentUserFailRequirements(testId)); } catch (CommunicationException) { _testClient = _factory.CreateChannel(); return(_testClient.GetCurrentUserFailRequirements(testId)); } }
public bool IsPassagesNumberNotOverlimit(int testId) { try { return(_testClient.IsPassagesNumberNotOverlimit(testId)); } catch (CommunicationException) { _testClient = _factory.CreateChannel(); return(_testClient.IsPassagesNumberNotOverlimit(testId)); } }
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; }
public StartTestParams StartTest(int testId) { try { return(_testClient.StartTest(testId)); } catch (CommunicationException) { _testClient = _factory.CreateChannel(); return(_testClient.StartTest(testId)); } }
public string GetAppealHtml(int sessionId) { try { return(_testClient.GetAppealHtml(sessionId)); } catch (CommunicationException) { _testClient = _factory.CreateChannel(); return(_testClient.GetAppealHtml(sessionId)); } }
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)); } }
public EndSessionResult EndSession() { try { return(_testClient.EndSession()); } catch (CommunicationException) { _testClient = _factory.CreateChannel(); return(_testClient.EndSession()); } }
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; }
void WHEN_SendingDeregistration_as_json(ITestClient testClient) { _browser.Delete(UrlList.TestClients_Root + "/" + testClient.Id, with => with.Accept("application/json")); }
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; }
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); }
// TODO: duplicated void THEN_test_client_is_busy(ITestClient testClient) { Xunit.Assert.Equal(TestClientStatuses.Running, testClient.Status); }
void THEN_test_client_is_free(ITestClient testClient) { Xunit.Assert.Equal(TestClientStatuses.NoTasks, testClient.Status); }
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; } }
ITestClient GivenSendingRegistrationAsJson(ITestClient testClient) { WhenSendingRegistrationAsJson(testClient); return _response.Body.DeserializeJson<TestClient>(); }
ITestClient GIVEN_SendingRegistration_as_Json(ITestClient testClient) { WHEN_SendingRegistration_as_Json(testClient); return _response.Body.DeserializeJson<TestClient>(); }
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; } }
ITestClient WhenSendingRegistrationAsJson(ITestClient testClient) { _response = _browser.Post(UrlList.TestClientRegistrationPoint_absPath, with => { with.JsonBody(testClient); with.Accept("application/json"); }); return _response.Body.DeserializeJson<TestClient>(); }
void WhenSendingDeregistrationAsXml(ITestClient testClient) { _browser.Delete(UrlList.TestClients_Root + "/" + testClient.Id, with => with.Accept("application/xml")); }
// TODO: duplicated void ThenTestClientIsBusy(ITestClient testClient) { Assert.Equal(TestClientStatuses.Running, testClient.Status); }
void ThenTestClientIsFree(ITestClient testClient) { Assert.Equal(TestClientStatuses.NoTasks, testClient.Status); }