public void PostsController_Edit_Post() { var postViewModel = new PostViewModel { Id = 6 }; var viewResult = _postsController.Edit(postViewModel) as ViewResult; var model = Mapper.Map <Post>(postViewModel); _postRepository.ReceivedWithAnyArgs().Update(model); _postRepository.ClearReceivedCalls(); var categories = (viewResult.Model as PostViewModel).Categories; Assert.IsTrue(categories.SequenceEqual(TestsHelper.GetCategories(), new SelectListItemComparer())); }
public void TestPassThrough() { short[] data = TestsHelper.LoadAudioFile("test_mono_44100.raw"); Assert.IsNotNull(data, "Failed to load test data (check DATA_PATH in TestsHelper.cs)"); AudioBuffer buffer = new AudioBuffer(); AudioProcessor processor = new AudioProcessor(44100, buffer); processor.Reset(44100, 1); processor.Consume(data, data.Length); processor.Flush(); CollectionAssert.AreEqual(data, buffer.data); }
public async void LoadRelatedEntitiesAsync_Should_Populate_Order_With_Customer_With_Setting() { // Arrange var context = TestsHelper.CreateNorthwindDbContext(CreateNorthwindDbOptions); var order = CreateTestOrders(context)[0]; order.TrackingState = TrackingState.Added; // Act await context.LoadRelatedEntitiesAsync(order); // Assert Assert.NotNull(order.Customer.CustomerSetting); Assert.Equal(order.Customer.CustomerId, order.Customer.CustomerSetting.CustomerId); }
public void ExecuteQueryTimeSeriesAsync_SqlCommand_ShouldReturnResultSet() { const string functionName = "select * from tb_timeseries_shareclass"; var result = sqlQueryManager .ExecuteQueryTimeSeriesAsync(functionName) .Take(100) .ToListAsync() .Result; Assert.True(result.Count == 100); Assert.True(result[0].Length == 6); TestsHelper.PrintTableOutput(this.output, functionName, result); }
public void TearDown() { string failedTestsDirectoryName = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); if (TestContext.CurrentContext.Result.Outcome.Status is TestStatus.Failed && wrongVisualizationCloud != null) { var pathResult = WrongVisualizationSaver.SaveAndGetPathToWrongVisualization( wrongVisualizationCloud, VisualizationImageSize, failedTestsDirectoryName); TestsHelper.HandleErrors(HandleError, pathResult); createdTempFileNames.Add(pathResult.Value); } }
public void LoadRelatedEntities_Should_Populate_Product_With_HolidayPromo() { // Arrange var context = TestsHelper.CreateNorthwindDbContext(CreateNorthwindDbOptions); var product = CreateTestProductsWithPromos(context)[0]; product.TrackingState = TrackingState.Added; // Act context.LoadRelatedEntities(product); // Assert Assert.NotNull(product.HolidayPromo); Assert.Equal(product.PromoId, product.HolidayPromo.PromoId); }
public void LoadRelatedEntities_Should_Populate_Order_With_Customer_With_Territory() { // Arrange var context = TestsHelper.CreateNorthwindDbContext(CreateNorthwindDbOptions); var order = CreateTestOrders(context)[0]; order.TrackingState = TrackingState.Added; // Act context.LoadRelatedEntities(order); // Assert Assert.NotNull(order.Customer.Territory); Assert.Equal(order.Customer.TerritoryId, order.Customer.Territory.TerritoryId); }
public void ExecuteQuery_WithValidColumns_ShouldReturnResultSet(string function) { string[] columns = new[] { "ID", "NAME" }; var result = sqlQueryManager .ExecuteQueryAsync(function, DateTime.Now, null, columns) .ToListAsync() .Result; Assert.True(result[0].Length == 2); Assert.Contains(result[0], a => a == columns[0]); Assert.Contains(result[0], a => a == columns[1]); TestsHelper.PrintTableOutput(this.output, function, result); }
public void GivenTheFollowingExistingCustomerOrders(Table table) { var orders = new List <ClientEntities.Order>(); foreach (var row in table.Rows) { string custId = row["CustomerId"]; TestsHelper.EnsureTestCustomer(custId, "Test Customer " + custId); int[] productIds = TestsHelper.CreateTestProducts(); ScenarioContext.Current.Add("ProductIds", productIds); var order = TestsHelper.CreateTestOrder(custId, productIds); orders.Add(order.ToClientEntity()); } ScenarioContext.Current.Add("ExistingCustOrders", orders); }
public async void LoadRelatedEntitiesAsync_Should_Populate_Employee_Territories_With_Area() { // Arrange var context = TestsHelper.CreateNorthwindDbContext(CreateNorthwindDbOptions); var employee = CreateTestEmployees(context)[0]; employee.TrackingState = TrackingState.Added; // Act await context.LoadRelatedEntitiesAsync(employee); // Assert Assert.False(employee.Territories.Any(t => t.Area == null)); Assert.False(employee.Territories.Any(t => t.AreaId != t.Area.AreaId)); }
public async void LoadRelatedEntitiesAsync_Should_Populate_Multiple_Orders_With_Customer() { // Arrange var context = TestsHelper.CreateNorthwindDbContext(CreateNorthwindDbOptions); var orders = CreateTestOrders(context); orders.ForEach(o => o.TrackingState = TrackingState.Added); // Act await context.LoadRelatedEntitiesAsync(orders); // Assert Assert.False(orders.Any(o => o.Customer == null)); Assert.False(orders.Any(o => o.Customer.CustomerId != o.CustomerId)); }
public static async Task ChangeAttendedStatusAndNotesOnParticipantsAsync( UserType userType, string plant, int id, ParticipantToChangeDto[] dtos, HttpStatusCode expectedStatusCode = HttpStatusCode.OK, string expectedMessageOnBadRequest = null) { var serializePayload = JsonConvert.SerializeObject(dtos); var content = new StringContent(serializePayload, Encoding.UTF8, "application/json"); var response = await TestFactory.Instance.GetHttpClient(userType, plant) .PutAsync($"{Route}/{id}/AttendedStatusAndNotes", content); await TestsHelper.AssertResponseAsync(response, expectedStatusCode, expectedMessageOnBadRequest); }
public async Task StreamingTest( [Values(1, 2, 3)] int count, [Range(0, 100, 25)] int nullsPercentage) { var sourceNode = TestsHelper.GenerateListNode(count, nullsPercentage); var serializer = ListSerializerFactory.CreateSerializer(SerializeFactory, DeserializeFactory); await using var stream = new MemoryStream(); await serializer.Serialize(sourceNode, stream); stream.Seek(0, SeekOrigin.Begin); var cloneNode = await serializer.Deserialize(stream); TestsHelper.CheckEqual(sourceNode, cloneNode); }
public async Task GetTaskDefinitionsWithNoTaskDefinitionsReturnsNoTaskDefinitions() { mockRepo.Setup(repo => repo.GetTaskDefinitionsAsync()) .ReturnsAsync(TestsHelper.GetTaskDefinitions(0)) .Verifiable(); var actionResult = await taskDefinitionsController.GetTaskDefinitions(); var okResult = actionResult as OkObjectResult; var values = okResult.Value as IEnumerable <TaskDefinition>; Assert.IsNotNull(values); Assert.AreEqual(values.Count(), 0); mockRepo.Verify(); }
//_______________________________________________________________________________________________________________________ private void CDgVars_CellValueChanged(object sender, DataGridViewCellEventArgs e) { Location loc = (Location)TestObjectBase.LinkedObject(sLnkCurrentLocation); if (loc == null) { return; } if (cDgVars.Rows[e.RowIndex].Cells[0].Value.Equals(DBNull.Value)) { if (e.ColumnIndex == 1) { long id = TestsHelper.saveVariable(TestObjectBase.NO_ID, cDgVars.Rows[e.RowIndex].Cells[1].Value.ToString()); cDgVars.Rows[e.RowIndex].Cells[0].Value = id; } else if (e.ColumnIndex == 2 && cDgVars.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() != "") { string name = "$tstVar" + cDgVars.Rows.Count; long id = TestsHelper.saveVariable(TestObjectBase.NO_ID, name); TestsHelper.setLocationVariableValue(loc, id, cDgVars.Rows[e.RowIndex].Cells[2].Value.ToString()); cDgVars.Rows[e.RowIndex].Cells[0].Value = id; cDgVars.Rows[e.RowIndex].Cells[1].Value = name; } else if (e.ColumnIndex == 3 && cDgVars.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() != "") { string name = "$tstVar" + cDgVars.Rows.Count; long id = TestsHelper.saveVariable(TestObjectBase.NO_ID, name); TestsHelper.saveVariableDetail(TestsHelper.getVariableByID(id), cDgVars.Rows[e.RowIndex].Cells[3].Value.ToString()); cDgVars.Rows[e.RowIndex].Cells[0].Value = id; cDgVars.Rows[e.RowIndex].Cells[1].Value = name; } return; } if (e.ColumnIndex == 1) { TestsHelper.saveVariable((long)cDgVars.Rows[e.RowIndex].Cells[0].Value, cDgVars.Rows[e.RowIndex].Cells[1].Value.ToString()); } else if (e.ColumnIndex == 2) { TestsHelper.saveLocationVariable(loc, TestsHelper.getVariableByID((long)cDgVars.Rows[e.RowIndex].Cells[0].Value)); TestsHelper.setLocationVariableValue(loc, (long)cDgVars.Rows[e.RowIndex].Cells[0].Value, cDgVars.Rows[e.RowIndex].Cells[2].Value.ToString()); } else if (e.ColumnIndex == 3) { TestsHelper.saveVariableDetail(TestsHelper.getVariableByID((long)cDgVars.Rows[e.RowIndex].Cells[0].Value), cDgVars.Rows[e.RowIndex].Cells[3].Value.ToString()); } ShowLasError(); }
public void Deleting_Parent_Should_Delete_Children() { // Arrange var context = TestsHelper.CreateNorthwindDbContext(CreateNorthwindDbOptions); var product = new Product { ProductName = "TestProduct" }; var category = new Category { CategoryName = "TestCategory", Products = new List <Product> { product } }; context.Categories.Add(category); context.SaveChanges(); int categoryId = category.CategoryId; int productId = product.ProductId; context.Entry(product).State = EntityState.Detached; context.Entry(category).State = EntityState.Detached; product = new Product { ProductId = productId, CategoryId = categoryId, ProductName = "TestProduct" }; category = new Category { CategoryId = categoryId, CategoryName = "TestCategory", Products = new List <Product> { product } }; // Act // First mark child and parent as unchanged (to attach) context.Entry(product).State = EntityState.Unchanged; context.Entry(category).State = EntityState.Unchanged; // Then mark child and parent as deleted context.Entry(product).State = EntityState.Deleted; context.Entry(category).State = EntityState.Deleted; context.SaveChanges(); // Assert Assert.Equal(EntityState.Detached, context.Entry(category).State); Assert.Equal(EntityState.Detached, context.Entry(product).State); }
public async void LoadRelatedEntitiesAsync_With_Complex_Types() { var context = TestsHelper.CreateFamilyDbContext(CreateDbOptions.DropCreateDatabaseIfModelChanges); var parent = new Parent(Guid.NewGuid().ToString()); parent.Address = new Address(); context.Parents.Add(parent); context.SaveChanges(); // Act await context.LoadRelatedEntitiesAsync(parent); // Assert // previous call throws exception if not implemented properly. Assert.True(true); }
public async Task GetTrackByIsrcCode_Isrc_CorrectResult() { // arrange const string isrc = "GBBKS1700108"; var http = new HttpClient(); var accounts = new AccountsService(http, TestsHelper.GetLocalConfig()); var api = new TracksApi(http, accounts); // act var track = await api.GetTrackByIsrcCode(isrc); // assert Assert.AreEqual(isrc, track.ExternalIds.Isrc); }
public async Task GetTaskDefinitionWithValidIdReturnsOk() { TaskDefinition validTaskDefinition = TestsHelper.GetTaskDefinitions(1).First(); mockRepo.Setup(repo => repo.GetTaskDefinitionAsync(It.IsAny <Guid>())) .ReturnsAsync(validTaskDefinition) .Verifiable(); var actionResult = await taskDefinitionsController.GetTaskDefinition(Guid.NewGuid()); var okResult = actionResult as OkObjectResult; var value = okResult.Value as TaskDefinition; Assert.IsInstanceOfType(okResult, typeof(OkObjectResult)); Assert.AreEqual(value.Id, validTaskDefinition.Id); }
public void Apply_Changes_Should_Mark_ComplexType_Modified() { // Arrange var context = TestsHelper.CreateFamilyDbContext(CreateFamilyDbOptions); var parent = new MockFamily().Parent; parent.Address.StreetName = "123 Lee Ave."; parent.Address.ModifiedProperties = new[] { nameof(Address.StreetName) }; parent.Address.TrackingState = TrackingState.Modified; // Act context.ApplyChanges(parent); // Assert Assert.True(context.Entry(parent).ComplexProperty(p => p.Address).IsModified); }
protected static void ClassInitializeCommon(DiImplementationType diImplementationType, Func <IContainerInfo> createContainerInfo) { TestsHelper.SetupLogger(); Log4Tests.LogLevel = LogLevel.Debug; _diImplementationType = diImplementationType; _mainLifeTimeScopeTerminatedExecuted = false; _containerInfo = createContainerInfo(); _diContainer = _containerInfo.DiContainer; _diContainer.MainLifeTimeScope.LifeTimeScopeTerminated += (sender, e) => { _mainLifeTimeScopeTerminatedExecuted = true; }; }
public void ShouldParseHexagonCommand() { // Arrange string inputStrig = "Draw a heptagon with a side length of 270"; // Act var parser = new HeptagonParser(); Polygon res = parser.Parse(inputStrig); // Assert Assert.IsNotNull(res); var points = res.Points.ToList(); Assert.AreEqual(7, points.Count); Assert.IsTrue(TestsHelper.CheckDistance(points[0], points[1], 270, 1)); }
public async Task GetTrackByIsrcCode_NonExistentIsrc_ResultIsNull() { // arrange const string isrc = "NOPE12345678"; var http = new HttpClient(); var accounts = new AccountsService(http, TestsHelper.GetLocalConfig()); var api = new TracksApi(http, accounts); // act var track = await api.GetTrackByIsrcCode(isrc); // assert Assert.IsNull(track); }
public void Transport_Connector_CreateRequest_Basic() { // Arrange string payload = "payload"; HttpMethod method = HttpMethod.Post; var request = (HttpWebRequest)WebRequest.Create("https://somerandomuri.test"); this.requestMock.Stub(x => x.CreateRequest(this.baseUrl.ToString())).Return(request); // Act this.connector.CreateRequest(this.baseUrl.ToString(), HttpMethod.Post, payload); // Assert TestsHelper.AssertRequest(this.merchantId, this.secret, request, method); Assert.AreEqual(payload.Length, request.ContentLength); }
public RunsService( TestsHelper testsHelper, AppKeyRepository <Run> runsRepository, AppKeyRepository <Test> testsRepository, AppKeyRepository <TestRun> testRunsRepository, HubRunRunner runRunner, Paths paths ) { _testsHelper = testsHelper; _runsRepository = runsRepository; _testsRepository = testsRepository; _testRunsRepository = testRunsRepository; _runRunner = runRunner; _paths = paths; }
public async void PaginatedEnumerableStringSearchTest() { string prefix = "test"; var testEnumerable = TestsHelper.CreateStringEnumerable(100, prefix); PaginableSearchEngine <string> enumerableSearchEngine = new PaginableSearchEngine <string>(new EnumerableSearchEngine <string>(testEnumerable)); SearchQuery query = new SearchQuery(new SearchParameterSet( new List <TypedParameter <string> >() { new TypedParameter <string>("searchTerms", prefix) } )); EnumerableResultSearchTask <string> resultTask = (EnumerableResultSearchTask <string>)enumerableSearchEngine.CreateSearch(query) as EnumerableResultSearchTask <string>; Assert.Equal(testEnumerable.Take(20), (await resultTask.SearchResults <string>())); query = new SearchQuery(new SearchParameterSet( new List <TypedParameter <string> >() { new TypedParameter <string>("searchTerms", "1") } )); resultTask = (EnumerableResultSearchTask <string>)enumerableSearchEngine.CreateSearch(query); Assert.Equal(20, (await resultTask.SearchResults <string>()).Count()); resultTask = (EnumerableResultSearchTask <string>)enumerableSearchEngine.CreateSearch("2"); Assert.Equal(19, (await resultTask.SearchResults <string>()).Count()); resultTask = (EnumerableResultSearchTask <string>)enumerableSearchEngine.CreateSearch("test"); Assert.Equal(20, (await resultTask.SearchResults <string>()).Count()); query = new SearchQuery(new SearchParameterSet()); resultTask = (EnumerableResultSearchTask <string>)enumerableSearchEngine.CreateSearch(query); Assert.Equal(20, (await resultTask.SearchResults <string>()).Count()); resultTask = (EnumerableResultSearchTask <string>)enumerableSearchEngine.GetPage("", new PaginationParameters(91, 1, 20)); Assert.Equal(10, (await resultTask.SearchResults <string>()).Count()); resultTask = (EnumerableResultSearchTask <string>)enumerableSearchEngine.GetPage("", new PaginationParameters(0, 2, 50)); Assert.Equal(50, (await resultTask.SearchResults <string>()).Count()); }
public static async Task <int> CreateAreaTagAsync( UserType userType, string plant, string projectName, AreaTagType areaTagType, string disciplineCode, string areaCode, string tagNoSuffix, List <TagRequirementDto> requirements, int stepId, string description, string remark, string storageArea, string purchaseOrderCalloffCode, HttpStatusCode expectedStatusCode = HttpStatusCode.OK, string expectedMessageOnBadRequest = null) { var bodyPayload = new { projectName, areaTagType, disciplineCode, areaCode, tagNoSuffix, requirements, stepId, description, remark, storageArea, purchaseOrderCalloffCode }; var serializePayload = JsonConvert.SerializeObject(bodyPayload); var content = new StringContent(serializePayload, Encoding.UTF8, "application/json"); var response = await TestFactory.Instance.GetHttpClient(userType, plant).PostAsync($"{_route}/Area", content); await TestsHelper.AssertResponseAsync(response, expectedStatusCode, expectedMessageOnBadRequest); if (response.StatusCode != HttpStatusCode.OK) { return(-1); } var jsonString = await response.Content.ReadAsStringAsync(); return(JsonConvert.DeserializeObject <int>(jsonString)); }
public void State_Interceptor_Should_Mark_Many_To_Many_Entities_States(bool setState1, bool setState2) { // Arrange var context = TestsHelper.CreateNorthwindDbContext(CreateNorthwindDbOptions); var nw = new MockNorthwind(); var employee = nw.Employees[0]; var territory1 = employee.Territories[0]; var territory2 = employee.Territories[1]; employee.Territories = new List <Territory> { territory1, territory2 }; territory1.TrackingState = TrackingState.Modified; territory2.TrackingState = TrackingState.Modified; // Act var states = new[] { setState1?EntityState.Unchanged : null as EntityState?, setState2 ? EntityState.Unchanged : null as EntityState?, }; context .WithStateChangeInterceptor <Territory>((e, r) => { if (e.TerritoryId == "01581") { return(states[0]); } if (e.TerritoryId == "01730") { return(states[1]); } return(null); }) .ApplyChanges(employee); // Assert var expectedStates = new[] { setState1?EntityState.Unchanged : EntityState.Modified, setState2 ? EntityState.Unchanged : EntityState.Modified, }; Assert.Equal(expectedStates[0], context.Entry(territory1).State); Assert.Equal(expectedStates[1], context.Entry(territory2).State); }
public static JSParserResult RunTest(string sourceName, string resultName) { var source = TestsHelper.GetEmbeddedText("JsParser.Test.Parser.Source." + sourceName); // Fix line endings in test files. All should be unix way, but on some GIT clients it is updated automatically. source = source.Replace("\r\n", "\n"); var settings = new JavascriptParserSettings() { Filename = sourceName, }; var actualResult = (new JavascriptParser(settings)).Parse(source); var outDir = "C:\\js_parser_units_output"; Directory.CreateDirectory(outDir); // Save actual hierarchy xml var serialized = SimpleHierarchySerializer.Serialize(actualResult.Nodes); File.WriteAllText(outDir + "\\" + resultName, serialized); // Load test data var resName = "JsParser.Test.Parser.ExpectedResult." + resultName; var passed = false; if (TestsHelper.CheckEmbeddedRes(resName)) { File.WriteAllText(outDir + "\\" + resultName, SimpleHierarchySerializer.Serialize(actualResult.Nodes)); var expectedresultSerialized = TestsHelper.GetEmbeddedText(resName); var expectedresult = SimpleHierarchySerializer.Deserialize <CodeNode>(expectedresultSerialized); // Save expected hierarchy serialized File.WriteAllText(outDir + "\\" + resultName + ".ex", expectedresultSerialized); if (HierarchyComparer.Compare(actualResult.Nodes, expectedresult, new CodeNodeAssertComparer())) { passed = true; } } Assert.IsTrue(passed); return(actualResult); }
public void PostsController_Create_Post() { //Here post is actually Invalid. But model state will be true since the model is not passed via MVC pipeline. //Testing validation would actually be testing MVC Model Validation and hence skipping that part var postViewModel = new PostViewModel { Id = 6 }; var viewResult = _postsController.Create(postViewModel) as ViewResult; var model = Mapper.Map <Post>(postViewModel); _postRepository.ReceivedWithAnyArgs().Add(model); _postRepository.ClearReceivedCalls(); var categories = (viewResult.Model as PostViewModel).Categories.ToList(); Assert.IsTrue(categories.SequenceEqual(TestsHelper.GetCategories(), new SelectListItemComparer())); }